Review 2, phase 5a, fix round 1 (desktop and the engine side of Resolve and Restore). - Resolve applies Keep mine / Take the library's only to the conflict the dialog listed: when the head or what differs moved since, the new conflict is recorded and asked again; Sync re-works a pending conflict instead of re-showing a stale list. Take the library's first saves uncommitted changes as a version, and the editor takes it as one undo step (toast Undo, Ctrl+Z) that brings back only the settings both changed. - Restore saves unsaved changes as a version also while a conflict waits; a restore that changed nothing, or was undone, no longer marks the next version as a Restore. - The editor's saves and merges of a workspace project merge positions photo by photo (portable form) and ask where both sides changed a setting, never deciding for ours. - Read-only after a pull is signalled, and no save that can never be stored is left behind. - The chip is read again after edits; a background conflict waits for the open dialog; Send first and Delete show the conflict they met; Discard changes needs the typed name. - Open project... reaches the library's other projects (Save both's sibling, also from its toast); copies whose project or sequence is gone read Not in library and can be removed from the picker's Workspace rows; a delete whose local copy stays says so. - A workspace folder inside a library is refused before anything is written. - Conflict and Compare lines name heroes, exclusions and keyframes; History shows the PC name alone, never the program's prefixes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
866 lines
41 KiB
C#
866 lines
41 KiB
C#
using System.ComponentModel;
|
|
using System.Net;
|
|
using System.Windows.Input;
|
|
using System.Windows.Threading;
|
|
using Chronos.App.Archiving;
|
|
using Chronos.App.Editor;
|
|
using Chronos.App.Infrastructure;
|
|
using Chronos.App.Library;
|
|
using Chronos.App.Shell;
|
|
using Chronos.App.Workspace;
|
|
using Chronos.Core.Diagnostics;
|
|
using Chronos.Core.Export;
|
|
using Chronos.Core.Imaging;
|
|
using Chronos.Core.Imaging.Decoders;
|
|
using Chronos.Core.Localization;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Data;
|
|
using Chronos.Data.Jobs;
|
|
using Chronos.Data.Sync;
|
|
using Chronos.Protocol.Client;
|
|
using Chronos.Ui.Mvvm;
|
|
|
|
namespace Chronos.App.Sections;
|
|
|
|
/// <summary>
|
|
/// The Edit section (BRIEF §12.3; owner review 1, R7, formerly Sequence): opens the sequence the Library, Jobs, the
|
|
/// Server screen or its own picker chose into an <see cref="EditorViewModel"/>. A sequence of this PC's archive opens as a
|
|
/// project of the workspace (owner review 2, R8: editing never happens inside the library): the project of that sequence
|
|
/// opened last here; else, after "Open in workspace" asked which project (Main, another of its home, or a new one) and
|
|
/// which media, the project is checked out and its media copied by a job, and it opens once they are here. A server
|
|
/// sequence opens with this PC's proxies (the workspace takes server homes in phase 5b), and a capture (sample data
|
|
/// without an engine) opens the library as before. The next sequence is read first; only then does the open one close,
|
|
/// after its last edit is stored. Without a sequence, or after Change sequence, it shows the picker (the editor stays
|
|
/// open behind it until another sequence opens). A server sequence whose proxies are missing or out of date fetches them
|
|
/// first and opens once they are here, the open sequence staying open meanwhile; a workspace copy is followed the same
|
|
/// way. A failed open is reported once and leaves the open sequence open; an edit that cannot be saved is never dropped
|
|
/// without the user's confirmation, and never written after they chose to drop it. The step each sequence showed is
|
|
/// kept for the rest of the run. The section's in-window dialogs (Open in workspace, the project menu's) show over it.
|
|
/// </summary>
|
|
public sealed class SequenceViewModel : SectionViewModel
|
|
{
|
|
private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
|
|
private readonly Dictionary<Guid, StepMemory> _steps = [];
|
|
private readonly WorkspaceUi _workspaceUi;
|
|
private EditorViewModel? _editor;
|
|
private Guid? _openId;
|
|
private bool _isLoading;
|
|
private bool _isPicking;
|
|
private bool _showsPicker = true;
|
|
|
|
/// <summary>The shell's <see cref="ShellViewModel.SequenceRequests"/> this section has answered.</summary>
|
|
private int _seenRequests;
|
|
private Task _switch = Task.CompletedTask;
|
|
private PendingOpen? _fetch;
|
|
private ArchiveDialogViewModel? _dialog;
|
|
|
|
/// <summary>Dialogs that show once the open one closes (<see cref="OpenDialogWhenFree"/>), oldest first.</summary>
|
|
private readonly Queue<ArchiveDialogViewModel> _waiting = new();
|
|
|
|
/// <summary>The project the next open of its sequence takes (the picker's Workspace group, a project file, the project menu).</summary>
|
|
private ProjectRequest? _requested;
|
|
|
|
/// <summary>What to do with the editor of the project asked for once it opens (a project file's settings to apply), until another sequence opens.</summary>
|
|
private (ProjectRequest Request, Action<EditorViewModel> Action)? _afterOpen;
|
|
|
|
public SequenceViewModel(ShellViewModel shell)
|
|
: base(SectionKey.Edit, "Icon.Sequence")
|
|
{
|
|
Shell = shell;
|
|
_workspaceUi = new WorkspaceUi(this);
|
|
Picker = new SequencePickerViewModel(this);
|
|
OpenImportCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
|
|
OpenJobsCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs));
|
|
ChangeSequenceCommand = new RelayCommand(() => IsPicking = true, () => _editor is not null && !_isLoading && !_isPicking && _dialog is null);
|
|
CancelPickCommand = new RelayCommand(KeepOpenSequence, () => CanCancelPick);
|
|
shell.PropertyChanged += OnShellChanged;
|
|
}
|
|
|
|
public ShellViewModel Shell { get; }
|
|
|
|
/// <summary>The list the next sequence is chosen from.</summary>
|
|
public SequencePickerViewModel Picker { get; }
|
|
|
|
/// <summary>Import, from the picker of an empty library.</summary>
|
|
public ICommand OpenImportCommand { get; }
|
|
|
|
/// <summary>The Jobs screen, from the picker's line about proxies on their way.</summary>
|
|
public ICommand OpenJobsCommand { get; }
|
|
|
|
/// <summary>
|
|
/// Shows the picker over the open sequence (Ctrl+O, the title's ▾, Next on the last step); the editor is not closed and
|
|
/// its changes keep being saved as usual.
|
|
/// </summary>
|
|
public ICommand ChangeSequenceCommand { get; }
|
|
|
|
/// <summary>Hides the picker again, back to the open sequence (Esc); a server sequence chosen meanwhile no longer opens over it.</summary>
|
|
public ICommand CancelPickCommand { get; }
|
|
|
|
/// <summary>The open sequence; null shows the picker.</summary>
|
|
public EditorViewModel? Editor
|
|
{
|
|
get => _editor;
|
|
private set
|
|
{
|
|
if (!Set(ref _editor, value)) return;
|
|
// A sequence that opens ends the choice.
|
|
if (value is not null)
|
|
{
|
|
_isPicking = false;
|
|
OnPropertyChanged(nameof(IsPicking));
|
|
Picker.SearchText = string.Empty;
|
|
}
|
|
OnPropertyChanged(nameof(Title));
|
|
OnPickerChanged();
|
|
}
|
|
}
|
|
|
|
/// <summary>The id of the open sequence; null when none is open.</summary>
|
|
public Guid? OpenSequenceId => _editor is null ? null : _openId;
|
|
|
|
/// <summary>The workspace project open in the editor; null when none is (a server sequence, a capture's library sequence).</summary>
|
|
public Guid? OpenProjectId => (_editor?.Session.Source as WorkspaceSequenceSource)?.ProjectId;
|
|
|
|
/// <summary>The section's in-window dialog (Open in workspace, the project menu's); null when none is open.</summary>
|
|
public ArchiveDialogViewModel? Dialog
|
|
{
|
|
get => _dialog;
|
|
private set
|
|
{
|
|
if (!Set(ref _dialog, value)) return;
|
|
OnPropertyChanged(nameof(IsDialogOpen));
|
|
OnPropertyChanged(nameof(IsContentEnabled));
|
|
}
|
|
}
|
|
|
|
public bool IsDialogOpen => _dialog is not null;
|
|
|
|
/// <summary>The editor and the picker behind an open dialog take neither clicks nor keyboard focus.</summary>
|
|
public bool IsContentEnabled => _dialog is null;
|
|
|
|
/// <summary>What the project menus of this section's editors ask of it.</summary>
|
|
internal IWorkspaceUi WorkspaceDialogs => _workspaceUi;
|
|
|
|
public bool IsLoading
|
|
{
|
|
get => _isLoading;
|
|
private set
|
|
{
|
|
if (Set(ref _isLoading, value)) OnPickerChanged();
|
|
}
|
|
}
|
|
|
|
/// <summary>The picker shows over the open sequence, which stays laid out behind it.</summary>
|
|
public bool IsPicking
|
|
{
|
|
get => _isPicking;
|
|
private set
|
|
{
|
|
if (!Set(ref _isPicking, value)) return;
|
|
OnPropertyChanged(nameof(Title));
|
|
OnPickerChanged();
|
|
}
|
|
}
|
|
|
|
/// <summary>The picker is on screen: no sequence is open, or another is being chosen.</summary>
|
|
public bool ShowsPicker => _showsPicker;
|
|
|
|
/// <summary>An open sequence waits behind the picker, so Cancel (Esc) goes back to it; not while a switch is under way.</summary>
|
|
public bool CanCancelPick => _isPicking && _editor is not null && !_isLoading;
|
|
|
|
public string? CancelPickToolTip => _editor is { } editor ? Loc.L("Tooltips.Editor.Picker.Cancel", editor.Title) : null;
|
|
|
|
/// <summary>The server sequence whose proxies are on their way before it opens; null when none.</summary>
|
|
public string? FetchingTitle => _fetch?.Title;
|
|
|
|
/// <summary>"Getting the proxies · Harbour sunset", "Copying to the workspace · Harbour sunset".</summary>
|
|
public string? FetchingText => _fetch is { } fetch ? string.Join(Loc.Separator, Loc.L(fetch.TextKey), fetch.Title) : null;
|
|
|
|
/// <summary>The open sequence has an edit not stored yet (the save follows each change after a moment, and retries after a failure).</summary>
|
|
public bool HasPendingSave => _editor?.Session.HasPendingSave == true;
|
|
|
|
/// <summary>"Chronos — Harbour sunset" while a sequence is open and shown; the section's name while choosing one.</summary>
|
|
public override string Title => !_isPicking && _editor is { } editor ? editor.Title : Label;
|
|
|
|
/// <summary>Opens <paramref name="sequenceId"/> (the editor of another sequence is saved and closed first).</summary>
|
|
/// <param name="reload">Opens it again even when it is the open one (its proxies were fetched again).</param>
|
|
public Task OpenAsync(Guid sequenceId, bool reload = false)
|
|
{
|
|
_switch = SwitchAsync(_switch, sequenceId, reload);
|
|
return _switch;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Shows <paramref name="sequenceId"/> in the editor, as the Library does, and returns its editor once open; null
|
|
/// when it did not open (the reason was reported, or the open sequence's unsaved edit was kept) or waits for its
|
|
/// proxies or its workspace copy. <paramref name="project"/> names the workspace project to open (else the one opened
|
|
/// last, else the user is asked); <paramref name="whenOpened"/> runs on its editor once it opens, now or after the
|
|
/// copy, unless another sequence opens first.
|
|
/// </summary>
|
|
public async Task<EditorViewModel?> ShowAsync(Guid sequenceId, ProjectRequest? project = null, Action<EditorViewModel>? whenOpened = null)
|
|
{
|
|
_afterOpen = whenOpened is null ? null : (project ?? new ProjectRequest(sequenceId), whenOpened);
|
|
if (project is not null && project.SequenceId == sequenceId && !IsOpen(project))
|
|
{
|
|
_requested = project;
|
|
// Another project of the open sequence: it replaces the open one (its last edit stored first).
|
|
if (_openId == sequenceId)
|
|
{
|
|
// Edit on screen without asking the shell for the open sequence again (that would end a choice in the picker).
|
|
Shell.Navigate(SectionKey.Edit);
|
|
await OpenAsync(sequenceId, reload: true);
|
|
return Opened(sequenceId, project);
|
|
}
|
|
}
|
|
Shell.OpenSequence(sequenceId);
|
|
// Already the sequence asked for but not open (the shell did not change, so nothing started): opening it again is
|
|
// what is asked now, unless its proxies are on their way (it opens when they are here).
|
|
if (_openId != sequenceId && _switch.IsCompleted && Shell.CurrentSequenceId == sequenceId && !Fetching(sequenceId)) _ = OpenAsync(sequenceId);
|
|
await Settled(_switch);
|
|
return Opened(sequenceId, project);
|
|
}
|
|
|
|
/// <summary>Opens workspace project <paramref name="projectId"/> of <paramref name="sequenceId"/> (checked out and copied first when it is not here).</summary>
|
|
public Task<EditorViewModel?> OpenProjectAsync(Guid sequenceId, Guid projectId) => ShowAsync(sequenceId, new ProjectRequest(sequenceId, projectId));
|
|
|
|
/// <summary>The project chosen in the picker's Workspace group: the open one simply shows again, another opens.</summary>
|
|
public async Task PickProjectAsync(WorkspaceProjectItem item)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(item);
|
|
if (_editor is not null && item.ProjectId == OpenProjectId)
|
|
{
|
|
KeepOpenSequence();
|
|
return;
|
|
}
|
|
await OpenProjectAsync(item.SequenceId, item.ProjectId);
|
|
}
|
|
|
|
/// <summary>The project <paramref name="request"/> asks for is the open one (any project of it when it asks none; a library sequence counts as Main).</summary>
|
|
private bool IsOpen(ProjectRequest request) => _editor is { } editor && _openId == request.SequenceId && Satisfies(request, editor);
|
|
|
|
/// <summary><paramref name="editor"/> holds the project <paramref name="request"/> asks for.</summary>
|
|
private static bool Satisfies(ProjectRequest request, EditorViewModel editor)
|
|
{
|
|
if (editor.Session.Content.Sequence.Id != request.SequenceId) return false;
|
|
var workspace = editor.Session.Source as WorkspaceSequenceSource;
|
|
if (request.ProjectId is { } id) return workspace?.ProjectId == id;
|
|
return !request.Main || workspace is not { Workspace.IsMain: false };
|
|
}
|
|
|
|
/// <summary>
|
|
/// The editor of <paramref name="sequenceId"/> when it is the open one (a choice of another ends), its pending action
|
|
/// run; null while the project <paramref name="request"/> asks for is not the open one yet (its copy runs).
|
|
/// </summary>
|
|
private EditorViewModel? Opened(Guid sequenceId, ProjectRequest? request)
|
|
{
|
|
if (_openId != sequenceId || Editor is not { } editor) return null;
|
|
// Another project of it still on its way (its copy runs) leaves the picker on screen, with the line saying so.
|
|
if (request is not null && !Satisfies(request, editor)) return null;
|
|
// Asking for the open sequence ends a choice of another.
|
|
IsPicking = false;
|
|
RunAfterOpen(editor);
|
|
return editor;
|
|
}
|
|
|
|
private void RunAfterOpen(EditorViewModel editor)
|
|
{
|
|
if (_afterOpen is not { } pending || !Satisfies(pending.Request, editor)) return;
|
|
_afterOpen = null;
|
|
pending.Action(editor);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Opens the sequence chosen in the picker: the open one simply shows again; another opens once it is read, after the
|
|
/// open one's last edit is stored (or the user chose to discard it). Keeping an edit that cannot be stored keeps the
|
|
/// open sequence; a server sequence whose proxies are not here yet leaves the picker on screen while they arrive.
|
|
/// </summary>
|
|
public async Task PickAsync(SequenceItem item)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(item);
|
|
if (_editor is not null && item.Id == _openId)
|
|
{
|
|
KeepOpenSequence();
|
|
return;
|
|
}
|
|
await ShowAsync(item.Id);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fetches the proxies of server sequence <paramref name="remoteId"/> into this PC's cache (a download job, shown in
|
|
/// the job bar and on the Jobs screen) and opens it in the editor once they are here, if it is still the sequence
|
|
/// asked for.
|
|
/// </summary>
|
|
public async Task FetchProxiesAsync(Guid remoteId, string title)
|
|
{
|
|
var services = Shell.Services;
|
|
var sync = services.Sync;
|
|
if (sync.Server is not { } server || sync.Service is not { } service) throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
|
|
if (services.Engine is not { } engine || services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
|
var followed = _fetch is { } current && current.RemoteId == remoteId ? current.JobId : Guid.Empty;
|
|
StopFetch();
|
|
var fetch = new PendingOpen(remoteId, title, engine, "Editor.Proxies.Fetching", null);
|
|
fetch.Handler = job => _dispatcher.BeginInvoke(() => OnFetchChanged(fetch, job));
|
|
engine.JobChanged += fetch.Handler;
|
|
_fetch = fetch;
|
|
OnFetchingChanged();
|
|
Job job;
|
|
try
|
|
{
|
|
job = await service.EnqueueDownloadAsync(engine, server, remoteId, title, SyncDownloadMode.Proxies, null);
|
|
}
|
|
catch
|
|
{
|
|
// Nothing is on its way: the picker's line about it goes, and asking for the sequence again tries again.
|
|
if (ReferenceEquals(_fetch, fetch)) StopFetch();
|
|
throw;
|
|
}
|
|
fetch.JobId = job.Id;
|
|
// The download already followed (the same sequence asked for again) is not announced twice.
|
|
if (job.Id != followed)
|
|
Shell.Notify(Loc.L("Editor.Proxies.Fetching"), title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
|
// A download that ended before its id was known here is handled now.
|
|
if (await db.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended) OnFetchChanged(fetch, ended);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Stores the open sequence's last edit. When the save fails (archive offline, read-only, busy), asks whether to
|
|
/// discard the edit (BRIEF §12.1: modals only for destructive confirmations). No retry runs while the question is
|
|
/// open, so the answer holds: Discard drops the edit unwritten, Keep editing lets the retries go on.
|
|
/// </summary>
|
|
/// <returns>True when the editor may close: everything is stored or the user chose to discard.</returns>
|
|
public async Task<bool> ConfirmCloseAsync()
|
|
{
|
|
if (Editor is not { } editor || await editor.Session.FlushAsync()) return true;
|
|
var session = editor.Session;
|
|
if (!await session.HoldPendingAsync())
|
|
{
|
|
// A retry stored it meanwhile: nothing to ask.
|
|
session.KeepPending();
|
|
return true;
|
|
}
|
|
var discard = Shell.Services.Dialogs.Confirm(new ConfirmRequest
|
|
{
|
|
Heading = Loc.L("Editor.Unsaved.Title"),
|
|
Message = Loc.L("Editor.Unsaved.Message", editor.Title, session.LastSaveError?.Message ?? string.Empty),
|
|
SafeText = Loc.L("Editor.Unsaved.Keep"),
|
|
SafeToolTip = Loc.L("Tooltips.Editor.Unsaved.Keep"),
|
|
ActionText = Loc.L("Editor.Unsaved.Discard"),
|
|
ActionToolTip = Loc.L("Tooltips.Editor.Unsaved.Discard"),
|
|
IsDestructive = true,
|
|
});
|
|
if (discard) session.DiscardPending();
|
|
else session.KeepPending();
|
|
return discard;
|
|
}
|
|
|
|
/// <summary>Closes the open sequence (after <see cref="ConfirmCloseAsync"/>, which stores its last edit).</summary>
|
|
public async Task CloseAsync()
|
|
{
|
|
await Settled(_switch);
|
|
if (Editor is not { } editor) return;
|
|
Remember(editor);
|
|
Editor = null;
|
|
_openId = null;
|
|
await editor.DisposeAsync();
|
|
}
|
|
|
|
/// <summary>Shows <paramref name="editor"/>, which the caller opened over a source of its own (tests), as the open sequence.</summary>
|
|
internal void Attach(EditorViewModel editor)
|
|
{
|
|
_openId = editor.Session.Content.Sequence.Id;
|
|
if (_steps.TryGetValue(editor.Session.Content.Sequence.Id, out var memory)) editor.RestoreSteps(memory);
|
|
Editor = editor;
|
|
}
|
|
|
|
public override void Dispose()
|
|
{
|
|
Shell.PropertyChanged -= OnShellChanged;
|
|
StopFetch();
|
|
_dialog?.Dispose();
|
|
while (_waiting.TryDequeue(out var waiting)) waiting.Dispose();
|
|
Editor?.Dispose();
|
|
Picker.Dispose();
|
|
base.Dispose();
|
|
}
|
|
|
|
/// <summary>Shows <paramref name="dialog"/> over the section (one at a time: an open one is closed first).</summary>
|
|
internal void OpenDialog(ArchiveDialogViewModel dialog)
|
|
{
|
|
_dialog?.Dispose();
|
|
Dialog = dialog;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Shows <paramref name="dialog"/> now when no dialog is open, else once the open one (and those waiting before it)
|
|
/// closed: what the background found (a conflict an automatic sync met) never replaces what the user is doing.
|
|
/// </summary>
|
|
internal void OpenDialogWhenFree(ArchiveDialogViewModel dialog)
|
|
{
|
|
if (_dialog is null) OpenDialog(dialog);
|
|
else _waiting.Enqueue(dialog);
|
|
}
|
|
|
|
/// <summary>Closes <paramref name="dialog"/> if it is still the open one; the next one waiting shows (one closed meanwhile is skipped).</summary>
|
|
internal void CloseDialog(ArchiveDialogViewModel dialog)
|
|
{
|
|
if (!ReferenceEquals(_dialog, dialog)) return;
|
|
dialog.Dispose();
|
|
Dialog = null;
|
|
while (_waiting.TryDequeue(out var next))
|
|
{
|
|
if (next.IsClosed) continue;
|
|
OpenDialog(next);
|
|
break;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// "Remove local copy" of a project of the picker's Workspace group: the open project's goes through its menu; another,
|
|
/// even one that cannot open (its copy failed, or the library no longer has it), gets the same plan and choices here.
|
|
/// </summary>
|
|
public async Task RemoveProjectCopyAsync(WorkspaceProjectItem item)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(item);
|
|
if (_editor?.Project is { } menu && menu.ProjectId == item.ProjectId)
|
|
{
|
|
menu.RemoveCopyCommand.Execute(null);
|
|
return;
|
|
}
|
|
var workspace = Shell.Services.Workspace;
|
|
var (projectId, name) = (item.ProjectId, item.Name);
|
|
try
|
|
{
|
|
var plan = await workspace.PlanRemovalAsync(projectId);
|
|
OpenDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveCopyAsync(projectId, name, discard), async () =>
|
|
{
|
|
await workspace.SendAllAsync(projectId);
|
|
await RemoveCopyAsync(projectId, name, discard: false);
|
|
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, name), d => CloseDialog(d)));
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
Log.Warning("workspace", $"The removal of project {projectId} could not be planned", ex);
|
|
Shell.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true);
|
|
}
|
|
|
|
async Task RemoveCopyAsync(Guid id, string project, bool discard)
|
|
{
|
|
await workspace.RemoveLocalCopyAsync(id, discard);
|
|
Shell.Notify(Loc.L("Editor.Workspace.Removed"), project);
|
|
_ = Picker.ReloadAsync();
|
|
}
|
|
}
|
|
|
|
protected override void OnActivated()
|
|
{
|
|
OpenRequested();
|
|
ShowRequested();
|
|
if (_showsPicker) _ = Picker.ReloadAsync();
|
|
}
|
|
|
|
/// <summary>Opens the sequence the shell asks for when it is not the open one (nor one whose proxies are on their way).</summary>
|
|
private void OpenRequested()
|
|
{
|
|
if (Shell.CurrentSequenceId is { } id && id != _openId && !Fetching(id)) _ = OpenAsync(id);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Asking for the open sequence again (the Library, Jobs, a project file, also while Edit is on screen) ends a choice of
|
|
/// another; coming back to Edit alone leaves the choice on screen.
|
|
/// </summary>
|
|
private void ShowRequested()
|
|
{
|
|
if (Shell.SequenceRequests == _seenRequests) return;
|
|
_seenRequests = Shell.SequenceRequests;
|
|
if (_editor is not null && Shell.CurrentSequenceId == _openId) KeepOpenSequence();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Back to the open sequence (Cancel, Esc, or the open sequence chosen again): it is again the one asked for, and a
|
|
/// server sequence still waiting for its proxies no longer opens over it when they arrive (its download goes on).
|
|
/// </summary>
|
|
private void KeepOpenSequence()
|
|
{
|
|
if (_fetch is { } pending && pending.RemoteId != _openId) StopFetch();
|
|
Shell.KeepSequence(_openId);
|
|
IsPicking = false;
|
|
}
|
|
|
|
/// <summary>The proxies of server sequence <paramref name="sequenceId"/> are on their way: it opens when they are here.</summary>
|
|
private bool Fetching(Guid sequenceId) => _fetch?.RemoteId == sequenceId;
|
|
|
|
/// <summary>
|
|
/// Whether the picker shows changed (a sequence opened or failed to, Change sequence, Cancel): it reads the list again
|
|
/// each time it appears on screen.
|
|
/// </summary>
|
|
private void OnPickerChanged()
|
|
{
|
|
OnPropertyChanged(nameof(CanCancelPick));
|
|
OnPropertyChanged(nameof(CancelPickToolTip));
|
|
var shows = !_isLoading && (_editor is null || _isPicking);
|
|
if (shows != _showsPicker)
|
|
{
|
|
_showsPicker = shows;
|
|
OnPropertyChanged(nameof(ShowsPicker));
|
|
if (shows && IsSelected) _ = Picker.ReloadAsync();
|
|
}
|
|
CommandManager.InvalidateRequerySuggested();
|
|
}
|
|
|
|
private void OnFetchingChanged()
|
|
{
|
|
OnPropertyChanged(nameof(FetchingTitle));
|
|
OnPropertyChanged(nameof(FetchingText));
|
|
}
|
|
|
|
/// <summary>Keeps the step <paramref name="editor"/> shows and the steps visited, for when its sequence opens again in this run.</summary>
|
|
private void Remember(EditorViewModel editor) => _steps[editor.Session.Content.Sequence.Id] = editor.StepMemory();
|
|
|
|
private void OnShellChanged(object? sender, PropertyChangedEventArgs e)
|
|
{
|
|
if (!IsSelected) return;
|
|
if (e.PropertyName == nameof(ShellViewModel.CurrentSequenceId)) OpenRequested();
|
|
else if (e.PropertyName == nameof(ShellViewModel.SequenceRequests)) ShowRequested();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Where <paramref name="sequenceId"/> lives: this PC's index (opened as a workspace project,
|
|
/// <see cref="OpenWorkspaceAsync"/>; in a capture, the library itself), else a sequence of the signed-in server whose
|
|
/// proxies this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only shown
|
|
/// when the account may not change it. Null when it cannot open yet: its proxies are being fetched
|
|
/// (<see cref="FetchProxiesAsync"/>), its workspace copy runs, or the user closed "Open in workspace".
|
|
/// </summary>
|
|
private async Task<(ISequenceSource Source, string Title)?> OpenSourceAsync(AppServices services, Guid sequenceId)
|
|
{
|
|
if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
|
var processing = services.Processing?.Options;
|
|
var decoder = processing?.Archive.Decoder ?? DecoderFactory.CreateClient(null);
|
|
if (await db.Sequences.GetAsync(sequenceId) is { } row)
|
|
{
|
|
if (services.Workspace.IsEnabled) return await OpenWorkspaceAsync(services, services.Workspace, db, decoder, row);
|
|
var local = new LocalSequenceSource(db, sequenceId, decoder, services.Engine, processing?.Archive);
|
|
local.HeroChanged += OnHeroChanged;
|
|
return (local, row.DisplayTitle);
|
|
}
|
|
// A workspace project whose sequence left the index (its trash emptied, its folder gone): not a server's sequence to
|
|
// fetch; its local copy can only be removed (the picker's Remove local copy).
|
|
if (_requested is { ProjectId: { } projectId } asked && asked.SequenceId == sequenceId && services.Workspace.IsEnabled
|
|
&& await services.Workspace.FindAsync(projectId) is not null)
|
|
{
|
|
_requested = null;
|
|
throw new InvalidOperationException(Loc.L("Errors.Workspace.SequenceGone"));
|
|
}
|
|
var sync = services.Sync;
|
|
if (sync.Server is not { } server || sync.Service is not { } service || sync.ConnectEditor() is not { } api)
|
|
throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
|
|
// The proxy cache's index and files are read off the UI thread.
|
|
if (await Task.Run(() => service.OpenRemote(server, sequenceId)) is { } remote)
|
|
return (new RemoteSequenceSource(remote, api, decoder, readOnly: !sync.Policy.CanEdit), remote.Sequence.DisplayTitle);
|
|
using (api)
|
|
{
|
|
string title;
|
|
try
|
|
{
|
|
title = (await api.GetSequenceAsync(sequenceId, CancellationToken.None)).DisplayTitle;
|
|
}
|
|
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
|
{
|
|
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
|
|
}
|
|
await FetchProxiesAsync(sequenceId, title);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A sequence of this PC's archive opens as a project of the workspace (owner review 2, R8): the project asked for
|
|
/// (<see cref="_requested"/>), else the one of the sequence opened last here. One not here yet, or whose media are gone,
|
|
/// is checked out and its media copied by a job, after "Open in workspace" asked which project when the sequence has
|
|
/// none here (Main is made from the sequence's settings as they are, so edits made in the library before carry over);
|
|
/// it opens once the copy is done. Null while it cannot open yet.
|
|
/// </summary>
|
|
private async Task<(ISequenceSource Source, string Title)?> OpenWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db,
|
|
ImageDecoder decoder, Sequence row)
|
|
{
|
|
var request = TakeRequest(row.Id);
|
|
var entry = request switch
|
|
{
|
|
{ ProjectId: { } id } => await workspace.FindAsync(id),
|
|
{ Main: true } => (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain),
|
|
_ => await workspace.LastUsedAsync(row.Id),
|
|
};
|
|
if (entry is { HasMedia: true })
|
|
{
|
|
workspace.Remember(row.Id, entry.ProjectId);
|
|
return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
|
|
}
|
|
var projectId = entry?.ProjectId ?? request?.ProjectId;
|
|
string? newName = null;
|
|
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(row.Id)).All(p => p.Id != wanted))
|
|
{
|
|
// A project file of a project this home does not have (another PC's workspace): its sequence's Main takes it.
|
|
Log.Info("workspace", $"Project {wanted} is not a project of sequence {row.Id} here; its Main opens instead");
|
|
projectId = null;
|
|
if (_afterOpen is { } pending && pending.Request.SequenceId == row.Id) _afterOpen = (ProjectRequest.MainOf(row.Id), pending.Action);
|
|
}
|
|
else if (entry is null && projectId is null && request is not { Main: true })
|
|
{
|
|
if (await AskProjectAsync(workspace, row) is not { } choice)
|
|
{
|
|
_afterOpen = null;
|
|
Shell.KeepSequence(OpenSequenceId);
|
|
return null;
|
|
}
|
|
(projectId, newName) = (choice.ProjectId, choice.NewName);
|
|
}
|
|
var checkout = await workspace.CheckoutAsync(row.Id, projectId, newName);
|
|
await FollowCopyAsync(row.Id, row.DisplayTitle, checkout.Project.Id, checkout.Copy);
|
|
return null;
|
|
}
|
|
|
|
/// <summary>"Open in workspace": the projects of the sequence's home and the media; null when closed without a choice.</summary>
|
|
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row)
|
|
{
|
|
var projects = await workspace.HomeProjectsAsync(row.Id);
|
|
var dialog = new OpenInWorkspaceDialogViewModel(row.DisplayTitle, projects, d => CloseDialog(d));
|
|
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
|
|
IsLoading = false;
|
|
OpenDialog(dialog);
|
|
try
|
|
{
|
|
return await dialog.Choice;
|
|
}
|
|
finally
|
|
{
|
|
IsLoading = true;
|
|
}
|
|
}
|
|
|
|
/// <summary>The project the next open of <paramref name="sequenceId"/> takes, taken once; null when none was asked for.</summary>
|
|
private ProjectRequest? TakeRequest(Guid sequenceId)
|
|
{
|
|
if (_requested is not { } request || request.SequenceId != sequenceId) return null;
|
|
_requested = null;
|
|
return request;
|
|
}
|
|
|
|
/// <summary>Follows the workspace copy of a project's media (the picker's line, a toast): the project opens once it is done.</summary>
|
|
private async Task FollowCopyAsync(Guid sequenceId, string title, Guid projectId, Job copy)
|
|
{
|
|
var engine = Shell.Services.Engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
|
StopFetch();
|
|
var fetch = new PendingOpen(sequenceId, title, engine, "Editor.Workspace.Copying", projectId) { JobId = copy.Id };
|
|
fetch.Handler = job => _dispatcher.BeginInvoke(() => OnFetchChanged(fetch, job));
|
|
engine.JobChanged += fetch.Handler;
|
|
_fetch = fetch;
|
|
OnFetchingChanged();
|
|
Shell.Notify(Loc.L("Editor.Workspace.Copying"), title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
|
// A copy that ended before it was followed here is handled now.
|
|
if (Shell.Services.Database is { } db && await db.Jobs.GetAsync(copy.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
|
|
OnFetchChanged(fetch, ended);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The proxy download or workspace copy an open waits on moved: opens the sequence (the project copied) once it is done,
|
|
/// says why not when it failed.
|
|
/// </summary>
|
|
private void OnFetchChanged(PendingOpen fetch, Job job)
|
|
{
|
|
if (!ReferenceEquals(fetch, _fetch) || job.Id != fetch.JobId || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
|
|
StopFetch();
|
|
switch (job.State)
|
|
{
|
|
// Opened only when it is still the sequence asked for; otherwise the next visit opens it (from the cache, from the workspace).
|
|
case JobState.Done when Shell.CurrentSequenceId == fetch.RemoteId && IsSelected:
|
|
if (fetch.ProjectId is { } projectId) _requested = new ProjectRequest(fetch.RemoteId, projectId);
|
|
_ = OpenAsync(fetch.RemoteId, reload: true);
|
|
break;
|
|
case JobState.Failed:
|
|
Shell.Notify(Loc.L(fetch.ProjectId is null ? "Editor.Proxies.Failed" : "Editor.Workspace.CopyFailed"), job.Error ?? fetch.Title, Loc.L("Shell.Nav.Jobs"),
|
|
Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs), isError: true);
|
|
break;
|
|
}
|
|
}
|
|
|
|
private void StopFetch()
|
|
{
|
|
if (_fetch is not { } fetch) return;
|
|
_fetch = null;
|
|
if (fetch.Handler is { } handler) fetch.Engine.JobChanged -= handler;
|
|
OnFetchingChanged();
|
|
}
|
|
|
|
/// <summary>Set hero changed the frame the Library shows (any thread): its card loads the new thumbnail.</summary>
|
|
private void OnHeroChanged(Sequence row) => _dispatcher.BeginInvoke(() =>
|
|
{
|
|
if (Shell.Library.Items.FirstOrDefault(i => i.Id == row.Id) is { } item) item.Update(row);
|
|
});
|
|
|
|
/// <summary>Waits for <paramref name="task"/>; its failure was reported where it happened.</summary>
|
|
private static async Task Settled(Task task)
|
|
{
|
|
try
|
|
{
|
|
await task;
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
Log.Debug("editor", $"An earlier open of the editor failed: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private async Task SwitchAsync(Task previous, Guid sequenceId, bool reload)
|
|
{
|
|
await Settled(previous);
|
|
if (sequenceId == _openId && !reload) return;
|
|
// Asked for again while its proxies are on their way (the next visit, a second pick): it opens when they are here.
|
|
if (!reload && Fetching(sequenceId)) return;
|
|
var services = Shell.Services;
|
|
// The progress bar shows until the switch ends; the picker, its Cancel and the editor are hidden meanwhile.
|
|
IsLoading = true;
|
|
ISequenceSource? source = null;
|
|
try
|
|
{
|
|
// The next sequence is read first: the open one stays open when this one cannot open now.
|
|
if (await OpenSourceAsync(services, sequenceId) is not { } opened) return;
|
|
source = opened.Source;
|
|
SequenceContent content;
|
|
try
|
|
{
|
|
content = await source.LoadAsync(CancellationToken.None);
|
|
}
|
|
catch (ProxiesOutdatedException)
|
|
{
|
|
// The server's frames are no longer these proxies: fetch them again, then open.
|
|
await source.DisposeAsync();
|
|
source = null;
|
|
await FetchProxiesAsync(sequenceId, opened.Title);
|
|
return;
|
|
}
|
|
// Only now does the open sequence close: its last edit is stored first, or discarded on the user's word. Keeping
|
|
// it keeps the open sequence as the one asked for, so the next visit to Edit does not ask once more.
|
|
if (!await ConfirmCloseAsync())
|
|
{
|
|
Shell.KeepSequence(_openId);
|
|
IsPicking = false;
|
|
return;
|
|
}
|
|
// A server sequence that was waiting for its proxies is no longer the one asked for.
|
|
if (_fetch is { } pending && pending.RemoteId != sequenceId) StopFetch();
|
|
if (Editor is { } old)
|
|
{
|
|
Remember(old);
|
|
Editor = null;
|
|
_openId = null;
|
|
await old.DisposeAsync();
|
|
}
|
|
var processing = services.Processing?.Options;
|
|
var encoders = processing?.Encoders ?? [];
|
|
var session = new EditorSession(source, content, [.. encoders.SelectMany(e => e.Capabilities)]);
|
|
// The session owns the source from here on.
|
|
source = null;
|
|
EditorViewModel editor;
|
|
try
|
|
{
|
|
editor = new EditorViewModel(Shell, session, encoders, processing?.Host ?? EncoderHost.Client);
|
|
}
|
|
catch
|
|
{
|
|
await session.DisposeAsync();
|
|
throw;
|
|
}
|
|
if (_steps.TryGetValue(sequenceId, out var memory)) editor.RestoreSteps(memory);
|
|
// A workspace project's menu (▾ beside the title): its state, versions, sync and copies.
|
|
if (session.Source is WorkspaceSequenceSource workspace) editor.Project = new ProjectMenuViewModel(services.Workspace, workspace, session, _workspaceUi);
|
|
_openId = sequenceId;
|
|
Editor = editor;
|
|
services.Settings.LastEditedSequence = sequenceId;
|
|
services.SavePreferences();
|
|
if (_afterOpen is { } after && after.Request.SequenceId != sequenceId) _afterOpen = null;
|
|
RunAfterOpen(editor);
|
|
await editor.AttachJobsAsync();
|
|
if (editor.Project is { } project) await project.RefreshAsync();
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
// Whatever failed (index, decoder set-up, advisor, the job list), the section stays usable: the sequence open
|
|
// before (or the one that has just opened) stays open and is again the one asked for, so coming back to Edit
|
|
// neither tries nor reports it again; choosing the sequence again does.
|
|
Log.Warning("editor", $"Sequence {sequenceId} could not be opened", ex);
|
|
Shell.ReportError(ex);
|
|
Shell.KeepSequence(OpenSequenceId);
|
|
}
|
|
finally
|
|
{
|
|
if (source is not null) await source.DisposeAsync();
|
|
IsLoading = false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A job an open waits on, with its engine subscription: a server sequence's proxy download, or the workspace copy of a
|
|
/// project's media (<see cref="ProjectId"/>: the project that opens when it is done).
|
|
/// </summary>
|
|
private sealed class PendingOpen(Guid remoteId, string title, JobEngine engine, string textKey, Guid? projectId)
|
|
{
|
|
/// <summary>The sequence that opens when the job is done.</summary>
|
|
public Guid RemoteId { get; } = remoteId;
|
|
|
|
public string Title { get; } = title;
|
|
|
|
public JobEngine Engine { get; } = engine;
|
|
|
|
/// <summary>What the picker's line says is on its way.</summary>
|
|
public string TextKey { get; } = textKey;
|
|
|
|
public Guid? ProjectId { get; } = projectId;
|
|
|
|
public Guid JobId { get; set; }
|
|
|
|
public Action<Job>? Handler { get; set; }
|
|
}
|
|
|
|
/// <summary>What the project menu of an editor of this section asks of it: its dialogs, the shell's confirmations and toasts, opening and closing projects.</summary>
|
|
private sealed class WorkspaceUi(SequenceViewModel section) : IWorkspaceUi
|
|
{
|
|
public ArchiveDialogViewModel? Dialog => section.Dialog;
|
|
|
|
public void ShowDialog(ArchiveDialogViewModel dialog) => section.OpenDialog(dialog);
|
|
|
|
public void ShowDialogWhenFree(ArchiveDialogViewModel dialog) => section.OpenDialogWhenFree(dialog);
|
|
|
|
public void CloseDialog(ArchiveDialogViewModel dialog) => section.CloseDialog(dialog);
|
|
|
|
public bool Confirm(ConfirmRequest request) => section.Shell.Services.Dialogs.Confirm(request);
|
|
|
|
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false) =>
|
|
section.Shell.Notify(title, message, actionText, actionToolTip, action, isError);
|
|
|
|
public async Task OpenProjectAsync(Guid sequenceId, Guid projectId) => await section.OpenProjectAsync(sequenceId, projectId);
|
|
|
|
public async Task<bool> CloseProjectAsync()
|
|
{
|
|
if (!await section.ConfirmCloseAsync()) return false;
|
|
await section.CloseAsync();
|
|
// Coming back to Edit shows the picker rather than opening the project again.
|
|
section.Shell.KeepSequence(null);
|
|
return true;
|
|
}
|
|
|
|
public async Task SequenceChangedAsync(Guid sequenceId)
|
|
{
|
|
if (section.Shell.Services.Database is not { } db || await db.Sequences.GetAsync(sequenceId) is not { } row) return;
|
|
if (section.Shell.Library.Items.FirstOrDefault(i => i.Id == row.Id) is { } item) item.Update(row);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The workspace project an open of <see cref="SequenceId"/> takes (owner review 2, R8): <see cref="ProjectId"/>, else the
|
|
/// sequence's Main when <see cref="Main"/> (a <c>.chronos</c> file of format 1 applies to Main), else the one opened last.
|
|
/// </summary>
|
|
public sealed record ProjectRequest(Guid SequenceId, Guid? ProjectId = null, bool Main = false)
|
|
{
|
|
public static ProjectRequest MainOf(Guid sequenceId) => new(sequenceId, null, Main: true);
|
|
}
|