using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LageBuch.AppLogic.Services;
using LageBuch.AppLogic.Services.Map;
using LageBuch.AppLogic.Services.Weather;
using LageBuch.Domain;
using LageBuch.Domain.Time;
using LageBuch.Domain.ValueObjects;
using LageBuch.Persistence.MasterData;
using LageBuch.Sync;
namespace LageBuch.AppLogic.ViewModels;
public sealed partial class IncidentWorkspaceViewModel : ObservableObject, IDisposable
{
///
/// How many rail entries the narrow layout's bottom bar shows before the rest go behind MEHR.
/// Five cells across a 412dp phone leave ~82dp each, which fits an icon over a short label.
///
private const int PhoneNavSlots = 4;
private readonly IIncidentSession _session;
// The concrete local session, or null on a joined client. Guards what only exists on the device
// that owns the .lagebuch file: resuming a read-only file, and exporting straight from its disk.
private readonly LocalIncidentSession? _local;
private readonly IClock _clock;
private readonly ITicker _ticker;
private readonly MasterDataSet _masterData;
private readonly IFileDialogService _dialogs;
private readonly IAlarmService _alarm;
private readonly AlarmMute? _alarmMute;
private readonly IRegionPackLibrary? _mapPacks;
private readonly MapNightMode? _mapNightMode;
private readonly IWeatherSource? _weather;
private readonly IIncidentHostController _hostController;
private readonly IIncidentPdfExporter _pdfExporter;
private readonly ILastPdfExportStore? _lastPdfExportStore;
private readonly IMailComposer _mailComposer;
// The same app-lifetime store the session persists through (issue #167 review follow-up):
// its background writer's SaveFailed/SaveSucceeded never reached the UI before this, so a
// disk-full/locked/corrupt-DB write silently failed while the screen kept saying "gespeichert".
// Null for a joined client's remote workspace (RemoteIncidentSession writes nothing through
// this store), which is why both this and the dispatcher stay optional.
private readonly IIncidentStore? _store;
private readonly IUiDispatcher _uiDispatcher;
// The address a joined client dialled, as typed; null on a local incident. The session itself
// does not keep it.
private readonly string? _remoteHost;
// The checklist view models currently in the rail. Held separately from NavItems because each
// one owns a session.Changed subscription that has to be released on rebuild.
// Keyed by list id, so a rail rebuild hands each surviving list its existing view model.
private readonly Dictionary _checklists = new();
private bool _disposed;
public IncidentWorkspaceViewModel(IIncidentSession session, IClock clock, ITicker ticker, MasterDataSet masterData, IFileDialogService dialogs, IAlarmService alarm, IIncidentHostController hostController, IIncidentPdfExporter? pdfExporter = null, ILastPdfExportStore? lastPdfExport = null, IIncidentStore? store = null, IUiDispatcher? uiDispatcher = null, string? remoteHost = null, IMailComposer? mailComposer = null, AlarmMute? alarmMute = null, IRegionPackLibrary? mapPacks = null, MapNightMode? mapNightMode = null, IWeatherSource? weather = null)
{
ArgumentNullException.ThrowIfNull(session);
_mapPacks = mapPacks;
_mapNightMode = mapNightMode;
_weather = weather;
_session = session;
_local = session as LocalIncidentSession;
_clock = clock;
_ticker = ticker;
_masterData = masterData;
_dialogs = dialogs;
_alarm = alarm;
_hostController = hostController;
_hostController.JoinsClosedChanged += OnJoinsClosedChanged;
if (_local is not null)
{
_local.FileBytesNotWiped += OnFileBytesNotWiped;
}
_alarmMute = alarmMute;
if (_alarmMute is not null)
{
_alarmMute.Changed += OnAlarmMuteChanged;
}
_pdfExporter = pdfExporter ?? new NoopIncidentPdfExporter();
_lastPdfExportStore = lastPdfExport;
_mailComposer = mailComposer ?? new NoopMailComposer();
_store = store;
_uiDispatcher = uiDispatcher ?? new ImmediateUiDispatcher();
_remoteHost = remoteHost;
IsReadOnly = session.IsReadOnly;
// SaveFailed/SaveSucceeded fire on the store's background writer thread -- marshal onto
// the UI thread before touching PersistenceError. Unsubscribed in LeaveAsync, the one
// teardown path every caller already goes through, so this workspace doesn't outlive its
// own subscription to the app-lifetime store singleton.
if (_store is not null)
{
_store.SaveFailed += OnStoreSaveFailed;
_store.SaveSucceeded += OnStoreSaveSucceeded;
}
// Seed the export status line from the last persisted export (#262), so reopening the
// incident still shows "zuletzt exportiert" without requiring a fresh export this session.
// Only the file name is shown -- the full path is too long for the footer and lives in
// ExportStatusDetail (a tooltip) instead.
if (_lastPdfExportStore?.GetLastExport() is { } lastExport)
{
_exportStatus = $"Zuletzt exportiert: {Path.GetFileName(lastExport.Path)} um {lastExport.ExportedAt:HH:mm}";
_exportStatusDetail = lastExport.Path;
}
// Seed the backing fields directly so initialization doesn't trigger a write-back/save.
_keywordDisplay = _session.Incident.Keyword;
_incidentNumberInput = _session.Incident.IncidentNumber?.Value ?? string.Empty;
_addressDisplay = Formatting.Address(_session.Incident);
// The header is a projection of the incident's head data; any mutation -- the Einsatzdaten
// dialog on this device, or (host or joined client alike) a command from another device
// applied to this session -- re-reads it from the aggregate.
_session.Changed += RefreshIncidentData;
BuildChildren();
// A joined client renders exactly what the host broadcasts; wire the connection lifecycle so
// the workspace disables input while reconnecting and drops back to Home once the host is gone.
if (session is RemoteIncidentSession remote)
{
remote.Changed += OnRemoteLifecycle;
remote.Disconnected += OnRemoteDisconnected;
remote.Reconnected += OnRemoteReconnected;
remote.Ended += OnRemoteEnded;
remote.Reconciled += OnRemoteReconciled;
remote.ReconcileFailed += OnRemoteReconcileFailed;
remote.CommandRejected += OnRemoteCommandRejected;
}
// Polled rather than pushed: the offset moves on the session's reconcile loop, and the tick
// is already running for every countdown on screen.
if (session.IsRemote)
{
HostClockOffset = session.HostClockOffset;
_clockSkewRefresh = _ticker.Subscribe(() => HostClockOffset = _session.HostClockOffset);
}
// A joined client mirrors; it never saves. Which of the two the footer may claim is fixed here,
// at construction, from the session it was handed.
SyncState = session.IsRemote ? WorkspaceSyncState.Current : WorkspaceSyncState.Local;
}
private void OnRemoteDisconnected()
{
IsConnected = false;
// Said immediately rather than one poll interval later: while the link is down the Stand on
// screen is the last one we could confirm, and nothing may imply it is still live.
SyncState = WorkspaceSyncState.Unconfirmed;
}
// SyncState is deliberately not set back here — the reconcile that follows the reconnect is what
// actually establishes currency, and it raises Reconciled.
private void OnRemoteReconnected() => IsConnected = true;
private void OnRemoteEnded() => GoHomeRequested?.Invoke();
private void OnRemoteReconciled() => MarkSynced();
private void OnRemoteReconcileFailed() => SyncState = WorkspaceSyncState.Unconfirmed;
// Stays up until the operator dismisses it. Deliberately not cleared by the next applied snapshot:
// an unrelated change from another device would then wipe the notice before anyone had read it, and
// an input that silently did not take effect is the thing being fixed here, not something to
// half-report.
//
// It also withdraws the undo offer. On a joined client a change returns once it is queued, so the
// offer went up before the host answered; if the refused command was the offered one, RÜCKGÄNGIG
// would put back a state the host never left, over a peer's change. The refusal does not say which
// command it was, so any refusal withdraws the offer: losing one undo costs less than overwriting.
//
// Stryker disable all : only a RemoteIncidentSession raises this, so Sync.Hosting's
// WorkspaceCollaborationTests cover it; Stryker runs LageBuch.AppLogic.Tests alone.
private void OnRemoteCommandRejected(string reason)
{
// Withdrawn first, so whoever reacts to the banner never sees it beside the offer.
CloseUndoNotice();
CommandRejected = $"Änderung nicht übernommen: {reason}";
// Stryker restore all
}
private void MarkSynced()
{
LastSyncedAt = _clock.Now;
SyncState = WorkspaceSyncState.Current;
}
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanContinueEditing))]
[NotifyPropertyChangedFor(nameof(CanHost))]
[NotifyPropertyChangedFor(nameof(CanEditIncidentData))]
[NotifyCanExecuteChangedFor(nameof(CloseIncidentCommand))]
[NotifyCanExecuteChangedFor(nameof(ContinueEditingCommand))]
[NotifyCanExecuteChangedFor(nameof(EditIncidentDataCommand))]
[NotifyCanExecuteChangedFor(nameof(ChangeOperatorCommand))]
[NotifyCanExecuteChangedFor(nameof(OpenSituationReportCommand))]
[NotifyCanExecuteChangedFor(nameof(AddNavEntryCommand))]
[NotifyPropertyChangedFor(nameof(OperatorDisplay))]
private bool _isReadOnly;
[ObservableProperty]
private DateTimeOffset? _lastSavedAt;
// Null = healthy. Set from IIncidentStore.SaveFailed (background writer thread, marshalled via
// IUiDispatcher) and stays visible -- unlike the export/share status lines -- until a later
// save actually succeeds (SaveSucceeded), because a save that silently never reached disk is
// exactly what an incident logbook must never let the operator miss.
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowLocalSavedStatus))]
private string? _persistenceError;
// Under this a skew is noise next to how fast anyone reads a countdown; over it, a Trupp's
// remaining time on another device's screen visibly disagrees.
private static readonly TimeSpan ClockSkewWarningThreshold = TimeSpan.FromSeconds(30);
// ===== Joined-client sync state (#295). A joined device saves nothing locally, so the footer shows
// the host's Stand and whether that Stand is still confirmed, rather than a save that never
// happened. Settable so a render test can drive the footer without a live host. =====
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowLocalSavedStatus))]
[NotifyPropertyChangedFor(nameof(ShowSyncCurrentStatus))]
[NotifyPropertyChangedFor(nameof(ShowSyncUnconfirmedStatus))]
private WorkspaceSyncState _syncState;
///
/// When the host's state last landed on this device — the joined client's "Stand". Separate from
/// on purpose: that one is stamped by local activity in
/// OnChanged, which on a joined client is exactly the misleading value this replaces.
///
[ObservableProperty]
private DateTimeOffset? _lastSyncedAt;
///
/// How far the host's clock is ahead of this device's, read from the session every tick. A joined
/// client already runs its countdowns on host time; this only drives the footer warning. Settable
/// so a render test can drive the footer without a live host.
///
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ClockSkewWarning))]
private TimeSpan _hostClockOffset;
///
/// Null while this device's clock is within of the host's.
/// Otherwise says by how much. The countdowns here are right either way; the warning is so the
/// clock gets set before this device works on its own, hosting the next Einsatz.
///
public string? ClockSkewWarning =>
HostClockOffset.Duration() < ClockSkewWarningThreshold ? null : Formatting.ClockSkew(HostClockOffset);
///
/// Null = nothing was refused. The host's own reason for turning down the last change, shown as a
/// banner until the Lagebuchführer dismisses it (#295).
///
[ObservableProperty]
private string? _commandRejected;
/// The three footer states are mutually exclusive; the view binds one flag each, because
/// Avalonia bindings have no && and this keeps the condition in one testable place.
public bool ShowLocalSavedStatus => SyncState == WorkspaceSyncState.Local && PersistenceError is null;
///
public bool ShowSyncCurrentStatus => SyncState == WorkspaceSyncState.Current;
///
public bool ShowSyncUnconfirmedStatus => SyncState == WorkspaceSyncState.Unconfirmed;
[RelayCommand]
private void DismissCommandRejected() => CommandRejected = null;
[ObservableProperty]
private OperatorPromptViewModel? _pendingPrompt;
[ObservableProperty]
private ConfirmDialogViewModel? _pendingConfirm;
/// How long a "Rückgängig" offer stays up (#543): long enough to notice, short enough not to linger.
internal static readonly TimeSpan UndoNoticeLifetime = TimeSpan.FromSeconds(8);
// The "Rückgängig" offer after a toggle (#543); null while there is nothing to take back.
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasUndoNotice))]
[NotifyCanExecuteChangedFor(nameof(UndoCommand))]
private UndoNoticeViewModel? _undoNotice;
public bool HasUndoNotice => UndoNotice is not null;
private readonly IDisposable? _clockSkewRefresh;
// Ticks only while a notice shows, so an idle workspace holds no ticker subscription for it.
private IDisposable? _undoNoticeExpiry;
// The create-task overlay behind an ETB row's button (#88); null while no dialog is open.
[ObservableProperty]
private TaskDialogViewModel? _pendingTaskDialog;
// The Buchstabier-Helfer opened from the ETB (#592); null while it is closed.
[ObservableProperty]
private SpellingHelperDialogViewModel? _pendingSpellingHelper;
// The PDF section-selection overlay (#262); null while no export is in flight.
[ObservableProperty]
private PdfExportOptionsViewModel? _pendingPdfExportOptions;
// The Einsatzdaten overlay (Stichwort, Einsatznummer, Adresse); null while no dialog is open.
[ObservableProperty]
private IncidentDataDialogViewModel? _pendingIncidentDataDialog;
// The Abschnitt dialog behind the Führung board (form, edit, the Einsatzleitung's post); null while closed.
[ObservableProperty]
private CommandNodeDialogViewModel? _pendingCommandNodeDialog;
// The dialog behind the Führung board's Leitstelle badge, its channel (#926); null while closed.
[ObservableProperty]
private DispatchChannelDialogViewModel? _pendingDispatchChannelDialog;
// The person dialog behind the Führung board (Leiter, Melder, Führungsunterstützung, Fachberater); null while closed.
[ObservableProperty]
private LeadershipPersonDialogViewModel? _pendingLeadershipPersonDialog;
// The dialog that corrects or hands over a Funktion already held (Führung board, FUNKTIONEN); null while closed.
[ObservableProperty]
private RoleAssignmentDialogViewModel? _pendingRoleAssignmentDialog;
// ===== Header: display projections of the incident's head data. None of these write back --
// the only write path is the Einsatzdaten dialog (EditIncidentData), which replaced the inline
// Einsatznummer editor of #69. They are seeded in the constructor and refreshed from the
// aggregate by RefreshIncidentData on every session change. =====
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HeroText))]
[NotifyPropertyChangedFor(nameof(ShowEinsatznummerChip))]
[NotifyPropertyChangedFor(nameof(HasIncidentData))]
private string? _keywordDisplay;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HeroText))]
[NotifyPropertyChangedFor(nameof(HasEinsatznummer))]
[NotifyPropertyChangedFor(nameof(ShowEinsatznummerChip))]
[NotifyPropertyChangedFor(nameof(HasIncidentData))]
private string _incidentNumberInput = string.Empty;
// "Straße, Ortsteil" -- the same join the PDF header prints, so the two never disagree.
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowAddressLine))]
[NotifyPropertyChangedFor(nameof(ShowAddressLineInHeader))]
[NotifyPropertyChangedFor(nameof(HasIncidentData))]
private string? _addressDisplay;
// The header's hero: the Stichwort when known, else the Einsatznummer, else a placeholder for
// the rare incident that was given neither.
public string HeroText =>
!string.IsNullOrWhiteSpace(KeywordDisplay) ? KeywordDisplay
: !string.IsNullOrWhiteSpace(IncidentNumberInput) ? IncidentNumberInput
: "Unbenannter Einsatz";
public bool HasEinsatznummer => !string.IsNullOrWhiteSpace(IncidentNumberInput);
// The Einsatznummer is already occupying the hero slot when there's no Stichwort to show
// instead -- the chip would then be a redundant repeat of the hero text.
private bool IsEinsatznummerShownAsHero => string.IsNullOrWhiteSpace(KeywordDisplay) && HasEinsatznummer;
public bool ShowEinsatznummerChip => HasEinsatznummer && !IsEinsatznummerShownAsHero;
public bool ShowAddressLine => !string.IsNullOrWhiteSpace(AddressDisplay);
///
/// Whether the header itself shows the address. Separate from ,
/// which says whether there is one and feeds : folding
/// the phone into that would take the edit pencil away from an Einsatz that only has an
/// address. At 412dp the address is what pushes the Einsatznummer chip off the line, and it is
/// the one part of the identity already a tap away behind that pencil.
///
public bool ShowAddressLineInHeader => ShowAddressLine && !IsNarrow;
// Drives which affordance the header shows: a quiet pencil once anything is known, an explicit
// "+ Einsatzdaten ergänzen" while nothing is -- so an incident started without any head data
// always has a visible way to get some (#250).
public bool HasIncidentData =>
!string.IsNullOrWhiteSpace(KeywordDisplay) || HasEinsatznummer || ShowAddressLine;
public bool CanEditIncidentData => !IsReadOnly;
[RelayCommand(CanExecute = nameof(CanEditIncidentData))]
private void EditIncidentData()
{
// A template the format cannot read pre-fills nothing; the dialog then behaves as it did before #462.
_ = IncidentNumberFormat.TryParse(_masterData.Settings.IncidentNumberFormat, out var numberFormat);
// A saved address is looked up on the Lagekarte at once (fire-and-forget: a search that finds
// nothing clear leaves its hits in the LAGEKARTE tab, and a refusal lands in its ActionError).
var dialog = new IncidentDataDialogViewModel(
_session,
OnChanged,
_masterData.Keywords,
_masterData.Districts,
_masterData.Streets,
numberFormat,
onAddressSaved: () => _ = Lagekarte.LocateRecordedAddressAsync());
// Clear the overlay on either outcome; Save has already applied the edits on confirm, and
// the header projections refresh through the session's Changed event.
dialog.Closed += (_, _) => PendingIncidentDataDialog = null;
PendingIncidentDataDialog = dialog;
}
private void OpenCommandNodeDialog(CommandNodeDialogViewModel dialog)
{
dialog.Closed += (_, _) => PendingCommandNodeDialog = null;
PendingCommandNodeDialog = dialog;
}
private void OpenDispatchChannelDialog(DispatchChannelDialogViewModel dialog)
{
dialog.Closed += (_, _) => PendingDispatchChannelDialog = null;
PendingDispatchChannelDialog = dialog;
}
// A dialog replaced or dropped without closing (the workspace torn down under it) must stop
// following the session.
partial void OnPendingLeadershipPersonDialogChanged(
LeadershipPersonDialogViewModel? oldValue, LeadershipPersonDialogViewModel? newValue) => oldValue?.Detach();
private void OpenLeadershipPersonDialog(LeadershipPersonDialogViewModel dialog)
{
dialog.Closed += (_, _) => PendingLeadershipPersonDialog = null;
PendingLeadershipPersonDialog = dialog;
}
partial void OnPendingRoleAssignmentDialogChanged(
RoleAssignmentDialogViewModel? oldValue, RoleAssignmentDialogViewModel? newValue) => oldValue?.Detach();
private void OpenRoleAssignmentDialog(RoleAssignmentDialogViewModel dialog)
{
dialog.Closed += (_, _) => PendingRoleAssignmentDialog = null;
PendingRoleAssignmentDialog = dialog;
}
private void RefreshIncidentData()
{
var incident = _session.Incident;
KeywordDisplay = incident.Keyword;
IncidentNumberInput = incident.IncidentNumber?.Value ?? string.Empty;
AddressDisplay = Formatting.Address(incident);
OnPropertyChanged(nameof(OperatorDisplay));
// A list added, an entry hidden or shown, or a module going live, on this device or
// another one: the rail follows.
RebuildRailIfChanged();
}
/// Who documents on this device, shown in the header; null while read-only.
public string? OperatorDisplay => IsReadOnly ? null : _session.Operator?.Display;
public bool CanChangeOperator => !IsReadOnly && IsInputEnabled;
// A new Lagebuchführer takes over without leaving the incident (#469).
[RelayCommand(CanExecute = nameof(CanChangeOperator))]
private void ChangeOperator() =>
PendingPrompt = new OperatorPromptViewModel(
callSignOptions: _masterData.RadioCallSigns,
personnel: _masterData.Personnel,
previous: _session.Operator);
public CoMessprotokollViewModel CoMessprotokoll { get; private set; } = null!;
///
/// The left rail, in order: the built-in modules Stammdaten leaves visible, interleaved with
/// this Einsatz's Checklisten. Mutated in place on rebuild — replacing the collection would
/// break the view's ItemsSource binding.
///
public ObservableCollection NavItems { get; } = new();
///
/// The rail entry currently open. Two-way bound: it has to follow the operator's own taps as
/// well as drive them, or a jump to a tab this property already names (#422) would raise no
/// change and move nothing.
///
[ObservableProperty]
private WorkspaceNavItemViewModel? _selectedNavItem;
///
/// The user asked for the open module — a warning bar jumped to it — so the view puts the
/// caret in its first field (#542). Never raised for a rail entry reached by arrowing, a
/// rebuild or the phone's bottom bar: a module that takes focus whenever it appears is one the
/// rail cannot be arrowed past.
///
public event EventHandler? ModuleFocusRequested;
///
/// The rail entries the narrow bottom bar shows directly, and the ones behind its MEHR button.
/// The split is by position, because the order is the Kommandant's own: Stammdaten's
/// Navigation list is what decides which modules are one tap away on a phone.
///
///
/// Atemschutz falls into the overflow under the shipped order. That is survivable rather than
/// an oversight: a Rückzugsalarm is a lit header bar that jumps straight to the tab (#422), and
/// carries the quieter states out to the MEHR button.
///
public ObservableCollection PrimaryNavItems { get; } = new();
///
public ObservableCollection OverflowNavItems { get; } = new();
/// Whether MEHR has anything behind it — false on a rail of four or fewer.
[ObservableProperty]
private bool _hasOverflowNavItems;
///
/// A Checkliste behind MEHR still has to report. Without this its dot would be invisible until
/// the operator opened the overflow, which is the one moment it is no longer news.
///
[ObservableProperty]
private bool _overflowHasStatusDot;
///
/// Whether the workspace is laid out for a phone. Set by the shell from the actual width; the
/// container queries in the views handle everything that is purely presentational, and this
/// carries only the decisions a style setter cannot make — chiefly that an add-entry dock is a
/// sheet that starts closed rather than a strip that is always there.
///
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowAddressLineInHeader))]
private bool _isNarrow;
///
/// Hands the flag down to every module that lays out differently on a phone. Called again on
/// each rebuild, because replaces the module view models wholesale
/// and a fresh one would otherwise come up in the desktop layout on a phone.
///
partial void OnIsNarrowChanged(bool value) => PushNarrowToModules(value);
private void PushNarrowToModules(bool value)
{
foreach (var module in NarrowAwareModules())
{
module.IsNarrow = value;
}
}
private IEnumerable NarrowAwareModules()
{
// Every module the workspace owns, not only the ones that implement INarrowAware today:
// OfType does the filtering, and a module that gains the interface later is picked up
// without anyone having to remember this list. Null while the workspace is between
// sessions — DisposeChildren clears them and BuildNavItems has not run yet — which OfType
// also drops.
object?[] modules = [EtbTabs, Tasks, LeadershipTabs, InvolvedParties, IssuedItems, Scba, CoMessprotokoll, Files, Links, Contacts];
return modules.OfType();
}
/// Opens a rail entry from the narrow bottom bar or its MEHR flyout.
[RelayCommand]
private void SelectNavItem(WorkspaceNavItemViewModel? item)
{
if (item is not null)
{
SelectedNavItem = item;
}
}
partial void OnSelectedNavItemChanged(WorkspaceNavItemViewModel? value)
{
foreach (var item in NavItems)
{
item.IsSelected = ReferenceEquals(item, value);
}
}
private void RebuildNavSplit()
{
foreach (var item in OverflowNavItems)
{
item.PropertyChanged -= OnOverflowNavItemChanged;
}
PrimaryNavItems.Clear();
OverflowNavItems.Clear();
for (var i = 0; i < NavItems.Count; i++)
{
if (i < PhoneNavSlots)
{
PrimaryNavItems.Add(NavItems[i]);
continue;
}
OverflowNavItems.Add(NavItems[i]);
NavItems[i].PropertyChanged += OnOverflowNavItemChanged;
}
HasOverflowNavItems = OverflowNavItems.Count > 0;
UpdateOverflowStatusDot();
}
private void OnOverflowNavItemChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is null
or nameof(WorkspaceNavItemViewModel.IsComplete)
or nameof(WorkspaceNavItemViewModel.IsIncomplete))
{
UpdateOverflowStatusDot();
}
}
private void UpdateOverflowStatusDot() =>
OverflowHasStatusDot = OverflowNavItems.Any(item => item.IsComplete || item.IsIncomplete);
public EtbViewModel Etb { get; private set; } = null!;
public RolesViewModel Roles { get; private set; } = null!;
public ForcesViewModel Forces { get; private set; } = null!;
public InvolvedPartiesViewModel InvolvedParties { get; private set; } = null!;
public IssuedItemsViewModel IssuedItems { get; private set; } = null!;
public SituationReportsViewModel SituationReports { get; private set; } = null!;
/// The ETB rail entry, which shows and as tabs.
public EtbTabsViewModel EtbTabs { get; private set; } = null!;
public LeadershipViewModel Leadership { get; private set; } = null!;
/// The Führung rail entry, which shows , and as tabs.
public LeadershipTabsViewModel LeadershipTabs { get; private set; } = null!;
public LagekarteViewModel Lagekarte { get; private set; } = null!;
public ScbaViewModel Scba { get; private set; } = null!;
public FilesViewModel Files { get; private set; } = null!;
public LinksViewModel Links { get; private set; } = null!;
public ContactsViewModel Contacts { get; private set; } = null!;
public TasksViewModel Tasks { get; private set; } = null!;
public ReminderViewModel? Reminder { get; private set; }
public string StatusDisplay => Formatting.State(_session.Incident.State);
///
/// True while this device's alarm cues are muted in ÜBER (#699). The footer says so, so a crew
/// cannot lose the Rückzugsalarm without seeing it.
///
public bool AlarmsMuted => _alarmMute?.IsMuted ?? false;
public string ReadOnlyReason => _session.Incident.State == IncidentState.Closed
? "Abgeschlossen — schreibgeschützt"
: "Schreibgeschützt geöffnet";
public bool HasReminder => Reminder is not null;
///
/// Whether the header's quiet strip has anything to show: the ILS countdown or the next
/// Druckabfrage, still running and not yet due. Each leaves the strip for a row of its own
/// when it falls due, and the strip goes with the last of them.
///
public bool ShowsCountdownStrip =>
(Reminder?.IsCountingDown ?? false) || (Scba?.IsControlCountingDown ?? false);
private void OnHeaderSourceChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(ReminderViewModel.IsCountingDown)
or nameof(ScbaViewModel.IsControlCountingDown))
{
OnPropertyChanged(nameof(ShowsCountdownStrip));
}
if (e.PropertyName is null
or nameof(ScbaViewModel.IsAnyAlarm)
or nameof(ScbaViewModel.HasControlReminder)
or nameof(ScbaViewModel.IsAnyControlDue)
or nameof(TasksViewModel.HasDueTask)
or nameof(ReminderViewModel.IsDue))
{
UpdateMostUrgentWarning();
}
}
///
/// The open warning F9 goes to (#544), in the order the header bars run: Rückzugsalarm, a due
/// Druckabfrage, a due Aufgabe, the ILS Rückmeldung. Each condition is the one that shows its
/// bar, so F9 never goes somewhere the header does not name.
///
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowsWarningHintOnRetreat))]
[NotifyPropertyChangedFor(nameof(ShowsWarningHintOnPressureCheck))]
[NotifyPropertyChangedFor(nameof(ShowsWarningHintOnTaskDue))]
[NotifyPropertyChangedFor(nameof(ShowsWarningHintOnReminder))]
private WarningKind _mostUrgentWarning;
// The F9 key hint sits on the one bar F9 acts on, so it never names a bar F9 would skip.
public bool ShowsWarningHintOnRetreat => MostUrgentWarning == WarningKind.Retreat;
///
public bool ShowsWarningHintOnPressureCheck => MostUrgentWarning == WarningKind.PressureCheck;
///
public bool ShowsWarningHintOnTaskDue => MostUrgentWarning == WarningKind.TaskDue;
///
public bool ShowsWarningHintOnReminder => MostUrgentWarning == WarningKind.IlsReminder;
private void UpdateMostUrgentWarning() =>
MostUrgentWarning =
Scba is null ? WarningKind.None
: Scba.IsAnyAlarm ? WarningKind.Retreat
: Scba.HasControlReminder && Scba.IsAnyControlDue ? WarningKind.PressureCheck
: Tasks?.HasDueTask == true ? WarningKind.TaskDue
: Reminder?.IsDue == true ? WarningKind.IlsReminder
: WarningKind.None;
///
/// F9 found the ILS Rückmeldung most urgent (#544). It has nothing to jump to, so the view
/// puts focus on its ERLEDIGT button: the Rückmeldung is confirmed by a deliberate second key,
/// never by the shortcut alone.
///
public event EventHandler? ReminderFocusRequested;
///
/// Runs a global shortcut against this workspace (#544); false when it does not apply here, so
/// the key goes on to the focused control. Nothing runs while one of the workspace's overlays
/// is open: the overlay owns the keyboard until it closes.
///
public bool TryRunShortcut(KeyChord chord)
{
ArgumentNullException.ThrowIfNull(chord);
if (ShortcutRegistry.Find(chord) is not { } shortcut || IsOverlayOpen)
{
return false;
}
switch (shortcut.Action)
{
case ShortcutAction.ShowRailEntry:
return shortcut.RailIndex is { } index && index < NavItems.Count && ShowNavItem(NavItems[index]);
case ShortcutAction.NextModule:
return StepRail(+1);
case ShortcutAction.PreviousModule:
return StepRail(-1);
case ShortcutAction.NewEtbEntry:
if (!ShowEtbTab(EtbTabsViewModel.JournalTab, toStartField: true))
{
return false;
}
// On a phone the composer is a sheet that starts closed; the request for focus is
// skipped there, as everywhere on a phone.
if (IsNarrow)
{
Etb.OpenComposerCommand.Execute(null);
}
return true;
case ShortcutAction.OpenSituationReport:
return ShowSituationReport();
case ShortcutAction.MostUrgentWarning:
return RunMostUrgentWarning();
default:
return false;
}
}
private bool IsOverlayOpen =>
PendingPrompt is not null || PendingConfirm is not null || PendingTaskDialog is not null
|| PendingPdfExportOptions is not null || PendingIncidentDataDialog is not null
|| PendingSpellingHelper is not null
|| PendingCommandNodeDialog is not null || PendingDispatchChannelDialog is not null
|| PendingLeadershipPersonDialog is not null
|| PendingRoleAssignmentDialog is not null;
private bool StepRail(int step)
{
if (NavItems.Count == 0)
{
return false;
}
var current = SelectedNavItem is { } open ? NavItems.IndexOf(open) : -1;
var next = current < 0 ? 0 : (current + step + NavItems.Count) % NavItems.Count;
return ShowNavItem(NavItems[next]);
}
// Each goes through the bar's own command, so F9 and a click on the bar cannot disagree.
private bool RunMostUrgentWarning()
{
UpdateMostUrgentWarning();
switch (MostUrgentWarning)
{
case WarningKind.Retreat:
Scba.ShowAlarmingTruppCommand.Execute(null);
return true;
case WarningKind.PressureCheck:
Scba.ShowMostUrgentControlCommand.Execute(null);
return true;
case WarningKind.TaskDue:
Tasks.ShowMostOverdueTaskCommand.Execute(null);
return true;
case WarningKind.IlsReminder:
ReminderFocusRequested?.Invoke(this, EventArgs.Empty);
return true;
default:
return false;
}
}
// ===== Joined-client connection state (#52 §7). Always "connected" locally; on a remote session
// it tracks the SignalR link so the view can grey out input while reconnecting. =====
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsInputEnabled))]
[NotifyPropertyChangedFor(nameof(ShowConnectedHost))]
[NotifyCanExecuteChangedFor(nameof(ChangeOperatorCommand))]
[NotifyCanExecuteChangedFor(nameof(AddNavEntryCommand))]
private bool _isConnected = true;
// A reconnecting client cannot send a rail edit either.
partial void OnIsConnectedChanged(bool value) => RefreshCanHide(NavLiveness.LiveModules(_session.Incident));
/// "verbunden mit ‹host›" in a joined client's header (#464); null on a local incident.
public string? ConnectedHostText => _remoteHost is null ? null : $"verbunden mit {_remoteHost}";
/// Hidden while reconnecting: the "Verbindung getrennt" banner speaks then.
public bool ShowConnectedHost => _remoteHost is not null && IsConnected;
/// Modules are interactive only while connected — a reconnecting client can't send commands.
public bool IsInputEnabled => IsConnected;
/// Set by the shell to navigate back to Home (host gone, or the user left the client).
public Action? GoHomeRequested { get; set; }
[RelayCommand]
private void LeaveToHome() => GoHomeRequested?.Invoke();
///
/// Asks before the shell leaves this workspace (#463), and runs on
/// confirm. The dialog is the same whatever the destination; its wording only says whether
/// leaving also cuts off other devices -- which is also why Stammdaten need no lock of their
/// own: ends the sharing or the connection before the editor opens.
///
public void ConfirmLeaveThen(Action leave)
{
ArgumentNullException.ThrowIfNull(leave);
var dialog = (IsSharing, _session.IsRemote) switch
{
(true, _) => new ConfirmDialogViewModel(
"Freigabe beenden?",
"Beim Verlassen wird die Freigabe beendet — verbundene Geräte werden getrennt.",
"VERLASSEN",
leave),
(_, true) => new ConfirmDialogViewModel(
"Verbindung trennen?",
"Beim Verlassen wird die Verbindung zum Einsatz getrennt.",
"TRENNEN",
leave),
_ => new ConfirmDialogViewModel(
"Einsatz verlassen?",
"Der Einsatz wird verlassen. Er ist gespeichert und lässt sich über die Übersicht wieder öffnen.",
"VERLASSEN",
leave),
};
dialog.Closed += (_, _) => PendingConfirm = null;
PendingConfirm = dialog;
}
///
/// Called by the shell when this workspace is being left. Stops sharing it, tears down a joined
/// client's SignalR/HTTP connection, and drops this workspace's subscription to the
/// (app-lifetime, singleton) store, so a closed workspace doesn't keep reacting to saves it can
/// no longer show.
///
public async ValueTask LeaveAsync()
{
// The host controller is app-lifetime too (#463): left running, it would keep serving this
// incident to its clients after the operator moved on, and a later share would come back
// with the old PIN and the Stammdaten it serialized at the start.
if (IsSharing)
{
await StopSharingAsync();
}
if (_store is not null)
{
// IncidentStore is an app-lifetime singleton and its SaveFailed/SaveSucceeded carry no
// incident identity -- unsubscribing before every write queued by THIS workspace has
// landed would either drop a genuine late failure on the floor, or (worse) let it
// surface as the NEXT incident's PersistenceError once someone reuses the store. A
// local session shouldn't be left with writes in flight when leaving anyway, so
// draining here is free.
await _store.FlushAsync();
_store.SaveFailed -= OnStoreSaveFailed;
_store.SaveSucceeded -= OnStoreSaveSucceeded;
}
if (_session is IAsyncDisposable disposable)
{
await disposable.DisposeAsync();
}
}
private void OnStoreSaveFailed(Exception ex) =>
_uiDispatcher.Post(() => PersistenceError = $"Speichern fehlgeschlagen: {ex.Message} — Änderungen werden NICHT gesichert.");
// Marshalling only when there's actually something to clear skips a pointless dispatcher hop
// on every ordinary successful save -- the overwhelmingly common case. Reading PersistenceError
// off the writer thread here is safe (reference-type reads are atomic, and clearing an
// already-null value is a no-op) even though the authoritative write to it happens later, on
// the UI thread. A Post queued by a handler that ran during LeaveAsync's FlushAsync (just
// before the unsubscribe above) can still be sitting in the UI dispatcher's queue when
// LeaveAsync returns -- harmless, since by then the shell has already navigated away and
// nothing reads this now-orphaned VM's PersistenceError again.
private void OnStoreSaveSucceeded()
{
if (PersistenceError is not null)
{
_uiDispatcher.Post(() => PersistenceError = null);
}
}
///
/// The single synchronous teardown point for everything this workspace owns: every child tab
/// view model (and, through them, the ticker subscriptions Scba/Tasks/Reminder each hold) and
/// the four remote-session lifecycle events wired up in the constructor. Idempotent, since the
/// shell can reach it from more than one navigate-away path for the same workspace instance.
/// LeaveAsync above stays the async remote-session teardown; the shell calls both, in that
/// order, when leaving to Home.
///
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_session.Changed -= RefreshIncidentData;
PendingLeadershipPersonDialog = null;
PendingRoleAssignmentDialog = null;
_hostController.JoinsClosedChanged -= OnJoinsClosedChanged;
if (_local is not null)
{
_local.FileBytesNotWiped -= OnFileBytesNotWiped;
}
_clockSkewRefresh?.Dispose();
if (_alarmMute is not null)
{
_alarmMute.Changed -= OnAlarmMuteChanged;
}
if (_session is RemoteIncidentSession remote)
{
remote.Changed -= OnRemoteLifecycle;
remote.Disconnected -= OnRemoteDisconnected;
remote.Reconnected -= OnRemoteReconnected;
remote.Ended -= OnRemoteEnded;
remote.Reconciled -= OnRemoteReconciled;
remote.ReconcileFailed -= OnRemoteReconcileFailed;
remote.CommandRejected -= OnRemoteCommandRejected;
}
DisposeChildren();
}
// A host broadcast can change lifecycle state under a joined client (e.g. the host closes the
// incident); keep the status live and flip the whole workspace to read-only when the lifecycle
// itself changes. The head data (Stichwort/Einsatznummer/Adresse) is refreshed separately by
// RefreshIncidentData, which is wired for local and remote sessions alike.
private void OnRemoteLifecycle()
{
// An applied snapshot is itself proof of currency — the strongest kind, since it came from the
// host — so it stamps the Stand just as a reconcile pass does.
MarkSynced();
OnPropertyChanged(nameof(StatusDisplay));
if (_session.IsReadOnly != IsReadOnly)
{
IsReadOnly = _session.IsReadOnly;
BuildChildren();
}
}
private void OnChanged()
{
// Every module funnels through here after mutating, so this is the one place that keeps
// the ETB list level with the journal regardless of which tab produced the entry.
Etb.Sync();
LastSavedAt = _clock.Now;
}
// Every child subscribes to _session.Changed (and Scba/Tasks/Reminder additionally to _ticker)
// in its own constructor; disposing the outgoing instance is what unsubscribes the old handler.
// Shared by BuildChildren (issue #167 P2 finding — replacing children used to be uneven, leaking
// stale subscriptions on every rebuild) and by Dispose (issue #279 P1 finding — the workspace
// itself was never torn down on navigate-home, so the *last* generation of children outlived it).
private void DisposeChildren()
{
// The nav items own their checklist subscriptions, and each ChecklistViewModel owns a
// session.Changed handler — so both generations have to go, not just the collection.
foreach (var item in NavItems)
{
item.Dispose();
}
NavItems.Clear();
// The split holds the same instances and, for the overflow, a subscription on each.
foreach (var item in OverflowNavItems)
{
item.PropertyChanged -= OnOverflowNavItemChanged;
}
PrimaryNavItems.Clear();
OverflowNavItems.Clear();
HasOverflowNavItems = false;
OverflowHasStatusDot = false;
foreach (var checklist in _checklists.Values)
{
checklist.Dispose();
}
_checklists.Clear();
// The rail is gone with NavItems, so whatever it had open is gone too. BuildChildren opens
// the same entry again on the new rail; after Dispose nothing is left open.
SelectedNavItem = null;
Etb?.Dispose();
Roles?.Dispose();
Forces?.Dispose();
InvolvedParties?.Dispose();
IssuedItems?.Dispose();
SituationReports?.Dispose();
Leadership?.Dispose();
Lagekarte?.Dispose();
if (Scba is not null)
{
// Not covered by Dispose: the workspace owns this subscription, and an outgoing
// Atemschutz view model must not go on steering the rail of the workspace that
// replaced it.
Scba.RevealRequested -= OnScbaRevealRequested;
Scba.PropertyChanged -= OnHeaderSourceChanged;
}
Scba?.Dispose();
Files?.Dispose();
CoMessprotokoll?.Dispose();
if (Tasks is not null)
{
// Same reason as Atemschutz above (#460).
Tasks.RevealRequested -= OnTasksRevealRequested;
Tasks.PropertyChanged -= OnHeaderSourceChanged;
}
Tasks?.Dispose();
if (Reminder is not null)
{
Reminder.PropertyChanged -= OnHeaderSourceChanged;
}
Reminder?.Dispose();
// An offer made by the outgoing generation must not outlive it: the rebuild may be the
// switch to read-only, where taking a tick back is no longer allowed.
CloseUndoNotice();
}
private void BuildChildren()
{
// A rebuild replaces every rail entry, and the rail stays on the one that was open (#542):
// on a joined device a sync read-only flip runs this because of something done elsewhere.
// A Checkliste's key is shared by every list, so its label tells them apart.
var reopen = SelectedNavItem is { } open ? (open.ModuleKey, open.Header) : default((string Key, string Header)?);
// The same goes for the tab the ETB had open.
var reopenEtbTab = EtbTabs is { } etbTabs ? etbTabs.SelectedTabIndex : EtbTabsViewModel.JournalTab;
// The same goes for the tab Führung had open.
var reopenTab = LeadershipTabs is { } tabs ? tabs.SelectedTabIndex : LeadershipTabsViewModel.OrganisationTab;
DisposeChildren();
// Every rebuild is a read-only flip or the first build; a refusal from before it no longer
// describes anything the Lagebuchführer can retry.
NavEditError = null;
Etb = new EtbViewModel(
_session,
_clock,
_masterData,
OnChanged,
OpenTaskDialog,
OfferReminderReset,
entryId => Tasks.RevealTasksFrom(entryId),
OpenSpellingHelper);
SituationReports = new SituationReportsViewModel(
_session,
OnChanged,
_masterData.Settings.DispatchCentreName,
(message, label, onConfirmed) => RequestConfirmAs("Lagemeldung", message, label, onConfirmed),
_masterData.RadioCallSigns,
_masterData.Streets
.Select(street => street.Name.Trim())
.Where(name => name.Length > 0)
.Distinct(StringComparer.Ordinal)
.ToList());
EtbTabs = new EtbTabsViewModel(Etb, SituationReports, reopenEtbTab);
Roles = new RolesViewModel(_session, _clock, _masterData, OnChanged, OpenRoleAssignmentDialog);
Forces = new ForcesViewModel(_session, _clock, _masterData, OnChanged, RequestConfirm);
InvolvedParties = new InvolvedPartiesViewModel(_session, OnChanged, RequestConfirm);
Leadership = new LeadershipViewModel(
_session,
_clock,
_masterData,
OnChanged,
(title, message, confirmed, label) => RequestConfirmAs(title, message, label, confirmed),
OpenCommandNodeDialog,
OpenLeadershipPersonDialog,
OpenRoleAssignmentDialog,
OfferUndo,
OpenDispatchChannelDialog);
Lagekarte = new LagekarteViewModel(_session, OnChanged, _mapPacks, _mapNightMode, _dialogs, RequestConfirm, _weather, _clock);
LeadershipTabs = new LeadershipTabsViewModel(Leadership, Roles, Forces, Lagekarte, reopenTab);
IssuedItems = new IssuedItemsViewModel(
_session, OnChanged, _masterData.Devices, RequestConfirm, ContactEntry.Roster(_masterData.Personnel, _masterData.Vehicles));
Scba = new ScbaViewModel(_session, _masterData, _clock, _ticker, _alarm, OnChanged);
Scba.RevealRequested += OnScbaRevealRequested;
Scba.PropertyChanged += OnHeaderSourceChanged;
Files = new FilesViewModel(_session, _dialogs, OnChanged, RequestConfirm, _clock);
Links = new LinksViewModel(_masterData.Links, _dialogs);
Contacts = new ContactsViewModel(_masterData.Personnel, _dialogs, _masterData.Vehicles);
CoMessprotokoll = new CoMessprotokollViewModel(_session, _clock, OnChanged, _masterData.Premises, _masterData.Gases);
Tasks = new TasksViewModel(_session, _clock, _ticker, _alarm, _masterData, OnChanged, OfferUndo);
Tasks.RevealRequested += OnTasksRevealRequested;
Tasks.PropertyChanged += OnHeaderSourceChanged;
// The ILS reminder is autonomous, time-driven host-side logging (§ IsRemote) — a joined
// client must not run its own, or the host's journal would be double-logged.
Reminder = _session.IsReadOnly || _session.IsRemote
? null
: new ReminderViewModel(
_session,
_clock,
_ticker,
_alarm,
OnChanged,
_masterData.Settings.IlsReminderIntervalMinutes,
_masterData.Settings.IlsReminderFollowUpIntervalMinutes,
_masterData.Settings.DispatchCentreName);
if (Reminder is not null)
{
Reminder.PropertyChanged += OnHeaderSourceChanged;
}
BuildNavItems();
if (reopen is { } previous)
{
SelectedNavItem = NavItems.FirstOrDefault(item =>
string.Equals(item.ModuleKey, previous.Key, StringComparison.Ordinal)
&& string.Equals(item.Header, previous.Header, StringComparison.Ordinal))
?? NavItems.FirstOrDefault();
}
OnPropertyChanged(nameof(Etb));
OnPropertyChanged(nameof(Roles));
OnPropertyChanged(nameof(Forces));
OnPropertyChanged(nameof(InvolvedParties));
OnPropertyChanged(nameof(IssuedItems));
OnPropertyChanged(nameof(SituationReports));
OnPropertyChanged(nameof(EtbTabs));
OnPropertyChanged(nameof(Leadership));
OnPropertyChanged(nameof(LeadershipTabs));
OnPropertyChanged(nameof(Scba));
OnPropertyChanged(nameof(CoMessprotokoll));
OnPropertyChanged(nameof(Files));
OnPropertyChanged(nameof(Links));
OnPropertyChanged(nameof(Contacts));
OnPropertyChanged(nameof(Tasks));
OnPropertyChanged(nameof(Reminder));
UpdateMostUrgentWarning();
OnPropertyChanged(nameof(HasReminder));
OnPropertyChanged(nameof(ShowsCountdownStrip));
}
///
/// Builds the rail from the Stammdaten layout and this Einsatz's own Checklisten.
///
///
/// A is created only for a list that survives resolution: a
/// hidden list's items are unreachable, so there is nothing to keep in sync, and building one
/// anyway would be a session subscription nobody ever reads.
///
private void BuildNavItems()
{
RebuildRail();
// The modules are freshly constructed by BuildChildren, so they start in the desktop
// layout. A ChecklistViewModel has no narrow layout of its own, so RebuildRail has
// nothing to push when it creates one.
PushNarrowToModules(IsNarrow);
}
///
/// Re-resolves the rail from the Stammdaten layout, this Einsatz's Checklisten, its overrides
/// and the modules with live work, keeping every module view model and every surviving
/// .
///
///
/// is updated in place: an entry still on the rail keeps its
/// , moved to its new position, and every entry gets the
/// shortcut hint of that position. The open entry stays open when it is still on the rail;
/// when it left, the entry that took its place opens — the next one, or the previous one when
/// it was last. A Checkliste that left the rail has its view model disposed, which releases its
/// session subscription.
///
private void RebuildRail()
{
var live = NavLiveness.LiveModules(_session.Incident);
RebuildRail(live, ResolveRail(live));
}
private void RebuildRail(IReadOnlySet live, IReadOnlyList specs)
{
var reopenKey = SelectedNavItem?.RailKey;
var reopenIndex = SelectedNavItem is { } open ? NavItems.IndexOf(open) : 0;
var modules = new Dictionary(StringComparer.Ordinal)
{
[NavModules.Etb] = EtbTabs,
[NavModules.Tasks] = Tasks,
[NavModules.Leadership] = LeadershipTabs,
[NavModules.InvolvedParties] = InvolvedParties,
[NavModules.IssuedItems] = IssuedItems,
[NavModules.Scba] = Scba,
[NavModules.Co] = CoMessprotokoll,
[NavModules.Files] = Files,
[NavModules.Links] = Links,
[NavModules.Contacts] = Contacts,
};
// An entry that stays on the rail keeps its item: replacing it would re-template the open
// module and drop the caret of whoever is typing, when the change came from another device.
var existing = NavItems.ToDictionary(item => item.RailKey, StringComparer.Ordinal);
var wanted = new List();
var kept = new Dictionary();
foreach (var spec in specs)
{
var railKey = NavigationLayout.KeyOf(spec);
if (spec.List is { } list)
{
if (!_checklists.Remove(list.Id, out var checklist))
{
checklist = new ChecklistViewModel(_session, list, OnChanged);
}
kept[list.Id] = checklist;
wanted.Add(existing.Remove(railKey, out var listItem)
? listItem
: new WorkspaceNavItemViewModel(WorkspaceNavItemViewModel.HeaderFor(list.Title), checklist, checklist, railKey: railKey));
continue;
}
if (modules.TryGetValue(spec.ModuleKey, out var content))
{
wanted.Add(existing.Remove(railKey, out var moduleItem)
? moduleItem
: new WorkspaceNavItemViewModel(ModuleLabels.Header(spec.ModuleKey), content, moduleKey: spec.ModuleKey, railKey: railKey));
}
}
// What is left in existing has left the rail; its item holds a subscription on its
// checklist, and RebuildNavSplit below releases the overflow's own.
foreach (var gone in existing.Values)
{
NavItems.Remove(gone);
gone.Dispose();
}
for (var i = 0; i < wanted.Count; i++)
{
var item = wanted[i];
var at = NavItems.IndexOf(item);
if (at < 0)
{
NavItems.Insert(i, item);
}
else if (at != i)
{
NavItems.Move(at, i);
}
item.ShortcutHint = ShortcutRegistry.HintFor(i);
}
// What is left are the Checklisten that left the rail.
foreach (var gone in _checklists.Values)
{
gone.Dispose();
}
_checklists.Clear();
foreach (var (id, checklist) in kept)
{
_checklists.Add(id, checklist);
}
// The ETB is always on the rail, so there is always a neighbour to fall back on.
if (reopenKey is not null)
{
SelectedNavItem = NavItems.FirstOrDefault(item => string.Equals(item.RailKey, reopenKey, StringComparison.Ordinal))
?? NavItems[Math.Clamp(reopenIndex, 0, NavItems.Count - 1)];
}
RebuildNavSplit();
RefreshCanHide(live);
RebuildAddableNavEntries();
}
private IReadOnlyList ResolveRail(IReadOnlySet live)
{
var incident = _session.Incident;
// Live work overrides only this Einsatz's own „Ausblenden“ — work that arrived while the
// module was hidden here, e.g. from a peer. A module the Stammdaten layout switches off
// stays off with live work, as it always has: its header bars still show, with no tab.
var forced = live
.Where(key => incident.NavOverrides.TryGetValue(key, out var visible) && !visible)
.ToHashSet(StringComparer.Ordinal);
return NavigationLayout.Resolve(_masterData.Navigation, incident.Checklists, incident.NavOverrides, forced);
}
///
/// Rebuilds the rail only when its entries or their order changed, so a change that leaves the
/// rail as it is — the first Aufgabe making Aufgaben live — only refreshes „Ausblenden“ and the
/// „+“ and does not touch the tab strip at all.
///
private void RebuildRailIfChanged()
{
var live = NavLiveness.LiveModules(_session.Incident);
var specs = ResolveRail(live);
if (specs.Select(NavigationLayout.KeyOf).SequenceEqual(NavItems.Select(item => item.RailKey), StringComparer.Ordinal))
{
RefreshCanHide(live);
RebuildAddableNavEntries();
return;
}
RebuildRail(live, specs);
}
private void RefreshCanHide(IReadOnlySet live)
{
foreach (var item in NavItems)
{
item.CanHide = !IsReadOnly
&& IsInputEnabled
&& !string.Equals(item.RailKey, NavModules.Etb, StringComparison.Ordinal)
&& !live.Contains(item.RailKey);
}
HideNavItemCommand.NotifyCanExecuteChanged();
}
///
/// Fills the „+“ choices: every entry of this Einsatz the rail does not show, and today's
/// Stammdaten Checklisten (#337: read live) whose Vorlage the Einsatz does not hold yet. Both
/// stay empty in a read-only Einsatz.
///
private void RebuildAddableNavEntries()
{
var hidden = new List();
var addable = new List();
if (!IsReadOnly)
{
var incident = _session.Incident;
// Everything the Einsatz could show, in rail order: the same resolution with every
// entry switched on. Whatever of that the rail lacks is hidden.
var everything = new Dictionary(StringComparer.Ordinal);
foreach (var key in NavModules.All)
{
everything[key] = true;
}
foreach (var list in incident.Checklists)
{
everything[ChecklistList.NavKey(list.Id)] = true;
}
foreach (var spec in NavigationLayout.Resolve(_masterData.Navigation, incident.Checklists, everything))
{
var key = NavigationLayout.KeyOf(spec);
if (!NavItems.Any(item => string.Equals(item.RailKey, key, StringComparison.Ordinal)))
{
var header = spec.List is { } list
? WorkspaceNavItemViewModel.HeaderFor(list.Title)
: ModuleLabels.Header(spec.ModuleKey);
hidden.Add(new AddableNavEntryViewModel(header, key, null));
}
}
foreach (var template in _masterData.ChecklistTemplates.Where(t => !incident.Checklists.Any(l => l.Id == t.Id)))
{
addable.Add(new AddableNavEntryViewModel(WorkspaceNavItemViewModel.HeaderFor(template.Title), null, template));
}
}
// Called on every session change; an open „+“ flyout keeps its items unless they changed.
Replace(HiddenNavEntries, hidden);
Replace(AddableChecklists, addable);
HasAddableNavEntries = HiddenNavEntries.Count > 0 || AddableChecklists.Count > 0;
}
private static void Replace(ObservableCollection target, List items)
{
if (target.SequenceEqual(items))
{
return;
}
target.Clear();
foreach (var item in items)
{
target.Add(item);
}
}
/// The „Ausgeblendet“ choices behind the rail's „+“.
public ObservableCollection HiddenNavEntries { get; } = new();
/// The „Checkliste hinzufügen“ choices behind the rail's „+“.
public ObservableCollection AddableChecklists { get; } = new();
/// Whether the „+“ has anything to offer; always false in a read-only Einsatz.
[ObservableProperty]
private bool _hasAddableNavEntries;
///
/// Why the last rail edit on this device was refused, in German; cleared by the next one that
/// succeeds. A joined device's refusal by the host arrives as .
///
[ObservableProperty]
private string? _navEditError;
[RelayCommand]
private void DismissNavEditError() => NavEditError = null;
/// „Ausblenden“: takes an entry off the rail for this Einsatz only.
[RelayCommand(CanExecute = nameof(CanHideNavItem))]
private void HideNavItem(WorkspaceNavItemViewModel? item)
{
if (item is { CanHide: true })
{
EditRail(() => _session.SetNavVisibility(item.RailKey, false));
}
}
private static bool CanHideNavItem(WorkspaceNavItemViewModel? item) => item?.CanHide ?? false;
///
/// One of the „+“ choices: brings a hidden entry back, or copies a Stammdaten Checkliste into
/// this Einsatz and opens it.
///
[RelayCommand(CanExecute = nameof(CanEditRail))]
private void AddNavEntry(AddableNavEntryViewModel? entry)
{
if (entry?.Template is { } template)
{
var key = ChecklistList.NavKey(template.Id);
// Offered before another device added the same Vorlage, or the list is hidden here: it
// is already in the Einsatz, so it comes back on the rail and opens, with no refusal.
if (_session.Incident.Checklists.Any(list => list.Id == template.Id))
{
if (!NavItems.Any(item => string.Equals(item.RailKey, key, StringComparison.Ordinal))
&& !EditRail(() => _session.SetNavVisibility(key, true)))
{
return;
}
NavEditError = null;
ShowNavItem(NavItems.FirstOrDefault(item => string.Equals(item.RailKey, key, StringComparison.Ordinal)));
return;
}
var seed = new ChecklistSeed(
template.Id,
template.Title,
template.Items.Select(i => (i.Text, i.IsMandatory)).ToList());
// On a joined device the list arrives with the host's broadcast, after this returns;
// there is nothing to open yet, and the rail shows it when it lands.
if (EditRail(() => _session.AddChecklist(seed)))
{
ShowNavItem(NavItems.FirstOrDefault(item => string.Equals(item.RailKey, key, StringComparison.Ordinal)));
}
}
else if (entry?.RailKey is { } railKey)
{
EditRail(() => _session.SetNavVisibility(railKey, true));
}
}
private bool CanEditRail => !IsReadOnly && IsInputEnabled;
// The domain refuses a Vorlage already in the Einsatz, a closed Einsatz, and anything over its
// caps; each of those is a sentence for the Lagebuchführer, never a crash mid-Einsatz.
private bool EditRail(Action edit)
{
try
{
edit();
}
catch (InvalidOperationException ex)
{
NavEditError = ex.Message;
return false;
}
catch (ArgumentException ex)
{
NavEditError = MessageOf(ex);
return false;
}
// The session's Changed event has already brought the rail along: at once on this device,
// with the host's broadcast on a joined one.
NavEditError = null;
OnChanged();
return true;
}
// ArgumentException.Message appends " (Parameter 'x')" in English; the Lagebuchführer gets
// the domain's German sentence alone.
private static string MessageOf(ArgumentException ex)
{
var message = ex.Message;
var cut = message.LastIndexOf(" (", StringComparison.Ordinal);
return ex.ParamName is not null && cut > 0 && message.EndsWith($"'{ex.ParamName}')", StringComparison.Ordinal)
? message[..cut]
: message;
}
///
/// One of the Atemschutz header bars was tapped (#422): bring the Atemschutz tab forward. The
/// Trupp itself is already selected by ; scrolling its row into
/// sight is the view's part.
///
///
/// The rail is resolved from Stammdaten, so there is no fixed tab index — the entry is found
/// by the module view model it carries. A brigade may have switched Atemschutz off entirely
/// while the header bars, driven by the view model rather than the rail, still appear; then
/// there is no tab to open and the selected Trupp is all this leaves behind.
///
private void OnScbaRevealRequested(object? sender, EventArgs e) => ShowModule(Scba);
///
/// The Aufgabe-fällig bar asked for a task (#460): bring the Aufgaben tab forward, exactly as
/// does for Atemschutz.
///
private void OnTasksRevealRequested(object? sender, EventArgs e) => ShowModule(Tasks);
// The ETB rail entry on one of its two tabs: Ctrl+N wants the journal, Ctrl+L the Lagemeldung,
// whichever the ETB had open last.
private bool ShowEtbTab(int tab, bool toStartField = false)
{
// Stryker disable all : NavigationLayout.Resolve always keeps the ETB in the rail, so this
// guard only covers the moment between two sessions, when the rail is empty.
if (NavItems.FirstOrDefault(item => ReferenceEquals(item.Content, EtbTabs)) is not { } etb)
{
return false;
}
// Stryker restore all
EtbTabs.SelectedTabIndex = tab;
return ShowNavItem(etb, toStartField);
}
///
/// Opens the Lagemeldung tab of the ETB (#592) on the newest draft, starting one when there is
/// none: from Ctrl+L, and from the Rückmeldung row the moment the ILS is due — the report is
/// what that row is asking for.
///
[RelayCommand(CanExecute = nameof(CanWriteSituationReport))]
private void OpenSituationReport() => ShowSituationReport();
private bool CanWriteSituationReport => !IsReadOnly;
private bool ShowSituationReport()
{
if (IsReadOnly || !ShowEtbTab(EtbTabsViewModel.SituationReportTab, toStartField: true))
{
return false;
}
SituationReports.OpenNewestDraft();
return true;
}
private void ShowModule(object module) =>
ShowNavItem(NavItems.FirstOrDefault(item => ReferenceEquals(item.Content, module)));
// The path for "the user asked for this module" (#542): a warning bar or a shortcut (#544),
// never arrowing the rail. toStartField sends the caret to the first field even when focus is
// already somewhere in the module — Ctrl+N from an ETB row has to land in VON.
private bool ShowNavItem(WorkspaceNavItemViewModel? navItem, bool toStartField = false)
{
if (navItem is null)
{
return false;
}
SelectedNavItem = navItem;
// Not on a phone: there focus pops the soft keyboard over half the module.
if (!IsNarrow)
{
ModuleFocusRequested?.Invoke(this, new ModuleFocusRequestedEventArgs(toStartField));
}
return true;
}
///
/// Generic confirm-before-acting hook for children (e.g. ForcesViewModel removing a unit) that
/// need the same destructive-action guard as without each owning
/// its own ConfirmDialogViewModel wiring. The caller names what is removed in the title
/// (#670), as every other confirm does. The button says ENTFERNEN;
/// names another.
///
private void RequestConfirm(string title, string message, Action onConfirmed) =>
RequestConfirmAs(title, message, "ENTFERNEN", onConfirmed);
/// The same guard with a button that says what happens, such as SENDEN (#592).
private void RequestConfirmAs(string title, string message, string confirmLabel, Action onConfirmed)
{
var dialog = new ConfirmDialogViewModel(title, message, confirmLabel, onConfirmed);
dialog.Closed += (_, _) => PendingConfirm = null;
PendingConfirm = dialog;
}
///
/// Offers a change back for (#543). A newer offer replaces the
/// one showing: only the latest toggle can be taken back, and Ctrl+Z always means that one.
///
private void OfferUndo(string message, Action undo)
{
CloseUndoNotice();
var notice = new UndoNoticeViewModel(message, undo, _clock.Now + UndoNoticeLifetime);
notice.Closed += OnUndoNoticeClosed;
UndoNotice = notice;
_undoNoticeExpiry = _ticker.Subscribe(ExpireUndoNotice);
}
/// Ctrl+Z: takes back the change the notice offers. Does nothing while none shows.
[RelayCommand(CanExecute = nameof(HasUndoNotice))]
private void Undo() => UndoNotice?.UndoCommand.Execute(null);
private void ExpireUndoNotice()
{
if (UndoNotice is { } notice && _clock.Now >= notice.ExpiresAt)
{
CloseUndoNotice();
}
}
private void OnUndoNoticeClosed(object? sender, EventArgs e) => CloseUndoNotice();
private void CloseUndoNotice()
{
_undoNoticeExpiry?.Dispose();
_undoNoticeExpiry = null;
if (UndoNotice is { } notice)
{
notice.Closed -= OnUndoNoticeClosed;
UndoNotice = null;
}
}
///
/// An ETB entry to the Leitstelle was just added (#415): ask whether it was the Rückmeldung, and
/// if so restart the reminder without logging it a second time. Resolved at call time, because
/// Etb is built before Reminder; a joined client or a read-only file has none and is not asked.
///
private void OfferReminderReset()
{
if (Reminder is not { IsRunning: true } reminder)
{
return;
}
var dialog = new ConfirmDialogViewModel(
"Rückmeldung erfolgt?",
$"War das die Rückmeldung an {reminder.DispatchCentreName}? Der Rückmelde-Timer startet dann neu.",
"NEU STARTEN",
reminder.AcknowledgeWithoutEntry);
dialog.Closed += (_, _) => PendingConfirm = null;
PendingConfirm = dialog;
}
///
/// True on a joined client. Closing the incident is the host's call alone (#465), so the
/// EINSATZ ABSCHLIESSEN button is hidden here — and the host refuses a client's close anyway.
///
public bool IsClient => _session.IsRemote;
private bool CanClose => !IsReadOnly && !IsClient;
// Closing is permanent (the incident becomes read-only), so confirm first. If a Trupp is
// still under air, call that out — closing mid-Atemschutz is a serious mistake. So is a Gerät
// still out: once closed, the Ausgabeliste can no longer record it coming back.
[RelayCommand(CanExecute = nameof(CanClose))]
private void CloseIncident()
{
var activeTrupps = _session.Incident.ScbaTrupps.Count(t => t.IsActive || t.IsWithdrawing);
var itemsOut = _session.Incident.ItemsOut;
var warnings = string.Concat(
activeTrupps > 0 ? $"ACHTUNG: {activeTrupps} Atemschutztrupp(s) noch unter PA. " : string.Empty,
itemsOut > 0 ? $"ACHTUNG: {itemsOut} Gerät(e) noch nicht zurückgegeben. " : string.Empty);
var message = warnings + "Der Einsatz wird unwiderruflich abgeschlossen und schreibgeschützt. Fortfahren?";
// The final PDF is usually the next thing the Lagebuchführer makes, and a closed incident
// can no longer be corrected, so offer it here (#425); sending it by e-mail is a nested
// follow-up, since mailing always exports first. Both open the usual section dialog.
ConfirmDialogViewModel? dialog = null;
dialog = new ConfirmDialogViewModel(
"Einsatz abschließen?",
message,
"ABSCHLIESSEN",
() =>
{
PerformClose();
if (dialog?.IsOptionChecked != true)
{
return;
}
if (dialog.IsSubOptionChecked)
{
OpenPdfExportOptions(RunExportAndMailAsync, "PDF ERSTELLEN & MAILEN");
}
else
{
OpenPdfExportOptions(RunExportAsync);
}
},
CanExport ? "PDF exportieren" : null,
CanMailPdf ? "und per E-Mail senden" : null);
// Clear the overlay on either outcome; PerformClose has already run on confirm.
dialog.Closed += (_, _) => PendingConfirm = null;
PendingConfirm = dialog;
}
/// Opens the create-task overlay pre-filled from an ETB entry's text, either from the
/// input dock's "add & create task" button or an existing row's create-task icon (#88, #247).
///
private void OpenTaskDialog(string text, Guid? sourceEntryId)
{
var dialog = new TaskDialogViewModel(_session, _masterData, text, OnChanged, sourceEntryId);
// Clear the overlay on either outcome; Save has already added the task on confirm.
dialog.Closed += (_, _) => PendingTaskDialog = null;
PendingTaskDialog = dialog;
}
/// Opens the Buchstabier-Helfer over the ETB (#592).
private void OpenSpellingHelper()
{
var dialog = new SpellingHelperDialogViewModel();
dialog.Closed += (_, _) => PendingSpellingHelper = null;
PendingSpellingHelper = dialog;
}
private void PerformClose()
{
_session.Close();
IsReadOnly = true; // notifies CanContinueEditing + both commands
LastSavedAt = _clock.Now;
BuildChildren();
OnPropertyChanged(nameof(StatusDisplay));
}
// Editable only when read-only AND not finished — a closed incident stays read-only. Resuming a
// file is a local-only concept: a joined client has no local file to reopen (_local is null).
public bool CanContinueEditing => _local is not null && IsReadOnly && _session.Incident.State == IncidentState.Open;
[RelayCommand(CanExecute = nameof(CanContinueEditing))]
private void ContinueEditing() =>
PendingPrompt = new OperatorPromptViewModel(
callSignOptions: _masterData.RadioCallSigns,
personnel: _masterData.Personnel);
// Called by the view when the prompt confirms (Result set). The one overlay serves both
// "Weiter bearbeiten" and a Lagebuchführer handover; the prompt knows which it was opened for.
public void ConfirmPendingPrompt()
{
var prompt = PendingPrompt;
var op = prompt?.Result;
PendingPrompt = null;
if (op is null)
{
return;
}
if (prompt!.IsHandover)
{
_session.ChangeOperator(op);
OnPropertyChanged(nameof(OperatorDisplay));
return;
}
_local!.ContinueEditing(op); // CanContinueEditing guarantees _local is not null
IsReadOnly = false; // notifies CanContinueEditing, OperatorDisplay + the commands
LastSavedAt = _clock.Now;
BuildChildren();
}
public void CancelPendingPrompt() => PendingPrompt = null;
// The host renders from its own .lagebuch; a joined client renders the synced state with
// attachments from its cache (#465, SessionPdfExport). Either way it needs a platform that can
// actually render one -- QuestPDF doesn't support Android (QuestPDF/QuestPDF#1432), so that head
// supplies NoopIncidentPdfExporter and hides the button.
public bool CanExport => _pdfExporter.CanExport;
// The one-line export outcome: a fresh success/failure message, or (before any export this
// session) seeded from ILastPdfExportStore in the constructor. Shows only the file name --
// the full path made this line too wide for the footer -- with the full path (when known)
// available via ExportStatusDetail for a tooltip.
[ObservableProperty]
private string? _exportStatus;
[ObservableProperty]
private string? _exportStatusDetail;
// Opens the section-selection overlay (#262); the actual generate/write/share work is the
// overlay's own awaitable ExportCommand (RunExportAsync below), so this stays synchronous.
[RelayCommand(CanExecute = nameof(CanExport))]
private void ExportPdf() => OpenPdfExportOptions(RunExportAsync);
// Mailing needs both halves: a PDF to attach and a mail program to hand it to. Neither exists
// on Android, which is why the close dialog there never offers it.
private bool CanMailPdf => CanExport && _mailComposer.CanCompose;
private void OpenPdfExportOptions(Func onExport, string exportLabel = "EXPORTIEREN")
{
var dialog = new PdfExportOptionsViewModel(onExport, exportLabel);
// Guards against a stale dialog's Closed firing after a newer one has already replaced it
// in PendingPdfExportOptions -- Export() awaits real async work while the dialog stays up,
// so (unlike the app's other Closed-clears-overlay dialogs) this one's Closed can in
// principle arrive well after this dialog stopped being "the" pending one.
dialog.Closed += (_, _) =>
{
if (PendingPdfExportOptions == dialog)
{
PendingPdfExportOptions = null;
}
};
PendingPdfExportOptions = dialog;
}
// Returns the written PDF's path, or null when the save dialog was cancelled or the export
// failed -- the status line already says which.
[SuppressMessage(
"Design",
"CA1031",
Justification = "Export can fail in several ways (disk full, exporter throwing, etc.); surfaces in the status line.")]
private async Task RunExportAsync(IncidentPdfSections sections)
{
// Reuse the incident's own name -- its .lagebuch file's base name (date+time, see
// HomeViewModel.NewIncidentAsync) -- rather than the Einsatznummer, which is usually still
// unknown at export time (#69) and previously fell back to the literal "Einsatz.pdf". A
// joined client has no file, so it names the PDF the same way from the incident's start.
// The "Einsatz-" prefix says what the file is once it sits among other downloads.
var baseName = _local is not null
? Path.GetFileNameWithoutExtension(_local.Path)
: _session.Incident.StartedAt.ToString("yyyyMMdd-HHmm", CultureInfo.InvariantCulture);
var suggested = "Einsatz-" + baseName + ".pdf";
var path = await _dialogs.PickExportPdfAsync(suggested);
if (string.IsNullOrWhiteSpace(path))
{
return null; // cancelled -- no status change, dialog still closes normally
}
try
{
byte[] bytes;
var missing = 0;
if (_local is not null)
{
bytes = await _local.ExportPdfAsync(_pdfExporter, sections);
}
else
{
(bytes, missing) = await SessionPdfExport.ExportAsync(_session, _pdfExporter, _clock, sections);
}
await File.WriteAllBytesAsync(path, bytes);
await _dialogs.ShareFileAsync(path, "application/pdf");
ExportStatus = missing == 0
? $"PDF exportiert: {Path.GetFileName(path)}"
: $"PDF exportiert: {Path.GetFileName(path)} ({missing} {(missing == 1 ? "Anhang" : "Anhänge")} nicht verfügbar)";
ExportStatusDetail = path;
_lastPdfExportStore?.SetLastExport(path, _clock.Now);
return path;
}
catch (Exception ex)
{
ExportStatus = FailureReasons.ForExport(ex);
ExportStatusDetail = null; // nothing to point a tooltip at -- the export failed
return null;
}
}
// The close dialog's "PDF erstellen und per E-Mail senden": the same export, then the PDF goes
// to the mail program with a subject built from the Einsatzdaten. ExportStatusDetail keeps the
// path, so whatever the mail program did, the file is still one tooltip away.
[SuppressMessage(
"Design",
"CA1031",
Justification = "A mail program that fails to start must not lose the exported PDF; surfaces in the status line.")]
private async Task RunExportAndMailAsync(IncidentPdfSections sections)
{
var path = await RunExportAsync(sections);
if (path is null)
{
return;
}
var name = Path.GetFileName(path);
var incident = _session.Incident;
try
{
var result = await _mailComposer.ComposeAsync(
new MailDraft(IncidentMail.Subject(incident), IncidentMail.Body(incident), path));
ExportStatus = result switch
{
MailComposeResult.Attached => $"PDF per E-Mail vorbereitet: {name}",
MailComposeResult.OpenedWithoutAttachment => $"E-Mail geöffnet – PDF bitte anhängen: {name}",
_ => $"PDF exportiert: {name} – E-Mail-Programm nicht gefunden",
};
}
catch (Exception)
{
// A fixed reason: whatever the mail program said is nothing to act on (#655).
ExportStatus = $"PDF exportiert: {name} – E-Mail-Programm ließ sich nicht starten";
}
}
// ===== Multi-device hosting (#52): flip "Im Netzwerk freigeben" to expose this open incident. =====
// Only offered on a platform that can host and while the incident is editable — a read-only
// (closed or unresumed) incident is nothing to collaborate on.
public bool CanHost => _hostController.CanHost && !IsReadOnly;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShareButtonText))]
private bool _isSharing;
// Why sharing failed to start, shown inline on the status line; null while all is well. Only a
// failure earns header space — the address of a running share lives in ShareAddress instead.
[ObservableProperty]
private string? _shareStatus;
// Where joining devices dial in, while sharing. Kept off the header line and shown only on demand
// behind the PIN: the ELW sets the address up once and rarely needs it again, while the header
// is shared with the Lagebuchführer readout and ran out of width with the URLs in it.
[ObservableProperty]
private string? _shareAddress;
// The 4-digit PIN a joining device must enter; the one thing read out per joining device (§ #64).
[ObservableProperty]
private string? _sharePin;
// Too many wrong PINs have closed joins (#288): someone may be guessing. Devices already joined
// keep working; a new one needs the PIN RenewSharePin draws. Deliberately not renewed on its
// own -- a PIN that renews itself only spreads the same guesses across rotations.
[ObservableProperty]
private bool _shareJoinsClosed;
// This host's Kennung, for a Lagebuchführer on a joining device whose app reports a changed one.
[ObservableProperty]
private string? _shareKennung;
public string ShareButtonText => IsSharing ? "FREIGABE BEENDEN" : "IM NETZWERK FREIGEBEN";
[RelayCommand]
private void RenewSharePin()
{
_hostController.RenewPin();
ShareJoinsClosed = _hostController.JoinsClosed;
SharePin = _hostController.SharePin;
}
// Raised on a request thread when the budget runs out, so marshal before touching bound state.
// ÜBER sets the switch on the UI thread today; marshal anyway, like every other event here.
private void OnAlarmMuteChanged(object? sender, EventArgs e) =>
_uiDispatcher.Post(() => OnPropertyChanged(nameof(AlarmsMuted)));
// Raised on the host's request thread, after the removal has already been broadcast.
private void OnFileBytesNotWiped(Exception ex) =>
_uiDispatcher.Post(() => Files.ReportRemoteRemovalNotWiped(ex.Message));
private void OnJoinsClosedChanged(object? sender, EventArgs e) =>
_uiDispatcher.Post(() =>
{
ShareJoinsClosed = IsSharing && _hostController.JoinsClosed;
SharePin = IsSharing ? _hostController.SharePin : null;
});
[RelayCommand]
[SuppressMessage(
"Design",
"CA1031",
Justification = "Host start can fail in several ways (port in use etc.); surfaces in the status line.")]
private async Task ToggleSharing()
{
// Hosting exposes the local .lagebuch, so it needs the concrete local session. The toggle is
// only shown when CanHost (a hostable platform with a local session), so _local is non-null here.
if (_local is null)
{
return;
}
if (IsSharing)
{
// Stopping cuts off every joined device mid-Einsatz, the same as leaving, which already
// asks (ConfirmLeaveThen); the ✕ that triggers it is a small target beside another (#604).
var dialog = new ConfirmDialogViewModel(
"Freigabe beenden?",
"Verbundene Geräte werden getrennt.",
"BEENDEN",
() => _ = StopSharingAsync());
dialog.Closed += (_, _) => PendingConfirm = null;
PendingConfirm = dialog;
return;
}
try
{
// Binds every interface (loopback + LAN). Can still fail — most likely the
// port is already taken by another instance sharing on this machine — so surface that
// in the status line rather than letting it escape the command.
// _masterData, not a fresh provider read: joined clients must get the set this
// workspace is actually running on (#183).
await _hostController.StartAsync(_local, _masterData);
}
catch (Exception ex)
{
ShareStatus = FailureReasons.ForSharing(ex);
return;
}
IsSharing = true;
ShareStatus = null; // clears a previous attempt's failure
ShareAddress = _hostController.ShareHint;
SharePin = _hostController.SharePin;
ShareKennung = _hostController.ShareKennung;
}
private async Task StopSharingAsync()
{
await _hostController.StopAsync();
IsSharing = false;
ShareStatus = null;
ShareAddress = null;
SharePin = null;
ShareJoinsClosed = false;
ShareKennung = null;
}
}