RunicNavigator class

Namespace Runic.Navigation in Runic.Navigation 0.23.0

public sealed class RunicNavigator : IAsyncDisposable, IDisposable

Inherits or implements IAsyncDisposable, IDisposable.

Owns the navigation regions and entries of one window. Register it per window scope with RunicNavigationServiceCollectionExtensions.AddRunicNavigation.

Remarks

Each region admits one transition at a time: a later request supersedes earlier ones that have not started committing, or, in a region created with NavigationAdmission.RejectWhileBusy, is rejected while an earlier one runs. Guards, initialize and resume run outside commit turns; a commit re-checks the region and applies the new state in one turn. Disposing the navigator cancels in-flight transitions and retires every entry; owned content is disposed outside commit turns.

When the model context implements IRunicModelHookScheduler, as RunicModelContext and Runic.Navigation.Wpf's DispatcherModelContext do, factories, guards, initialize, resume and arrival hooks and the disposal of owned content each run as a separate operation on the model's thread, never inline in the caller's frame or in a commit turn. Otherwise they run outside turns, on the caller's thread until its first await or on the thread pool. The navigator's own work between hooks always continues on the thread pool.

Constructors

RunicNavigator

public RunicNavigator(RunicNavigatorOptions options)

Creates a navigator for one window.

Fields

LogCategory

public const string LogCategory = "Runic.Navigation"

The category of the navigator's log entries (events 1060-1079).

Properties

HookCancellationToken

public static CancellationToken HookCancellationToken { get; }

Gets the token of the navigation hook whose code runs on the calling asynchronous flow, such as a departure guard, an initialize, resume or arrival hook, or CancellationToken.None outside hooks. It is the token the hook received: cancelled when the transition is superseded, cancelled or closed, or, for an activation hook, when its entry stops being current.

Remarks

The hook's continuations keep it, however they resume. Code that a hook's modal dialog pumps, such as an input handler, is not the hook's code and sees CancellationToken.None. A presentation uses it to end work that a hook started on its behalf; Runic.Application.Views ends a browser interaction request with it.

IsBusy

public bool IsBusy { get; }

Gets whether a transition of any region or selection of this navigator is in flight or a retirement is running: it is false exactly when RunicNavigator.WhenIdleAsync would complete at once.

Remarks

It counts what RunicNavigator.WhenIdleAsync waits for: every region's and selection's transitions until their tasks complete, retirements that no request awaits, and the guard of a Back whose callers have all cancelled, until that guard returns. It can therefore stay true after every region's NavigationRegion.IsBusy is false.

The value is a snapshot and raises no change notification. Bind a progress indicator to NavigationRegion.IsBusy, which reports its changes through NavigationRegion.PropertyChanged, and await RunicNavigator.WhenIdleAsync to wait for the navigator.

IsClosed

public bool IsClosed { get; }

Gets whether RunicNavigator.DisposeAsync has started or the model context closed (see IRunicModelContextLifetime). A closed navigator rejects requests as NavigationRejection.Closed, throws ObjectDisposedException from RunicNavigator.CreateRegion and ignores RunicNavigator.AttachPresentation.

ModelContext

public IRunicModelContext ModelContext { get; }

Gets the model context whose turns commit this navigator's state. Owned content is bound to it.

Services

public IServiceProvider? Services { get; }

Gets the service provider passed to target factories, or null when none was configured.

UnretiredEntryCount

public int UnretiredEntryCount { get; }

Gets the entries that have not finished retiring: pending, committed, and removed entries whose cleanup is still running. It is zero after RunicNavigator.DisposeAsync.

Methods

AddDepartureGuard

public IDisposable AddDepartureGuard(INavigationRegionGuard guard, NavigationRegionGuardOptions? options = null)

Registers a guard that is asked before a transition of any region of this navigator departs, after the guards of the entries and of the regions (NavigationRegion.AddDepartureGuard), once per transition. Its NavigationRegionDeparture.Region is the region the request was made to (for a request of a NavigationSelection, the region it leaves or removes), and its NavigationRegionDeparture.Entries and NavigationRegionDeparture.Kind cover every region of the transition.

Parameters

guard

The guard.

options

When the guard is asked; by default after the entries' guards, and skipped for retained entries and for ClearHistory.

Returns

An IDisposable that removes the guard.

Remarks

The rules of NavigationRegion.AddDepartureGuard apply. A window close that clears its regions one after another, such as WPF's GuardWindowClose or a Runic View's CanCloseAsync, asks the guard once per region that has entries; to ask once per close, register it on the window's main region instead, or remember the answer. A guard asked NavigationRegionGuardOrder.BeforeEntries that vetoes is asked for the first such region, before any page's guard, so the window stays open with every region as it was.

AttachPresentation

public IDisposable AttachPresentation(INavigationPresentation presentation)

Attaches a presentation that shows this navigator's content. Presentation integrations, such as the Runic Views runtime, call it; applications do not.

Parameters

presentation

The presentation to attach.

Returns

An IDisposable that detaches the presentation.

Remarks

When owned content retires, after its child regions are closed and before the content is disposed, the navigator calls INavigationPresentation.Forget on each attached presentation, outside model turns. A presentation that throws is logged (event 1064, step Forget) and does not skip the others. A presentation attached after the navigator started closing (RunicNavigator.IsClosed) is ignored, and the returned IDisposable does nothing.

BackAsync

public ValueTask<NavigationResult<object>> BackAsync(NavigationRequestOptions? options = null, CancellationToken cancellationToken = default)

Goes back in the innermost presented region that can: what a window's Back button, the mouse's Back button or Alt+Left does. A result entry (NavigationRegion.PushForResult) that is current is dismissed, as a dialog closes on Back; another region goes BackAsync.

Parameters

options

The request's options.

cancellationToken

Cancels the request before it commits.

Remarks

The region is found from the regions and selections no entry owns, the most recently created first; within a region, the regions and selections its current entry's content owns, the most recently created first, are tried before the region itself, and a selection is followed only into its selected region. The first region found that has a current result entry, or a retained entry to go back to, goes back.

The request is an ordinary one, guarded and returned as a result. With no such region it is NavigationRejection.NoHistory and nothing runs.

Called on the navigator, every region counts as presented. A presentation host's Back counts only the regions it presents: a Runic Views page's Back (navigation-path/1) skips a region that no Bridge of the window presents, and the regions below it.

CreateRegion

public NavigationRegion<TContent> CreateRegion<TContent>(object owner, INavigationTarget<TContent>? initial = null, NavigationRegionOptions? options = null) where TContent : class

Creates a region owned by owner. A region owned by the content of an owned entry is that entry's child and closes when it retires; other regions close when the navigator is disposed.

Parameters

owner

The object that owns the region, such as the ViewModel exposing it.

initial

Content committed synchronously as the first entry. It must implement neither INavigationInitialize nor INavigationInitialize. Content that a Create target constructs can take its NavigationEntryContext as a constructor parameter. Before the method returns, the entry's NavigationEntryContext.StateChanged and INavigationAware.OnNavigatedTo run on the caller's thread with NavigationOperation.Reset.

options

The region's child policy.

CreateSelection

public NavigationSelection CreateSelection(object owner, IEnumerable<NavigationRegion> regions, NavigationSelectionOptions? options = null)

Creates a selection among sibling regions that owner owns, such as the tabs of a page that each keep their own stack: which region is presented, changed with NavigationSelection.SelectAsync as a guarded transition. The selection is one of the owner's regions: it closes with them when the owner's entry retires, or when the navigator is disposed.

Parameters

owner

The object that owns the regions and the selection, such as the ViewModel exposing them.

regions

The regions, in presentation order: live regions of this navigator, owned by owner, each once and in no other selection. It may be empty; NavigationSelection.Add appends regions later.

options

The initially selected region and the admission policy.

Exceptions

ArgumentException

A region belongs to another navigator, has an owner other than owner, is closed (other than by the retirement of owner), is already in a selection, or appears twice.

ArgumentOutOfRangeException

NavigationSelectionOptions.SelectedIndex is not the index of a region.

InvalidOperationException

owner is shared between entries (NavigationTarget.Share).

ObjectDisposedException

The navigator is closed.

Remarks

No guard is asked and no transition runs. A selection whose owner already started retiring starts closed, and takes the owner's regions, which that retirement closed or which RunicNavigator.CreateRegion created closed. Own the regions and the selection by the page that shows them, so that retiring the page asks every region's entries as NavigationDepartureKind.Retire.

DiscardRegionAsync

public ValueTask DiscardRegionAsync(NavigationRegion region)

Closes region without asking its guards and retires its entries, for a region the application created for a tab and then didn't add to its selection, such as one whose first page a guard or an unmatched link kept out. It is no longer one of its owner's regions, so RunicNavigator.GetPath doesn't record it.

Exceptions

InvalidOperationException

The region is in a selection.

Remarks

Only for a region that is in no selection and that no page presents.

Dispose

public void Dispose()

Starts RunicNavigator.DisposeAsync and returns without waiting for it, so a synchronous container disposal on the model's thread can't deadlock against a commit that needs that thread. Prefer RunicNavigator.DisposeAsync: after this method returns, owned content may still be disposing in the background.

Remarks

It is idempotent and shares one disposal with RunicNavigator.DisposeAsync. Failures are logged (1073).

DisposeAsync

public ValueTask DisposeAsync()

Refuses new requests and ends every open NavigationRegion.PushForResult request as Dismissed (or Completed when its return already committed), so guards awaiting a result unblock. Then cancels in-flight transitions and waits for them up to the close timeout, and closes and retires every entry region by region in creation order. Does not run guards.

Remarks

Each region is cleared in a model turn so the change is serialized with its commit. The wait for those turns is bounded by RunicNavigatorOptions.CloseTimeout for the whole disposal: when a turn stays blocked, that region is cleared outside a turn after the timeout and a warning (1068) is logged, the notifications it owes are posted, and the remaining regions are cleared without waiting. Disposal always completes; content disposal itself is not bounded. Retiring an entry whose initialize hook is running waits for the hook, within the same close timeout, before it disposes the content; once the wait for cancelled transitions timed out the hook is not awaited again and a warning (1069) is logged. An initialize hook never starts on content that retirement already claimed. The worst case of a disposal is about twice RunicNavigatorOptions.CloseTimeout (transition wait plus clearing turns), plus content disposal.

Retired content whose presentation keeps work for it (INavigationPresentation.ForgetAsync), such as a Runic Views operation declared with RunicOperationRetirement.Drain, is disposed when that work ends. Disposal waits for it up to one more RunicNavigatorOptions.CloseTimeout, then logs a warning (1077) per entry and completes; the content, its entry scope and its lease are still released once the work ends.

With a model context that implements IRunicModelHookScheduler, owned content is disposed as scheduled operations on the model's thread. Those that haven't started by the clearing turns' deadline run on the thread pool instead, so disposal still completes when the model's thread is blocked. Never block the model's thread on this task (for example with GetAwaiter().GetResult() in a WPF OnExit): content would then be disposed off that thread after the timeout. Call RunicNavigator.Dispose there, which doesn't wait.

GetPath

public NavigationPath GetPath(INavigationRouteMap? routes = null)

Gets the navigator's state as a serializable NavigationPath: every region and selection that no entry's content owns, by position in creation order, each with its entries and, below each entry, the regions and selections its content owns; the selected region of each selection; and each entry's route.

Parameters

routes

The route map, or null for the INavigationRouteMap of RunicNavigator.Services.

Exceptions

InvalidOperationException

routes is null and RunicNavigator.Services has no INavigationRouteMap.

Remarks

The state is read at one moment; a request in flight is not part of it. An entry that no route of routes describes is recorded with a null route, with the regions below it. Closed regions and pending entries are left out.

Routes come from INavigationRouteMap.GetRoute, which runs on the caller's thread after the state is read. The path holds no content: persist it as the application persists its own state, for example with NavigationPath.ToJson next to the window placement.

RestoreAsync

public ValueTask<NavigationRestoreResult> RestoreAsync(NavigationPath path, NavigationRestoreOptions? options = null, CancellationToken cancellationToken = default)

Rebuilds path, for example one that RunicNavigator.GetPath saved before a restart: each region is reconciled with the path's entries through ordinary navigation requests, so departure guards, preparation hooks, INavigationAware notifications and arrival hooks run as for any navigation.

Parameters

path

The path to rebuild.

options

The route map, what an unmapped entry does, and the bounds; the defaults without it.

cancellationToken

Cancels the requests not yet committed; the restore then stops.

Exceptions

InvalidOperationException

No route map was passed in options or registered in RunicNavigator.Services.

ArgumentOutOfRangeException

A bound of options is less than 1.

OperationCanceledException

cancellationToken was cancelled.

Remarks

For each region, the entries whose routes already match the path from the bottom stay, with their content. Then the rest of the region goes: BackToAsync the last entry that stays, or ResetAsync with the path's first entry when none stays, or ClearAsync when the path's region is empty. The path's remaining entries are pushed one at a time. After an entry is in place, the regions and selections its content owns are restored the same way, before the entry above it is pushed; a selection then selects its saved region with NavigationSelection.SelectAsync, and a region collection gets its missing tabs from NavigationSelectionOptions.RestoreRegion.

Restoring fails softly: what can't be restored is left out and reported in NavigationRestoreResult.Issues (log event 1220), and the rest is restored. An entry whose route no route matches stops its region by default, so the region keeps the entries below it and none above it (NavigationRestoreOptions.UnmappedEntries). A request that does not commit, because a guard refused or the request failed, stops that region; its sibling regions are still restored. Entries and tabs beyond NavigationRestoreOptions.MaximumEntriesPerRegion and NavigationRestoreOptions.MaximumRegionsPerSelection are left out. Regions and selections that the owner has but the path doesn't name, and tabs beyond the path's, are left as they are. A tab that NavigationSelectionOptions.RestoreRegion created and that nothing could be restored into is discarded (RunicNavigator.DiscardRegionAsync).

Call it once the window's regions exist, such as after the window opened. Don't call it from a navigation hook of this navigator: its requests would be NavigationRejection.Reentrant.

WhenIdleAsync

public ValueTask WhenIdleAsync(CancellationToken cancellationToken = default)

Completes when no transition of any region or selection of this navigator is in flight and no retirement is running. A transition counts until its task completes: its guards, preparation, commit, the retirement of the departed entries and the arrival hook of the arrived entry (INavigationArrived).

Parameters

cancellationToken

Stops waiting.

Remarks

Unlike NavigationRegion.WhenIdleAsync, it waits for every region, for retirements that no request awaits, and for the guard of a Back whose callers have all cancelled, until that guard returns.

A hook of a transition of this navigator (a factory, guard, initialize, resume or arrival hook) that awaits it deadlocks: the navigator is not idle while the hook runs. The same holds for the NavigationRegion.WhenIdleAsync of the hook's region.