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
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:
1 parent
efa87f68ce
commit
9b24cf74fc
370 files changed
+29237
-287
No files matched your search
@@ -94,6 +94,15 @@ public abstract class ArchiveDialogViewModel : LocalizedViewModel
|
||||
ErrorText = null;
|
||||
ErrorToolTip = null;
|
||||
}
|
||||
|
||||
/// <summary>The dialog was closed (disposed): one still waiting to be shown no longer is.</summary>
|
||||
public bool IsClosed { get; private set; }
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
IsClosed = true;
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A fact of the rebuild dialog ("Sidecars · 412"); a path stays left to right, a missing value says why in its tooltip.</summary>
|
||||
|
||||
@@ -20,7 +20,7 @@ public static class ArchiveFailures
|
||||
// any more (FrameTrash.RestoreAsync). Other IOExceptions and InvalidDataExceptions (a sidecar of another sequence)
|
||||
// carry technical text.
|
||||
LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or NestedRenameException or StaleDeletePlanException
|
||||
or SequenceInLibraryException or TrashMismatchException => ex.Message,
|
||||
or SequenceInLibraryException or TrashMismatchException or Core.Project.ProjectTooLargeException => ex.Message,
|
||||
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
|
||||
DatabaseException => Loc.L("Archive.Failed.Index"),
|
||||
ArgumentException => Loc.L("Archive.Failed.Gone"),
|
||||
|
||||
@@ -5,6 +5,7 @@ using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Projects;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
@@ -45,7 +46,8 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
Source = source;
|
||||
_codecs = codecs ?? [];
|
||||
_basis = content.Project;
|
||||
History = new ProjectHistory(content.Project);
|
||||
// Undo steps take outside changes as the source merges them (a workspace project: positions photo by photo).
|
||||
History = new ProjectHistory(content.Project, merge: (basis, ours, theirs) => source.Merge(basis, ours, theirs).Merged);
|
||||
History.Changed += OnProjectChanged;
|
||||
_saver = new ProjectSaver(SaveAsync, saveDelay ?? DefaultSaveDelay);
|
||||
_saver.Failed += OnSaveFailed;
|
||||
@@ -67,6 +69,12 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
/// <summary>A save met settings changed on the server too (<see cref="Conflict"/> was null): the user picks a side.</summary>
|
||||
public event Action<ProjectConflictException>? ConflictFound;
|
||||
|
||||
/// <summary>
|
||||
/// An edit not stored yet met a newer Chronos's settings stored meanwhile, which this one never merges with: the edit
|
||||
/// was kept aside at the path given (<see cref="ISequenceSource.SetAsideAsync"/>) and the newer settings shown read-only.
|
||||
/// </summary>
|
||||
public event Action<string>? EditSetAside;
|
||||
|
||||
public ISequenceSource Source { get; }
|
||||
|
||||
/// <summary>A server sequence edited with proxies: saved, analysed and rendered on the server.</summary>
|
||||
@@ -165,11 +173,15 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// The jobs that render <paramref name="export"/> and its batch: one job on this PC (the sequence is prepared once),
|
||||
/// one per preset on a server, where a render node uploads one file per job (BRIEF §14.7).
|
||||
/// one per preset on a server, where a render node uploads one file per job (BRIEF §14.7), and for a workspace project
|
||||
/// one per preset at its home with the project's portable settings (<see cref="IProjectRenders"/>, owner review 2, R8).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArchiveJobRequest> RenderRequests(ExportSettings export) => IsRemote
|
||||
? ProcessingJobs.RenderEach(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export })
|
||||
: [RenderRequest(export)];
|
||||
public IReadOnlyList<ArchiveJobRequest> RenderRequests(ExportSettings export) => Source switch
|
||||
{
|
||||
IProjectRenders renders => renders.RenderRequests(Content.Sequence, Project, export, Content.SourceWidth, Content.SourceHeight),
|
||||
_ when IsRemote => ProcessingJobs.RenderEach(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export }),
|
||||
_ => [RenderRequest(export)],
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values.
|
||||
@@ -185,10 +197,11 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles <see cref="Conflict"/> against the server's settings as the last save read them. Both choices first take
|
||||
/// in what only the server changed (like any merge, without an undo step). <paramref name="keepMine"/> then saves
|
||||
/// the editor's values of the settings both changed; otherwise the server's values become the project as one
|
||||
/// undoable step, so Ctrl+Z brings the editor's back (and saves them).
|
||||
/// Settles <see cref="Conflict"/> against the settings stored meanwhile (the server's, a workspace's working state a sync
|
||||
/// wrote) as the last save read them. Both choices first take in what only the other side changed (like any merge,
|
||||
/// without an undo step). <paramref name="keepMine"/> then saves the editor's values of the settings both changed;
|
||||
/// otherwise the other side's values become the project as one undoable step, so Ctrl+Z brings the editor's back (and
|
||||
/// saves them).
|
||||
/// </summary>
|
||||
/// <returns>False when there is no conflict to settle (a later save already went through).</returns>
|
||||
public bool ResolveConflict(bool keepMine)
|
||||
@@ -197,8 +210,17 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
Conflict = null;
|
||||
var basis = _basis;
|
||||
_basis = theirs;
|
||||
History.Replace(ProjectMerge.Merge(basis, Project, theirs));
|
||||
if (!keepMine) History.Apply(ProjectMerge.Merge(basis, theirs, Project));
|
||||
try
|
||||
{
|
||||
History.Replace(Source.Merge(basis, Project, theirs).Merged);
|
||||
if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged);
|
||||
}
|
||||
catch (NewerSettingsException ex)
|
||||
{
|
||||
// Never merged with a newer Chronos's settings: the edit is kept aside, those settings shown read-only.
|
||||
_ = TakeNewerAsync(theirs, ex, CancellationToken.None);
|
||||
return true;
|
||||
}
|
||||
// The change waiting for its retry goes now, on top of the server's settings.
|
||||
_ = _saver.FlushAsync();
|
||||
return true;
|
||||
@@ -230,7 +252,9 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
/// <summary>
|
||||
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
|
||||
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken,
|
||||
/// and a read waits for the one under way, so each follows the frames the one before it took.
|
||||
/// and a read waits for the one under way, so each follows the frames the one before it took. A stored project of a
|
||||
/// newer Chronos met with an edit not stored yet is never merged: the edit is kept aside and the newer settings shown
|
||||
/// read-only (<see cref="EditSetAside"/>).
|
||||
/// </summary>
|
||||
public async Task ReloadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -240,13 +264,21 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
{
|
||||
var content = await Source.LoadAsync(cancellationToken);
|
||||
Follow(content);
|
||||
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
|
||||
// retry meets them and asks (Conflict).
|
||||
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
|
||||
// Settings a server or a sync stored that conflict with the editor's waiting change are not merged over it: that
|
||||
// change's retry meets them and asks (Conflict).
|
||||
ProjectMergeResult? merge = null;
|
||||
try
|
||||
{
|
||||
merge = Conflict is null ? Source.Merge(_basis, Project, content.Project) : null;
|
||||
}
|
||||
catch (NewerSettingsException ex)
|
||||
{
|
||||
await TakeNewerAsync(content.Project, ex, cancellationToken);
|
||||
}
|
||||
if (merge is not null && (!Source.AsksConflicts || !merge.HasConflicts))
|
||||
{
|
||||
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
|
||||
_basis = content.Project;
|
||||
History.Replace(merged);
|
||||
History.Replace(merge.Merged);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -256,6 +288,46 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
ContentChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the project again after the user took the other side's values of the settings both changed (a workspace
|
||||
/// project's "Take the library's", settled by its sync): what only the other side changed comes in as any merge does,
|
||||
/// without an undo step (<paramref name="kept"/>: the stored project as keeping the editor's values would have left
|
||||
/// it), then the values taken become the project as one undoable step, so Ctrl+Z brings the editor's back (and saves
|
||||
/// them), as <see cref="ResolveConflict"/> does for a server's.
|
||||
/// </summary>
|
||||
/// <returns>That step, which a toast's Undo can take back while it is the last change; null when it changed nothing.</returns>
|
||||
public async Task<ProjectRestore?> TakeOverAsync(ProjectSettings kept, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kept);
|
||||
await _saver.FlushAsync();
|
||||
var taken = await BeginReadAsync();
|
||||
ProjectRestore? step = null;
|
||||
try
|
||||
{
|
||||
var content = await Source.LoadAsync(cancellationToken);
|
||||
Follow(content);
|
||||
var basis = _basis;
|
||||
_basis = content.Project;
|
||||
try
|
||||
{
|
||||
History.Replace(Source.Merge(basis, Project, kept).Merged);
|
||||
var before = Project;
|
||||
if (!IsReadOnly && History.Apply(Source.Merge(kept, Project, content.Project).Merged)) step = new ProjectRestore(this, before, Project);
|
||||
}
|
||||
catch (NewerSettingsException ex)
|
||||
{
|
||||
_basis = basis;
|
||||
await TakeNewerAsync(content.Project, ex, cancellationToken);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
taken.SetResult();
|
||||
}
|
||||
ContentChanged?.Invoke();
|
||||
return step;
|
||||
}
|
||||
|
||||
/// <summary>Stores pending changes now; false when the save failed (the change stays pending and is retried).</summary>
|
||||
public Task<bool> FlushAsync() => _saver.FlushAsync();
|
||||
|
||||
@@ -304,6 +376,40 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stored project is a newer Chronos's (<paramref name="newer"/>) while the editor holds an edit not stored yet,
|
||||
/// which this Chronos can neither merge with it nor store over it (<see cref="NewerSettingsException"/>): the edit is
|
||||
/// kept aside by the source (<see cref="ISequenceSource.SetAsideAsync"/>, said by <see cref="EditSetAside"/>), never
|
||||
/// dropped silently, and only then are the newer settings taken, read-only, the pending save dropped with it. A source
|
||||
/// that keeps nothing aside, or a set-aside that fails, leaves the editor as it is (logged): the next read tries again.
|
||||
/// Never throws.
|
||||
/// </summary>
|
||||
private async Task TakeNewerAsync(ProjectSettings newer, NewerSettingsException cause, CancellationToken cancellationToken)
|
||||
{
|
||||
var unsaved = Project;
|
||||
string? kept;
|
||||
try
|
||||
{
|
||||
kept = await Source.SetAsideAsync(unsaved, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet could not be kept aside; it stays in the editor", ex);
|
||||
return;
|
||||
}
|
||||
if (kept is null)
|
||||
{
|
||||
Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet meets newer settings and stays in the editor: {cause.Message}");
|
||||
return;
|
||||
}
|
||||
Log.Info("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet was kept in {kept}: the stored project is a newer Chronos's ({cause.Message})");
|
||||
_saver.Drop();
|
||||
Conflict = null;
|
||||
_basis = newer;
|
||||
History.Replace(newer);
|
||||
EditSetAside?.Invoke(kept);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new
|
||||
/// one under way until the returned source is completed.
|
||||
@@ -352,7 +458,9 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
|
||||
private void OnProjectChanged()
|
||||
{
|
||||
_saver.Schedule(Project);
|
||||
// A read-only project takes what is read again (a workspace pull of a newer Chronos's settings) without a save that
|
||||
// could never be stored and would be retried for ever.
|
||||
if (!IsReadOnly) _saver.Schedule(Project);
|
||||
ProjectChanged?.Invoke();
|
||||
}
|
||||
|
||||
@@ -405,7 +513,7 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
Conflict = null;
|
||||
_basis = stored;
|
||||
// Someone else's change was merged in: show it without an undo step (edits made since the save are kept).
|
||||
if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored));
|
||||
if (!ProjectMerge.SameValues(stored, project)) History.Replace(Source.Merge(project, Project, stored).Merged);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Diagnostics;
|
||||
@@ -89,6 +90,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
/// <summary>The user chose a step since the editor opened.</summary>
|
||||
private bool _stepChosen;
|
||||
|
||||
private Workspace.ProjectMenuViewModel? _project;
|
||||
private bool _disposed;
|
||||
|
||||
public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host)
|
||||
@@ -147,6 +149,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
session.ContentChanged += OnContentChanged;
|
||||
session.SaveFailed += OnSaveFailed;
|
||||
session.ConflictFound += OnConflictFound;
|
||||
session.EditSetAside += OnEditSetAside;
|
||||
session.Source.JobChanged += OnJobChanged;
|
||||
session.Source.ReadOnlyChanged += OnReadOnlyChanged;
|
||||
shell.Services.Sync.Changed += OnSyncChanged;
|
||||
@@ -175,6 +178,23 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
/// <summary>A server sequence edited with proxies (the header says where it lives).</summary>
|
||||
public bool IsRemote => Session.IsRemote;
|
||||
|
||||
/// <summary>
|
||||
/// The project menu beside the title (owner review 2, R8) when the sequence is open as a workspace project: its state,
|
||||
/// Save version, Sync, History and the rest; null otherwise (a server sequence, a capture's library sequence).
|
||||
/// </summary>
|
||||
public Workspace.ProjectMenuViewModel? Project
|
||||
{
|
||||
get => _project;
|
||||
internal set
|
||||
{
|
||||
_project?.Dispose();
|
||||
Set(ref _project, value);
|
||||
OnPropertyChanged(nameof(HasProject));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasProject => _project is not null;
|
||||
|
||||
/// <summary>The server a server sequence lives on ("Studio NAS"); null for a sequence of this PC.</summary>
|
||||
public string? ServerName => IsRemote ? Shell.Services.Server.ServerName ?? Loc.L("Server.Label.Server") : null;
|
||||
|
||||
@@ -462,7 +482,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
|
||||
/// <summary>Why the controls that change the project are disabled; null while they are not.</summary>
|
||||
public string? LockedToolTip => IsOutdated ? Loc.L("Tooltips.Editor.Outdated", ServerName)
|
||||
: IsReadOnly ? Loc.L("Tooltips.Editor.ReadOnly")
|
||||
: IsReadOnly ? Loc.L(Session.Source is WorkspaceSequenceSource ? "Errors.Workspace.ReadOnly" : "Tooltips.Editor.ReadOnly")
|
||||
: IsBusy ? Loc.L("Tooltips.Editor.Busy")
|
||||
: null;
|
||||
|
||||
@@ -706,11 +726,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
Session.ContentChanged -= OnContentChanged;
|
||||
Session.SaveFailed -= OnSaveFailed;
|
||||
Session.ConflictFound -= OnConflictFound;
|
||||
Session.EditSetAside -= OnEditSetAside;
|
||||
Session.Source.JobChanged -= OnJobChanged;
|
||||
Session.Source.ReadOnlyChanged -= OnReadOnlyChanged;
|
||||
Shell.Services.Sync.Changed -= OnSyncChanged;
|
||||
Shell.Services.SequenceReorganized -= OnSequenceReorganized;
|
||||
foreach (var tab in Tabs) tab.Dispose();
|
||||
_project?.Dispose();
|
||||
base.Dispose();
|
||||
await Session.DisposeAsync();
|
||||
}
|
||||
@@ -1034,17 +1056,43 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"): the
|
||||
/// dialog lists them; Keep mine overwrites the server's, Take server (the safe default, also on Esc) shows theirs as
|
||||
/// one undoable step. Saving waits until then.
|
||||
/// An edit not stored yet met a newer Chronos's settings a sync took (owner review 2, R8): it was kept aside in the
|
||||
/// project's folder, never dropped, and the toast says so; the newer settings show read-only.
|
||||
/// </summary>
|
||||
private void OnEditSetAside(string path) => _dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (_disposed) return;
|
||||
Shell.ShowToast(new Toast { Title = Loc.L("Editor.Workspace.EditSetAside"), Message = Loc.L("Editor.Workspace.EditSetAsideMessage") });
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"), or, for
|
||||
/// a workspace project, that a sync took from the library while the edit waited (owner review 2, R8): the dialog lists
|
||||
/// them; Keep mine overwrites the other side's, Take server or the library's (the safe default, also on Esc) shows theirs
|
||||
/// as one undoable step. Saving waits until then.
|
||||
/// </summary>
|
||||
private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (_disposed || Session.Conflict is null) return;
|
||||
var keepMine = Shell.Services.Dialogs.Confirm(ConflictRequest(conflict, Title, ServerName ?? string.Empty));
|
||||
var request = Session.Source is WorkspaceSequenceSource ? LibraryConflictRequest(conflict, Title) : ConflictRequest(conflict, Title, ServerName ?? string.Empty);
|
||||
var keepMine = Shell.Services.Dialogs.Confirm(request);
|
||||
if (!_disposed) Session.ResolveConflict(keepMine);
|
||||
});
|
||||
|
||||
/// <summary>The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps.</summary>
|
||||
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title) => new()
|
||||
{
|
||||
Heading = Loc.L("Editor.Workspace.Conflict.Title"),
|
||||
Message = Loc.L("Editor.Workspace.Edited.Message", title),
|
||||
Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10)),
|
||||
DetailToolTip = Loc.L("Tooltips.Editor.Workspace.Differences"),
|
||||
SafeText = Loc.L("Editor.Workspace.Conflict.TakeHome"),
|
||||
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.TakeHomeUndo"),
|
||||
ActionText = Loc.L("Server.Sync.Action.KeepMine"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.KeepMine"),
|
||||
IsDestructive = true,
|
||||
};
|
||||
|
||||
/// <summary>The conflict prompt: what differs (the editor's value, then the server's) and what each choice replaces.</summary>
|
||||
internal static ConfirmRequest ConflictRequest(ProjectConflictException conflict, string title, string server) => new()
|
||||
{
|
||||
@@ -1134,13 +1182,16 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done }) ClearVisited();
|
||||
// A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first.
|
||||
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
|
||||
// An analysis may have written its Auto values into the library's settings (Main): the project takes them or says so.
|
||||
if (job.State == JobState.Done && _project is { } project) _ = project.JobEndedAsync(job);
|
||||
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frames of the server sequence changed while it is open (any thread): everything that changes the project is
|
||||
/// disabled and says why, and a toast offers to fetch the proxies again.
|
||||
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's
|
||||
/// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
|
||||
/// server sequence, offering to fetch the proxies again).
|
||||
/// </summary>
|
||||
private void OnReadOnlyChanged() => _dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
@@ -1152,6 +1203,12 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
OnPropertyChanged(nameof(RenderChoiceToolTip));
|
||||
OnRenderStateChanged();
|
||||
OnBusyChanged();
|
||||
// A workspace project a sync turned read-only (a newer Chronos saved it): said once, the controls say why too.
|
||||
if (IsReadOnly && Session.Source is WorkspaceSequenceSource)
|
||||
{
|
||||
Shell.ShowToast(new Toast { Title = Loc.L("Editor.Workspace.ReadOnly"), Message = Loc.L("Errors.Workspace.ReadOnly") });
|
||||
return;
|
||||
}
|
||||
if (!IsOutdated) return;
|
||||
var (id, title) = (Session.Content.Sequence.Id, Title);
|
||||
Shell.ShowToast(new Toast
|
||||
|
||||
@@ -4,6 +4,7 @@ using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
@@ -34,6 +35,12 @@ public interface ISequenceSource : IAsyncDisposable
|
||||
/// </summary>
|
||||
bool IsOutdated { get; }
|
||||
|
||||
/// <summary>
|
||||
/// A change stored meanwhile by someone else to settings the editor changed too is asked about
|
||||
/// (<see cref="ProjectConflictException"/>), never merged over the editor's: a server sequence, a workspace project.
|
||||
/// </summary>
|
||||
bool AsksConflicts => IsRemote;
|
||||
|
||||
/// <summary><see cref="IsReadOnly"/> changed (any thread).</summary>
|
||||
event Action? ReadOnlyChanged;
|
||||
|
||||
@@ -67,6 +74,20 @@ public interface ISequenceSource : IAsyncDisposable
|
||||
/// <exception cref="EditorException">The editor's own reason the project was not stored, worded for the user.</exception>
|
||||
Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The three-way merge of the editor's projects, all three naming this source's frames (<see cref="ProjectMerge"/>): member
|
||||
/// by member, a member both sides changed listed as a conflict and settled for <paramref name="ours"/>. A workspace
|
||||
/// project merges its frame positions photo by photo, as its sync does.
|
||||
/// </summary>
|
||||
ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs);
|
||||
|
||||
/// <summary>
|
||||
/// Keeps <paramref name="unsaved"/>, an edit that can no longer be stored (the stored project became a newer Chronos's,
|
||||
/// which this one never merges with), where the user finds it and nothing sends it; returns where, or null when this
|
||||
/// source keeps nothing aside (the edit then stays in the editor as it is).
|
||||
/// </summary>
|
||||
Task<string?> SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
|
||||
|
||||
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
|
||||
Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Chronos.Data.Projects;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Advice;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Sections;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
@@ -36,7 +37,10 @@ public sealed class ProjectFiles(ShellViewModel shell)
|
||||
/// <summary>
|
||||
/// Opens the project file at <paramref name="path"/>: its sequence in the editor (found by id, else by archive and
|
||||
/// folder), then the file's settings as one undo step. Says in one sentence why when the file cannot be read, its
|
||||
/// sequence is not in the library, or the sequence cannot take the settings now.
|
||||
/// sequence is not in the library, or the sequence cannot take the settings now. With the workspace (owner review 2,
|
||||
/// R8), a file of format 2 opens its project there (a workspace's own <c>project.chronos</c> as it is; a copy of one
|
||||
/// gives that project its settings), and a file of format 1 gives its settings to the sequence's Main project, which
|
||||
/// opens in the workspace (copied first when it is not there yet).
|
||||
/// </summary>
|
||||
public async Task OpenAsync(string path)
|
||||
{
|
||||
@@ -53,16 +57,30 @@ public sealed class ProjectFiles(ShellViewModel shell)
|
||||
return;
|
||||
}
|
||||
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
if (await ProjectBundles.ResolveAsync(db, bundle) is not { } sequence)
|
||||
var home = bundle.Workspace is { Home: { IsArchive: true } h } ? await db.Sequences.GetAsync(h.SequenceId) : null;
|
||||
if ((home ?? await ProjectBundles.ResolveAsync(db, bundle)) is not { } sequence)
|
||||
{
|
||||
Log.Info("project", $"Project file '{path}': sequence {bundle.Sequence.Id} ('{bundle.Sequence.Folder}' in archive {bundle.Archive.Id}) not in the index");
|
||||
shell.Notify(Loc.L("Editor.ProjectFile.NotFound"), bundle.Sequence.Title ?? Path.GetFileName(path), Loc.L("Shell.Nav.Archive"),
|
||||
Loc.L("Tooltips.Nav.Archive"), () => shell.Navigate(SectionKey.Archive), isError: true);
|
||||
return;
|
||||
}
|
||||
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
|
||||
if (await shell.Sequence.ShowAsync(sequence.Id) is not { } editor) return;
|
||||
Apply(editor, bundle);
|
||||
if (!shell.Services.Workspace.IsEnabled)
|
||||
{
|
||||
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
|
||||
if (await shell.Sequence.ShowAsync(sequence.Id) is { } editor) Apply(editor, bundle);
|
||||
return;
|
||||
}
|
||||
if (bundle.Workspace is { } workspace)
|
||||
{
|
||||
// A workspace's own working state opens as it is; a copy of one (saved elsewhere, another PC's) gives its project its settings.
|
||||
var own = shell.Services.Workspace.Store.Find(workspace.ProjectId) is { } project
|
||||
&& string.Equals(Path.GetFullPath(project.BundlePath), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
|
||||
await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle));
|
||||
return;
|
||||
}
|
||||
// Format 1: the settings go to the sequence's Main project, once it is open (now, or after its copy into the workspace).
|
||||
await shell.Sequence.ShowAsync(sequence.Id, ProjectRequest.MainOf(sequence.Id), editor => Apply(editor, bundle));
|
||||
}
|
||||
|
||||
/// <summary>Gives the open sequence the file's settings, unless the editor cannot change them now (a job runs, read-only).</summary>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
@@ -8,7 +9,11 @@ namespace Chronos.App.Editor;
|
||||
/// <see cref="EndRun"/> (the drag or key press ended); any other edit, undo or redo also ends the run. The oldest steps
|
||||
/// are dropped beyond <see cref="Capacity"/>.
|
||||
/// </summary>
|
||||
public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
|
||||
/// <param name="merge">
|
||||
/// The three-way merge (basis, ours, theirs) that gives each step an outside change (<see cref="Replace"/>): the source's,
|
||||
/// which merges a workspace project's frame positions photo by photo; <see cref="ProjectMerge.Merge"/> when null.
|
||||
/// </param>
|
||||
public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200, Func<ProjectSettings, ProjectSettings, ProjectSettings, ProjectSettings>? merge = null)
|
||||
{
|
||||
private readonly LinkedList<ProjectSettings> _undo = new();
|
||||
private readonly LinkedList<ProjectSettings> _redo = new();
|
||||
@@ -64,13 +69,25 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
|
||||
/// <summary>
|
||||
/// Adopts a project changed outside the editor (analysis advice, another client's edit merged on save) without an
|
||||
/// undo step. Every undo and redo snapshot takes the same outside change, so undo reverts only the user's own steps
|
||||
/// and never brings back a value that predates the adopted change.
|
||||
/// and never brings back a value that predates the adopted change. Settings of a newer Chronos on either side (a pull
|
||||
/// took them: the project is shown read-only) are never merged with this one's (<see cref="ProjectMerge"/>), so no step
|
||||
/// can take that change: the undo and redo steps go instead, and undo never brings back values from before it.
|
||||
/// </summary>
|
||||
public void Replace(ProjectSettings current)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(current);
|
||||
if (ProjectMerge.SameValues(current, Current)) return;
|
||||
var rebase = new ProjectMerge.Rebase(Current, current);
|
||||
if (current.IsNewerFormat || Current.IsNewerFormat || _undo.Any(s => s.IsNewerFormat) || _redo.Any(s => s.IsNewerFormat))
|
||||
{
|
||||
_undo.Clear();
|
||||
_redo.Clear();
|
||||
_runKey = null;
|
||||
Current = current;
|
||||
Changed?.Invoke();
|
||||
return;
|
||||
}
|
||||
var (basis, theirs) = (Current, current);
|
||||
Func<ProjectSettings, ProjectSettings> rebase = merge is null ? new ProjectMerge.Rebase(basis, theirs).Apply : step => merge(basis, step, theirs);
|
||||
Rebase(_undo, rebase);
|
||||
Rebase(_redo, rebase);
|
||||
_runKey = null;
|
||||
@@ -97,9 +114,9 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private static void Rebase(LinkedList<ProjectSettings> steps, ProjectMerge.Rebase rebase)
|
||||
private static void Rebase(LinkedList<ProjectSettings> steps, Func<ProjectSettings, ProjectSettings> rebase)
|
||||
{
|
||||
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value);
|
||||
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase(node.Value);
|
||||
}
|
||||
|
||||
private bool Move(ProjectSettings target)
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
|
||||
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server), both made from <c>basis</c>.
|
||||
/// Values are compared member by member down the JSON tree; a member only one side changed takes that side's value, a
|
||||
/// member both changed takes the editor's (the user is looking at it). <see cref="Conflicts"/> lists those members for
|
||||
/// a source that asks the user instead (a server sequence, BRIEF §14.5).
|
||||
/// </summary>
|
||||
public static class ProjectMerge
|
||||
{
|
||||
public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
ArgumentNullException.ThrowIfNull(theirs);
|
||||
return new Rebase(basis, theirs).Apply(ours);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The members both sides changed to different values, in document order: the path below the project
|
||||
/// ("exposure.deflickerWindow.manual"), the editor's value and theirs as JSON (null when absent).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<SettingsDifference> Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
ArgumentNullException.ThrowIfNull(theirs);
|
||||
var conflicts = new List<SettingsDifference>();
|
||||
Collect(JsonNode.Parse(basis.ToJson()), JsonNode.Parse(ours.ToJson()), JsonNode.Parse(theirs.ToJson()), string.Empty, conflicts);
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
/// <summary>True when both projects store the same values.</summary>
|
||||
public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson();
|
||||
|
||||
private static JsonNode? Merge(JsonNode? basis, JsonNode? ours, JsonNode? theirs)
|
||||
{
|
||||
if (JsonNode.DeepEquals(ours, basis)) return theirs?.DeepClone();
|
||||
if (JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return ours?.DeepClone();
|
||||
if (ours is not JsonObject mine || theirs is not JsonObject other) return ours?.DeepClone();
|
||||
var common = basis as JsonObject;
|
||||
var merged = new JsonObject();
|
||||
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
|
||||
{
|
||||
var value = Merge(common?[name], mine[name], other[name]);
|
||||
if (value is not null || mine.ContainsKey(name)) merged[name] = value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/// <summary>The members <see cref="Merge(JsonNode?, JsonNode?, JsonNode?)"/> settles for the editor although both sides changed them.</summary>
|
||||
private static void Collect(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List<SettingsDifference> conflicts)
|
||||
{
|
||||
if (JsonNode.DeepEquals(ours, basis) || JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return;
|
||||
if (ours is JsonObject mine && theirs is JsonObject other)
|
||||
{
|
||||
var common = basis as JsonObject;
|
||||
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
|
||||
Collect(common?[name], mine[name], other[name], path.Length == 0 ? name : path + "." + name, conflicts);
|
||||
return;
|
||||
}
|
||||
conflicts.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, ours?.ToJsonString(), theirs?.ToJsonString()));
|
||||
}
|
||||
|
||||
/// <summary>One outside change (<paramref name="basis"/> → <paramref name="theirs"/>) applied to any number of projects made from the basis.</summary>
|
||||
public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs)
|
||||
{
|
||||
private readonly JsonNode? _basis = JsonNode.Parse(basis.ToJson());
|
||||
private readonly JsonNode? _theirs = JsonNode.Parse(theirs.ToJson());
|
||||
|
||||
public ProjectSettings Apply(ProjectSettings ours)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
return ProjectSettings.FromJson(Merge(_basis, JsonNode.Parse(ours.ToJson()), _theirs)?.ToJsonString() ?? "{}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,9 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
|
||||
private bool _flushRequested;
|
||||
private bool _stopped;
|
||||
private int _failures;
|
||||
|
||||
/// <summary>Changes dropped (<see cref="Drop"/>): a write that fails after one is not retried.</summary>
|
||||
private int _drops;
|
||||
private CancellationTokenSource? _wait;
|
||||
|
||||
/// <summary>No write starts until <see cref="Release"/> (or <see cref="Stop"/>): the user is being asked about the pending change.</summary>
|
||||
@@ -103,6 +106,22 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
|
||||
lock (_gate) ReleaseHold();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drops what is pending, a write under way included should it fail, and keeps saving what is scheduled from now on: the
|
||||
/// change was kept elsewhere (set aside when the stored project became a newer Chronos's, where it can never be stored).
|
||||
/// </summary>
|
||||
public void Drop()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_pending = null;
|
||||
_drops++;
|
||||
_failures = 0;
|
||||
LastError = null;
|
||||
_wait?.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops what is pending and stops retrying (the editor closed and the user chose to discard the change).</summary>
|
||||
public void Stop()
|
||||
{
|
||||
@@ -153,8 +172,10 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
|
||||
continue;
|
||||
}
|
||||
ProjectSettings next;
|
||||
int drops;
|
||||
lock (_gate)
|
||||
{
|
||||
drops = _drops;
|
||||
_flushRequested = false;
|
||||
if (_pending is null)
|
||||
{
|
||||
@@ -184,9 +205,16 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastError = ex;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_drops != drops)
|
||||
{
|
||||
// Dropped while it was written (kept elsewhere): not retried, and no failure to report.
|
||||
EndWrite();
|
||||
wait = TimeSpan.Zero;
|
||||
continue;
|
||||
}
|
||||
LastError = ex;
|
||||
// A newer change contains this one (projects are whole snapshots); otherwise this one waits for the retry.
|
||||
if (!_stopped) _pending ??= next;
|
||||
failures = ++_failures;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Chronos.Data.Projects;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>A source whose renders are made otherwise than from the project as the editor holds it (a workspace project: at its home).</summary>
|
||||
public interface IProjectRenders
|
||||
{
|
||||
/// <summary>The jobs that render <paramref name="export"/> of <paramref name="project"/> (the editor's settings, positions on the source's frames).</summary>
|
||||
IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A workspace project open in the editor (owner review 2, R8: editing happens in the workspace, never inside the
|
||||
/// library): the frames and pixels of the media the workspace holds (<c>media/media.json</c>, the proxies), the project
|
||||
/// from its working state (<c>project.chronos</c>, positions placed on those frames), saved there atomically under the
|
||||
/// project's lease and merged against the basis like <see cref="LocalSequenceSource"/> (a pull or a copy job writes it
|
||||
/// too): frame positions photo by photo as the sync merges them (<see cref="Merge"/>), and settings the editor changed to
|
||||
/// other values than those stored meanwhile asked about (<see cref="ProjectConflictException"/>), never decided for the
|
||||
/// editor. A pull that brings a newer Chronos's settings turns it read-only (<see cref="ReadOnlyChanged"/>). Jobs run on
|
||||
/// this PC's engine against the home's sequence (same id): an analysis reads the home's originals, a
|
||||
/// render renders the home's originals with the project's portable settings and records the project and the version
|
||||
/// (<see cref="RenderRequests"/>). The deep report is the home's while its frames are the media's, else the copy the
|
||||
/// workspace took. A copy job that changed the media (Update media) makes saves made against the frames read before refused
|
||||
/// (<see cref="FramesChangedException"/>) until the editor has read them again and moved its positions by frame.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
|
||||
{
|
||||
private const int JobsListed = 200;
|
||||
|
||||
private readonly WorkspaceSync _sync;
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly ImageDecoder _decoder;
|
||||
private readonly JobEngine? _engine;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<IRenderFrameSource> _retired = [];
|
||||
private IRenderFrameSource? _frames;
|
||||
private IFrameSource? _pixels;
|
||||
private int _frameCount;
|
||||
private int _framesVersion = -1;
|
||||
private Guid[] _frameIds = [];
|
||||
private FramePhotos _photos = new([]);
|
||||
private BundleWorkspace? _workspace;
|
||||
private bool _readOnly;
|
||||
private int _disposed;
|
||||
|
||||
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sync);
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
_sync = sync;
|
||||
_db = db;
|
||||
_decoder = decoder;
|
||||
_engine = engine;
|
||||
ProjectId = projectId;
|
||||
if (engine is not null) engine.JobChanged += OnJobChanged;
|
||||
}
|
||||
|
||||
public Guid ProjectId { get; }
|
||||
|
||||
/// <summary>The project's folder in the workspace.</summary>
|
||||
public WorkspaceProject Project => _sync.Store.Project(ProjectId);
|
||||
|
||||
/// <summary>The workspace section of the project file as read last (name, Main, home, base, media); null before the first read.</summary>
|
||||
public BundleWorkspace? Workspace => Volatile.Read(ref _workspace);
|
||||
|
||||
/// <summary>The frames version of the home the media read last were copied at; -1 before the first read.</summary>
|
||||
public int MediaFramesVersion => Volatile.Read(ref _framesVersion);
|
||||
|
||||
/// <summary>The photos of the media read last, in frame order (what positions name).</summary>
|
||||
public FramePhotos Photos => Volatile.Read(ref _photos);
|
||||
|
||||
public bool IsRemote => false;
|
||||
|
||||
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
|
||||
public bool IsReadOnly => Volatile.Read(ref _readOnly);
|
||||
|
||||
public bool IsOutdated => false;
|
||||
|
||||
/// <summary>The library's values and the editor's are asked about where both changed a setting, as a sync asks.</summary>
|
||||
public bool AsksConflicts => true;
|
||||
|
||||
/// <summary>The working state read again holds a newer Chronos's settings (a pull took them), or no longer does.</summary>
|
||||
public event Action? ReadOnlyChanged;
|
||||
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
/// <exception cref="EditorException">
|
||||
/// The workspace holds no media for the project (copy them again), the project is gone, or a sync or a copy kept it for
|
||||
/// longer than the sync waits (<see cref="WorkspaceSync.LockWait"/>).
|
||||
/// </exception>
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
WorkspaceSession session;
|
||||
try
|
||||
{
|
||||
session = await _sync.OpenAsync(ProjectId, cancellationToken);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
throw new EditorException(Loc.L("Errors.Workspace.NotCheckedOut"), ex);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
|
||||
}
|
||||
catch (LeaseUnavailableException ex)
|
||||
{
|
||||
// A long sync or copy holds the project: nothing was read, opening it again later reads it whole.
|
||||
Log.Info("editor", $"Workspace project {ProjectId} is busy: {ex.Message}");
|
||||
throw new EditorException(Loc.L("Errors.Workspace.Busy"), ex);
|
||||
}
|
||||
if (session is not { Sequence: { } media, Media: { } index }) throw new EditorException(Loc.L("Errors.Workspace.MediaMissing"));
|
||||
var home = session.Bundle.Workspace!.Home;
|
||||
var row = await _db.Sequences.GetAsync(home.SequenceId, cancellationToken);
|
||||
var archive = row is null ? null : await _db.Archives.GetAsync(row.ArchiveId, cancellationToken);
|
||||
IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var frames = media.Frames;
|
||||
Swap(media, index, session.Bundle.Workspace!, session.IsReadOnly);
|
||||
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
|
||||
// The home's row (camera, interval, tags) with the frames this workspace holds.
|
||||
var sequence = (row ?? media.Sequence) with
|
||||
{
|
||||
FrameCount = frames.Count,
|
||||
FramesVersion = index.FramesVersion,
|
||||
FirstCapture = times.Count > 0 ? times[0] : null,
|
||||
LastCapture = times.Count > 0 ? times[^1] : null,
|
||||
SettingsJson = session.Working.ToJson(),
|
||||
};
|
||||
var folder = archive is null ? null : new ArchivePaths(archive.RootPath).Sequence(row!.Folder);
|
||||
var (deep, otherFrames) = ReadReport(folder, row?.FramesVersion == index.FramesVersion, session.Project.AnalysisPath, frames.Count);
|
||||
var context = SequenceContext.FromFrames(frames);
|
||||
return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight,
|
||||
folder?.Exports, [.. renders.OrderByDescending(r => r.Created)], [])
|
||||
{
|
||||
DeepOfOtherFrames = otherFrames,
|
||||
};
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <remarks>Only a copy job changes the workspace's frames (Update media): its media index is compared with the one read last.</remarks>
|
||||
public Task<bool> FramesCurrentAsync(CancellationToken cancellationToken) => Task.Run(() =>
|
||||
{
|
||||
var (framesVersion, ids) = (Volatile.Read(ref _framesVersion), Volatile.Read(ref _frameIds));
|
||||
try
|
||||
{
|
||||
return Project.ReadMedia() is { } media && media.FramesVersion == framesVersion && media.Frames.Select(f => f.Id).SequenceEqual(ids);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Log.Warning("editor", $"The media index of workspace project {ProjectId} cannot be read", ex);
|
||||
return false;
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>Whether the home's frames moved past those the workspace holds (frames added or removed there): "Update media" copies them again.</summary>
|
||||
public async Task<bool> HomeFramesChangedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Workspace is not { } workspace || MediaFramesVersion < 0) return false;
|
||||
return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion;
|
||||
}
|
||||
|
||||
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
IFrameSource? pixels;
|
||||
int count;
|
||||
lock (_gate) (pixels, count) = (_pixels, _frameCount);
|
||||
if (pixels is null || (uint)index >= (uint)count) return null;
|
||||
// The loader decodes synchronously: an async delegate keeps a superseded decode's cancellation in user code (R4).
|
||||
return await Task.Run(async () => await pixels.LoadAsync(index, maxLongEdge, cancellationToken).ConfigureAwait(false), cancellationToken);
|
||||
}
|
||||
|
||||
/// <exception cref="EditorException">The project is read-only, or its media are gone.</exception>
|
||||
/// <exception cref="FramesChangedException">The media changed since they were read (a copy job): read them again first.</exception>
|
||||
/// <exception cref="ProjectConflictException">
|
||||
/// The working state stored meanwhile (a sync took the library's versions) holds other values of settings this edit
|
||||
/// changed too: nothing is stored until the user keeps theirs or takes the library's.
|
||||
/// </exception>
|
||||
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
var framesVersion = Volatile.Read(ref _framesVersion);
|
||||
if (framesVersion < 0) throw new InvalidOperationException("LoadAsync first.");
|
||||
var folder = Project;
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
using (await folder.LockAsync(_sync.LockWait, cancellationToken))
|
||||
{
|
||||
var bundle = folder.ReadBundle();
|
||||
if (bundle.IsReadOnly || project.IsNewerFormat) throw new EditorException(Loc.L("Errors.Workspace.ReadOnly"));
|
||||
var media = folder.ReadMedia() ?? throw new EditorException(Loc.L("Errors.Workspace.MediaMissing"));
|
||||
// A copy job moved the working state onto other frames: the editor reads them and moves its positions first.
|
||||
if (media.FramesVersion != framesVersion) throw new FramesChangedException(Loc.L("Errors.Workspace.MediaChanged"));
|
||||
var stored = ProjectSettings.FromJson(ProjectContent.Place(bundle.Project.ToJson(), media.Photos), allowNewer: true);
|
||||
var merged = project;
|
||||
if (!ProjectMerge.SameValues(stored, basis))
|
||||
{
|
||||
var merge = Merge(basis, project, stored, media.Photos);
|
||||
if (merge.HasConflicts) throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, merge.Conflicts);
|
||||
merged = merge.Merged;
|
||||
}
|
||||
if (ProjectMerge.SameValues(merged, stored)) return merged;
|
||||
folder.WriteBundle(bundle with { Project = merged, Saved = DateTimeOffset.UtcNow });
|
||||
return merged;
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The editor's merges as the sync merges (owner review 2, R8): member by member, and frame positions photo by photo and
|
||||
/// flag by flag in the portable form, so an exclusion or a keyframe a sync wrote meanwhile stays beside the editor's own
|
||||
/// (positional arrays would take one side whole). All three name the frames of the media read last.
|
||||
/// </summary>
|
||||
public ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => Merge(basis, ours, theirs, Photos);
|
||||
|
||||
private static ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, FramePhotos photos)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
ArgumentNullException.ThrowIfNull(theirs);
|
||||
var merge = ProjectMerge.MergeWithConflicts(basis, ours, theirs);
|
||||
// Positions only one side moved, or none, merge alike either way; the portable form is needed where both did.
|
||||
if (photos.Count == 0 || !merge.Conflicts.Any(c => NamesPosition(c.Path)) || basis.IsNewerFormat || ours.IsNewerFormat || theirs.IsNewerFormat) return merge;
|
||||
var portable = ProjectMerge.MergeWithConflicts(Portable(basis, photos), Portable(ours, photos), Portable(theirs, photos));
|
||||
var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(portable.Merged.ToJson()), photos), allowNewer: true);
|
||||
return portable with { Merged = placed };
|
||||
|
||||
static ProjectSettings Portable(ProjectSettings settings, FramePhotos photos) =>
|
||||
ProjectSettings.FromJson(ProjectContent.ToPortable(settings, photos), allowNewer: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps an edit the working state can no longer take (a sync brought a newer Chronos's settings) as a version file in
|
||||
/// <c>versions/.replaced</c>, where a take of the library's values keeps the working state it replaces: outside the chain
|
||||
/// of versions, so it is never sent, and never lost. Written under the project's lease, its positions parked by photo.
|
||||
/// </summary>
|
||||
/// <exception cref="Core.Archiving.LeaseUnavailableException">Another writer kept the project for longer than the sync waits.</exception>
|
||||
public Task<string?> SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unsaved);
|
||||
var folder = Project;
|
||||
var (photos, framesVersion, basis) = (Photos, MediaFramesVersion, Workspace?.Base);
|
||||
return Task.Run<string?>(async () =>
|
||||
{
|
||||
using (await folder.LockAsync(_sync.LockWait, cancellationToken))
|
||||
{
|
||||
var portable = ProjectContent.ToPortable(unsaved, photos);
|
||||
var version = new ProjectVersion
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ProjectId = ProjectId,
|
||||
ParentId = basis?.VersionId,
|
||||
Number = (basis?.Number ?? 0) + 1,
|
||||
Kind = ProjectVersionKind.Commit,
|
||||
ClientName = Environment.MachineName,
|
||||
SettingsJson = portable,
|
||||
ContentHash = ProjectContent.Hash(portable),
|
||||
SettingsFormat = ProjectContent.FormatOf(portable),
|
||||
FramesVersion = Math.Max(0, framesVersion),
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
var path = Path.Combine(folder.VersionsDirectory, WorkspaceProject.ReplacedFolder, Path.GetFileName(folder.VersionPath(version)));
|
||||
ProjectSidecars.WriteVersion(path, version);
|
||||
return path;
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A merge path of a frame position (an exclusion, the hero, a camera keyframe, a frame waiting for its photo).</summary>
|
||||
private static bool NamesPosition(string path) =>
|
||||
path is "excludedFrames" or "heroFrame" || path.StartsWith("camera.keyframes", StringComparison.Ordinal) || path.StartsWith("pendingFrames", StringComparison.Ordinal);
|
||||
|
||||
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken);
|
||||
return job.Id;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) =>
|
||||
(await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
|
||||
|
||||
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) =>
|
||||
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
|
||||
|
||||
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) =>
|
||||
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job of this PC's
|
||||
/// engine per preset, with the project's portable settings (positions parked by photo, placed on the home's frames by
|
||||
/// the render) and the project recorded on the render; the version too when the settings are those of the last
|
||||
/// version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is, without a version).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
|
||||
var hash = ProjectContent.Hash(portable);
|
||||
var (tipId, tipHash) = Tip();
|
||||
var version = new ProjectVersion
|
||||
{
|
||||
Id = tipId ?? Guid.Empty,
|
||||
ProjectId = ProjectId,
|
||||
Number = 0,
|
||||
SettingsJson = portable,
|
||||
ContentHash = hash,
|
||||
};
|
||||
var requests = ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight);
|
||||
if (tipId is not null && string.Equals(tipHash, hash, StringComparison.OrdinalIgnoreCase)) return requests;
|
||||
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
List<IRenderFrameSource> sources;
|
||||
lock (_gate)
|
||||
{
|
||||
sources = [.. _retired];
|
||||
if (_frames is not null) sources.Add(_frames);
|
||||
_retired.Clear();
|
||||
(_frames, _pixels) = (null, null);
|
||||
}
|
||||
foreach (var source in sources)
|
||||
{
|
||||
if (source is IAsyncDisposable disposable) await disposable.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the media read now: a frame source over them when they differ from those read before (the old one is disposed
|
||||
/// with this source, as a decode may still read it), their frames and photos, the project's workspace section, and
|
||||
/// whether the settings are a newer Chronos's (said by <see cref="ReadOnlyChanged"/> when that changed).
|
||||
/// </summary>
|
||||
private void Swap(WorkspaceSequence media, WorkspaceMedia index, BundleWorkspace workspace, bool readOnly)
|
||||
{
|
||||
var ids = media.Frames.Select(f => f.Id).ToArray();
|
||||
bool changed;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_frames is null || index.FramesVersion != _framesVersion || !ids.AsSpan().SequenceEqual(_frameIds))
|
||||
{
|
||||
if (_frames is not null) _retired.Add(_frames);
|
||||
_frames = media.OpenFrames(_decoder);
|
||||
_pixels = (IFrameSource)_frames;
|
||||
_frameCount = media.Frames.Count;
|
||||
}
|
||||
_frameIds = ids;
|
||||
_framesVersion = index.FramesVersion;
|
||||
_photos = index.Photos;
|
||||
_workspace = workspace;
|
||||
changed = _readOnly != readOnly;
|
||||
_readOnly = readOnly;
|
||||
}
|
||||
if (changed) ReadOnlyChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The version a render may name, with its content hash: the base, which the home holds, while no version waits to be
|
||||
/// sent; none otherwise. A version not sent yet may never reach the home under its id (a replay or a save-both sends it
|
||||
/// under another), so a render of it names the project alone.
|
||||
/// </summary>
|
||||
private (Guid? Id, string? Hash) Tip()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_sync.Unpushed(ProjectId).Count > 0) return (null, null);
|
||||
return Project.ReadBundle().Workspace?.Base is { } basis ? (basis.VersionId, basis.ContentHash) : (null, null);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static string? WithoutVersion(string? parametersJson)
|
||||
{
|
||||
if (parametersJson is null || JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters) is not { } parameters) return parametersJson;
|
||||
return JsonSerializer.Serialize(parameters with { ProjectVersionId = null }, ProtocolJson.Default.RenderJobParameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The deep report the editor shows: the home's while its frames are the workspace's, else the copy the workspace took;
|
||||
/// whether one of another number of frames was read instead.
|
||||
/// </summary>
|
||||
private static (DeepAnalysisReport? Report, bool OtherFrames) ReadReport(SequencePaths? home, bool sameFrames, string copied, int frameCount)
|
||||
{
|
||||
var otherFrames = false;
|
||||
foreach (var path in new[] { sameFrames ? home?.AnalysisPath : null, copied })
|
||||
{
|
||||
if (path is null || !File.Exists(path)) continue;
|
||||
try
|
||||
{
|
||||
var report = DeepAnalysisReport.Load(path);
|
||||
if (report.FrameCount == frameCount) return (report, false);
|
||||
otherFrames = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("editor", $"{path} cannot be read", ex);
|
||||
}
|
||||
}
|
||||
return (null, otherFrames);
|
||||
}
|
||||
|
||||
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ using Chronos.App.Jobs;
|
||||
using Chronos.App.Library;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
@@ -23,6 +24,7 @@ using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
@@ -71,6 +73,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
|
||||
Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine);
|
||||
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
|
||||
Encoders = new MediaFoundationInventory();
|
||||
Formats = new WicFormatInventory(() => _wic);
|
||||
@@ -117,6 +120,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// </summary>
|
||||
public event Action<Guid>? SequenceReorganized;
|
||||
|
||||
/// <summary>The workspace where Edit opens projects (owner review 2, R8), with this PC's archive as their home.</summary>
|
||||
public WorkspaceHost Workspace { get; }
|
||||
|
||||
public IEncoderInventory Encoders { get; set; }
|
||||
|
||||
/// <summary>Decode tier per format on this PC and the missing codec extensions (Settings › Formats).</summary>
|
||||
@@ -169,11 +175,12 @@ public sealed class AppServices : IAsyncDisposable
|
||||
typeof(AppServices).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
|
||||
/// queued (it is never claimed here).</summary>
|
||||
/// queued (it is never claimed here). The workspace copy is the desktop's alone: it writes into this PC's workspace.</summary>
|
||||
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
|
||||
[
|
||||
.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
|
||||
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
|
||||
.. services.Database is { } db && services.Archives is { } archives ? WorkspaceJobs.CreateHandlers(db, archives) : [],
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -57,6 +57,7 @@ public sealed class AppSettings
|
||||
public const int DefaultThumbnailMemoryItems = 2_000;
|
||||
public const int DefaultCacheLimitGb = 20;
|
||||
public const int DefaultScanIntervalMinutes = 10;
|
||||
public const int DefaultWorkspaceKeptVersions = 20;
|
||||
|
||||
/// <summary>2⁻⁴ of white: the deep analysis' night threshold (a mean log2 luminance of −4).</summary>
|
||||
public const double DefaultNightBrightnessPercent = 6.25;
|
||||
@@ -155,6 +156,19 @@ public sealed class AppSettings
|
||||
/// <summary>Upper bound of the disk cache in GB.</summary>
|
||||
public int CacheLimitGb { get; set; } = DefaultCacheLimitGb;
|
||||
|
||||
// ---- Workspace (owner review 2, R8) ----
|
||||
/// <summary>The workspace, where projects are edited outside the library; null = <c>workspace</c> under the data folder.</summary>
|
||||
public string? WorkspaceFolder { get; set; }
|
||||
|
||||
/// <summary>A version saved in the workspace is sent to its home at once (and the home's new versions taken).</summary>
|
||||
public bool WorkspaceAutoSync { get; set; } = true;
|
||||
|
||||
/// <summary>Versions taken from a home that a workspace project keeps besides its base and the versions not sent yet.</summary>
|
||||
public int WorkspaceKeptVersions { get; set; } = DefaultWorkspaceKeptVersions;
|
||||
|
||||
/// <summary>The workspace project opened last for each sequence (sequence id → project id); Edit opens it again.</summary>
|
||||
public Dictionary<Guid, Guid> WorkspaceRecent { get; set; } = [];
|
||||
|
||||
// ---- Server ----
|
||||
public string? ServerUrl { get; set; }
|
||||
public string? ServerUsername { get; set; }
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:lib="clr-namespace:Chronos.App.Library"
|
||||
xmlns:ws="clr-namespace:Chronos.App.Workspace"
|
||||
IsVisibleChanged="OnVisibleChanged">
|
||||
<!--
|
||||
The sequence picker of Edit (owner review 1, R7), over the section's view model: one searchable list of this PC's and
|
||||
the server's sequences, newest first; Enter or a double-click opens one, Esc clears the search and then goes back to
|
||||
the open sequence. Each row reads as its title to screen readers; the date, frames and states columns are as wide as
|
||||
their widest row, so the states are never cut.
|
||||
The sequence picker of Edit (owner review 1, R7), over the section's view model: the workspace's projects (owner review
|
||||
2, R8), then one searchable list of this PC's and the server's sequences, newest first; Enter or a double-click opens
|
||||
one, Esc clears the search and then goes back to the open sequence. Each row reads as its title (a project: its name,
|
||||
sequence and state) to screen readers; the date, frames and states columns are as wide as their widest row, so the
|
||||
states are never cut.
|
||||
-->
|
||||
<UserControl.Resources>
|
||||
<DataTemplate x:Key="Template.Status" DataType="{x:Type v:CardStatus}">
|
||||
@@ -24,6 +26,11 @@
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
|
||||
<EventSetter Event="MouseDoubleClick" Handler="OnRowDoubleClick" />
|
||||
</Style>
|
||||
<!-- A project of the workspace reads as its name, its sequence and where it stands. -->
|
||||
<Style x:Key="ListBoxItem.ProjectRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Description}" />
|
||||
<EventSetter Event="MouseDoubleClick" Handler="OnProjectDoubleClick" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Border Style="{StaticResource Border.Panel}" MaxWidth="880" Margin="16,24,16,16">
|
||||
@@ -57,49 +64,99 @@
|
||||
<ProgressBar Grid.Row="2" Margin="16,0" Height="6" IsIndeterminate="True" Visibility="{Binding Picker.IsLoading, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.Name="{l:Loc Editor.Picker.Loading}" />
|
||||
|
||||
<ListBox x:Name="List" Grid.Row="3" Margin="0,4,0,8" ItemsSource="{Binding Picker.Items}" SelectedItem="{Binding Picker.Selected}" SelectionMode="Single"
|
||||
ItemContainerStyle="{StaticResource ListBoxItem.PickerRow}" TextSearch.TextPath="Title" VirtualizingPanel.IsVirtualizing="True"
|
||||
VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
ScrollViewer.ScrollChanged="OnScrollChanged" AutomationProperties.Name="{l:Loc Editor.Picker.List}" ToolTip="{l:Loc Tooltips.Editor.Picker.Row}"
|
||||
KeyboardNavigation.TabNavigation="Continue" Grid.IsSharedSizeScope="True" SelectionChanged="OnSelectionChanged">
|
||||
<ListBox.InputBindings>
|
||||
<KeyBinding Key="Enter" Command="{Binding Picker.OpenCommand}" />
|
||||
</ListBox.InputBindings>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type lib:SequenceItem}">
|
||||
<Grid Height="40">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="2*" MinWidth="140" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="84" SharedSizeGroup="PickerDate" />
|
||||
<ColumnDefinition Width="*" MinWidth="80" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="56" SharedSizeGroup="PickerFrames" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="PickerStates" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<!-- Pictures stay left to right in a right-to-left window. -->
|
||||
<Border Width="64" Height="36" CornerRadius="4" Background="{DynamicResource Brush.Card}" ClipToBounds="True" FlowDirection="LeftToRight"
|
||||
lib:ThumbnailLoading.Width="64">
|
||||
<Image Source="{Binding Thumbnail}" Stretch="UniformToFill" />
|
||||
</Border>
|
||||
<!-- Cells that may be shortened show their text in their tooltip (an empty camera has none). -->
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Title}" Margin="12,0,0,0" FontWeight="SemiBold" ToolTip="{Binding Title}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding Camera}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
ToolTip="{Binding Camera, Converter={x:Static ui:EmptyToNullConverter.Instance}}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding FramesText}" Margin="12,0,0,0" />
|
||||
<ItemsControl Grid.Column="5" Margin="12,0,0,0" ItemsSource="{Binding Statuses}" ItemTemplate="{StaticResource Template.Status}"
|
||||
ItemsPanel="{StaticResource Panel.Row}" VerticalAlignment="Center" Focusable="False" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<!-- Owner review 2, R8: two groups, the workspace's projects (each with where it stands) above the library's sequences. -->
|
||||
<Grid Grid.Row="3">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc Editor.Picker.Workspace}" Style="{StaticResource Text.Label}" Margin="16,8,16,2"
|
||||
Visibility="{Binding Picker.HasWorkspaceItems, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ListBox x:Name="Projects" Grid.Row="1" Margin="0,2,0,4" MaxHeight="184" ItemsSource="{Binding Picker.WorkspaceItems}" SelectedItem="{Binding Picker.SelectedProject}"
|
||||
SelectionMode="Single" ItemContainerStyle="{StaticResource ListBoxItem.ProjectRow}" TextSearch.TextPath="Name" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
AutomationProperties.Name="{l:Loc Editor.Picker.Workspace}" ToolTip="{l:Loc Tooltips.Editor.Picker.Project}" KeyboardNavigation.TabNavigation="Continue"
|
||||
Grid.IsSharedSizeScope="True" Visibility="{Binding Picker.HasWorkspaceItems, Converter={StaticResource BoolToVisibility}}">
|
||||
<ListBox.InputBindings>
|
||||
<KeyBinding Key="Enter" Command="{Binding Picker.OpenProjectCommand}" />
|
||||
<KeyBinding Key="Delete" Command="{Binding Picker.RemoveCopyCommand}" />
|
||||
</ListBox.InputBindings>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type ws:WorkspaceProjectItem}">
|
||||
<!-- Remove local copy also for a project that cannot open (its copy failed, or the library no longer has it). -->
|
||||
<Grid Height="40" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}">
|
||||
<Grid.ContextMenu>
|
||||
<ContextMenu>
|
||||
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding PlacementTarget.Tag.Picker.RemoveCopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Editor.Project.RemoveCopy}" />
|
||||
</ContextMenu>
|
||||
</Grid.ContextMenu>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" MinWidth="120" />
|
||||
<ColumnDefinition Width="2*" MinWidth="120" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="ProjectState" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<!-- Pictures stay left to right in a right-to-left window. -->
|
||||
<Border Width="64" Height="36" CornerRadius="4" Background="{DynamicResource Brush.Card}" ClipToBounds="True" FlowDirection="LeftToRight"
|
||||
lib:ThumbnailLoading.Width="64" DataContext="{Binding Sequence}">
|
||||
<Image Source="{Binding Thumbnail}" Stretch="UniformToFill" />
|
||||
</Border>
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Name}" Margin="12,0,0,0" FontWeight="SemiBold" ToolTip="{Binding Name}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding SequenceTitle}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
ToolTip="{Binding SequenceTitle}" />
|
||||
<ui:StatusGlyph Grid.Column="3" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}" Margin="12,0,8,0" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc Editor.Picker.Library}" Style="{StaticResource Text.Label}" Margin="16,8,16,2"
|
||||
Visibility="{Binding Picker.HasWorkspaceItems, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ListBox x:Name="List" Grid.Row="3" Margin="0,4,0,8" ItemsSource="{Binding Picker.Items}" SelectedItem="{Binding Picker.Selected}" SelectionMode="Single"
|
||||
ItemContainerStyle="{StaticResource ListBoxItem.PickerRow}" TextSearch.TextPath="Title" VirtualizingPanel.IsVirtualizing="True"
|
||||
VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
ScrollViewer.ScrollChanged="OnScrollChanged" AutomationProperties.Name="{l:Loc Editor.Picker.List}" ToolTip="{l:Loc Tooltips.Editor.Picker.Row}"
|
||||
KeyboardNavigation.TabNavigation="Continue" Grid.IsSharedSizeScope="True" SelectionChanged="OnSelectionChanged">
|
||||
<ListBox.InputBindings>
|
||||
<KeyBinding Key="Enter" Command="{Binding Picker.OpenCommand}" />
|
||||
</ListBox.InputBindings>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type lib:SequenceItem}">
|
||||
<Grid Height="40">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="2*" MinWidth="140" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="84" SharedSizeGroup="PickerDate" />
|
||||
<ColumnDefinition Width="*" MinWidth="80" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="56" SharedSizeGroup="PickerFrames" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="PickerStates" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<!-- Pictures stay left to right in a right-to-left window. -->
|
||||
<Border Width="64" Height="36" CornerRadius="4" Background="{DynamicResource Brush.Card}" ClipToBounds="True" FlowDirection="LeftToRight"
|
||||
lib:ThumbnailLoading.Width="64">
|
||||
<Image Source="{Binding Thumbnail}" Stretch="UniformToFill" />
|
||||
</Border>
|
||||
<!-- Cells that may be shortened show their text in their tooltip (an empty camera has none). -->
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Title}" Margin="12,0,0,0" FontWeight="SemiBold" ToolTip="{Binding Title}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding Camera}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
ToolTip="{Binding Camera, Converter={x:Static ui:EmptyToNullConverter.Instance}}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding FramesText}" Margin="12,0,0,0" />
|
||||
<ItemsControl Grid.Column="5" Margin="12,0,0,0" ItemsSource="{Binding Statuses}" ItemTemplate="{StaticResource Template.Status}"
|
||||
ItemsPanel="{StaticResource Panel.Row}" VerticalAlignment="Center" Focusable="False" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<ui:EmptyState Grid.Row="3" Message="{l:Loc Library.Empty}" Visibility="{Binding Picker.IsEmptyLibrary, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Shell.Nav.Import}" Command="{Binding OpenImportCommand}" ToolTip="{l:Loc Tooltips.Nav.Import}" />
|
||||
</ui:EmptyState>
|
||||
<ui:EmptyState Grid.Row="3" Message="{l:Loc Editor.Picker.NoMatch}" Visibility="{Binding Picker.IsNoMatch, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Editor.Picker.Clear}" Command="{Binding Picker.ClearCommand}" ToolTip="{l:Loc Tooltips.Editor.Picker.Clear}" />
|
||||
</ui:EmptyState>
|
||||
<ui:EmptyState Grid.Row="3" Message="{l:Loc Library.Empty}" Visibility="{Binding Picker.IsEmptyLibrary, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Shell.Nav.Import}" Command="{Binding OpenImportCommand}" ToolTip="{l:Loc Tooltips.Nav.Import}" />
|
||||
</ui:EmptyState>
|
||||
<ui:EmptyState Grid.Row="3" Message="{l:Loc Editor.Picker.NoMatch}" Visibility="{Binding Picker.IsNoMatch, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Editor.Picker.Clear}" Command="{Binding Picker.ClearCommand}" ToolTip="{l:Loc Tooltips.Editor.Picker.Clear}" />
|
||||
</ui:EmptyState>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
</UserControl>
|
||||
@@ -49,6 +49,14 @@ public partial class SequencePickerView : UserControl
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
/// <summary>A double-click on a project of the Workspace group opens it (the left button only).</summary>
|
||||
private void OnProjectDoubleClick(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (e.ChangedButton != MouseButton.Left || sender is not ListBoxItem { DataContext: Workspace.WorkspaceProjectItem item } || Section is not { } section) return;
|
||||
if (section.Picker.OpenProjectCommand.CanExecute(item)) section.Picker.OpenProjectCommand.Execute(item);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
/// <summary>Esc anywhere in the picker: the search first, then back to the open sequence.</summary>
|
||||
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Library;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Repositories;
|
||||
@@ -11,10 +14,14 @@ using Chronos.Ui.Mvvm;
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
/// <summary>
|
||||
/// The sequence picker of the Edit section (owner review 1, R7): this PC's sequences and, while signed in, the server's
|
||||
/// sequences without a copy here, newest first, searched by title, camera or tag as the user types (after 250 ms, like
|
||||
/// the Library) and read page by page as the list scrolls. One sequence is chosen and opened; when the list loads, the
|
||||
/// open sequence is selected, else the one edited last (pages are read until it is listed), else the first.
|
||||
/// The sequence picker of the Edit section (owner review 1, R7), in two groups (owner review 2, R8): the Workspace, the
|
||||
/// projects this PC's workspace holds, each with where it stands against its home (read after the list shows), the one
|
||||
/// saved last first; and the Library, this PC's sequences and, while signed in, the server's sequences without a copy
|
||||
/// here, newest first, read page by page as the list scrolls. Both are searched by what the user types (after 250 ms,
|
||||
/// like the Library): projects by their name or their sequence's title, sequences by title, camera or tag. A project
|
||||
/// opens as it is; a sequence opens in the workspace (its project opened last, else "Open in workspace" asks). When the
|
||||
/// list loads, the open project and sequence are selected, else the one edited last (pages are read until it is
|
||||
/// listed), else the first.
|
||||
/// </summary>
|
||||
public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
{
|
||||
@@ -25,9 +32,12 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
private LibraryPager? _pager;
|
||||
private string _searchText = string.Empty;
|
||||
private SequenceItem? _selected;
|
||||
private WorkspaceProjectItem? _selectedProject;
|
||||
private bool _isLoading;
|
||||
private bool _hasLoaded;
|
||||
private Task _loading = Task.CompletedTask;
|
||||
private Task _workspaceLoading = Task.CompletedTask;
|
||||
private Task _workspaceStates = Task.CompletedTask;
|
||||
private int _pageSize = LibraryPager.DefaultPageSize;
|
||||
|
||||
/// <summary>Counts reloads, so a reload that a newer one replaced stops reading pages.</summary>
|
||||
@@ -40,6 +50,8 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
_searchDelay.Tick += (_, _) => _ = ReloadAsync();
|
||||
_open = new AsyncRelayCommand(() => (Selected ?? Items.FirstOrDefault()) is { } item ? _section.PickAsync(item) : Task.CompletedTask, () => Items.Count > 0);
|
||||
OpenItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _section.PickAsync(item) : Task.CompletedTask);
|
||||
OpenProjectCommand = new AsyncRelayCommand((p, _) => (p as WorkspaceProjectItem ?? SelectedProject) is { } item ? _section.PickProjectAsync(item) : Task.CompletedTask);
|
||||
RemoveCopyCommand = new AsyncRelayCommand((p, _) => (p as WorkspaceProjectItem ?? SelectedProject) is { } item ? _section.RemoveProjectCopyAsync(item) : Task.CompletedTask);
|
||||
SearchOpenCommand = new AsyncRelayCommand(OpenFromSearchAsync);
|
||||
ClearCommand = new RelayCommand(() => SearchText = string.Empty);
|
||||
}
|
||||
@@ -47,6 +59,31 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
/// <summary>The sequences listed, in order.</summary>
|
||||
public ObservableCollection<SequenceItem> Items { get; } = [];
|
||||
|
||||
/// <summary>The projects of the workspace listed (the Workspace group), the one saved last first.</summary>
|
||||
public ObservableCollection<WorkspaceProjectItem> WorkspaceItems { get; } = [];
|
||||
|
||||
/// <summary>The Workspace group shows (it lists a project).</summary>
|
||||
public bool HasWorkspaceItems => WorkspaceItems.Count > 0;
|
||||
|
||||
public WorkspaceProjectItem? SelectedProject
|
||||
{
|
||||
get => _selectedProject;
|
||||
set => Set(ref _selectedProject, value);
|
||||
}
|
||||
|
||||
/// <summary>Opens a project of the Workspace group (double-click, Enter in its list), else the selected one.</summary>
|
||||
public ICommand OpenProjectCommand { get; }
|
||||
|
||||
/// <summary>"Remove local copy…" of a project of the Workspace group (its menu, Delete in its list), also one that cannot open.</summary>
|
||||
public ICommand RemoveCopyCommand { get; }
|
||||
|
||||
/// <summary>The Workspace group read last, then its projects' states (tests wait for it).</summary>
|
||||
public async Task WorkspaceLoadedAsync()
|
||||
{
|
||||
await _workspaceLoading;
|
||||
await _workspaceStates;
|
||||
}
|
||||
|
||||
/// <summary>Title, camera or tag text; the list follows a moment after the last key.</summary>
|
||||
public string SearchText
|
||||
{
|
||||
@@ -73,10 +110,10 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
}
|
||||
|
||||
/// <summary>There is no sequence at all: Import is offered.</summary>
|
||||
public bool IsEmptyLibrary => _hasLoaded && !_isLoading && Items.Count == 0 && string.IsNullOrWhiteSpace(_searchText);
|
||||
public bool IsEmptyLibrary => _hasLoaded && !_isLoading && Items.Count == 0 && WorkspaceItems.Count == 0 && string.IsNullOrWhiteSpace(_searchText);
|
||||
|
||||
/// <summary>The search matches nothing: Clear search is offered.</summary>
|
||||
public bool IsNoMatch => _hasLoaded && !_isLoading && Items.Count == 0 && !string.IsNullOrWhiteSpace(_searchText);
|
||||
public bool IsNoMatch => _hasLoaded && !_isLoading && Items.Count == 0 && WorkspaceItems.Count == 0 && !string.IsNullOrWhiteSpace(_searchText);
|
||||
|
||||
/// <summary>The list read last (capture and tests wait for it).</summary>
|
||||
public Task Loading => _loading;
|
||||
@@ -120,6 +157,7 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
{
|
||||
if (_searchDelay.IsEnabled) await ReloadAsync();
|
||||
else await _loading;
|
||||
await _workspaceLoading;
|
||||
}
|
||||
|
||||
/// <summary>The next page, when the list scrolled near its end.</summary>
|
||||
@@ -134,18 +172,24 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
{
|
||||
_searchDelay.Stop();
|
||||
_pager?.Cancel();
|
||||
// The projects' states still being read stop asking.
|
||||
_generation++;
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private async Task OpenFromSearchAsync()
|
||||
{
|
||||
await SettleAsync();
|
||||
if (_section.ShowsPicker && (Selected ?? Items.FirstOrDefault()) is { } item) await _section.PickAsync(item);
|
||||
if (!_section.ShowsPicker) return;
|
||||
if ((Selected ?? Items.FirstOrDefault()) is { } item) await _section.PickAsync(item);
|
||||
// Only projects match what was typed: the first of them.
|
||||
else if ((SelectedProject ?? WorkspaceItems.FirstOrDefault()) is { } project) await _section.PickProjectAsync(project);
|
||||
}
|
||||
|
||||
private async Task LoadFirstAsync()
|
||||
{
|
||||
var generation = _generation;
|
||||
_workspaceLoading = LoadWorkspaceAsync(generation);
|
||||
var filter = new LibraryFilter { Text = string.IsNullOrWhiteSpace(_searchText) ? null : _searchText.Trim(), Sort = SequenceSort.Newest };
|
||||
_merge.Reset(filter, Shell.Library.RemoteSequences);
|
||||
if (Shell.Services.Database is not { } db)
|
||||
@@ -209,6 +253,73 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Workspace group: the workspace's projects matching the search, then each one's state as its home tells it
|
||||
/// (filled in as they come; a read a newer one replaced stops).
|
||||
/// </summary>
|
||||
private async Task LoadWorkspaceAsync(int generation)
|
||||
{
|
||||
var services = Shell.Services;
|
||||
if (!services.Workspace.IsAvailable || services.Database is not { } db)
|
||||
{
|
||||
ClearWorkspace();
|
||||
return;
|
||||
}
|
||||
var text = _searchText.Trim();
|
||||
var items = new List<WorkspaceProjectItem>();
|
||||
try
|
||||
{
|
||||
foreach (var entry in (await services.Workspace.ListAsync()).OrderByDescending(e => e.Saved))
|
||||
{
|
||||
var row = await db.Sequences.GetAsync(entry.SequenceId);
|
||||
var item = new WorkspaceProjectItem(entry, row is null ? null : new SequenceItem(row, services.Thumbnails));
|
||||
if (text.Length > 0 && !item.Name.Contains(text, StringComparison.CurrentCultureIgnoreCase)
|
||||
&& !item.SequenceTitle.Contains(text, StringComparison.CurrentCultureIgnoreCase))
|
||||
continue;
|
||||
items.Add(item);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Log.Warning("workspace", "The workspace could not be listed", ex);
|
||||
if (generation == _generation) ClearWorkspace();
|
||||
return;
|
||||
}
|
||||
if (generation != _generation) return;
|
||||
WorkspaceItems.Clear();
|
||||
foreach (var item in items) WorkspaceItems.Add(item);
|
||||
SelectedProject = WorkspaceItems.FirstOrDefault(i => i.ProjectId == _section.OpenProjectId) ?? WorkspaceItems.FirstOrDefault();
|
||||
OnPropertyChanged(nameof(HasWorkspaceItems));
|
||||
RaiseStates();
|
||||
_workspaceStates = ReadStatesAsync(items, generation);
|
||||
}
|
||||
|
||||
/// <summary>Each listed project's state, asked of its home one after the other (a home may make a read wait a few seconds).</summary>
|
||||
private async Task ReadStatesAsync(IReadOnlyList<WorkspaceProjectItem> items, int generation)
|
||||
{
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (generation != _generation) return;
|
||||
// This Chronos cannot read its working state: there is no state to ask for.
|
||||
if (!item.IsReadable) continue;
|
||||
try
|
||||
{
|
||||
item.Status = await Shell.Services.Workspace.StatusAsync(item.ProjectId);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Info("workspace", $"The state of project {item.ProjectId} could not be read: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearWorkspace()
|
||||
{
|
||||
WorkspaceItems.Clear();
|
||||
SelectedProject = null;
|
||||
OnPropertyChanged(nameof(HasWorkspaceItems));
|
||||
}
|
||||
|
||||
/// <summary>The sequence selected first: the open one, else the one edited last.</summary>
|
||||
private Guid? Wanted => _section.OpenSequenceId ?? Shell.Services.Settings.LastEditedSequence;
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Editor/EditorStyles.xaml" />
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Workspace/WorkspaceDialogs.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
@@ -27,7 +28,8 @@
|
||||
The open sequence stays laid out behind the picker (hidden, not collapsed: collapsing it would shrink the preview
|
||||
and render it again when it comes back), and while a switch is under way (the progress bar shows).
|
||||
-->
|
||||
<Grid x:Name="EditorHost">
|
||||
<!-- Behind an open dialog the editor takes neither clicks nor the keyboard. -->
|
||||
<Grid x:Name="EditorHost" IsEnabled="{Binding IsContentEnabled}">
|
||||
<Grid.Style>
|
||||
<Style TargetType="Grid">
|
||||
<Style.Triggers>
|
||||
@@ -51,6 +53,8 @@
|
||||
<KeyBinding Key="D1" Modifiers="Control+Shift" Command="{Binding ActualSizeCommand}" />
|
||||
<KeyBinding Key="R" Modifiers="Control" Command="{Binding RenderCommand}" />
|
||||
<KeyBinding Key="A" Modifiers="Control+Shift" Command="{Binding AnalyseCommand}" />
|
||||
<!-- Owner review 2, R8: Save version of the workspace project. -->
|
||||
<KeyBinding Key="S" Modifiers="Control" Command="{Binding Project.SaveVersionCommand}" />
|
||||
<!-- Steps by number; no Alt+NumPad bindings, which type characters into text fields. -->
|
||||
<KeyBinding Key="D1" Modifiers="Alt" Command="{Binding GoToStepCommand}" CommandParameter="1" />
|
||||
<KeyBinding Key="D2" Modifiers="Alt" Command="{Binding GoToStepCommand}" CommandParameter="2" />
|
||||
@@ -64,6 +68,7 @@
|
||||
</Grid.InputBindings>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="52" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="44" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
@@ -94,6 +99,38 @@
|
||||
Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
</Grid>
|
||||
</Button>
|
||||
<!-- Owner review 2, R8: the workspace project, where it stands, and its menu (versions, sync, history, projects, the local copy). -->
|
||||
<Button x:Name="ProjectButton" DockPanel.Dock="Left" Style="{StaticResource Button.Subtle}" Margin="0,0,12,0" Padding="8,0" MaxWidth="280" Height="30"
|
||||
VerticalAlignment="Center" Click="OnOpenProjectMenu" ToolTip="{Binding Project.MenuToolTip}" AutomationProperties.Name="{Binding Project.MenuName}"
|
||||
Visibility="{Binding HasProject, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Project.Name}" FontWeight="SemiBold" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
|
||||
<ui:StatusGlyph Grid.Column="1" Kind="{Binding Project.StateKind}" Text="{Binding Project.StateText}" FontSize="12" Margin="8,0,0,0" VerticalAlignment="Center"
|
||||
infra:LiveRegion.Text="{Binding Project.StateText}" AutomationProperties.LiveSetting="Polite" />
|
||||
<ui:Icon Grid.Column="2" Glyph="{StaticResource Icon.ChevronDown}" Size="14" Margin="6,0,0,0" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
</Grid>
|
||||
<Button.ContextMenu>
|
||||
<ContextMenu>
|
||||
<MenuItem Header="{l:Loc Editor.Project.SaveVersion}" Command="{Binding Project.SaveVersionCommand}" InputGestureText="Ctrl+S"
|
||||
ToolTip="{Binding Project.SaveVersionToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.Sync}" Command="{Binding Project.SyncCommand}" ToolTip="{Binding Project.StateToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.History}" Command="{Binding Project.HistoryCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.History}" />
|
||||
<Separator />
|
||||
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Rename}" />
|
||||
<MenuItem Header="{l:Loc Editor.Project.Delete}" Command="{Binding Project.DeleteCommand}" ToolTip="{Binding Project.DeleteToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
<Separator />
|
||||
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.RemoveCopy}" />
|
||||
</ContextMenu>
|
||||
</Button.ContextMenu>
|
||||
</Button>
|
||||
<ui:StatusGlyph DockPanel.Dock="Left" Kind="Remote" Text="{Binding RemoteText}" ToolTip="{Binding RemoteToolTip}" FontSize="{StaticResource Size.Body}" Margin="0,0,12,0"
|
||||
MaxWidth="220" VerticalAlignment="Center" Visibility="{Binding IsRemote, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding Summary}" Style="{StaticResource Text.Secondary}" FontSize="{StaticResource Size.Body}" VerticalAlignment="Center"
|
||||
@@ -127,12 +164,23 @@
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- Owner review 2, R8: the library's frames moved past the workspace's; Update media copies them again (positions follow their photos). -->
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Card}" Padding="12,6" Margin="0,0,0,8"
|
||||
Visibility="{Binding Project.HasMediaUpdate, Converter={StaticResource BoolToVisibility}, FallbackValue=Collapsed}">
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Editor.Workspace.UpdateMedia}" Command="{Binding Project.UpdateMediaCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Workspace.UpdateMedia}" ToolTipService.ShowOnDisabled="True" />
|
||||
<ui:StatusGlyph Kind="Warning" Text="{Binding Project.MediaUpdateText}" ToolTip="{l:Loc Tooltips.Editor.Workspace.MediaChanged}" VerticalAlignment="Center"
|
||||
infra:LiveRegion.Text="{Binding Project.MediaUpdateText}" AutomationProperties.LiveSetting="Polite" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
<!-- The path (owner review 1, R7): one row of steps, each with where it stands; any step opens at any time (Alt+n, ←/→ in the bar). -->
|
||||
<ListBox x:Name="Steps" Grid.Row="1" Style="{StaticResource ListBox.Steps}" ItemsSource="{Binding Tabs}" SelectedItem="{Binding SelectedTab}"
|
||||
<ListBox x:Name="Steps" Grid.Row="2" Style="{StaticResource ListBox.Steps}" ItemsSource="{Binding Tabs}" SelectedItem="{Binding SelectedTab}"
|
||||
ItemContainerStyle="{StaticResource ListBoxItem.Step}" Margin="0,0,0,8" AutomationProperties.Name="{l:Loc Editor.Path}" KeyDown="OnStepsKeyDown"
|
||||
PreviewKeyDown="OnStepsPreviewKeyDown" PreviewMouseLeftButtonDown="OnStepsPreviewMouseDown" SelectionChanged="OnStepsSelectionChanged" />
|
||||
|
||||
<Grid Grid.Row="2">
|
||||
<Grid Grid.Row="3">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Panel}" />
|
||||
@@ -269,6 +317,13 @@
|
||||
</Grid>
|
||||
|
||||
<!-- The picker (owner review 1, R7): without an open sequence, or over it after Change sequence. -->
|
||||
<sections:SequencePickerView x:Name="Picker" Visibility="{Binding ShowsPicker, Converter={StaticResource BoolToVisibility}}" />
|
||||
<sections:SequencePickerView x:Name="Picker" Visibility="{Binding ShowsPicker, Converter={StaticResource BoolToVisibility}}" IsEnabled="{Binding IsContentEnabled}" />
|
||||
|
||||
<!-- In-window dialogs (Open in workspace, the project menu's) over a scrim; the keyboard stays inside the dialog. -->
|
||||
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
|
||||
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
|
||||
<Border Background="{DynamicResource Brush.Scrim}" />
|
||||
<ContentPresenter x:Name="DialogHost" Content="{Binding Dialog}" Margin="20" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -26,6 +26,7 @@ public partial class SequenceView : UserControl
|
||||
EditorRoot.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
|
||||
EditorRoot.AddHandler(KeyUpEvent, new KeyEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
|
||||
EditorRoot.IsKeyboardFocusWithinChanged += OnEditorFocusWithinChanged;
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
}
|
||||
|
||||
private EditorViewModel? Editor => (DataContext as SequenceViewModel)?.Editor;
|
||||
@@ -88,11 +89,12 @@ public partial class SequenceView : UserControl
|
||||
|
||||
/// <summary>
|
||||
/// Space plays or pauses, arrows step a frame (BRIEF §12.3) — unless a text field or a control that uses the key has
|
||||
/// it, or the picker covers the editor.
|
||||
/// it, or the picker or a dialog covers the editor.
|
||||
/// </summary>
|
||||
private void OnKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Handled || IsPicking || Editor is not { } editor || Keyboard.Modifiers != ModifierKeys.None || e.OriginalSource is TextBoxBase) return;
|
||||
if (e.Handled || IsPicking || (DataContext as SequenceViewModel)?.IsDialogOpen == true || Editor is not { } editor || Keyboard.Modifiers != ModifierKeys.None
|
||||
|| e.OriginalSource is TextBoxBase) return;
|
||||
var command = e.Key switch
|
||||
{
|
||||
Key.Space => editor.PlayCommand,
|
||||
@@ -201,6 +203,29 @@ public partial class SequenceView : UserControl
|
||||
|
||||
private void EndEditRun() => Editor?.Session.EndEditRun();
|
||||
|
||||
/// <summary>The project button (▾ beside the title) opens its menu under itself.</summary>
|
||||
private void OnOpenProjectMenu(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is not Button { ContextMenu: { } menu } button) return;
|
||||
menu.DataContext = button.DataContext;
|
||||
menu.PlacementTarget = button;
|
||||
menu.Placement = PlacementMode.Bottom;
|
||||
menu.IsOpen = true;
|
||||
}
|
||||
|
||||
/// <summary>A dialog that opens takes the keyboard: its first field or button.</summary>
|
||||
private void OnSectionChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName != nameof(SequenceViewModel.Dialog) || DataContext is not SequenceViewModel { Dialog: not null } || !IsVisible) return;
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
|
||||
}
|
||||
|
||||
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.OldValue is SequenceViewModel old) old.PropertyChanged -= OnSectionChanged;
|
||||
if (e.NewValue is SequenceViewModel section) section.PropertyChanged += OnSectionChanged;
|
||||
}
|
||||
|
||||
/// <summary>The preview renders at the size it is shown, in device pixels.</summary>
|
||||
private void OnPreviewSizeChanged(object sender, SizeChangedEventArgs e)
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -520,6 +520,34 @@
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Workspace (owner review 2, R8) ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Workspace}">
|
||||
<!-- The folder is shown, opened and changed here (another folder after its plan; nothing is moved: moving it with its projects comes with phase 5c). -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Folder}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Style="{StaticResource TextBox.Path}" IsReadOnly="True" Text="{Binding WorkspaceRows.Folder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.WorkspaceFolder}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Workspace.Folder}" />
|
||||
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding WorkspaceRows.OpenCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenWorkspace}"
|
||||
Margin="10,0,0,0" />
|
||||
<Button Grid.Column="2" Content="{l:Loc Settings.Workspace.Change}" Command="{Binding WorkspaceRows.ChangeCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.ChangeWorkspace}" Margin="8,0,0,0"
|
||||
Visibility="{Binding WorkspaceRows.CanChange, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Sync}">
|
||||
<CheckBox Content="{l:Loc Settings.Workspace.AfterSave}" IsChecked="{Binding WorkspaceRows.AutoSync}" ToolTip="{l:Loc Tooltips.Settings.WorkspaceSync}" Margin="0,4,0,0" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Kept}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding WorkspaceRows.KeptChoices}" SelectedItem="{Binding WorkspaceRows.SelectedKept}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.KeptVersions}" AutomationProperties.Name="{l:Loc Settings.Workspace.Kept}" />
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Server ================= -->
|
||||
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Server}">
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Default}">
|
||||
|
||||
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Import;
|
||||
@@ -86,6 +87,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
"Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
|
||||
new(SettingsPage.Formats, ["Settings.Formats.Title", "Settings.Formats.Column.Tier", "Settings.Formats.Install"]),
|
||||
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
|
||||
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.Kept"]),
|
||||
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
|
||||
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
|
||||
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
|
||||
@@ -166,6 +168,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
// Saving applies them to the log files (App.SaveSettings).
|
||||
Logs = new LogSettingsRows(_s, Save);
|
||||
|
||||
// ---- Workspace ----
|
||||
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => Shell.Services.Workspace.Root, OpenWorkspaceFolder, ChangeWorkspaceFolderAsync);
|
||||
|
||||
// ---- Storage ----
|
||||
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
|
||||
{
|
||||
@@ -718,6 +723,31 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
private set => Set(ref _cacheUsageText, value);
|
||||
}
|
||||
|
||||
// ---------------- Workspace ----------------
|
||||
|
||||
/// <summary>Settings › Workspace (owner review 2, R8): the folder, Sync automatically and Kept versions.</summary>
|
||||
public WorkspaceSettingsRows WorkspaceRows { get; }
|
||||
|
||||
/// <summary>Shows the workspace folder in Explorer (made, with its manifest, when the workspace was never used).</summary>
|
||||
private void OpenWorkspaceFolder()
|
||||
{
|
||||
try
|
||||
{
|
||||
ShellActions.Reveal(Shell.Services.Workspace.Store.Root);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Another workspace folder, after its plan (nothing is moved): Edit lists its projects from then on.</summary>
|
||||
private async Task ChangeWorkspaceFolderAsync()
|
||||
{
|
||||
await WorkspaceFolderChange.ChooseAsync(Shell);
|
||||
WorkspaceRows.Refresh();
|
||||
}
|
||||
|
||||
// ---------------- Server ----------------
|
||||
|
||||
public EditableField DefaultServer { get; }
|
||||
@@ -1176,7 +1206,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
|
||||
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert,
|
||||
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy,
|
||||
];
|
||||
|
||||
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
|
||||
@@ -1534,6 +1564,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
case SettingsPage.Updates:
|
||||
_s.CheckForUpdates = defaults.CheckForUpdates;
|
||||
break;
|
||||
case SettingsPage.Workspace:
|
||||
WorkspaceRows.Reset();
|
||||
break;
|
||||
case SettingsPage.Advanced:
|
||||
Logs.Reset();
|
||||
break;
|
||||
@@ -1611,6 +1644,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
LastEditedSequence = _s.LastEditedSequence,
|
||||
FirstRunCompleted = _s.FirstRunCompleted,
|
||||
JobsClearedAt = _s.JobsClearedAt,
|
||||
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
|
||||
WorkspaceFolder = _s.WorkspaceFolder,
|
||||
WorkspaceRecent = _s.WorkspaceRecent,
|
||||
};
|
||||
// Start with Windows lives in the registry, not in the settings file: its default is off.
|
||||
Startup.SetEnabled(false);
|
||||
@@ -1642,6 +1678,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
_interfacePriority?.Update();
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
Logs.Refresh();
|
||||
WorkspaceRows.Refresh();
|
||||
UpdatePreview();
|
||||
LoadCertificates();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1656,6 +1693,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
// Secrets and machine-bound values stay on this PC.
|
||||
copy.ProtectedToken = null;
|
||||
copy.Window = null;
|
||||
copy.WorkspaceFolder = null;
|
||||
copy.WorkspaceRecent = [];
|
||||
var path = Path.Combine(folder, $"Chronos settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
|
||||
await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
|
||||
Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
@@ -1688,6 +1727,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
imported.RailCollapsed = _s.RailCollapsed;
|
||||
imported.LastEditedSequence = _s.LastEditedSequence;
|
||||
imported.FirstRunCompleted = _s.FirstRunCompleted;
|
||||
// The workspace is this PC's: its folder and the projects opened last stay.
|
||||
imported.WorkspaceFolder = _s.WorkspaceFolder;
|
||||
imported.WorkspaceRecent = _s.WorkspaceRecent;
|
||||
ApplyAll(imported);
|
||||
// Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
|
||||
// archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
|
||||
@@ -1717,6 +1759,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
foreach (var row in Formats) row.Refresh();
|
||||
foreach (var row in MissingExtensions) row.Refresh();
|
||||
Logs.Refresh();
|
||||
WorkspaceRows.Refresh();
|
||||
ArchiveRoot.Refresh();
|
||||
FolderTemplate.Refresh();
|
||||
FileTemplate.Refresh();
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Text.Json.Nodes;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
@@ -90,6 +91,9 @@ public static class SyncText
|
||||
["heroFrame"] = "Server.Setting.HeroFrame",
|
||||
};
|
||||
|
||||
/// <summary>The paths of positions parked by photo: "pendingFrames.<photo>.<flag>".</summary>
|
||||
private const string PendingPrefix = "pendingFrames.";
|
||||
|
||||
/// <summary>"originals · proxies", "proxies" (cached server proxies) or "—".</summary>
|
||||
public static string Local(SyncEntry entry)
|
||||
{
|
||||
@@ -165,26 +169,54 @@ public static class SyncText
|
||||
/// One line per setting or sequence field among <paramref name="differences"/> ("Deflicker window 41 here, 33 on the
|
||||
/// server", "Tags differ"), at most <paramref name="max"/>; the editor's settings conflicts read the same.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Differences(IEnumerable<SettingsDifference> differences, int max)
|
||||
public static IReadOnlyList<string> Differences(IEnumerable<SettingsDifference> differences, int max) => Differences(differences, max, null);
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="Differences(IEnumerable{SettingsDifference}, int)"/>, each line with both values worded by
|
||||
/// <paramref name="worded"/> (setting, this side's value, the other side's) instead of "here, on the server": a
|
||||
/// workspace project against its library, a version against now. One setting differing on several photos (positions
|
||||
/// parked by photo) is one line with their count: "Excluded frames (3)".
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Differences(IEnumerable<SettingsDifference> differences, int max, Func<string, string, string, string>? worded)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(differences);
|
||||
var lines = new List<string>();
|
||||
var shown = new HashSet<string>(StringComparer.Ordinal);
|
||||
worded ??= (label, mine, server) => Loc.L("Server.Conflict.Difference", label, mine, server);
|
||||
// One line per setting, in the order met; the photos each differs on counted.
|
||||
var settings = new List<(string Key, string? Field, SettingsDifference First, HashSet<string> Photos)>();
|
||||
var index = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var difference in differences)
|
||||
{
|
||||
var (key, field) = Setting(difference.Path);
|
||||
if (!shown.Add(key)) continue;
|
||||
if (!index.TryGetValue(key, out var at))
|
||||
{
|
||||
index[key] = at = settings.Count;
|
||||
settings.Add((key, field, difference, new HashSet<string>(StringComparer.Ordinal)));
|
||||
}
|
||||
if (PhotoOf(difference.Path) is { } photo) settings[at].Photos.Add(photo);
|
||||
}
|
||||
var lines = new List<string>();
|
||||
foreach (var (key, field, difference, photos) in settings)
|
||||
{
|
||||
var label = Loc.L(key);
|
||||
var metadata = difference.Path.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal);
|
||||
lines.Add((metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine
|
||||
&& (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server
|
||||
? Loc.L("Server.Conflict.Difference", label, mine, server)
|
||||
: Loc.L("Server.Conflict.Changed", label));
|
||||
lines.Add(photos.Count > 1 ? Loc.L("Server.Conflict.Count", label, Formatting.Count(photos.Count))
|
||||
: (metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine
|
||||
&& (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server
|
||||
? worded(label, mine, server)
|
||||
: Loc.L("Server.Conflict.Changed", label));
|
||||
if (lines.Count == max) break;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>The photo a path of positions parked by photo names ("pendingFrames.<photo>.excluded"); null for any other path.</summary>
|
||||
private static string? PhotoOf(string path)
|
||||
{
|
||||
if (!path.StartsWith(PendingPrefix, StringComparison.Ordinal)) return null;
|
||||
var flag = path.LastIndexOf('.');
|
||||
return flag > PendingPrefix.Length ? path[PendingPrefix.Length..flag] : null;
|
||||
}
|
||||
|
||||
/// <summary>The row's buttons, in the order the mockup shows them.</summary>
|
||||
public static IReadOnlyList<SyncAction> Actions(SyncEntry entry, SyncRights rights)
|
||||
{
|
||||
@@ -259,9 +291,23 @@ public static class SyncText
|
||||
/// <summary>
|
||||
/// The label key of a difference path and the member below the setting it reaches ("isAuto", "manual", … of an
|
||||
/// Auto parameter; null for the setting itself): "exposure.deflickerWindow.manual" is the deflicker window's manual value.
|
||||
/// Positions parked by photo (a workspace project's portable form, owner review 2, R8) read as the setting they hold:
|
||||
/// "hero" (two heroes chosen), "pendingFrames.<photo>.keyframes" or ".excluded".
|
||||
/// </summary>
|
||||
private static (string Key, string? Field) Setting(string path)
|
||||
{
|
||||
if (path == ProjectMerge.HeroPath) return ("Server.Setting.HeroFrame", null);
|
||||
if (path.StartsWith(PendingPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
// The flag is the last segment: the photo's key between may hold dots of its own.
|
||||
return path[(path.LastIndexOf('.') + 1)..] switch
|
||||
{
|
||||
"excluded" => ("Server.Setting.ExcludedFrames", null),
|
||||
"hero" => ("Server.Setting.HeroFrame", null),
|
||||
"keyframes" => ("Server.Setting.Keyframes", null),
|
||||
_ => ("Server.Setting.Other", null),
|
||||
};
|
||||
}
|
||||
var segments = path.Split('.');
|
||||
for (var length = segments.Length; length > 0; length--)
|
||||
{
|
||||
|
||||
@@ -21,6 +21,9 @@ public enum SettingsPage
|
||||
Rendering,
|
||||
Formats,
|
||||
Storage,
|
||||
|
||||
/// <summary>The workspace where projects are edited (owner review 2, R8): its folder, Sync automatically, Kept versions.</summary>
|
||||
Workspace,
|
||||
Server,
|
||||
Updates,
|
||||
Advanced,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Workspace (owner review 2, R8): the workspace folder (shown with Open, and Change, which uses another
|
||||
/// folder after a plan without moving anything; moving it with its projects comes with phase 5c), Sync automatically (a version saved is sent to its home at once, and the home's
|
||||
/// new versions taken; on by default) and Kept versions (the versions taken from the home a project keeps in the
|
||||
/// workspace besides its base and those not sent; 20 by default). Each choice is stored and saved at once. A value set
|
||||
/// elsewhere (an imported or hand-edited settings file) is listed with the presets; one below 1 is shown as 1, as the
|
||||
/// workspace applies it.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Func<string> folder, Action open, Func<Task>? change = null) : ObservableObject
|
||||
{
|
||||
public static readonly int[] KeptPresets = [5, 10, 20, 50, 100, 200];
|
||||
|
||||
/// <summary>The workspace folder in use.</summary>
|
||||
public string Folder => folder();
|
||||
|
||||
/// <summary>Shows the folder in Explorer.</summary>
|
||||
public RelayCommand OpenCommand { get; } = new(open);
|
||||
|
||||
/// <summary>Uses another folder, after its plan (WorkspaceFolderChange); none where the folder cannot change.</summary>
|
||||
public AsyncRelayCommand ChangeCommand { get; } = new(change ?? (() => Task.CompletedTask), () => change is not null);
|
||||
|
||||
public bool CanChange => change is not null;
|
||||
|
||||
public bool AutoSync
|
||||
{
|
||||
get => settings.WorkspaceAutoSync;
|
||||
set
|
||||
{
|
||||
if (settings.WorkspaceAutoSync == value) return;
|
||||
settings.WorkspaceAutoSync = value;
|
||||
save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> KeptChoices =>
|
||||
[.. (KeptPresets.Contains(Kept) ? KeptPresets : KeptPresets.Append(Kept)).Order().Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Workspace.Versions", n)))];
|
||||
|
||||
public SettingsOption<int> SelectedKept
|
||||
{
|
||||
get => KeptChoices.First(c => c.Value == Kept);
|
||||
set
|
||||
{
|
||||
if (value is null || value.Value == settings.WorkspaceKeptVersions) return;
|
||||
settings.WorkspaceKeptVersions = value.Value;
|
||||
save();
|
||||
OnPropertyChanged(nameof(KeptChoices));
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The defaults of every row (Reset section); the caller saves. The folder stays (Change chooses it, after its plan).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
var defaults = new AppSettings();
|
||||
settings.WorkspaceAutoSync = defaults.WorkspaceAutoSync;
|
||||
settings.WorkspaceKeptVersions = defaults.WorkspaceKeptVersions;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Labels in the current language, values as the settings have them now.</summary>
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
|
||||
/// <summary>The value the workspace applies: at least one version.</summary>
|
||||
private int Kept => Math.Max(1, settings.WorkspaceKeptVersions);
|
||||
}
|
||||
@@ -7,7 +7,9 @@ using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
@@ -41,9 +43,12 @@ public static class ErrorText
|
||||
private static string? Describe(Exception ex) => ex switch
|
||||
{
|
||||
LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException
|
||||
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message,
|
||||
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException or Core.Project.ProjectTooLargeException => ex.Message,
|
||||
// A template an archive refused (Settings › Archive, or this PC's templates for a new archive): the rule it breaks.
|
||||
TemplateRuleException rule => Loc.L("Errors.Template." + rule.Rule),
|
||||
// The workspace (owner review 2, R8): its own sentences, a home out of reach, a project the home refused.
|
||||
Workspace.WorkspaceException or HomeUnavailableException or ProjectException or WorkspaceSyncException or ProjectVersionTooLargeException =>
|
||||
Workspace.WorkspaceText.Failure(ex),
|
||||
// The server words its errors in the client's language (Accept-Language).
|
||||
ChronosApiException api when FromServer(api.Error) => api.Error.Message,
|
||||
// Any other reply (a reverse proxy's 502 page while the server restarts, its 413 for a large body, a bare 500) holds
|
||||
|
||||
@@ -0,0 +1,724 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Workspace;
|
||||
|
||||
/// <summary>What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project.</summary>
|
||||
public interface IWorkspaceUi
|
||||
{
|
||||
/// <summary>The dialog open now; null when none is.</summary>
|
||||
ArchiveDialogViewModel? Dialog { get; }
|
||||
|
||||
/// <summary>Shows <paramref name="dialog"/> now, in place of an open one (the dialog the user acted in leads to it).</summary>
|
||||
void ShowDialog(ArchiveDialogViewModel dialog);
|
||||
|
||||
/// <summary>
|
||||
/// Shows <paramref name="dialog"/> now when no dialog is open, else once the open one closes: something found in the
|
||||
/// background (a conflict an automatic sync met) never replaces what the user is doing.
|
||||
/// </summary>
|
||||
void ShowDialogWhenFree(ArchiveDialogViewModel dialog);
|
||||
|
||||
void CloseDialog(ArchiveDialogViewModel dialog);
|
||||
|
||||
/// <summary>True when the user chose the action (a destructive confirmation).</summary>
|
||||
bool Confirm(ConfirmRequest request);
|
||||
|
||||
void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false);
|
||||
|
||||
/// <summary>Opens project <paramref name="projectId"/> of <paramref name="sequenceId"/> in the editor (checked out and copied first when it is not here).</summary>
|
||||
Task OpenProjectAsync(Guid sequenceId, Guid projectId);
|
||||
|
||||
/// <summary>Closes the open project (its last edit stored first); the picker shows. False when the user kept it open.</summary>
|
||||
Task<bool> CloseProjectAsync();
|
||||
|
||||
/// <summary>The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again.</summary>
|
||||
Task SequenceChangedAsync(Guid sequenceId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The project menu of the editor's title (▾, owner review 2, R8) for a workspace project: where it stands (the chip, read
|
||||
/// again a moment after each edit), Save version (Ctrl+S, an optional note; sent at once with Settings › Workspace › Sync
|
||||
/// automatically), Sync, History (Compare, Restore as one undo step), Open project (another project of the sequence, at
|
||||
/// the library or here), New project, Rename, Delete project (never Main) and Remove local copy, and the "Update media"
|
||||
/// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a
|
||||
/// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A
|
||||
/// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict
|
||||
/// shown; one an automatic sync met waits for the dialog open to close. Call from the UI thread.
|
||||
/// </summary>
|
||||
public sealed class ProjectMenuViewModel : LocalizedViewModel
|
||||
{
|
||||
/// <summary>How long after the last edit the chip reads the working state again (a little after the editor's save).</summary>
|
||||
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
|
||||
|
||||
private readonly WorkspaceHost _host;
|
||||
private readonly WorkspaceSequenceSource _source;
|
||||
private readonly EditorSession _session;
|
||||
private readonly IWorkspaceUi _ui;
|
||||
private readonly AsyncRelayCommand _sync;
|
||||
private readonly AsyncRelayCommand _updateMedia;
|
||||
|
||||
/// <summary>The thread the menu was made on (the UI's); null where there is none (tests run inline).</summary>
|
||||
private readonly SynchronizationContext? _context = SynchronizationContext.Current;
|
||||
private WorkspaceStatus? _status;
|
||||
private bool _isSyncing;
|
||||
private bool _homeFramesChanged;
|
||||
private Guid _copyJob;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Counts the editor's changes, so only the last one's state read applies.</summary>
|
||||
private int _changes;
|
||||
|
||||
/// <summary>The conflict dialog asked in the background, until it is closed (one is asked at a time).</summary>
|
||||
private ConflictDialogViewModel? _asking;
|
||||
|
||||
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
|
||||
{
|
||||
_host = host;
|
||||
_source = source;
|
||||
_session = session;
|
||||
_ui = ui;
|
||||
_sync = new AsyncRelayCommand(() => SyncAsync(), () => !_isSyncing);
|
||||
_updateMedia = new AsyncRelayCommand(UpdateMediaAsync, () => _copyJob == Guid.Empty);
|
||||
SaveVersionCommand = new RelayCommand(OpenSaveVersion, () => CanSaveVersion);
|
||||
HistoryCommand = new AsyncRelayCommand(OpenHistoryAsync);
|
||||
OpenProjectCommand = new AsyncRelayCommand(OpenOtherProjectAsync);
|
||||
NewProjectCommand = new AsyncRelayCommand(OpenNewProjectAsync);
|
||||
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
|
||||
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
|
||||
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
|
||||
source.JobChanged += OnJobChanged;
|
||||
session.ProjectChanged += OnProjectChanged;
|
||||
}
|
||||
|
||||
public Guid ProjectId => _source.ProjectId;
|
||||
|
||||
public Guid SequenceId => _session.Content.Sequence.Id;
|
||||
|
||||
public bool IsMain => _source.Workspace?.IsMain == true;
|
||||
|
||||
/// <summary>The project's name (Main in the UI language).</summary>
|
||||
public string Name => _source.Workspace is { } workspace ? WorkspaceText.ProjectName(workspace.Name, workspace.IsMain) : string.Empty;
|
||||
|
||||
public WorkspaceStatus? Status => _status;
|
||||
|
||||
public bool IsSyncing => _isSyncing;
|
||||
|
||||
public string StateText => WorkspaceText.State(_status, _isSyncing);
|
||||
|
||||
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
|
||||
|
||||
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing);
|
||||
|
||||
/// <summary>The ▾ button: its name, then where the project stands, then what the menu holds.</summary>
|
||||
public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText);
|
||||
|
||||
/// <summary>The button's accessible name: the project and its state.</summary>
|
||||
public string MenuName => string.Join(Loc.Separator, Name, StateText);
|
||||
|
||||
/// <summary>
|
||||
/// The home's frames moved past those the workspace holds, or the library names photos otherwise since the copy (hashed,
|
||||
/// converted) and the media could not learn it yet (the last read of the library says so; a later one that taught them
|
||||
/// clears it): the banner offers Update media.
|
||||
/// </summary>
|
||||
public bool HasMediaUpdate => _homeFramesChanged || _status is { MediaOutdated: true };
|
||||
|
||||
/// <summary>A copy of the media runs (Update media): the banner says so.</summary>
|
||||
public bool IsUpdatingMedia => _copyJob != Guid.Empty;
|
||||
|
||||
public string MediaUpdateText => Loc.L(IsUpdatingMedia ? "Editor.Workspace.Updating" : "Editor.Workspace.MediaChanged");
|
||||
|
||||
/// <summary>A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project.</summary>
|
||||
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone };
|
||||
|
||||
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
|
||||
: _status?.State == WorkspaceState.Gone ? Loc.L("Errors.Workspace.DeletedAtHome")
|
||||
: _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict")
|
||||
: Loc.L("Tooltips.Editor.Project.SaveVersion");
|
||||
|
||||
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : Loc.L("Tooltips.Editor.Project.Delete");
|
||||
|
||||
/// <summary>Save version… (Ctrl+S): the note dialog.</summary>
|
||||
public ICommand SaveVersionCommand { get; }
|
||||
|
||||
public ICommand SyncCommand => _sync;
|
||||
|
||||
public ICommand HistoryCommand { get; }
|
||||
|
||||
/// <summary>Open project…: another project of the sequence, one of the library's (a Save both sibling, another PC's) or a new one.</summary>
|
||||
public ICommand OpenProjectCommand { get; }
|
||||
|
||||
public ICommand NewProjectCommand { get; }
|
||||
|
||||
public ICommand RenameCommand { get; }
|
||||
|
||||
public ICommand DeleteCommand { get; }
|
||||
|
||||
public ICommand RemoveCopyCommand { get; }
|
||||
|
||||
public ICommand UpdateMediaCommand => _updateMedia;
|
||||
|
||||
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
|
||||
public async Task RefreshAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var status = await _host.StatusAsync(ProjectId);
|
||||
var moved = await _source.HomeFramesChangedAsync(CancellationToken.None);
|
||||
if (_disposed) return;
|
||||
_homeFramesChanged = moved;
|
||||
Apply(status);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"The state of project {ProjectId} could not be read", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A job of the sequence ended: where the project stands is read again; after an analysis, which writes its Auto
|
||||
/// values into the library's settings (Main's), the project takes them at once with Sync automatically.
|
||||
/// </summary>
|
||||
public async Task JobEndedAsync(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
await RefreshAsync();
|
||||
if (_disposed || !_host.Settings.WorkspaceAutoSync || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse)) return;
|
||||
if (_status is { State: WorkspaceState.Behind }) await SyncAsync(quiet: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
|
||||
/// sync took from the home comes into the editor, a conflict it met is asked about.
|
||||
/// </summary>
|
||||
/// <exception cref="WorkspaceException">Why no version could be saved (the edit could not be stored, a conflict, read-only).</exception>
|
||||
public async Task SaveVersionAsync(string? note)
|
||||
{
|
||||
await StoreEditAsync();
|
||||
var result = await _host.SaveVersionAsync(ProjectId, note);
|
||||
if (_disposed) return;
|
||||
Apply(result.Status);
|
||||
if (result.Synced is { } taken) await TakeAsync(taken);
|
||||
if (result.Version is null)
|
||||
{
|
||||
_ui.Notify(Loc.L("Editor.Workspace.NothingNew"), Name);
|
||||
}
|
||||
else if (result.Synced is { Pushed.Count: > 0 } synced)
|
||||
{
|
||||
// The home numbers what it stores: the last one sent is this version.
|
||||
_ui.Notify(Loc.L("Editor.Workspace.SavedSent", Formatting.Count(synced.Pushed[^1].Number)), Name);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name);
|
||||
}
|
||||
if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error), isError: error is not HomeUnavailableException);
|
||||
// Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here.
|
||||
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
|
||||
else if (result.Status.Conflict is { } conflict) AskConflict(conflict);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sync: the home's new versions taken into the editor, the local ones sent; a conflict is asked about (once the open
|
||||
/// dialog closes when <paramref name="quiet"/>: the sync ran in the background).
|
||||
/// </summary>
|
||||
public async Task SyncAsync(bool quiet = false)
|
||||
{
|
||||
if (_isSyncing) return;
|
||||
SetSyncing(true);
|
||||
try
|
||||
{
|
||||
await StoreEditAsync();
|
||||
var result = await _host.SyncAsync(ProjectId);
|
||||
if (_disposed) return;
|
||||
Apply(result.Status);
|
||||
await TakeAsync(result);
|
||||
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
|
||||
else if (result.Status.Conflict is { } conflict) AskConflict(conflict, background: quiet);
|
||||
else if (!quiet) _ui.Notify(Loc.L(result.Status.State == WorkspaceState.InSync ? "Editor.Workspace.InSync" : "Editor.Workspace.Synced"), Name);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"Project {ProjectId} could not be synced", ex);
|
||||
_ui.Notify(Loc.L(ex is HomeUnavailableException ? "Editor.Workspace.Offline" : "Editor.Workspace.SyncFailed"), WorkspaceText.Failure(ex),
|
||||
isError: ex is not HomeUnavailableException);
|
||||
await RefreshAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
SetSyncing(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles the conflict <paramref name="shown"/> listed (else the one recorded) as chosen, then brings the settled
|
||||
/// working state into the editor: the library's values taken as one undo step (the toast's Undo, Ctrl+Z), what Save
|
||||
/// both made offered by its toast. When what differs changed since it was shown, nothing is settled and it is asked again.
|
||||
/// A project deleted in the library meanwhile is said so once, nothing asked again: its work stays here (the copy Save
|
||||
/// both made holding it too, offered by its toast).
|
||||
/// </summary>
|
||||
public async Task ResolveAsync(ConflictChoice choice, WorkspaceConflict? shown = null)
|
||||
{
|
||||
await StoreEditAsync();
|
||||
var result = await _host.ResolveAsync(ProjectId, choice, shown: shown);
|
||||
if (_disposed) return;
|
||||
Apply(result.Status);
|
||||
if (result.Status.State == WorkspaceState.Gone)
|
||||
{
|
||||
NotifyGone();
|
||||
NotifySavedAs(result);
|
||||
return;
|
||||
}
|
||||
if (result.Status.Conflict is { } again)
|
||||
{
|
||||
await TakeAsync(result);
|
||||
AskConflict(again);
|
||||
return;
|
||||
}
|
||||
if (result.Kept is { } kept)
|
||||
{
|
||||
if (await _session.TakeOverAsync(kept) is { } step)
|
||||
_ui.Notify(Loc.L("Editor.Workspace.TookLibrary"), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.UndoTake"), () => step.Undo());
|
||||
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
|
||||
}
|
||||
else
|
||||
{
|
||||
await TakeAsync(result, force: true);
|
||||
}
|
||||
NotifySavedAs(result);
|
||||
}
|
||||
|
||||
/// <summary>The project Save both made, offered by its toast.</summary>
|
||||
private void NotifySavedAs(WorkspaceSyncResult result)
|
||||
{
|
||||
if (result.SavedAs is not { } copy) return;
|
||||
var sequenceId = SequenceId;
|
||||
_ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name, Loc.L("Editor.Workspace.OpenCopy"), Loc.L("Tooltips.Editor.Workspace.OpenCopy", copy.Name),
|
||||
() => _ = _ui.OpenProjectAsync(sequenceId, copy.Id));
|
||||
}
|
||||
|
||||
/// <summary>The library no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
|
||||
private void NotifyGone() => _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome"));
|
||||
|
||||
/// <summary>
|
||||
/// Restores <paramref name="version"/> as the project, as one undo step (uncommitted changes are saved as a version
|
||||
/// first, so nothing is lost); the toast's Undo takes it back while it is the last change.
|
||||
/// </summary>
|
||||
public async Task RestoreAsync(ProjectVersion version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
await StoreEditAsync();
|
||||
var restored = await _host.RestoreAsync(ProjectId, version.Id);
|
||||
if (_disposed) return;
|
||||
var before = _session.Project;
|
||||
if (_session.Edit(_ => restored))
|
||||
{
|
||||
_session.EndEditRun();
|
||||
var undo = new ProjectRestore(_session, before, _session.Project);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.Restored", Formatting.Count(version.Number)), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.Undo"),
|
||||
() => undo.Undo());
|
||||
}
|
||||
else
|
||||
{
|
||||
_ui.Notify(Loc.L("Editor.Copy.Same"), Name);
|
||||
}
|
||||
await RefreshAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings that differ between the project now and <paramref name="version"/>, the version placed on the media's
|
||||
/// frames first: exclusions, the hero and keyframes compare as the settings they are (a photo the media lack stays
|
||||
/// parked, and reads as such).
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Compare(ProjectVersion version, int max = 12)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
var photos = _source.Photos;
|
||||
if (_session.Project.IsNewerFormat || ProjectContent.FormatOf(version.SettingsJson) > ProjectSettings.CurrentVersion)
|
||||
return WorkspaceText.CompareLines(SyncRules.Differences(ProjectContent.ToPortable(_session.Project, photos), version.SettingsJson, 64), max);
|
||||
var then = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Rebind(version.SettingsJson, photos), photos), allowNewer: true);
|
||||
return WorkspaceText.CompareLines(SyncRules.Differences(_session.Project.ToJson(), then.ToJson(), 64), max);
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
_source.JobChanged -= OnJobChanged;
|
||||
_session.ProjectChanged -= OnProjectChanged;
|
||||
// A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time).
|
||||
if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
protected override void OnLanguageChanged()
|
||||
{
|
||||
base.OnLanguageChanged();
|
||||
RaiseState();
|
||||
}
|
||||
|
||||
private void OpenSaveVersion()
|
||||
{
|
||||
if (!CanSaveVersion) return;
|
||||
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog));
|
||||
}
|
||||
|
||||
private async Task OpenHistoryAsync()
|
||||
{
|
||||
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog);
|
||||
_ui.ShowDialog(dialog);
|
||||
try
|
||||
{
|
||||
await StoreEditAsync();
|
||||
var history = await _host.HistoryAsync(ProjectId, Math.Max(50, _host.Settings.WorkspaceKeptVersions));
|
||||
dialog.Show(history, ProjectContent.Hash(ProjectContent.ToPortable(_session.Project, _source.Photos)));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"The history of project {ProjectId} could not be read", ex);
|
||||
dialog.ShowFailure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Open project…: "Open in workspace" over the library's projects of the sequence but the open one (a Save both
|
||||
/// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not
|
||||
/// here yet).
|
||||
/// </summary>
|
||||
private async Task OpenOtherProjectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await StoreEditAsync();
|
||||
var projects = (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != ProjectId).ToList();
|
||||
var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog,
|
||||
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)]);
|
||||
_ui.ShowDialog(dialog);
|
||||
if (await dialog.Choice is not { } choice || _disposed) return;
|
||||
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(SequenceId, choice.NewName!, _status?.Base?.VersionId)).Id;
|
||||
await _ui.OpenProjectAsync(SequenceId, id);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OpenNewProjectAsync()
|
||||
{
|
||||
var names = await OtherNamesAsync(null);
|
||||
_ui.ShowDialog(new ProjectNameDialogViewModel(false, string.Empty, names, async name =>
|
||||
{
|
||||
await StoreEditAsync();
|
||||
// From the open project's last version at the home, so the new one starts where this one is there.
|
||||
var created = await _host.CreateProjectAsync(SequenceId, name, _status?.Base?.VersionId);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
|
||||
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
|
||||
}, _ui.CloseDialog));
|
||||
}
|
||||
|
||||
private async Task OpenRenameAsync()
|
||||
{
|
||||
var names = await OtherNamesAsync(ProjectId);
|
||||
_ui.ShowDialog(new ProjectNameDialogViewModel(true, _source.Workspace?.Name ?? string.Empty, names, async name =>
|
||||
{
|
||||
await _host.RenameAsync(ProjectId, name);
|
||||
await _session.ReloadAsync();
|
||||
_ui.Notify(Loc.L("Editor.Workspace.Renamed"), name);
|
||||
RaiseState();
|
||||
}, _ui.CloseDialog));
|
||||
}
|
||||
|
||||
private async Task DeleteAsync()
|
||||
{
|
||||
if (IsMain) return;
|
||||
var name = Name;
|
||||
if (!_ui.Confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Editor.Project.DeleteTitle", name),
|
||||
Message = Loc.L("Editor.Project.DeleteMessage"),
|
||||
SafeText = Loc.L("Editor.Project.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"),
|
||||
ActionText = Loc.L("Editor.Project.DeleteAction"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Project.DeleteAction"),
|
||||
IsDestructive = true,
|
||||
}))
|
||||
return;
|
||||
try
|
||||
{
|
||||
// Everything sent first, while the project is still open: a delete that cannot happen leaves it as it was.
|
||||
await SaveAndSendAsync();
|
||||
var (sequenceId, projectId) = (SequenceId, ProjectId);
|
||||
if (!await _ui.CloseProjectAsync()) return;
|
||||
// The library's delete stands even when the local copy could not go with it: it is said, and Remove local copy takes it later.
|
||||
if (await _host.DeleteProjectAsync(projectId)) _ui.Notify(Loc.L("Editor.Workspace.Deleted", name));
|
||||
else _ui.Notify(Loc.L("Editor.Workspace.Deleted", name), Loc.L("Errors.Workspace.CopyKept"), isError: true);
|
||||
await _ui.SequenceChangedAsync(sequenceId);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"Project {ProjectId} was not deleted", ex);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OpenRemoveCopyAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await StoreEditAsync();
|
||||
var plan = await _host.PlanRemovalAsync(ProjectId);
|
||||
var (projectId, name) = (ProjectId, Name);
|
||||
_ui.ShowDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveAsync(projectId, discard), async () =>
|
||||
{
|
||||
await SaveAndSendAsync();
|
||||
await RemoveAsync(projectId, discard: false);
|
||||
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"The removal of project {ProjectId} could not be planned", ex);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The working state saved as a version and everything sent, for Send first and Delete project. A conflict the sync
|
||||
/// meets is asked about at once (in place of the dialog that asked for it), never left behind a reason to discard.
|
||||
/// </summary>
|
||||
/// <exception cref="WorkspaceException">Something could not be sent: a conflict to settle first, or the work not in the library yet.</exception>
|
||||
private async Task SaveAndSendAsync()
|
||||
{
|
||||
await StoreEditAsync();
|
||||
if (CanSaveVersion) await _host.CommitAsync(ProjectId);
|
||||
var result = await _host.SyncAsync(ProjectId);
|
||||
Apply(result.Status);
|
||||
await TakeAsync(result);
|
||||
// Nothing can be sent to a project the library no longer has: only Discard takes the copy, its work kept aside.
|
||||
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
|
||||
if (result.Status.Conflict is { } conflict)
|
||||
{
|
||||
AskConflict(conflict);
|
||||
throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
|
||||
}
|
||||
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
|
||||
}
|
||||
|
||||
private async Task RemoveAsync(Guid projectId, bool discard)
|
||||
{
|
||||
// Checked before the editor closes, so a copy that cannot go leaves it open.
|
||||
if (!discard)
|
||||
{
|
||||
var status = await _host.StatusAsync(projectId, askHome: false);
|
||||
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
|
||||
}
|
||||
var name = Name;
|
||||
if (!await _ui.CloseProjectAsync()) return;
|
||||
await _host.RemoveLocalCopyAsync(projectId, discard);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.Removed"), name);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<string>> OtherNamesAsync(Guid? except)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != except).Select(p => p.Name)];
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// The home checks the name again when the project is made.
|
||||
Log.Info("workspace", $"The projects of sequence {SequenceId} could not be listed: {ex.Message}");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UpdateMediaAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await StoreEditAsync();
|
||||
var job = await _host.QueueCopyAsync(ProjectId);
|
||||
_copyJob = job.Id;
|
||||
RaiseState();
|
||||
_ui.Notify(Loc.L("Editor.Workspace.Copying"), _session.Content.Sequence.DisplayTitle);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"The media of project {ProjectId} could not be copied again", ex);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The editor's last edit stored in the working state before an operation reads it.</summary>
|
||||
/// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception>
|
||||
private async Task StoreEditAsync()
|
||||
{
|
||||
if (await _session.FlushAsync()) return;
|
||||
throw new WorkspaceException(Loc.L("Errors.Workspace.EditNotStored"), _session.LastSaveError);
|
||||
}
|
||||
|
||||
/// <summary>What a sync, resolve or restore took from the home comes into the editor, merged with what was edited meanwhile.</summary>
|
||||
private async Task TakeAsync(WorkspaceSyncResult result, bool force = false)
|
||||
{
|
||||
if (force || result.Pulled.Count > 0) await _session.ReloadAsync();
|
||||
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asks how to settle <paramref name="conflict"/>, the choice applying to it as listed. One a sync met in the
|
||||
/// <paramref name="background"/> (after an analysis) waits for the open dialog to close, and is asked once: the chip
|
||||
/// says Conflict meanwhile, and Sync asks again.
|
||||
/// </summary>
|
||||
private void AskConflict(WorkspaceConflict conflict, bool background = false)
|
||||
{
|
||||
if (background && _asking is { IsClosed: false }) return;
|
||||
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
|
||||
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
|
||||
_ui.CloseDialog, conflict.NewerFormat);
|
||||
if (!background)
|
||||
{
|
||||
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
|
||||
_asking?.Dispose();
|
||||
_asking = null;
|
||||
_ui.ShowDialog(dialog);
|
||||
return;
|
||||
}
|
||||
_asking = dialog;
|
||||
_ui.ShowDialogWhenFree(dialog);
|
||||
}
|
||||
|
||||
/// <summary>The editor's project changed (an edit, undo, a merge; the UI thread): the chip reads the working state again a moment later.</summary>
|
||||
private void OnProjectChanged()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_ = RefreshLocalAsync(++_changes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After the last change's save: where the working state stands now (changed, saved as versions), the library's facts
|
||||
/// (newer, out of reach) kept from the last time it was asked; no read of the home on every edit.
|
||||
/// </summary>
|
||||
private async Task RefreshLocalAsync(int change)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The save follows the change after a moment (and is retried after a failure): read once it is stored.
|
||||
for (var wait = 0; wait == 0 || (_session.HasPendingSave && wait < 10); wait++)
|
||||
{
|
||||
await Task.Delay(StateRefreshDelay);
|
||||
if (_disposed || change != _changes) return;
|
||||
}
|
||||
if (_isSyncing || _session.HasPendingSave) return;
|
||||
var local = await _host.StatusAsync(ProjectId, askHome: false);
|
||||
if (_disposed || change != _changes || _isSyncing) return;
|
||||
Apply(WithLocal(_status, local));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Debug("workspace", $"The state of project {ProjectId} could not be read after an edit: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The state read without the home (<paramref name="local"/>) with what the last read of the home said (how far the
|
||||
/// library is ahead, whether it could be reached, whether it still has the project), in the order the sync ranks them.
|
||||
/// </summary>
|
||||
internal static WorkspaceStatus WithLocal(WorkspaceStatus? last, WorkspaceStatus local)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(local);
|
||||
if (last is null) return local;
|
||||
var gone = last.State == WorkspaceState.Gone;
|
||||
// A base that moved since (a sync) leaves how far the library is ahead unknown until it is asked again.
|
||||
var behind = last.Base?.VersionId == local.Base?.VersionId ? last.Behind : 0;
|
||||
// A project the library no longer has holds no conflict to answer (the one recorded stays for the record).
|
||||
var status = local with
|
||||
{
|
||||
Behind = behind,
|
||||
Offline = last.Offline,
|
||||
HomeHead = last.HomeHead,
|
||||
MediaOutdated = last.MediaOutdated,
|
||||
Conflict = gone ? null : local.Conflict,
|
||||
};
|
||||
var state = gone ? WorkspaceState.Gone
|
||||
: status.MediaRemoved ? WorkspaceState.MediaRemoved
|
||||
: status.Damaged > 0 ? WorkspaceState.Damaged
|
||||
: status.Conflict is not null ? WorkspaceState.Conflict
|
||||
: status.Offline ? WorkspaceState.Offline
|
||||
: status.Behind > 0 ? WorkspaceState.Behind
|
||||
: status.Ahead > 0 ? WorkspaceState.Ahead
|
||||
: status.Modified ? WorkspaceState.Modified
|
||||
: WorkspaceState.InSync;
|
||||
return status with { State = state };
|
||||
}
|
||||
|
||||
/// <summary>A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread.</summary>
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job.Id != _copyJob || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
|
||||
if (_context is { } context) context.Post(_ => _ = CopyEndedAsync(job), null);
|
||||
else _ = CopyEndedAsync(job);
|
||||
}
|
||||
|
||||
/// <summary>The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not.</summary>
|
||||
private async Task CopyEndedAsync(Job job)
|
||||
{
|
||||
if (_disposed || job.Id != _copyJob) return;
|
||||
_copyJob = Guid.Empty;
|
||||
if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true);
|
||||
try
|
||||
{
|
||||
if (job.State == JobState.Done) await _session.ReloadAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"The new media of project {ProjectId} could not be read", ex);
|
||||
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
|
||||
}
|
||||
await RefreshAsync();
|
||||
RaiseState();
|
||||
}
|
||||
|
||||
private void Apply(WorkspaceStatus status)
|
||||
{
|
||||
_status = status;
|
||||
RaiseState();
|
||||
}
|
||||
|
||||
private void SetSyncing(bool syncing)
|
||||
{
|
||||
_isSyncing = syncing;
|
||||
_sync.RaiseCanExecuteChanged();
|
||||
RaiseState();
|
||||
}
|
||||
|
||||
private void RaiseState()
|
||||
{
|
||||
OnPropertyChanged(nameof(Status));
|
||||
OnPropertyChanged(nameof(Name));
|
||||
OnPropertyChanged(nameof(IsMain));
|
||||
OnPropertyChanged(nameof(IsSyncing));
|
||||
OnPropertyChanged(nameof(StateText));
|
||||
OnPropertyChanged(nameof(StateKind));
|
||||
OnPropertyChanged(nameof(StateToolTip));
|
||||
OnPropertyChanged(nameof(MenuToolTip));
|
||||
OnPropertyChanged(nameof(MenuName));
|
||||
OnPropertyChanged(nameof(HasMediaUpdate));
|
||||
OnPropertyChanged(nameof(IsUpdatingMedia));
|
||||
OnPropertyChanged(nameof(MediaUpdateText));
|
||||
OnPropertyChanged(nameof(CanSaveVersion));
|
||||
OnPropertyChanged(nameof(SaveVersionToolTip));
|
||||
OnPropertyChanged(nameof(DeleteToolTip));
|
||||
_updateMedia.RaiseCanExecuteChanged();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Workspace;
|
||||
|
||||
/// <summary>What "Open in workspace" chose: an existing project of the home (<see cref="ProjectId"/>) or a new one (<see cref="NewName"/>), and the media.</summary>
|
||||
public sealed record OpenChoice(Guid? ProjectId, string? NewName, string Media);
|
||||
|
||||
/// <summary>
|
||||
/// A project of the home offered by "Open in workspace" (Main in the UI language). One whose copy here this Chronos cannot
|
||||
/// read (<paramref name="Unreadable"/>: why) is shown, disabled, its reason in the tooltip.
|
||||
/// </summary>
|
||||
public sealed record ProjectOption(SequenceProject Project, string? Unreadable = null)
|
||||
{
|
||||
public string Label => WorkspaceText.ProjectName(Project.Name, Project.IsMain);
|
||||
|
||||
/// <summary>It can be chosen: its copy here, if any, is one this Chronos reads.</summary>
|
||||
public bool IsAvailable => Unreadable is null;
|
||||
|
||||
public string ToolTip => Unreadable ?? Loc.L("Tooltips.Editor.OpenWorkspace.Projects");
|
||||
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
|
||||
/// <summary>Project names as the home takes them: 1 to 60 characters, no control character, each once per sequence (case does not count).</summary>
|
||||
public static class ProjectNames
|
||||
{
|
||||
/// <summary>The problem of <paramref name="name"/>, or null when the home takes it.</summary>
|
||||
public static string? Validate(string name, IEnumerable<string> others)
|
||||
{
|
||||
var trimmed = name?.Trim() ?? string.Empty;
|
||||
if (trimmed.Length is 0 or > ProjectService.MaxNameLength || trimmed.Any(char.IsControl)) return Loc.L("Errors.Workspace.InvalidName");
|
||||
return others.Any(o => string.Equals(o, trimmed, StringComparison.OrdinalIgnoreCase)) ? Loc.L("Errors.Workspace.NameTaken") : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet, and by the project
|
||||
/// menu's Open project: which project of its home (Main, made from the sequence's settings as they are, or another) or a
|
||||
/// new one with its name, and the media to copy (proxies; the originals come in phase 5c). Open queues the copy; the
|
||||
/// sequence opens once it is done.
|
||||
/// </summary>
|
||||
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly TaskCompletionSource<OpenChoice?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private ProjectOption? _selected;
|
||||
private bool _isNew;
|
||||
|
||||
/// <param name="taken">The names a new project cannot take (default: those of <paramref name="projects"/>).</param>
|
||||
/// <param name="copy">What the copy of the media writes and the free space of the workspace's drive; null when not measured (shown as nothing).</param>
|
||||
/// <param name="unreadable">
|
||||
/// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen.
|
||||
/// </param>
|
||||
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
|
||||
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null)
|
||||
: base(close)
|
||||
{
|
||||
SequenceTitle = sequenceTitle;
|
||||
Copy = copy;
|
||||
CopyFacts = copy is null ? []
|
||||
:
|
||||
[
|
||||
new DialogFact(Loc.L("Editor.OpenWorkspace.Size"), Formatting.Bytes(copy.Bytes), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.Size")),
|
||||
new DialogFact(Loc.L("Editor.OpenWorkspace.Free"), copy.Free is { } free ? Formatting.Bytes(free) : Loc.L("Server.Sync.None"),
|
||||
Reason: Loc.L(copy.TooLittleSpace ? "Errors.Workspace.NoRoom" : "Tooltips.Editor.OpenWorkspace.Free")),
|
||||
];
|
||||
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))];
|
||||
_selected = Projects.FirstOrDefault(p => p.IsAvailable);
|
||||
_isNew = !HasProjects;
|
||||
var names = taken ?? [.. projects.Select(p => p.Name)];
|
||||
NewName = new EditableField(string.Empty, n => ProjectNames.Validate(n, names), _ => { }, () => Loc.L("Tooltips.Editor.OpenWorkspace.Name"));
|
||||
NewName.PropertyChanged += (_, _) => Refresh();
|
||||
OpenCommand = new RelayCommand(Open, () => CanOpen);
|
||||
}
|
||||
|
||||
/// <summary>Completes with the user's choice, or null when the dialog was closed without one.</summary>
|
||||
public Task<OpenChoice?> Choice => _choice.Task;
|
||||
|
||||
public string SequenceTitle { get; }
|
||||
|
||||
/// <summary>The copy's bytes and the drive's free space, when measured.</summary>
|
||||
public WorkspaceCopyFacts? Copy { get; }
|
||||
|
||||
/// <summary>"Copy size" and "Free space", under the media.</summary>
|
||||
public IReadOnlyList<DialogFact> CopyFacts { get; }
|
||||
|
||||
/// <summary>The drive lacks room for the copy: the free space says so (the copy would stop saying how much is missing).</summary>
|
||||
public bool IsShortOfSpace => Copy?.TooLittleSpace == true;
|
||||
|
||||
public string Heading => Loc.L("Editor.OpenWorkspace.Title");
|
||||
|
||||
public IReadOnlyList<ProjectOption> Projects { get; }
|
||||
|
||||
/// <summary>A project of the home can be chosen (one this Chronos cannot read here is only listed).</summary>
|
||||
public bool HasProjects => Projects.Any(p => p.IsAvailable);
|
||||
|
||||
public ProjectOption? SelectedProject
|
||||
{
|
||||
get => _selected;
|
||||
set
|
||||
{
|
||||
if (value is { IsAvailable: false }) return;
|
||||
if (Set(ref _selected, value) && value is not null) IsExisting = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A project the home has.</summary>
|
||||
public bool IsExisting
|
||||
{
|
||||
get => !_isNew;
|
||||
set
|
||||
{
|
||||
if (value) IsNew = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new project, named in <see cref="NewName"/>.</summary>
|
||||
public bool IsNew
|
||||
{
|
||||
get => _isNew;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _isNew, value || !HasProjects)) return;
|
||||
OnPropertyChanged(nameof(IsExisting));
|
||||
Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
public EditableField NewName { get; }
|
||||
|
||||
/// <summary>The proxies, the only media this phase copies.</summary>
|
||||
public bool IsProxies => true;
|
||||
|
||||
/// <summary>The originals: offered from phase 5c, to render on this PC.</summary>
|
||||
public bool CanCopyOriginals => false;
|
||||
|
||||
public ICommand OpenCommand { get; }
|
||||
|
||||
public bool CanOpen => _isNew ? !NewName.HasErrors : _selected is { IsAvailable: true };
|
||||
|
||||
public string OpenToolTip => _isNew && NewName.Error is { } error ? error : Loc.L("Tooltips.Editor.OpenWorkspace.Open");
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
// Closed without a choice (Cancel, Esc, another sequence asked for).
|
||||
_choice.TrySetResult(null);
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private void Open()
|
||||
{
|
||||
if (!CanOpen) return;
|
||||
_choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), BundleMedia.Proxies) : new OpenChoice(_selected!.Project.Id, null, BundleMedia.Proxies));
|
||||
Close();
|
||||
}
|
||||
|
||||
private void Refresh()
|
||||
{
|
||||
OnPropertyChanged(nameof(CanOpen));
|
||||
OnPropertyChanged(nameof(OpenToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Names a project: "New project" (made from the open project's last version at the home) or "Rename".</summary>
|
||||
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly Func<string, Task> _save;
|
||||
|
||||
/// <param name="others">The names of the sequence's other projects (each name is used once).</param>
|
||||
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
IsRename = rename;
|
||||
_save = save;
|
||||
var taken = others.ToList();
|
||||
Name = new EditableField(name, n => ProjectNames.Validate(n, taken), _ => { }, () => Loc.L("Tooltips.Editor.ProjectName.Name"));
|
||||
Name.PropertyChanged += (_, _) =>
|
||||
{
|
||||
OnPropertyChanged(nameof(SaveToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
};
|
||||
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy && !Name.HasErrors);
|
||||
}
|
||||
|
||||
public bool IsRename { get; }
|
||||
|
||||
public string Heading => Loc.L(IsRename ? "Editor.ProjectName.Rename" : "Editor.ProjectName.New");
|
||||
|
||||
public string SaveText => Loc.L(IsRename ? "Editor.ProjectName.Apply" : "Editor.ProjectName.Create");
|
||||
|
||||
public EditableField Name { get; }
|
||||
|
||||
public ICommand SaveCommand { get; }
|
||||
|
||||
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create");
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await _save(Name.Text.Trim());
|
||||
Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", "Naming a project failed", ex);
|
||||
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Save version" (Ctrl+S): an optional note, then the version is saved (and sent when Sync automatically is on).</summary>
|
||||
public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
/// <summary>A note is a line of the history: longer text is cut there.</summary>
|
||||
public const int MaxNoteLength = 200;
|
||||
|
||||
private readonly Func<string?, Task> _save;
|
||||
private string _note = string.Empty;
|
||||
|
||||
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
ProjectName = projectName;
|
||||
_save = save;
|
||||
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy);
|
||||
}
|
||||
|
||||
public string ProjectName { get; }
|
||||
|
||||
public string Heading => Loc.L("Editor.SaveVersion.Title", ProjectName);
|
||||
|
||||
public string Note
|
||||
{
|
||||
get => _note;
|
||||
set => Set(ref _note, (value ?? string.Empty).Length > MaxNoteLength ? value![..MaxNoteLength] : value ?? string.Empty);
|
||||
}
|
||||
|
||||
public ICommand SaveCommand { get; }
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await _save(string.IsNullOrWhiteSpace(_note) ? null : _note.Trim());
|
||||
Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", "Saving a version failed", ex);
|
||||
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A version in the History flyout: number, author, time, note, what made it, and Compare and Restore.</summary>
|
||||
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore) : ObservableObject
|
||||
{
|
||||
public ProjectVersion Version { get; } = version;
|
||||
|
||||
public string Number => Formatting.Count(Version.Number);
|
||||
|
||||
public string Author => WorkspaceText.Author(Version);
|
||||
|
||||
public string When => WorkspaceText.When(Version.CreatedAt);
|
||||
|
||||
public string Note => Version.Note ?? string.Empty;
|
||||
|
||||
public string KindText => WorkspaceText.VersionKind(Version.Kind);
|
||||
|
||||
/// <summary>Saved here, waiting to be sent.</summary>
|
||||
public bool IsUnsent { get; } = unsent;
|
||||
|
||||
/// <summary>The version the working state was last saved as (nothing differs).</summary>
|
||||
public bool IsCurrent { get; } = isCurrent;
|
||||
|
||||
/// <summary>"Version 3 · Saved · STUDIO-PC · 28/10/2026 18:02 · note": the row for screen readers and its tooltip.</summary>
|
||||
public string Description => string.Join(Loc.Separator, new[] { Loc.L("Editor.History.Version", Number), KindText, Author, When, Note }.Where(s => s.Length > 0));
|
||||
|
||||
public ICommand CompareCommand { get; } = compare;
|
||||
|
||||
public ICommand RestoreCommand { get; } = restore;
|
||||
|
||||
public string CompareToolTip => Loc.L("Tooltips.Editor.History.Compare", Number);
|
||||
|
||||
public string RestoreToolTip => Loc.L("Tooltips.Editor.History.Restore", Number);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The History flyout of a workspace project: its versions newest first (those not sent yet marked), Compare (the
|
||||
/// settings that differ from the project now) and Restore (the version as the project again, one undo step).
|
||||
/// </summary>
|
||||
public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly Func<ProjectVersion, Task<IReadOnlyList<string>>> _compare;
|
||||
private readonly Func<ProjectVersion, Task> _restore;
|
||||
private string? _comparedTitle;
|
||||
private IReadOnlyList<string> _compared = [];
|
||||
private bool _isLoaded;
|
||||
|
||||
public HistoryDialogViewModel(string projectName, Func<ProjectVersion, Task<IReadOnlyList<string>>> compare, Func<ProjectVersion, Task> restore,
|
||||
Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
ProjectName = projectName;
|
||||
_compare = compare;
|
||||
_restore = restore;
|
||||
}
|
||||
|
||||
public string ProjectName { get; }
|
||||
|
||||
public string Heading => Loc.L("Editor.History.Title", ProjectName);
|
||||
|
||||
public ObservableCollection<HistoryRowViewModel> Rows { get; } = [];
|
||||
|
||||
/// <summary>The home could not be asked: only this PC's versions are listed.</summary>
|
||||
public bool IsOffline { get; private set; }
|
||||
|
||||
public bool IsEmpty => _isLoaded && Rows.Count == 0;
|
||||
|
||||
/// <summary>"Version 3 → now" over the comparison; null before one.</summary>
|
||||
public string? ComparedTitle { get => _comparedTitle; private set => Set(ref _comparedTitle, value); }
|
||||
|
||||
public IReadOnlyList<string> Compared { get => _compared; private set => Set(ref _compared, value); }
|
||||
|
||||
/// <summary>Lists <paramref name="history"/>; <paramref name="currentHash"/> marks the version the project is now.</summary>
|
||||
public void Show(WorkspaceHistory history, string? currentHash)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(history);
|
||||
Rows.Clear();
|
||||
foreach (var version in history.Versions)
|
||||
{
|
||||
var current = currentHash is not null && string.Equals(version.ContentHash, currentHash, StringComparison.OrdinalIgnoreCase);
|
||||
Rows.Add(new HistoryRowViewModel(version, history.Unsent.Contains(version.Id), current,
|
||||
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy)));
|
||||
}
|
||||
IsOffline = history.Offline;
|
||||
_isLoaded = true;
|
||||
OnPropertyChanged(nameof(IsOffline));
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
}
|
||||
|
||||
/// <summary>A failure of the read that lists the versions, shown in the flyout.</summary>
|
||||
public void ShowFailure(Exception ex)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ex);
|
||||
_isLoaded = true;
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
|
||||
}
|
||||
|
||||
public async Task CompareAsync(ProjectVersion version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
ClearError();
|
||||
try
|
||||
{
|
||||
var lines = await _compare(version);
|
||||
ComparedTitle = Loc.L("Editor.History.Compared", Formatting.Count(version.Number));
|
||||
Compared = lines.Count == 0 ? [Loc.L("Editor.History.Same")] : lines;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"Version {version.Number} could not be compared", ex);
|
||||
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RestoreAsync(ProjectVersion version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await _restore(version);
|
||||
IsBusy = false;
|
||||
Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"Version {version.Number} could not be restored", ex);
|
||||
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sync that met settings both sides changed (owner review 2, R8: asked only on real conflicts): what differs, then
|
||||
/// Keep mine, Take the library's, or Save both (this workspace's versions go to a sibling project). Later leaves the
|
||||
/// conflict for the next Sync; editing goes on meanwhile. A conflict of format (the library's project saved by a newer
|
||||
/// Chronos, <see cref="WorkspaceConflict.NewerFormat"/>) cannot be merged either way: only Save both and Later are offered.
|
||||
/// </summary>
|
||||
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly Func<ConflictChoice, Task> _resolve;
|
||||
|
||||
/// <param name="newerFormat">The library holds a newer Chronos's settings: nothing is merged, Save both is the only choice.</param>
|
||||
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
|
||||
Action<ArchiveDialogViewModel> close, bool newerFormat = false)
|
||||
: base(close)
|
||||
{
|
||||
ProjectName = projectName;
|
||||
SiblingName = siblingName;
|
||||
IsNewerFormat = newerFormat;
|
||||
// The format's number says nothing to the user: the line names the cause.
|
||||
Differences = newerFormat ? [Loc.L("Editor.Workspace.Conflict.NewerFormat")] : differences;
|
||||
_resolve = resolve;
|
||||
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy && CanMerge);
|
||||
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy && CanMerge);
|
||||
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
|
||||
}
|
||||
|
||||
/// <summary>The library's project was saved by a newer Chronos.</summary>
|
||||
public bool IsNewerFormat { get; }
|
||||
|
||||
/// <summary>Keep mine and Take the library's are offered (not for a conflict of format, which neither can settle).</summary>
|
||||
public bool CanMerge => !IsNewerFormat;
|
||||
|
||||
public string ProjectName { get; }
|
||||
|
||||
/// <summary>The project Save both makes for this workspace's versions.</summary>
|
||||
public string SiblingName { get; }
|
||||
|
||||
public string Heading => Loc.L("Editor.Workspace.Conflict.Title");
|
||||
|
||||
public string Message => Loc.L(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", ProjectName);
|
||||
|
||||
public IReadOnlyList<string> Differences { get; }
|
||||
|
||||
public string DifferencesToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences");
|
||||
|
||||
public ICommand KeepMineCommand { get; }
|
||||
|
||||
public ICommand TakeHomeCommand { get; }
|
||||
|
||||
public ICommand SaveBothCommand { get; }
|
||||
|
||||
public string SaveBothToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", SiblingName);
|
||||
|
||||
private async Task ResolveAsync(ConflictChoice choice)
|
||||
{
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await _resolve(choice);
|
||||
IsBusy = false;
|
||||
Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"The conflict of '{ProjectName}' could not be settled ({choice})", ex);
|
||||
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Remove local copy": the plan (files and size of the copy; versions not sent and changes not saved), then Remove
|
||||
/// (only when everything is at the library), Send first (sends, then removes), or Discard changes (removes once the
|
||||
/// user typed the project's name; the unsent work is kept aside in the workspace's trash). A project the library no
|
||||
/// longer has (<see cref="WorkspaceRemovalPlan.Gone"/>), or a copy whose working state cannot be read
|
||||
/// (<see cref="WorkspaceRemovalPlan.Damaged"/>), can only be discarded that way.
|
||||
/// </summary>
|
||||
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly Func<bool, Task> _remove;
|
||||
private readonly Func<Task> _sendFirst;
|
||||
private readonly Func<bool> _confirmDiscard;
|
||||
|
||||
/// <param name="confirmDiscard">The typed confirmation Discard changes asks first (<see cref="ConfirmDiscard"/>); true when the user confirmed.</param>
|
||||
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
Plan = plan;
|
||||
_remove = remove;
|
||||
_sendFirst = sendFirst;
|
||||
_confirmDiscard = confirmDiscard;
|
||||
Facts =
|
||||
[
|
||||
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
|
||||
new DialogFact(Loc.L("Editor.RemoveCopy.Size"), Formatting.Bytes(plan.Bytes)),
|
||||
new DialogFact(Loc.L("Editor.RemoveCopy.Unsent"), Formatting.Count(plan.Unsent)),
|
||||
new DialogFact(Loc.L("Editor.RemoveCopy.Changed"), Loc.L(plan.Modified ? "Editor.RemoveCopy.Yes" : "Editor.RemoveCopy.No")),
|
||||
];
|
||||
RemoveCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(false)), () => !IsBusy && plan.IsSafe && !plan.Offline && !plan.Gone);
|
||||
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone && !plan.Damaged);
|
||||
DiscardCommand = new AsyncRelayCommand(DiscardAsync, () => !IsBusy && HasUnsent);
|
||||
}
|
||||
|
||||
public WorkspaceRemovalPlan Plan { get; }
|
||||
|
||||
/// <summary>"Remove local copy of Main"; a damaged copy by the name it is still known by, else as a damaged copy (never by its folder's id).</summary>
|
||||
public string Heading => !Plan.Damaged ? Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false))
|
||||
: Plan.KnownName is { Length: > 0 } known ? Loc.L("Editor.RemoveCopy.Title", known)
|
||||
: Loc.L("Editor.RemoveCopy.DamagedTitle");
|
||||
|
||||
public IReadOnlyList<DialogFact> Facts { get; }
|
||||
|
||||
/// <summary>Something would not be at the library after the removal (or the library no longer has the project): Discard changes shows.</summary>
|
||||
public bool HasUnsent => !Plan.IsSafe || Plan.Gone;
|
||||
|
||||
public ICommand RemoveCommand { get; }
|
||||
|
||||
public ICommand SendFirstCommand { get; }
|
||||
|
||||
public ICommand DiscardCommand { get; }
|
||||
|
||||
public string RemoveToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
|
||||
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
|
||||
: !Plan.IsSafe ? Loc.L("Errors.Workspace.Unsent")
|
||||
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
|
||||
: Loc.L("Tooltips.Editor.RemoveCopy.Remove");
|
||||
|
||||
public string SendFirstToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
|
||||
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
|
||||
: Plan.Conflict ? Loc.L("Errors.Workspace.Conflict")
|
||||
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
|
||||
: Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
|
||||
|
||||
public string DiscardToolTip => Loc.L("Tooltips.Editor.RemoveCopy.Discard");
|
||||
|
||||
/// <summary>
|
||||
/// The typed confirmation of Discard changes (the plan's cross-cutting rule for what Chronos cannot bring back): the
|
||||
/// project's name, as shown, typed before Discard enables.
|
||||
/// </summary>
|
||||
public static ConfirmRequest DiscardRequest(string projectName) => new()
|
||||
{
|
||||
Heading = Loc.L("Editor.RemoveCopy.DiscardTitle", projectName),
|
||||
Message = Loc.L("Editor.RemoveCopy.DiscardMessage"),
|
||||
SafeText = Loc.L("Editor.Project.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Keep"),
|
||||
ActionText = Loc.L("Editor.RemoveCopy.Discard"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Discard"),
|
||||
IsDestructive = true,
|
||||
TypedConfirmation = projectName,
|
||||
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeName"),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The typed confirmation of discarding a damaged copy (<see cref="WorkspaceRemovalPlan.Damaged"/>): the name it is still
|
||||
/// known by (<see cref="WorkspaceRemovalPlan.KnownName"/>), never its folder's id; with no name known, the number of its
|
||||
/// files, as the plan shows it.
|
||||
/// </summary>
|
||||
public static ConfirmRequest DiscardRequest(WorkspaceRemovalPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
if (plan.KnownName is { Length: > 0 } known) return DiscardRequest(known);
|
||||
var files = Formatting.Count(plan.Files);
|
||||
return DiscardRequest(string.Empty) with
|
||||
{
|
||||
Heading = Loc.L("Editor.RemoveCopy.DamagedDiscard"),
|
||||
TypedConfirmation = files,
|
||||
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeFiles", files),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Asks <see cref="DiscardRequest(string)"/> through <paramref name="ui"/>: true when the user typed the name and confirmed.</summary>
|
||||
public static bool ConfirmDiscard(IWorkspaceUi ui, string projectName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ui);
|
||||
return ui.Confirm(DiscardRequest(projectName));
|
||||
}
|
||||
|
||||
/// <summary>Asks <see cref="DiscardRequest(WorkspaceRemovalPlan)"/> through <paramref name="ui"/>: true when the user typed what it asks and confirmed.</summary>
|
||||
public static bool ConfirmDiscard(IWorkspaceUi ui, WorkspaceRemovalPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ui);
|
||||
return ui.Confirm(DiscardRequest(plan));
|
||||
}
|
||||
|
||||
private async Task DiscardAsync()
|
||||
{
|
||||
if (!_confirmDiscard()) return;
|
||||
await RunAsync(() => _remove(true));
|
||||
}
|
||||
|
||||
private async Task RunAsync(Func<Task> action)
|
||||
{
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await action();
|
||||
IsBusy = false;
|
||||
Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("workspace", $"The local copy of project {Plan.ProjectId} was not removed", ex);
|
||||
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:ar="clr-namespace:Chronos.App.Archiving"
|
||||
xmlns:ws="clr-namespace:Chronos.App.Workspace"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure">
|
||||
<!-- The in-window dialogs of Edit's workspace (owner review 2, R8), with the dialog kit of the Archive screen. -->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- A history row: focusable for the arrow keys; screen readers hear the version, what made it, who, when and the note. -->
|
||||
<Style x:Key="ListBoxItem.History" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Description}" />
|
||||
<Setter Property="ToolTip" Value="{Binding Description}" />
|
||||
</Style>
|
||||
|
||||
<!-- A project of Open in workspace: one whose copy here this Chronos cannot read is disabled, its reason in the tooltip. -->
|
||||
<Style x:Key="ComboBoxItem.Project" TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
|
||||
<Setter Property="IsEnabled" Value="{Binding IsAvailable}" />
|
||||
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Label}" />
|
||||
<Setter Property="AutomationProperties.HelpText" Value="{Binding ToolTip}" />
|
||||
</Style>
|
||||
|
||||
<!-- Open in workspace: which project of the sequence's home, or a new one, and the media to copy. -->
|
||||
<DataTemplate DataType="{x:Type ws:OpenInWorkspaceDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="520">
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
<TextBlock Text="{Binding SequenceTitle}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" TextTrimming="CharacterEllipsis" ToolTip="{Binding SequenceTitle}" />
|
||||
<Grid Margin="0,16,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{l:Loc Editor.OpenWorkspace.Project}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
|
||||
<RadioButton Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.Existing}" IsChecked="{Binding IsExisting}" IsEnabled="{Binding HasProjects}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Existing}" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<ComboBox Grid.Column="2" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label" IsEnabled="{Binding HasProjects}"
|
||||
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Projects}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
|
||||
<RadioButton Grid.Row="1" Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.New}" IsChecked="{Binding IsNew}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.New}" VerticalAlignment="Center" Margin="0,8,12,0" />
|
||||
<TextBox Grid.Row="1" Grid.Column="2" Margin="0,8,0,0" Text="{Binding NewName.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
IsEnabled="{Binding IsNew}" ToolTip="{Binding NewName.ToolTip}" MaxLength="60" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.New}" />
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc Editor.OpenWorkspace.Media}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,14,0,0" />
|
||||
<StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,14,0,0">
|
||||
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies, Mode=OneWay}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Proxies}" Margin="0,0,16,0" />
|
||||
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="False"
|
||||
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<!-- What the copy writes and the room the workspace's drive has for it. -->
|
||||
<ItemsControl ItemsSource="{Binding CopyFacts}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type ar:DialogFact}">
|
||||
<Grid Margin="0,0,0,6">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="CopyFactLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" Typography.NumeralAlignment="Tabular" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<ui:StatusGlyph Kind="Warning" Text="{l:Loc Editor.OpenWorkspace.NoRoom}" ToolTip="{l:Loc Errors.Workspace.NoRoom}" FontSize="12" HorizontalAlignment="Left"
|
||||
Margin="116,2,0,0" Visibility="{Binding IsShortOfSpace, Converter={StaticResource BoolToVisibility}}" />
|
||||
<DockPanel Margin="0,20,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.OpenWorkspace.Open}" Command="{Binding OpenCommand}"
|
||||
ToolTip="{Binding OpenToolTip}" ToolTipService.ShowOnDisabled="True" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- New project and Rename: the name, checked as it is typed. -->
|
||||
<DataTemplate DataType="{x:Type ws:ProjectNameDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="460">
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
|
||||
<Grid Margin="0,14,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Editor.ProjectName.Name}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Name.ToolTip}"
|
||||
MaxLength="60" AutomationProperties.Name="{l:Loc Editor.ProjectName.Name}" />
|
||||
</Grid>
|
||||
<DockPanel Margin="0,18,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{Binding SaveText}" Command="{Binding SaveCommand}" ToolTip="{Binding SaveToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Save version (Ctrl+S): an optional note; Enter saves. -->
|
||||
<DataTemplate DataType="{x:Type ws:SaveVersionDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="460">
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
<Grid Margin="0,14,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Editor.SaveVersion.Note}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Note, UpdateSourceTrigger=PropertyChanged}" ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Note}" MaxLength="200"
|
||||
AutomationProperties.Name="{l:Loc Editor.SaveVersion.Note}" />
|
||||
</Grid>
|
||||
<DockPanel Margin="0,18,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.SaveVersion.Save}" Command="{Binding SaveCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Save}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- History: a flyout under the title, newest first; Compare shows what differs from now below the list, Restore brings a version back. -->
|
||||
<DataTemplate DataType="{x:Type ws:HistoryDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="620" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="40,40,0,0">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<DockPanel>
|
||||
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{l:Loc Editor.History.Offline}" ToolTip="{l:Loc Tooltips.Editor.History.Offline}" FontSize="12"
|
||||
VerticalAlignment="Center" Visibility="{Binding IsOffline, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
</DockPanel>
|
||||
<Grid Grid.Row="1" Margin="0,12,0,0" MinHeight="120">
|
||||
<ListBox ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.History}" Grid.IsSharedSizeScope="True"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" AutomationProperties.Name="{l:Loc Editor.History.List}" KeyboardNavigation.TabNavigation="Continue">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type ws:HistoryRowViewModel}">
|
||||
<Grid Height="36">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="36" SharedSizeGroup="HistoryNumber" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="HistoryKind" />
|
||||
<ColumnDefinition Width="Auto" MaxWidth="160" SharedSizeGroup="HistoryAuthor" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="HistoryWhen" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.CellNumber}" Text="{Binding Number}" FontWeight="SemiBold" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding KindText}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Author}" Margin="12,0,0,0" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding When}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
Typography.NumeralAlignment="Tabular" />
|
||||
<DockPanel Grid.Column="4" Margin="12,0,0,0">
|
||||
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{l:Loc Tooltips.Editor.History.NotSent}" FontSize="12"
|
||||
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsUnsent, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Done" Text="{l:Loc Editor.History.Current}" ToolTip="{l:Loc Tooltips.Editor.History.Current}" FontSize="12"
|
||||
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsCurrent, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Note}" />
|
||||
</DockPanel>
|
||||
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Content="{l:Loc Editor.History.Compare}" Command="{Binding CompareCommand}"
|
||||
ToolTip="{Binding CompareToolTip}" Margin="12,0,0,0" />
|
||||
<Button Grid.Column="6" Style="{StaticResource Button.Row}" Content="{l:Loc Editor.History.Restore}" Command="{Binding RestoreCommand}"
|
||||
ToolTip="{Binding RestoreToolTip}" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<TextBlock Style="{StaticResource Text.Secondary}" Text="{l:Loc Editor.History.Empty}" HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
<!-- What differs between now and the version compared. -->
|
||||
<Border Grid.Row="2" Style="{StaticResource Border.Card}" Margin="0,12,0,0" Padding="12,10" MaxHeight="160"
|
||||
Visibility="{Binding ComparedTitle, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{Binding ComparedTitle}" FontWeight="SemiBold" infra:LiveRegion.Text="{Binding ComparedTitle}"
|
||||
AutomationProperties.LiveSetting="Polite" />
|
||||
<ScrollViewer Margin="0,6,0,0" VerticalScrollBarVisibility="Auto" Focusable="False">
|
||||
<ItemsControl ItemsSource="{Binding Compared}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding}" TextWrapping="Wrap" Margin="0,0,0,4" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
<DockPanel Grid.Row="3" Margin="0,16,0,0">
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Editor.History.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" IsDefault="True"
|
||||
MinWidth="96" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
|
||||
</DockPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's, Save both, or Later (only Save both and Later for a newer Chronos's project). -->
|
||||
<DataTemplate DataType="{x:Type ws:ConflictDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="560">
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" TextTrimming="None" />
|
||||
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
|
||||
<Border Style="{StaticResource Border.Card}" Margin="0,14,0,0" Padding="12,10" ToolTip="{Binding DifferencesToolTip}">
|
||||
<ItemsControl ItemsSource="{Binding Differences}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding}" TextWrapping="Wrap" Margin="0,0,0,4" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Border>
|
||||
<WrapPanel HorizontalAlignment="Right" Margin="0,20,0,0">
|
||||
<Button Content="{l:Loc Editor.Workspace.Conflict.Later}" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.Later}" IsCancel="True"
|
||||
MinWidth="96" Margin="0,0,8,8" />
|
||||
<Button Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}" MinWidth="96" Margin="0,0,8,8"
|
||||
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Content="{l:Loc Editor.Workspace.Conflict.TakeHome}" Command="{Binding TakeHomeCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.TakeHome}"
|
||||
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.KeepMine}" Command="{Binding KeepMineCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
|
||||
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
|
||||
<!-- A conflict of format: Save both is the only choice that settles it. -->
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}"
|
||||
IsDefault="{Binding IsNewerFormat, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
|
||||
Visibility="{Binding CanMerge, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</WrapPanel>
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" HorizontalAlignment="Right" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Remove local copy: the plan, then Remove (all at the library), Send first, or Discard changes. -->
|
||||
<DataTemplate DataType="{x:Type ws:RemoveCopyDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="520">
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
<TextBlock Text="{l:Loc Editor.RemoveCopy.Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
|
||||
<ItemsControl ItemsSource="{Binding Facts}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type ar:DialogFact}">
|
||||
<Grid Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="FactLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" Typography.NumeralAlignment="Tabular" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<WrapPanel HorizontalAlignment="Right" Margin="0,18,0,0">
|
||||
<Button Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" IsDefault="True" MinWidth="96"
|
||||
Margin="0,0,8,8" />
|
||||
<Button Style="{StaticResource Button.Destructive}" Content="{l:Loc Editor.RemoveCopy.Discard}" Command="{Binding DiscardCommand}" ToolTip="{Binding DiscardToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,8,8" Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Content="{l:Loc Editor.RemoveCopy.SendFirst}" Command="{Binding SendFirstCommand}" ToolTip="{Binding SendFirstToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Destructive}" Content="{l:Loc Editor.RemoveCopy.Remove}" Command="{Binding RemoveCommand}" ToolTip="{Binding RemoveToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,0,8" />
|
||||
</WrapPanel>
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" HorizontalAlignment="Right" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
|
||||
namespace Chronos.App.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Choosing another workspace folder (owner review 2, R8): Settings › Workspace › Change, and the refusal of a folder
|
||||
/// inside a library, where Edit cannot be used until one is chosen. The folder is picked, its plan shown and confirmed
|
||||
/// (the projects the folder in use keeps, those the new one holds), a workspace project open in the editor closes (its
|
||||
/// last edit stored first), and only then does the setting change. Nothing is moved or deleted: the projects of the
|
||||
/// folder left stay there, listed again once it is chosen back. Moving a workspace with its projects comes in phase 5c.
|
||||
/// </summary>
|
||||
public static class WorkspaceFolderChange
|
||||
{
|
||||
/// <summary>The shell's flow: its folder picker and confirmation, its editor, its toasts.</summary>
|
||||
public static async Task<bool> ChooseAsync(ShellViewModel shell)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(shell);
|
||||
var changed = await ChooseAsync(shell.Services.Workspace, shell.Services.Dialogs, async () =>
|
||||
{
|
||||
if (shell.Sequence.Editor?.Session.Source is not WorkspaceSequenceSource) return true;
|
||||
if (!await shell.Sequence.ConfirmCloseAsync()) return false;
|
||||
await shell.Sequence.CloseAsync();
|
||||
shell.KeepSequence(null);
|
||||
return true;
|
||||
}, message => shell.Notify(Loc.L("Settings.Workspace.NotChanged"), message, isError: true));
|
||||
if (changed) shell.Notify(Loc.L("Settings.Workspace.Changed"), shell.Services.Workspace.Root);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Picks a folder through <paramref name="dialogs"/>, confirms its plan, lets <paramref name="closeProject"/> close a
|
||||
/// workspace project open in the editor (false keeps everything as it is), then makes it the workspace's folder.
|
||||
/// <paramref name="failed"/> hears why a folder was refused. True when the folder changed.
|
||||
/// </summary>
|
||||
public static async Task<bool> ChooseAsync(WorkspaceHost host, IAppDialogs dialogs, Func<Task<bool>> closeProject, Action<string> failed)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
ArgumentNullException.ThrowIfNull(dialogs);
|
||||
ArgumentNullException.ThrowIfNull(closeProject);
|
||||
ArgumentNullException.ThrowIfNull(failed);
|
||||
if (dialogs.PickFolder(Loc.L("Settings.Workspace.ChooseTitle"), Directory.Exists(host.Root) ? host.Root : null) is not { } folder) return false;
|
||||
try
|
||||
{
|
||||
var plan = await host.PlanFolderAsync(folder);
|
||||
if (plan.IsSame) return false;
|
||||
if (plan.InsideLibrary)
|
||||
{
|
||||
failed(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder));
|
||||
return false;
|
||||
}
|
||||
if (!dialogs.Confirm(Request(plan))) return false;
|
||||
if (!await closeProject()) return false;
|
||||
await host.UseFolderAsync(plan.Folder);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException or WorkspaceException)
|
||||
{
|
||||
Log.Warning("workspace", $"The workspace folder was not changed to {folder}", ex);
|
||||
failed(ex is WorkspaceException ? ex.Message : Loc.L("Errors.Workspace.FolderUnusable", folder));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The plan as a confirmation: where Edit's projects come from now, and what stays where it is.</summary>
|
||||
public static ConfirmRequest Request(WorkspaceFolderPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Settings.Workspace.ChangeTitle"),
|
||||
Message = Loc.L("Settings.Workspace.ChangeMessage", plan.Folder, plan.Current),
|
||||
Detail = string.Join(Environment.NewLine, Loc.L("Settings.Workspace.ProjectsLeft", Formatting.Count(plan.ProjectsLeft)),
|
||||
Loc.L("Settings.Workspace.ProjectsFound", Formatting.Count(plan.ProjectsFound))),
|
||||
IsDetailMonospaced = false,
|
||||
SafeText = Loc.L("Archive.Dialog.Cancel"),
|
||||
SafeToolTip = Loc.L("Tooltips.Settings.KeepWorkspace"),
|
||||
ActionText = Loc.L("Settings.Workspace.Use"),
|
||||
ActionToolTip = Loc.L("Tooltips.Settings.UseWorkspace"),
|
||||
};
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,72 @@
|
||||
using Chronos.App.Library;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
|
||||
/// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed
|
||||
/// as damaged, one a newer Chronos wrote as such, by the name each is still known by.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
|
||||
{
|
||||
private WorkspaceStatus? _status;
|
||||
|
||||
public WorkspaceEntry Entry { get; } = entry;
|
||||
|
||||
/// <summary>The sequence's row of the library, for its thumbnail; null when the index no longer has it.</summary>
|
||||
public SequenceItem? Sequence { get; } = sequence;
|
||||
|
||||
public Guid ProjectId => Entry.ProjectId;
|
||||
|
||||
public Guid SequenceId => Entry.SequenceId;
|
||||
|
||||
/// <summary>The project's name (Main in the UI language).</summary>
|
||||
public string Name => WorkspaceText.ProjectName(Entry.Name, Entry.IsMain);
|
||||
|
||||
public string SequenceTitle => Sequence?.Title ?? Entry.SequenceTitle;
|
||||
|
||||
public WorkspaceStatus? Status
|
||||
{
|
||||
get => _status;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _status, value)) return;
|
||||
OnPropertyChanged(nameof(StateText));
|
||||
OnPropertyChanged(nameof(StateKind));
|
||||
OnPropertyChanged(nameof(StateToolTip));
|
||||
OnPropertyChanged(nameof(Description));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Its working state cannot be read: it cannot open, and Remove local copy keeps its files aside.</summary>
|
||||
public bool IsDamaged => Entry.Damaged;
|
||||
|
||||
/// <summary>A newer Chronos wrote its working state: it neither opens nor goes from here, and stays as it is.</summary>
|
||||
public bool IsNewer => Entry.Newer;
|
||||
|
||||
/// <summary>This Chronos reads its working state: it opens, and its state is asked of its home.</summary>
|
||||
public bool IsReadable => Entry.IsReadable;
|
||||
|
||||
public string StateText => Entry.Newer ? Loc.L("Editor.Workspace.State.NewerCopy")
|
||||
: Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
|
||||
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
|
||||
|
||||
public StatusKind StateKind => Entry.Newer ? StatusKind.Warning
|
||||
: Entry.Damaged ? StatusKind.Error
|
||||
: Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
|
||||
|
||||
public string StateToolTip => Entry.Newer ? Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")
|
||||
: Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")
|
||||
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
|
||||
|
||||
/// <summary>"Vertical social · Harbour sunset · In sync": what screen readers hear for the row.</summary>
|
||||
public string Description => string.Join(Loc.Separator, Name, SequenceTitle, StateText);
|
||||
|
||||
public override string ToString() => Name;
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
namespace Chronos.App.Workspace;
|
||||
|
||||
/// <summary>How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free.</summary>
|
||||
public static class WorkspaceText
|
||||
{
|
||||
/// <summary>The project's name; the Main project in the UI language.</summary>
|
||||
public static string ProjectName(string name, bool isMain) =>
|
||||
isMain && string.Equals(name, ProjectService.MainName, StringComparison.Ordinal) ? Loc.L("Editor.Project.Main") : name;
|
||||
|
||||
/// <summary>The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs.</summary>
|
||||
public static string State(WorkspaceStatus? status, bool syncing = false) =>
|
||||
syncing ? Loc.L("Editor.Workspace.State.Syncing") : status is null ? Loc.L("Editor.Workspace.State.Reading") : Loc.L("Editor.Workspace.State." + status.State);
|
||||
|
||||
public static StatusKind Kind(WorkspaceStatus? status, bool syncing = false) => syncing ? StatusKind.Running : status?.State switch
|
||||
{
|
||||
WorkspaceState.InSync => StatusKind.Synced,
|
||||
WorkspaceState.Modified or WorkspaceState.Ahead => StatusKind.Queued,
|
||||
WorkspaceState.Behind => StatusKind.Remote,
|
||||
WorkspaceState.Conflict => StatusKind.Error,
|
||||
WorkspaceState.Offline => StatusKind.Offline,
|
||||
WorkspaceState.MediaRemoved => StatusKind.NoProxies,
|
||||
WorkspaceState.Gone => StatusKind.Warning,
|
||||
WorkspaceState.Damaged => StatusKind.Error,
|
||||
_ => StatusKind.Queued,
|
||||
};
|
||||
|
||||
/// <summary>What the state means and what to do, with the counts behind it.</summary>
|
||||
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false) => syncing ? Loc.L("Tooltips.Editor.Workspace.State.Syncing")
|
||||
: status is null ? Loc.L("Tooltips.Editor.Workspace.State.Reading")
|
||||
: status.State switch
|
||||
{
|
||||
WorkspaceState.Ahead => Loc.L("Tooltips.Editor.Workspace.State.Ahead", Formatting.Count(status.Ahead)),
|
||||
WorkspaceState.Behind => Loc.L("Tooltips.Editor.Workspace.State.Behind", Formatting.Count(status.Behind)),
|
||||
WorkspaceState.Offline when status.Ahead > 0 => Loc.L("Tooltips.Editor.Workspace.State.OfflineAhead", Formatting.Count(status.Ahead)),
|
||||
var state => Loc.L("Tooltips.Editor.Workspace.State." + state),
|
||||
};
|
||||
|
||||
/// <summary>"Saved", "Merged", "Restored", "Imported", "Outside change".</summary>
|
||||
public static string VersionKind(ProjectVersionKind kind) => Loc.L("Editor.History.Kind." + kind);
|
||||
|
||||
/// <summary>
|
||||
/// Who made a version: its author, else the PC it was made on ("STUDIO-PC"), however the program that made it named
|
||||
/// itself ("chronos@STUDIO-PC" for the archive's own versions, "Chronos on STUDIO-PC" for those of test builds).
|
||||
/// </summary>
|
||||
public static string Author(ProjectVersion version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
if (version.Author is { Length: > 0 } author) return author;
|
||||
var client = version.ClientName?.Trim() ?? string.Empty;
|
||||
foreach (var prefix in ClientPrefixes)
|
||||
{
|
||||
if (client.Length > prefix.Length && client.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return client[prefix.Length..];
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>What programs put before the PC's name in a version's client name (not words of the UI: the PC alone is shown).</summary>
|
||||
private static readonly string[] ClientPrefixes = ["chronos@", "server@", "workspace@", "Chronos on "];
|
||||
|
||||
/// <summary>"28/10/2026 18:02".</summary>
|
||||
public static string When(DateTimeOffset at) => $"{Formatting.Date(at)} {Formatting.TimeOfDay(at)}";
|
||||
|
||||
/// <summary>
|
||||
/// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most <paramref name="max"/>.
|
||||
/// A conflict of format (<see cref="ProjectMerge.FormatPath"/>) reads as its cause, never as the format's numbers.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(differences);
|
||||
var list = differences.ToList();
|
||||
if (list.Any(d => d.Path == ProjectMerge.FormatPath)) return [Loc.L("Editor.Workspace.Conflict.NewerFormat")];
|
||||
return SyncText.Differences(list, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
|
||||
}
|
||||
|
||||
/// <summary>One line per setting that differs between now and a version ("Deflicker window 41 now, 33 in that version").</summary>
|
||||
public static IReadOnlyList<string> CompareLines(IEnumerable<SettingsDifference> differences, int max) =>
|
||||
SyncText.Differences(differences, max, (label, now, then) => Loc.L("Editor.History.Difference", label, now, then));
|
||||
|
||||
/// <summary>Why a workspace operation stopped, as one localized sentence chosen by cause; the exception's own text goes to the log.</summary>
|
||||
public static string Failure(Exception ex) => ex switch
|
||||
{
|
||||
WorkspaceException or LeaseUnavailableException => ex.Message,
|
||||
// A library that can be read but not written (a read-only share, a write-protected disk): the work waits here as offline.
|
||||
HomeUnavailableException { InnerException: ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } }
|
||||
or ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } => Loc.L("Errors.Workspace.ReadOnlyHome"),
|
||||
HomeUnavailableException or ArchiveOfflineException => Loc.L("Errors.Workspace.Offline"),
|
||||
ProjectException { Reason: ProjectError.NameTaken } => Loc.L("Errors.Workspace.NameTaken"),
|
||||
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
|
||||
ProjectException { Reason: ProjectError.MainCannotBeDeleted } => Loc.L("Errors.Workspace.MainKept"),
|
||||
ProjectException => Loc.L("Errors.Workspace.ProjectGone"),
|
||||
// A version over the size one may be: saved here (refused before anything was written) or sent (the home stored nothing).
|
||||
ProjectVersionTooLargeException or WorkspaceSyncException { Outcome: PushOutcome.TooLarge } =>
|
||||
Loc.L("Errors.Workspace.VersionTooLarge", ProjectSidecars.MaxVersionBytes >> 20),
|
||||
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
|
||||
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
|
||||
Editor.EditorException => ex.Message,
|
||||
_ => ArchiveFailures.Cause(ex),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user