The desktop now uses the per-home layout from P3.1: each home keeps its own projects, proxies and originals, and a server is known by its id whichever address reaches it. - Settings keep the known servers (id, name, last address, certificate, aliases, originals archive). Reset and Import keep them; Export leaves them out. - SyncHost records each server the first time it signs in with an id. It names the cache and workspace folders by that id, and re-keys the folders a server had under its addresses at sign-in. The re-key waits while transfer or workspace jobs are pending. - Download originals goes to the server's own archive. It is created beside this PC's archive at the first download, and a toast says where. A sequence that already has a local copy keeps receiving into that copy's archive. A server without an id keeps the 1.0 behaviour. - At start, after the index opens and before any job runs, the folders are sorted into their homes. A toast reports the result: sorted, pending or failed. - The workspace host gives each home's store its own sync. Find, List, usage, clean-up and the trash plan and empty cover every home. Server comparisons go through the identity, so a project stays Online when its server is reached by another address. - The render-node downloads and the server import staging move into the server's folder of the cache. The cache trim keeps `servers`, and the scheduled scan also scans the originals archives. - Settings shows the Home folders rows (Workspace) and the Known servers table (Server). The diagnostics bundle lists the homes. - The dead `AppPaths.CreateDirectories` and `ThumbnailsDirectory` are removed. Refs #66 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1136 lines
57 KiB
C#
1136 lines
57 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.Core.Project;
|
||
using Chronos.Data;
|
||
using Chronos.Data.Jobs;
|
||
using Chronos.Data.Projects;
|
||
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 sequence of
|
||
/// a server that keeps projects opens the same way as a project whose home is that server (phase 5b: its media downloaded
|
||
/// into the workspace; a project already there opens from it, the server reachable or not); one of an older server opens
|
||
/// with this PC's proxies, 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;
|
||
}
|
||
// A copy a newer Chronos wrote neither opens nor goes from here: the toast says so, nothing is offered over it.
|
||
if (item.IsNewer)
|
||
{
|
||
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), Loc.L("Errors.Workspace.NewerCopy"), isError: true);
|
||
return;
|
||
}
|
||
// A copy whose working state cannot be read cannot open: its removal plan is what it offers.
|
||
if (item.IsDamaged)
|
||
{
|
||
await RemoveProjectCopyAsync(item);
|
||
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);
|
||
// A damaged copy is named as it is still known, never by its folder's id (none when nothing knows it).
|
||
var shown = plan.Damaged ? plan.KnownName : name;
|
||
OpenDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveCopyAsync(projectId, shown, discard), async () =>
|
||
{
|
||
await workspace.SendAllAsync(projectId);
|
||
await RemoveCopyAsync(projectId, shown, discard: false);
|
||
}, () => plan.Damaged ? RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, plan) : 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 server's sequence: a workspace project
|
||
/// whose home is that server (<see cref="OpenServerWorkspaceAsync"/>), or, for a server that keeps no projects, one
|
||
/// 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 of this PC's archive 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 { IsServerHome: false })
|
||
{
|
||
_requested = null;
|
||
throw new InvalidOperationException(Loc.L("Errors.Workspace.SequenceGone"));
|
||
}
|
||
// A server sequence (owner review 2, R8, phase 5b): a project of it in the workspace opens from there, the server
|
||
// reachable or not; one of a server that keeps projects is checked out (asked which); an older server's opens with
|
||
// proxies as before.
|
||
if (services.Workspace.IsEnabled && await OpenServerWorkspaceAsync(services, services.Workspace, db, decoder, sequenceId) is { } project)
|
||
return project.Opened;
|
||
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, serverFormat: sync.SettingsFormat), 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);
|
||
WorkspaceEntry? entry;
|
||
if (request is { ProjectId: { } id }) entry = await workspace.FindAsync(id);
|
||
else if (request is { Main: true }) entry = (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain);
|
||
else
|
||
{
|
||
var (cancelled, chosen) = await PolicyEntryAsync(services, workspace, row.Id, row.DisplayTitle, _ => true);
|
||
if (cancelled)
|
||
{
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return null;
|
||
}
|
||
entry = chosen;
|
||
}
|
||
// This Chronos cannot read its working state (damaged, or a newer Chronos's): nothing is checked out over it.
|
||
if (entry is { IsReadable: false } unreadable) throw WorkspaceHost.Unreadable(unreadable);
|
||
// No project of the sequence here opens, and its Main here is such a copy (never among its projects): said at once,
|
||
// with Remove local copy for a damaged one, when nothing else could be chosen (Main asked for, or the home has no
|
||
// other project); otherwise "Open in workspace" lists Main as it is, disabled, and offers the others.
|
||
WorkspaceEntry? unreadableMain = null;
|
||
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, WorkspaceHost.ArchiveHome(row.Id)) is { } main)
|
||
{
|
||
if (request is { Main: true } || (await workspace.HomeProjectsAsync(row.Id)).All(p => p.IsMain))
|
||
{
|
||
RefuseUnreadable(main);
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return null;
|
||
}
|
||
unreadableMain = main;
|
||
}
|
||
if (entry is { HasMedia: true })
|
||
{
|
||
workspace.Remember(row.Id, entry.ProjectId);
|
||
workspace.RecordOpened(entry.ProjectId);
|
||
return (new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
|
||
}
|
||
var projectId = entry?.ProjectId ?? request?.ProjectId;
|
||
string? newName = null;
|
||
var media = DefaultMedia(services);
|
||
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, unreadableMain) is not { } choice)
|
||
{
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return null;
|
||
}
|
||
(projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
|
||
}
|
||
WorkspaceCheckout checkout;
|
||
try
|
||
{
|
||
checkout = await workspace.CheckoutAsync(row.Id, projectId, newName, media);
|
||
}
|
||
catch (WorkspaceException ex) when (ex.FolderRefused)
|
||
{
|
||
// Nothing was written: the way on is another workspace folder, offered from the refusal.
|
||
Log.Info("workspace", $"Sequence {row.Id} not checked out: {ex.Message}");
|
||
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), ex.Message, Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder"),
|
||
() => _ = WorkspaceFolderChange.ChooseAsync(Shell), isError: true);
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return null;
|
||
}
|
||
await FollowCopyAsync(row.Id, row.DisplayTitle, checkout.Project.Id, checkout.Copy);
|
||
return null;
|
||
}
|
||
|
||
/// <summary>The workspace's copy of the Main of <paramref name="home"/>'s sequence when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
|
||
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, BundleHome home)
|
||
{
|
||
if ((await workspace.HomeProjectsAsync(home)).FirstOrDefault(p => p.IsMain) is not { } main) return null;
|
||
return await workspace.FindAsync(main.Id) is { IsReadable: false } copy ? copy : null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Why a copy this Chronos cannot read does not open: a newer Chronos's is left as it is (nothing is offered over it), a
|
||
/// damaged one offers Remove local copy, whose Discard keeps its files aside.
|
||
/// </summary>
|
||
private void RefuseUnreadable(WorkspaceEntry copy)
|
||
{
|
||
Log.Info("workspace", $"Project {copy.ProjectId} here cannot be read by this Chronos ({(copy.Newer ? "newer" : "damaged")}): it is not opened");
|
||
if (copy.Newer)
|
||
{
|
||
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), Loc.L("Errors.Workspace.NewerCopy"), isError: true);
|
||
return;
|
||
}
|
||
var item = new WorkspaceProjectItem(copy, null);
|
||
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), Loc.L("Errors.Workspace.Damaged"), Loc.L("Editor.Project.RemoveCopy"),
|
||
Loc.L("Tooltips.Editor.Project.RemoveCopy"), () => _ = RemoveProjectCopyAsync(item), isError: true);
|
||
}
|
||
|
||
/// <summary>
|
||
/// A sequence of a server opens as a project of the workspace whose home is that server (phase 5b): the project asked
|
||
/// for, else the one of the sequence opened last here. One the workspace holds the media of opens from there, whether
|
||
/// this PC can reach the server or not (its sync, analyses and renders wait for it). Otherwise, signed in to a server
|
||
/// that keeps projects, the project is checked out, after "Open in workspace" asked which (when the sequence has none
|
||
/// here), and its media downloaded by a job; it opens once they are here. A copy this Chronos cannot read is refused as
|
||
/// for this PC's archive. Null when the server keeps no projects, or this PC is not signed in to it: the sequence then
|
||
/// opens with proxies as before (or says to connect).
|
||
/// </summary>
|
||
private async Task<ServerOpen?> OpenServerWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db, ImageDecoder decoder, Guid remoteId)
|
||
{
|
||
var request = _requested is { } asked && asked.SequenceId == remoteId ? asked : null;
|
||
WorkspaceEntry? entry;
|
||
if (request is { ProjectId: { } id }) entry = await workspace.FindAsync(id) is { IsServerHome: true } found && found.SequenceId == remoteId ? found : null;
|
||
else if (request is { Main: true }) entry = (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true });
|
||
else
|
||
{
|
||
var (cancelled, chosen) = await PolicyEntryAsync(services, workspace, remoteId, null, p => p.IsServerHome);
|
||
if (cancelled)
|
||
{
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return new ServerOpen(null);
|
||
}
|
||
entry = chosen;
|
||
}
|
||
var sync = services.Sync;
|
||
if (entry is { IsReadable: false } unreadable)
|
||
{
|
||
TakeRequest(remoteId);
|
||
throw WorkspaceHost.Unreadable(unreadable);
|
||
}
|
||
if (entry is { HasMedia: true })
|
||
{
|
||
TakeRequest(remoteId);
|
||
workspace.Remember(remoteId, entry.ProjectId);
|
||
workspace.RecordOpened(entry.ProjectId);
|
||
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server:
|
||
// made again whenever the sign-in changes, so a project opened signed out renders once signed in.
|
||
var server = entry.Home.Server;
|
||
var editorHome = new WorkspaceServerHome(() => sync.Identity.Same(sync.Server, server) ? sync.ConnectEditor() : null,
|
||
() => sync.Session);
|
||
return new ServerOpen((new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle));
|
||
}
|
||
// An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server.
|
||
if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null;
|
||
TakeRequest(remoteId);
|
||
try
|
||
{
|
||
var reached = workspace.Reachable(home);
|
||
var title = (await Task.Run(() => reached.SequenceAsync(CancellationToken.None))).Sequence.Title ?? entry?.SequenceTitle ?? string.Empty;
|
||
// No project of the sequence here opens and its Main here cannot be read: refused, or listed disabled, as for this PC's archive.
|
||
WorkspaceEntry? unreadableMain = null;
|
||
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, home) is { } main)
|
||
{
|
||
if (request is { Main: true } || (await workspace.HomeProjectsAsync(home)).All(p => p.IsMain))
|
||
{
|
||
RefuseUnreadable(main);
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return new ServerOpen(null);
|
||
}
|
||
unreadableMain = main;
|
||
}
|
||
var projectId = entry?.ProjectId ?? request?.ProjectId;
|
||
string? newName = null;
|
||
var media = DefaultMedia(services);
|
||
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(home)).All(p => p.Id != wanted))
|
||
{
|
||
// A project the server does not have (deleted there, or another server's): the sequence's Main opens instead.
|
||
Log.Info("workspace", $"Project {wanted} is not a project of server sequence {remoteId}; its Main opens instead");
|
||
projectId = null;
|
||
if (_afterOpen is { } pending && pending.Request.SequenceId == remoteId) _afterOpen = (ProjectRequest.MainOf(remoteId), pending.Action);
|
||
}
|
||
else if (entry is null && projectId is null && request is not { Main: true })
|
||
{
|
||
if (await AskProjectAsync(workspace, home, title, unreadableMain) is not { } choice)
|
||
{
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return new ServerOpen(null);
|
||
}
|
||
(projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
|
||
}
|
||
WorkspaceCheckout checkout;
|
||
try
|
||
{
|
||
checkout = await workspace.CheckoutAsync(home, projectId, newName, media);
|
||
}
|
||
catch (WorkspaceException ex) when (ex.FolderRefused)
|
||
{
|
||
// Nothing was written: the way on is another workspace folder, offered from the refusal.
|
||
Log.Info("workspace", $"Server sequence {remoteId} not checked out: {ex.Message}");
|
||
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), ex.Message, Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder"),
|
||
() => _ = WorkspaceFolderChange.ChooseAsync(Shell), isError: true);
|
||
_afterOpen = null;
|
||
Shell.KeepSequence(OpenSequenceId);
|
||
return new ServerOpen(null);
|
||
}
|
||
await FollowCopyAsync(remoteId, title, checkout.Project.Id, checkout.Copy);
|
||
return new ServerOpen(null);
|
||
}
|
||
catch (ProjectException ex) when (ex.Reason == ProjectError.SequenceNotFound)
|
||
{
|
||
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
|
||
}
|
||
catch (ProjectException ex) when (ex.Reason == ProjectError.SequenceEmpty)
|
||
{
|
||
throw new InvalidOperationException(Loc.L("Editor.Error.Empty"), ex);
|
||
}
|
||
catch (HomeUnavailableException ex)
|
||
{
|
||
// Said of the server, not of this PC's library.
|
||
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server: true), ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>"Open in workspace" for a sequence of this PC's archive; null when closed without a choice.</summary>
|
||
private Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row, WorkspaceEntry? unreadableMain = null) =>
|
||
AskProjectAsync(workspace, WorkspaceHost.ArchiveHome(row.Id), row.DisplayTitle, unreadableMain);
|
||
|
||
/// <summary>
|
||
/// "Open in workspace" for a sequence of <paramref name="home"/> (this PC's archive, or a server): its projects, the
|
||
/// media (Settings › Workspace › Media chosen first), what their copy writes and the room the workspace's drive has; null
|
||
/// when closed without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed
|
||
/// disabled, why in its tooltip.
|
||
/// </summary>
|
||
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, BundleHome home, string title, WorkspaceEntry? unreadableMain)
|
||
{
|
||
var projects = await workspace.HomeProjectsAsync(home);
|
||
WorkspaceCopyFacts? copy = null;
|
||
try
|
||
{
|
||
copy = await workspace.CopyFactsAsync(home);
|
||
}
|
||
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException
|
||
or UnauthorizedAccessException or ChronosApiException or System.Net.Http.HttpRequestException)
|
||
{
|
||
// Only shown: the copy measures again before it writes.
|
||
Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
|
||
}
|
||
var unreadable = unreadableMain is { } main
|
||
? new Dictionary<Guid, string>
|
||
{
|
||
[main.ProjectId] = Loc.L(main.Newer ? "Tooltips.Editor.Workspace.State.NewerCopy" : "Tooltips.Editor.Workspace.State.DamagedCopy"),
|
||
}
|
||
: null;
|
||
var dialog = new OpenInWorkspaceDialogViewModel(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive,
|
||
defaultMedia: DefaultMedia(Shell.Services));
|
||
// 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 media a checkout copies unless "Open in workspace" chose: Settings › Workspace › Media.</summary>
|
||
private static string DefaultMedia(AppServices services) => services.Settings.EffectiveDefaultMedia;
|
||
|
||
/// <summary>
|
||
/// The project of the sequence Edit opens when none was asked for (phase 5c, Settings › Workspace › Open project): the
|
||
/// one opened last, Main, or the one chosen in "Open which project?" when the workspace holds several (Cancelled: closed
|
||
/// without a choice). Only projects <paramref name="fits"/> takes count; none here: null.
|
||
/// </summary>
|
||
private async Task<(bool Cancelled, WorkspaceEntry? Entry)> PolicyEntryAsync(AppServices services, WorkspaceHost workspace, Guid sequenceId, string? title,
|
||
Func<WorkspaceEntry, bool> fits)
|
||
{
|
||
var last = await workspace.LastUsedAsync(sequenceId) is { } used && fits(used) ? used : null;
|
||
var policy = services.Settings.EffectiveOpenPolicy;
|
||
if (policy == WorkspaceOpenPolicy.LastUsed) return (false, last);
|
||
var here = (await workspace.ProjectsOfAsync(sequenceId)).Where(p => fits(p) && p.IsReadable).ToList();
|
||
if (policy == WorkspaceOpenPolicy.Main) return (false, here.FirstOrDefault(p => p.IsMain) ?? last);
|
||
if (here.Count < 2) return (false, last ?? here.FirstOrDefault());
|
||
var dialog = new OpenProjectDialogViewModel(title ?? here[0].SequenceTitle, here, last?.ProjectId, d => CloseDialog(d));
|
||
IsLoading = false;
|
||
OpenDialog(dialog);
|
||
try
|
||
{
|
||
return await dialog.Choice is { } chosen ? (false, chosen) : (true, null);
|
||
}
|
||
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();
|
||
// A first copy of a project's media the user cancelled removes what it wrote itself, once it has stopped (the job).
|
||
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>What the open of a server sequence as a workspace project came to: its source, or null while it waits (its copy runs, the dialog was closed).</summary>
|
||
private sealed record ServerOpen((ISequenceSource Source, string Title)? Opened);
|
||
|
||
/// <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);
|
||
}
|
||
|
||
public void ShowJobs() => section.Shell.Navigate(SectionKey.Jobs);
|
||
}
|
||
}
|
||
|
||
/// <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);
|
||
}
|