using System.Windows.Input; using Chronos.App.Archiving; using Chronos.App.Editor; using Chronos.App.Infrastructure; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Project; using Chronos.Data.Projects; using Chronos.Data.Sync; using Chronos.Data.Workspaces; using Chronos.Protocol; using Chronos.Ui.Controls; using Chronos.Ui.Mvvm; namespace Chronos.App.Workspace; /// What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project. public interface IWorkspaceUi { /// The dialog open now; null when none is. ArchiveDialogViewModel? Dialog { get; } /// Shows now, in place of an open one (the dialog the user acted in leads to it). void ShowDialog(ArchiveDialogViewModel dialog); /// /// Shows now when no dialog is open, else once the open one closes: something found in the /// background (a conflict an automatic sync met) never replaces what the user is doing. /// void ShowDialogWhenFree(ArchiveDialogViewModel dialog); void CloseDialog(ArchiveDialogViewModel dialog); /// True when the user chose the action (a destructive confirmation). bool Confirm(ConfirmRequest request); void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false); /// Opens project of in the editor (checked out and copied first when it is not here). Task OpenProjectAsync(Guid sequenceId, Guid projectId); /// Closes the open project (its last edit stored first); the picker shows. False when the user kept it open. Task CloseProjectAsync(); /// The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again. Task SequenceChangedAsync(Guid sequenceId); /// Shows the Jobs screen (a toast's Jobs action); nothing where there is none. void ShowJobs() { } } /// /// The project menu of the editor's title (▾, owner review 2, R8) for a workspace project: where it stands (the chip, read /// again a moment after each edit), Save version (Ctrl+S, an optional note; sent at once with Settings › Workspace › Sync /// automatically), Sync, History (Compare, Restore as one undo step), Open project (another project of the sequence, at /// the library or here), New project, Rename, Delete project (never Main) and Remove local copy, and the "Update media" /// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a /// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A /// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict /// shown; one an automatic sync met waits for the dialog open to close. A project whose home is a server (phase 5b) words /// its texts for the server, follows what the server tells of it (: the chip reads /// Server newer, or that the server no longer has it, its copy kept here), and renders only what the server holds /// (). Call from the UI thread. /// public sealed class ProjectMenuViewModel : LocalizedViewModel { /// How long after the last edit the chip reads the working state again (a little after the editor's save). public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600); /// How long after an analysis ended a change the home tells is taken as its Auto values reaching Main. private static readonly TimeSpan AnalysisTake = TimeSpan.FromMinutes(2); private readonly WorkspaceHost _host; private readonly WorkspaceSequenceSource _source; private readonly EditorSession _session; private readonly IWorkspaceUi _ui; private readonly AsyncRelayCommand _sync; private readonly AsyncRelayCommand _updateMedia; /// The thread the menu was made on (the UI's); null where there is none (tests run inline). private readonly SynchronizationContext? _context = SynchronizationContext.Current; private WorkspaceStatus? _status; private bool _isSyncing; private bool _homeFramesChanged; private Guid _copyJob; private bool _copyingOriginals; private bool _changingMedia; private bool _disposed; /// Counts the editor's changes, so only the last one's state read applies. private int _changes; /// The conflict dialog asked in the background, until it is closed (one is asked at a time). private ConflictDialogViewModel? _asking; /// /// When an analysis of the sequence ended while Sync automatically is on and the home had not told its new Main yet /// (a server catches up a moment later): the change it tells next is taken. /// private DateTime? _analysisEnded; public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui) { _host = host; _source = source; _session = session; _ui = ui; _sync = new AsyncRelayCommand(() => SyncAsync(), () => !_isSyncing); _updateMedia = new AsyncRelayCommand(UpdateMediaAsync, () => _copyJob == Guid.Empty); SaveVersionCommand = new RelayCommand(OpenSaveVersion, () => CanSaveVersion); HistoryCommand = new AsyncRelayCommand(OpenHistoryAsync); OpenProjectCommand = new AsyncRelayCommand(OpenOtherProjectAsync); NewProjectCommand = new AsyncRelayCommand(OpenNewProjectAsync); RenameCommand = new AsyncRelayCommand(OpenRenameAsync); DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain); RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync); CopyOriginalsCommand = new AsyncRelayCommand(CopyOriginalsAsync, () => !HoldsOriginals && !IsMediaBusy); ProxiesOnlyCommand = new AsyncRelayCommand(ProxiesOnlyAsync, () => HoldsOriginals && !IsMediaBusy); source.JobChanged += OnJobChanged; session.ProjectChanged += OnProjectChanged; host.HomeChanged += OnHomeChanged; } public Guid ProjectId => _source.ProjectId; public Guid SequenceId => _session.Content.Sequence.Id; public bool IsMain => _source.Workspace?.IsMain == true; /// The project's home is a server (phase 5b): its texts name the server, its renders are of what the server holds. public bool IsServerHome => _source.IsServerHome; /// The project's name (Main in the UI language). public string Name => _source.Workspace is { } workspace ? WorkspaceText.ProjectName(workspace.Name, workspace.IsMain) : string.Empty; public WorkspaceStatus? Status => _status; public bool IsSyncing => _isSyncing; public string StateText => WorkspaceText.State(_status, _isSyncing, IsServerHome); public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing); public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing, IsServerHome); /// The ▾ button: its name, then where the project stands, then what the menu holds. public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText); /// The button's accessible name: the project and its state. public string MenuName => string.Join(Loc.Separator, Name, StateText); /// /// The home's frames moved past those the workspace holds, or the library names photos otherwise since the copy (hashed, /// converted) and the media could not learn it yet (the last read of the library says so; a later one that taught them /// clears it): the banner offers Update media. /// public bool HasMediaUpdate => _homeFramesChanged || _status is { MediaOutdated: true }; /// A copy of the media runs (Update media): the banner says so. public bool IsUpdatingMedia => _copyJob != Guid.Empty; public string MediaUpdateText => IsUpdatingMedia ? Loc.L("Editor.Workspace.Updating") : WorkspaceText.ForHome("Editor.Workspace.MediaChanged", IsServerHome); public string MediaChangedToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.MediaChanged", IsServerHome); public string UpdateMediaToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.UpdateMedia", IsServerHome); /// A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project. public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone }; public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly") : _status?.State == WorkspaceState.Gone ? WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome) : _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict") : Loc.L("Tooltips.Editor.Project.SaveVersion"); public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : WorkspaceText.ForHome("Tooltips.Editor.Project.Delete", IsServerHome); public string RenameToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.Rename", IsServerHome); public string RemoveCopyToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.RemoveCopy", IsServerHome); /// Save version… (Ctrl+S): the note dialog. public ICommand SaveVersionCommand { get; } public ICommand SyncCommand => _sync; public ICommand HistoryCommand { get; } /// Open project…: another project of the sequence, one of the library's (a Save both sibling, another PC's) or a new one. public ICommand OpenProjectCommand { get; } public ICommand NewProjectCommand { get; } public ICommand RenameCommand { get; } public ICommand DeleteCommand { get; } public ICommand RemoveCopyCommand { get; } public ICommand UpdateMediaCommand => _updateMedia; /// The workspace holds the project's originals besides its proxies (phase 5c): renders run on this PC. public bool HoldsOriginals => _source.Workspace?.Media.Kind == BundleMedia.Originals; /// /// The media cannot change now: changes not saved as a version, a sync or a copy of the media running (the jobs of the /// sequence are asked when the command runs). /// public bool IsMediaBusy => _changingMedia || _isSyncing || _copyJob != Guid.Empty || _status is { Modified: true, ReadOnly: false }; /// Copy originals… (phase 5c): the project's originals into the workspace, to render on this PC. public ICommand CopyOriginalsCommand { get; } /// Proxies only… (phase 5c): the originals copied here deleted once the home is checked to hold each one. public ICommand ProxiesOnlyCommand { get; } /// What Copy originals… does, or why it is disabled (the media busy, or the originals here already). public string CopyOriginalsToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy") : HoldsOriginals ? Loc.L("Tooltips.Editor.Project.HasOriginals") : WorkspaceText.ForHome("Tooltips.Editor.Project.CopyOriginals", IsServerHome); /// What Proxies only… does, or why it is disabled (the media busy, or proxies only here already). public string ProxiesOnlyToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy") : !HoldsOriginals ? Loc.L("Tooltips.Editor.Project.ProxiesAlready") : WorkspaceText.ForHome("Tooltips.Editor.Project.ProxiesOnly", IsServerHome); /// Reads where the project stands (against its home) and whether the home's frames moved. public async Task RefreshAsync() { try { var status = await _host.StatusAsync(ProjectId); var moved = await _source.HomeFramesChangedAsync(CancellationToken.None); if (_disposed) return; _homeFramesChanged = moved; Apply(status); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"The state of project {ProjectId} could not be read", ex); } } /// /// A job of the sequence ended: where the project stands is read again; after an analysis, which writes its Auto /// values into the library's settings (Main's), the project takes them at once with Sync automatically. /// public async Task JobEndedAsync(Job job) { ArgumentNullException.ThrowIfNull(job); await RefreshAsync(); if (_disposed || !_host.Settings.WorkspaceAutoSync || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse)) return; if (_status is { State: WorkspaceState.Behind }) await SyncAsync(quiet: true); // A server writes the Auto values into Main a moment after its analysis ends: what it tells next is taken then. else if (IsServerHome) _analysisEnded = DateTime.UtcNow; } /// /// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a /// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here, /// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive, /// or one rendered on this PC from its originals (phase 5c), renders as it is: true. With Settings › Workspace › Version /// on render, a changed project is saved as a version first (). /// public async Task ReadyToRenderAsync() { if (_host.Settings.WorkspaceVersionOnRender && !await SaveForRenderAsync()) return false; // Rendered on this PC from the originals the workspace holds (phase 5c): the project renders as it is. if (!IsServerHome || _source.RendersLocally) return true; await StoreEditAsync(); var status = await _host.StatusAsync(ProjectId); if (_disposed) return false; Apply(status); if (status.State is WorkspaceState.Gone or WorkspaceState.Offline or WorkspaceState.Damaged or WorkspaceState.MediaRemoved) { _ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.StateToolTip(status, server: true), isError: status.State != WorkspaceState.Offline); return false; } if (status.Conflict is not null) { AskConflict(status.Conflict); return false; } if (status.Ahead == 0 && !status.Modified && _source.InStepWithHome(_session.Project) is not null) return true; if (!_ui.Confirm(new ConfirmRequest { Heading = Loc.L("Editor.Workspace.SendFirst.Title"), Message = Loc.L("Editor.Workspace.SendFirst.Message", Name), SafeText = Loc.L("Editor.Project.Keep"), SafeToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Keep"), ActionText = Loc.L("Editor.Workspace.SendFirst.Action"), ActionToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Action"), })) return false; try { await SaveAndSendAsync(); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"Project {ProjectId} could not be sent before its render", ex); _ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, server: true), isError: ex is not HomeUnavailableException); return false; } return !_disposed && _source.InStepWithHome(_session.Project) is not null; } /// /// Settings › Workspace › Version on render (phase 5c): a project changed since its last version is saved as a version /// noted "Render" before its render, and sent at once with Sync automatically when the home can be reached (out of reach, /// it waits here). False when it could not be saved, or the sync met a conflict to settle first. /// private async Task SaveForRenderAsync() { await StoreEditAsync(); var status = await _host.StatusAsync(ProjectId); if (_disposed) return false; Apply(status); if (!status.Modified || !CanSaveVersion) return true; WorkspaceSaveResult result; try { result = await _host.SaveVersionAsync(ProjectId, Loc.L("Editor.Workspace.RenderNote")); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"Project {ProjectId} could not be saved before its render", ex); _ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, IsServerHome), isError: true); return false; } if (_disposed) return false; Apply(result.Status); if (result.Synced is { } taken) await TakeAsync(taken); if (result.Version is { } version) { // The home numbers what it stores: the last one sent is this version. var number = result.Synced is { Pushed.Count: > 0 } synced ? synced.Pushed[^1].Number : version.Number; _ui.Notify(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(number)), Name); } if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException); if (result.Status.Conflict is not { } conflict) return true; AskConflict(conflict); return false; } /// /// Saves the working state as a version with , sent at once with Sync automatically; what the /// sync took from the home comes into the editor, a conflict it met is asked about. /// /// Why no version could be saved (the edit could not be stored, a conflict, read-only). public async Task SaveVersionAsync(string? note) { await StoreEditAsync(); var result = await _host.SaveVersionAsync(ProjectId, note); if (_disposed) return; Apply(result.Status); if (result.Synced is { } taken) await TakeAsync(taken); if (result.Version is null) { _ui.Notify(Loc.L("Editor.Workspace.NothingNew"), Name); } else if (result.Synced is { Pushed.Count: > 0 } synced) { // The home numbers what it stores: the last one sent is this version. _ui.Notify(Loc.L("Editor.Workspace.SavedSent", Formatting.Count(synced.Pushed[^1].Number)), Name); } else { _ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name); } if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException); // Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here. if (result.Status.State == WorkspaceState.Gone) NotifyGone(); else if (result.Status.Conflict is { } conflict) AskConflict(conflict); } /// /// Sync: the home's new versions taken into the editor, the local ones sent; a conflict is asked about (once the open /// dialog closes when : the sync ran in the background). /// public async Task SyncAsync(bool quiet = false) { if (_isSyncing) return; SetSyncing(true); try { await StoreEditAsync(); var result = await _host.SyncAsync(ProjectId); if (_disposed) return; Apply(result.Status); await TakeAsync(result); if (result.Status.State == WorkspaceState.Gone) NotifyGone(); else if (result.Status.Conflict is { } conflict) AskConflict(conflict, background: quiet); else if (!quiet) _ui.Notify(Loc.L(result.Status.State == WorkspaceState.InSync ? "Editor.Workspace.InSync" : "Editor.Workspace.Synced"), Name); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"Project {ProjectId} could not be synced", ex); _ui.Notify(ex is HomeUnavailableException ? WorkspaceText.ForHome("Editor.Workspace.Offline", IsServerHome) : Loc.L("Editor.Workspace.SyncFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: ex is not HomeUnavailableException); await RefreshAsync(); } finally { SetSyncing(false); } } /// /// Settles the conflict listed (else the one recorded) as chosen, then brings the settled /// working state into the editor: the library's values taken as one undo step (the toast's Undo, Ctrl+Z), what Save /// both made offered by its toast. When what differs changed since it was shown, nothing is settled and it is asked again. /// A project deleted in the library meanwhile is said so once, nothing asked again: its work stays here (the copy Save /// both made holding it too, offered by its toast). /// public async Task ResolveAsync(ConflictChoice choice, WorkspaceConflict? shown = null) { await StoreEditAsync(); var result = await _host.ResolveAsync(ProjectId, choice, shown: shown); if (_disposed) return; Apply(result.Status); if (result.Status.State == WorkspaceState.Gone) { NotifyGone(); NotifySavedAs(result); return; } if (result.Status.Conflict is { } again) { await TakeAsync(result); AskConflict(again); return; } if (result.Kept is { } kept) { if (await _session.TakeOverAsync(kept) is { } step) _ui.Notify(WorkspaceText.ForHome("Editor.Workspace.TookLibrary", IsServerHome), Name, Loc.L("Editor.Workspace.Undo"), WorkspaceText.ForHome("Tooltips.Editor.Workspace.UndoTake", IsServerHome), () => step.Undo()); if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId); } else { await TakeAsync(result, force: true); } NotifySavedAs(result); } /// The project Save both made, offered by its toast. private void NotifySavedAs(WorkspaceSyncResult result) { if (result.SavedAs is not { } copy) return; var sequenceId = SequenceId; _ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name, Loc.L("Editor.Workspace.OpenCopy"), Loc.L("Tooltips.Editor.Workspace.OpenCopy", copy.Name), () => _ = _ui.OpenProjectAsync(sequenceId, copy.Id)); } /// The home no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside). private void NotifyGone() => _ui.Notify(WorkspaceText.ForHome("Editor.Workspace.State.Gone", IsServerHome), WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome)); /// /// Restores as the project, as one undo step (uncommitted changes are saved as a version /// first, so nothing is lost); the toast's Undo takes it back while it is the last change. /// public async Task RestoreAsync(ProjectVersion version) { ArgumentNullException.ThrowIfNull(version); await StoreEditAsync(); var restored = await _host.RestoreAsync(ProjectId, version.Id); if (_disposed) return; var before = _session.Project; if (_session.Edit(_ => restored)) { _session.EndEditRun(); var undo = new ProjectRestore(_session, before, _session.Project); _ui.Notify(Loc.L("Editor.Workspace.Restored", Formatting.Count(version.Number)), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.Undo"), () => undo.Undo()); } else { _ui.Notify(Loc.L("Editor.Copy.Same"), Name); } await RefreshAsync(); } /// /// The settings that differ between the project now and , the version placed on the media's /// frames first: exclusions, the hero and keyframes compare as the settings they are (a photo the media lack stays /// parked, and reads as such). /// public IReadOnlyList Compare(ProjectVersion version, int max = 12) { ArgumentNullException.ThrowIfNull(version); var photos = _source.Photos; if (_session.Project.IsNewerFormat || ProjectContent.FormatOf(version.SettingsJson) > ProjectSettings.CurrentVersion) return WorkspaceText.CompareLines(SyncRules.Differences(ProjectContent.ToPortable(_session.Project, photos), version.SettingsJson, 64), max); var then = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Rebind(version.SettingsJson, photos), photos), allowNewer: true); return WorkspaceText.CompareLines(SyncRules.Differences(_session.Project.ToJson(), then.ToJson(), 64), max); } public override void Dispose() { _disposed = true; _source.JobChanged -= OnJobChanged; _session.ProjectChanged -= OnProjectChanged; _host.HomeChanged -= OnHomeChanged; // A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time). if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose(); base.Dispose(); } protected override void OnLanguageChanged() { base.OnLanguageChanged(); RaiseState(); } private void OpenSaveVersion() { if (!CanSaveVersion) return; _ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog, IsServerHome)); } private async Task OpenHistoryAsync() { var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog, IsServerHome); _ui.ShowDialog(dialog); try { await StoreEditAsync(); var history = await _host.HistoryAsync(ProjectId, Math.Max(50, _host.Settings.WorkspaceKeptVersions)); dialog.Show(history, ProjectContent.Hash(ProjectContent.ToPortable(_session.Project, _source.Photos))); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"The history of project {ProjectId} could not be read", ex); dialog.ShowFailure(ex); } } /// The project's home (this PC's archive, or a server). private BundleHome Home => _source.Workspace?.Home ?? WorkspaceHost.ArchiveHome(SequenceId); /// /// Open project…: "Open in workspace" over the home's projects of the sequence but the open one (a Save both /// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not /// here yet). /// private async Task OpenOtherProjectAsync() { try { await StoreEditAsync(); var home = Home; var projects = (await _host.HomeProjectsAsync(home)).Where(p => p.Id != ProjectId).ToList(); var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog, [.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)], server: IsServerHome); _ui.ShowDialog(dialog); if (await dialog.Choice is not { } choice || _disposed) return; var id = choice.ProjectId ?? (await _host.CreateProjectAsync(home, choice.NewName!, _status?.Base?.VersionId)).Id; await _ui.OpenProjectAsync(SequenceId, id); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex); _ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true); } } private async Task OpenNewProjectAsync() { var names = await OtherNamesAsync(null); var home = Home; _ui.ShowDialog(new ProjectNameDialogViewModel(false, string.Empty, names, async name => { await StoreEditAsync(); // From the open project's last version at the home, so the new one starts where this one is there. var created = await _host.CreateProjectAsync(home, name, _status?.Base?.VersionId); _ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle); _ = _ui.OpenProjectAsync(SequenceId, created.Id); }, _ui.CloseDialog, IsServerHome)); } private async Task OpenRenameAsync() { var names = await OtherNamesAsync(ProjectId); _ui.ShowDialog(new ProjectNameDialogViewModel(true, _source.Workspace?.Name ?? string.Empty, names, async name => { await _host.RenameAsync(ProjectId, name); await _session.ReloadAsync(); _ui.Notify(Loc.L("Editor.Workspace.Renamed"), name); RaiseState(); }, _ui.CloseDialog, IsServerHome)); } private async Task DeleteAsync() { if (IsMain) return; var name = Name; if (!_ui.Confirm(new ConfirmRequest { Heading = Loc.L("Editor.Project.DeleteTitle", name), Message = WorkspaceText.ForHome("Editor.Project.DeleteMessage", IsServerHome), SafeText = Loc.L("Editor.Project.Keep"), SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"), ActionText = Loc.L("Editor.Project.DeleteAction"), ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Project.DeleteAction", IsServerHome), IsDestructive = true, })) return; try { // Everything sent first, while the project is still open: a delete that cannot happen leaves it as it was. await SaveAndSendAsync(); var (sequenceId, projectId) = (SequenceId, ProjectId); if (!await _ui.CloseProjectAsync()) return; // The library's delete stands even when the local copy could not go with it: it is said, and Remove local copy takes it later. if (await _host.DeleteProjectAsync(projectId)) _ui.Notify(Loc.L("Editor.Workspace.Deleted", name)); else _ui.Notify(Loc.L("Editor.Workspace.Deleted", name), Loc.L("Errors.Workspace.CopyKept"), isError: true); await _ui.SequenceChangedAsync(sequenceId); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"Project {ProjectId} was not deleted", ex); _ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true); } } private async Task OpenRemoveCopyAsync() { try { await StoreEditAsync(); var plan = await _host.PlanRemovalAsync(ProjectId); var (projectId, name) = (ProjectId, Name); _ui.ShowDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveAsync(projectId, discard), async () => { await SaveAndSendAsync(); await RemoveAsync(projectId, discard: false); }, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog, IsServerHome)); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"The removal of project {ProjectId} could not be planned", ex); _ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true); } } /// /// The working state saved as a version and everything sent, for Send first and Delete project. A conflict the sync /// meets is asked about at once (in place of the dialog that asked for it), never left behind a reason to discard. /// /// Something could not be sent: a conflict to settle first, or the work not in the library yet. private async Task SaveAndSendAsync() { await StoreEditAsync(); if (CanSaveVersion) await _host.CommitAsync(ProjectId); var result = await _host.SyncAsync(ProjectId); Apply(result.Status); await TakeAsync(result); // Nothing can be sent to a project the home no longer has: only Discard takes the copy, its work kept aside. if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome)); if (result.Status.Conflict is { } conflict) { AskConflict(conflict); throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict")); } if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome)); } private async Task RemoveAsync(Guid projectId, bool discard) { // Checked before the editor closes, so a copy that cannot go leaves it open. if (!discard) { var status = await _host.StatusAsync(projectId, askHome: false); if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome)); } var name = Name; if (!await _ui.CloseProjectAsync()) return; await _host.RemoveLocalCopyAsync(projectId, discard); _ui.Notify(Loc.L("Editor.Workspace.Removed"), name); } private async Task> OtherNamesAsync(Guid? except) { try { return [.. (await _host.HomeProjectsAsync(Home)).Where(p => p.Id != except).Select(p => p.Name)]; } catch (Exception ex) when (ex is not OutOfMemoryException) { // The home checks the name again when the project is made. Log.Info("workspace", $"The projects of sequence {SequenceId} could not be listed: {ex.Message}"); return []; } } private async Task UpdateMediaAsync() { try { await StoreEditAsync(); var job = await _host.QueueCopyAsync(ProjectId); _copyJob = job.Id; RaiseState(); _ui.Notify(Loc.L("Editor.Workspace.Copying"), _session.Content.Sequence.DisplayTitle); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"The media of project {ProjectId} could not be copied again", ex); _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true); } } /// /// Copy originals…: refused while the media cannot change (, or a job of the sequence waits or /// runs); otherwise the copy is queued, the banner says it runs, and the editor reads the media again once it is done. /// private async Task CopyOriginalsAsync() { try { await StoreEditAsync(); if (await MediaRefusalAsync() is { } refusal) { _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), refusal, isError: true); return; } var job = await _host.QueueOriginalsCopyAsync(ProjectId); _copyJob = job.Id; _copyingOriginals = true; RaiseState(); _ui.Notify(Loc.L("Editor.Workspace.CopyingOriginals"), _session.Content.Sequence.DisplayTitle, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), _ui.ShowJobs); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"The originals of project {ProjectId} could not be queued for copy", ex); _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true); } } /// /// Proxies only…: the plan (each original hashed and weighed against the home, read now), confirmed by the user, then /// applied; the home out of reach, or anything changed since the plan, removes nothing. /// private async Task ProxiesOnlyAsync() { try { await StoreEditAsync(); if (await MediaRefusalAsync() is { } refusal) { _ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), refusal, isError: true); return; } SetChangingMedia(true); var plan = await _host.PlanProxiesOnlyAsync(ProjectId); if (_disposed) return; var detail = new List { Loc.L("Editor.ProxiesOnly.Originals", Formatting.Count(plan.Originals)), Loc.L("Editor.ProxiesOnly.Size", Formatting.Bytes(plan.Bytes)), }; if (plan.ToTrash > 0) detail.Add(Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(plan.ToTrash))); if (!_ui.Confirm(new ConfirmRequest { Heading = Loc.L("Editor.ProxiesOnly.Title", Name), Message = WorkspaceText.ForHome("Editor.ProxiesOnly.Message", IsServerHome), Detail = string.Join(Environment.NewLine, detail), IsDetailMonospaced = false, DetailToolTip = plan.ToTrash > 0 ? WorkspaceText.ForHome("Tooltips.Editor.ProxiesOnly.ToTrash", IsServerHome) : null, SafeText = Loc.L("Editor.Project.Keep"), SafeToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Keep"), ActionText = Loc.L("Editor.ProxiesOnly.Action"), ActionToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Action"), IsDestructive = true, })) return; var trashed = await _host.ProxiesOnlyAsync(ProjectId, plan); if (_disposed) return; await _session.ReloadAsync(); _ui.Notify(Loc.L("Editor.Workspace.OriginalsRemoved"), trashed > 0 ? Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(trashed)) : _session.Content.Sequence.DisplayTitle); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"The originals of project {ProjectId} were not removed", ex); _ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), WorkspaceText.Failure(ex, IsServerHome), isError: true); } finally { SetChangingMedia(false); await RefreshAsync(); } } /// /// Why the media cannot change now (Errors.Workspace.MediaBusy): changes not saved as a version, a copy or sync /// running, or an analysis, render or workspace job of the sequence waiting or running; null when they can. /// private async Task MediaRefusalAsync() { var local = await _host.StatusAsync(ProjectId, askHome: false); if (_disposed) return null; Apply(WithLocal(_status, local)); if (IsMediaBusy) return Loc.L("Errors.Workspace.MediaBusy"); var jobs = await _source.ListJobsAsync(CancellationToken.None); var sequenceId = SequenceId; return jobs.Any(j => j.State is JobState.Queued or JobState.Running or JobState.Paused && j.TargetIds.Contains(sequenceId) && j.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceCopy or JobKind.WorkspaceRender or JobKind.WorkspaceSend) ? Loc.L("Errors.Workspace.MediaBusy") : null; } /// The copy of the originals ended: said, with the frames that have none (they stay proxies, and a local render waits for them). private void NotifyOriginalsCopied() { int missing; try { missing = _source.Project.ReadMedia()?.Frames.Count(f => f.Original is null) ?? 0; } catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or UnauthorizedAccessException) { Log.Warning("workspace", $"The media of project {ProjectId} could not be read after the copy of its originals", ex); missing = 0; } if (missing == 0) _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), _session.Content.Sequence.DisplayTitle); else _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), Loc.L("Editor.Workspace.OriginalsMissing", Formatting.Count(missing))); } private void SetChangingMedia(bool changing) { _changingMedia = changing; RaiseState(); } /// The editor's last edit stored in the working state before an operation reads it. /// It could not be stored (it is retried in the background; nothing was lost). private async Task StoreEditAsync() { if (await _session.FlushAsync()) return; throw new WorkspaceException(Loc.L("Errors.Workspace.EditNotStored"), _session.LastSaveError); } /// What a sync, resolve or restore took from the home comes into the editor, merged with what was edited meanwhile. private async Task TakeAsync(WorkspaceSyncResult result, bool force = false) { if (force || result.Pulled.Count > 0) await _session.ReloadAsync(); if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId); } /// /// Asks how to settle , the choice applying to it as listed. One a sync met in the /// (after an analysis) waits for the open dialog to close, and is asked once: the chip /// says Conflict meanwhile, and Sync asks again. /// private void AskConflict(WorkspaceConflict conflict, bool background = false) { if (background && _asking is { IsClosed: false }) return; var lines = WorkspaceText.ConflictLines(conflict.Differences, 10, IsServerHome); var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict), _ui.CloseDialog, conflict.NewerFormat, IsServerHome); if (!background) { // Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list. _asking?.Dispose(); _asking = null; _ui.ShowDialog(dialog); return; } _asking = dialog; _ui.ShowDialogWhenFree(dialog); } /// The editor's project changed (an edit, undo, a merge; the UI thread): the chip reads the working state again a moment later. private void OnProjectChanged() { if (_disposed) return; _ = RefreshLocalAsync(++_changes); } /// /// After the last change's save: where the working state stands now (changed, saved as versions), the library's facts /// (newer, out of reach) kept from the last time it was asked; no read of the home on every edit. /// private async Task RefreshLocalAsync(int change) { try { // The save follows the change after a moment (and is retried after a failure): read once it is stored. for (var wait = 0; wait == 0 || (_session.HasPendingSave && wait < 10); wait++) { await Task.Delay(StateRefreshDelay); if (_disposed || change != _changes) return; } if (_isSyncing || _session.HasPendingSave) return; var local = await _host.StatusAsync(ProjectId, askHome: false); if (_disposed || change != _changes || _isSyncing) return; Apply(WithLocal(_status, local)); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Debug("workspace", $"The state of project {ProjectId} could not be read after an edit: {ex.Message}"); } } /// /// The state read without the home () with what the last read of the home said (how far the /// library is ahead, whether it could be reached, whether it still has the project), in the order the sync ranks them. /// internal static WorkspaceStatus WithLocal(WorkspaceStatus? last, WorkspaceStatus local) { ArgumentNullException.ThrowIfNull(local); if (last is null) return local; var gone = last.State == WorkspaceState.Gone; // A base that moved since (a sync) leaves how far the library is ahead unknown until it is asked again. var behind = last.Base?.VersionId == local.Base?.VersionId ? last.Behind : 0; // A project the library no longer has holds no conflict to answer (the one recorded stays for the record). var status = local with { Behind = behind, Offline = last.Offline, HomeHead = last.HomeHead, MediaOutdated = last.MediaOutdated, Conflict = gone ? null : local.Conflict, }; var state = gone ? WorkspaceState.Gone : status.MediaRemoved ? WorkspaceState.MediaRemoved : status.Damaged > 0 ? WorkspaceState.Damaged : status.Conflict is not null ? WorkspaceState.Conflict : status.Offline ? WorkspaceState.Offline : status.Behind > 0 ? WorkspaceState.Behind : status.Ahead > 0 ? WorkspaceState.Ahead : status.Modified ? WorkspaceState.Modified : WorkspaceState.InSync; return status with { State = state }; } /// A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread. private void OnJobChanged(Job job) { if (job.Id != _copyJob || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return; if (_context is { } context) context.Post(_ => _ = CopyEndedAsync(job), null); else _ = CopyEndedAsync(job); } /// /// The home told that this project changed there, or that changes may have been missed (any thread; phase 5b): where it /// stands is read again on the menu's thread, so the chip says Server newer, or that the server no longer has it. /// private void OnHomeChanged(WorkspaceHomeChange change) { if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase))) return; if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null); else _ = HomeChangedAsync(change); } private async Task HomeChangedAsync(WorkspaceHomeChange change) { if (_disposed || _isSyncing) return; await RefreshAsync(); // An analysis's Auto values reached Main at the server: with Sync automatically they are taken, as after an analysis here. if (_disposed || _analysisEnded is not { } ended || change.Change != ProjectChanges.Pushed) return; if (DateTime.UtcNow - ended > AnalysisTake) { _analysisEnded = null; return; } if (_status is not { State: WorkspaceState.Behind } || !_host.Settings.WorkspaceAutoSync) return; _analysisEnded = null; await SyncAsync(quiet: true); } /// The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not. private async Task CopyEndedAsync(Job job) { if (_disposed || job.Id != _copyJob) return; _copyJob = Guid.Empty; var originals = _copyingOriginals; _copyingOriginals = false; if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true); try { if (job.State == JobState.Done) await _session.ReloadAsync(); if (job.State == JobState.Done && originals) NotifyOriginalsCopied(); } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Warning("workspace", $"The new media of project {ProjectId} could not be read", ex); _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true); } await RefreshAsync(); RaiseState(); } private void Apply(WorkspaceStatus status) { _status = status; RaiseState(); } private void SetSyncing(bool syncing) { _isSyncing = syncing; _sync.RaiseCanExecuteChanged(); RaiseState(); } private void RaiseState() { OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(Name)); OnPropertyChanged(nameof(IsMain)); OnPropertyChanged(nameof(IsSyncing)); OnPropertyChanged(nameof(StateText)); OnPropertyChanged(nameof(StateKind)); OnPropertyChanged(nameof(StateToolTip)); OnPropertyChanged(nameof(MenuToolTip)); OnPropertyChanged(nameof(MenuName)); OnPropertyChanged(nameof(HasMediaUpdate)); OnPropertyChanged(nameof(IsUpdatingMedia)); OnPropertyChanged(nameof(MediaUpdateText)); OnPropertyChanged(nameof(CanSaveVersion)); OnPropertyChanged(nameof(SaveVersionToolTip)); OnPropertyChanged(nameof(DeleteToolTip)); OnPropertyChanged(nameof(IsServerHome)); OnPropertyChanged(nameof(RenameToolTip)); OnPropertyChanged(nameof(RemoveCopyToolTip)); OnPropertyChanged(nameof(MediaChangedToolTip)); OnPropertyChanged(nameof(UpdateMediaToolTip)); OnPropertyChanged(nameof(HoldsOriginals)); OnPropertyChanged(nameof(IsMediaBusy)); OnPropertyChanged(nameof(CopyOriginalsToolTip)); OnPropertyChanged(nameof(ProxiesOnlyToolTip)); _updateMedia.RaiseCanExecuteChanged(); CommandManager.InvalidateRequerySuggested(); } }