feat: owner review 2 phase 5a: workspace and projects with a local home (#14)
CI / Build and test (push) Successful in 9m43s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 27s
CI / PostgreSQL 16 integration (push) Failing after 8m41s
CI / PostgreSQL 17 integration (push) Successful in 12m37s
CI / Docker image (push) Successful in 56s
Release / Build, test and publish (push) Successful in 14m59s
Release / Server image (push) Successful in 1m51s

Edit opens a sequence as a project of a workspace folder outside the library. Projects have linear version histories kept as sidecars in .chronos/projects/, Main mirrors the sequence's settings, and sync merges setting by setting. Migration 0009, JobKind.WorkspaceCopy = 20, Settings › Workspace, and 241 new strings in 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #14.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 09:22:08 +01:00
1 parent efa87f68ce
commit 9b24cf74fc
370 files changed
+29237 -287

No files matched your search

+452 -26
View File
@@ -2,15 +2,19 @@ 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;
@@ -20,18 +24,24 @@ 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"/> (from this PC's archive, or a server
/// sequence with this PC's proxies). 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 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.
/// 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;
@@ -41,16 +51,27 @@ public sealed class SequenceViewModel : SectionViewModel
/// <summary>The shell's <see cref="ShellViewModel.SequenceRequests"/> this section has answered.</summary>
private int _seenRequests;
private Task _switch = Task.CompletedTask;
private ProxyFetch? _fetch;
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);
ChangeSequenceCommand = new RelayCommand(() => IsPicking = true, () => _editor is not null && !_isLoading && !_isPicking && _dialog is null);
CancelPickCommand = new RelayCommand(KeepOpenSequence, () => CanCancelPick);
shell.PropertyChanged += OnShellChanged;
}
@@ -97,6 +118,29 @@ public sealed class SequenceViewModel : SectionViewModel
/// <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;
@@ -129,8 +173,8 @@ public sealed class SequenceViewModel : SectionViewModel
/// <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".</summary>
public string? FetchingText => _fetch is { } fetch ? string.Join(Loc.Separator, Loc.L("Editor.Proxies.Fetching"), fetch.Title) : null;
/// <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;
@@ -149,19 +193,92 @@ public sealed class SequenceViewModel : SectionViewModel
/// <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.
/// 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)
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);
if (_openId != sequenceId) return null;
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;
return Editor;
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>
@@ -193,7 +310,7 @@ public sealed class SequenceViewModel : SectionViewModel
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 ProxyFetch(remoteId, title, engine);
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;
@@ -271,11 +388,84 @@ public sealed class SequenceViewModel : SectionViewModel
{
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();
@@ -349,9 +539,11 @@ public sealed class SequenceViewModel : SectionViewModel
}
/// <summary>
/// Where <paramref name="sequenceId"/> lives: this PC's index, 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 the proxies are not here yet: they are being fetched (<see cref="FetchProxiesAsync"/>).
/// 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)
{
@@ -360,10 +552,19 @@ public sealed class SequenceViewModel : SectionViewModel
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"));
@@ -386,20 +587,188 @@ public sealed class SequenceViewModel : SectionViewModel
}
}
/// <summary>The proxy download for an open waiting on it moved: opens the sequence once it is done, says why not when it failed.</summary>
private void OnFetchChanged(ProxyFetch fetch, Job job)
/// <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),
};
// 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, 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);
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, unreadableMain) is not { } choice)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return null;
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(row.Id, projectId, newName);
}
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 sequence's Main when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, Guid sequenceId)
{
if ((await workspace.HomeProjectsAsync(sequenceId)).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>
/// "Open in workspace": the projects of the sequence's home, the media, 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, Sequence row, WorkspaceEntry? unreadableMain = null)
{
var projects = await workspace.HomeProjectsAsync(row.Id);
WorkspaceCopyFacts? copy = null;
try
{
copy = await workspace.CopyFactsAsync(row.Id);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {row.Id} 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(row.DisplayTitle, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable);
// 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();
// 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.
// 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("Editor.Proxies.Failed"), job.Error ?? fetch.Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"),
() => Shell.Navigate(SectionKey.Jobs), isError: true);
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;
}
}
@@ -492,11 +861,16 @@ public sealed class SequenceViewModel : SectionViewModel
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)
{
@@ -514,17 +888,69 @@ public sealed class SequenceViewModel : SectionViewModel
}
}
/// <summary>A proxy download an open waits on, with its engine subscription.</summary>
private sealed class ProxyFetch(Guid remoteId, string title, JobEngine engine)
/// <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);
}