feat(app): Edit opens workspace projects, with versions, sync and the project menu

Owner review 2, phase 5a (R8), desktop package: editing moves out of the library. A sequence of this PC's archive
now opens in Edit as a project of the workspace (%LOCALAPPDATA%\Chronos\workspace, .\data\workspace when portable),
with this PC's archive as its home; the editor writes the workspace's working state, never the library.

- WorkspaceHost composes WorkspaceStore and WorkspaceSync over Settings > Workspace's folder: checkout and the
  WorkspaceCopy job, status, Save version with the sync after it (Sync automatically, on by default), sync (pull,
  then push), conflicts, restore, history, new / rename / delete project, and Remove local copy, which refuses
  while work is unsent unless the user sends it first or discards it, reads back the home's head and base and
  checks their hashes, and keeps discarded work in <workspace>/.trash; versions past Kept versions are pruned only
  once the home returns them with the same content.
- WorkspaceSequenceSource: frames and pixels of the media (proxies), the working state saved atomically under the
  project's lease and merged against the basis, the home's deep report while its frames are the media's, renders
  at the home with the portable settings recording the project and the version.
- Edit: the project opened last for the sequence, else "Open in workspace" (Main made from the sequence's settings,
  another project or a new one; proxies) checks out, copies and opens once the copy is done. The picker lists the
  workspace's projects with their state above the library. The title's project menu: Save version (Ctrl+S, note),
  Sync, History (compare, restore as one undo step), New project, Rename, Delete project, Remove local copy; a
  conflict dialog only on real conflicts (keep mine, take the library's, save both, later); Update media when the
  library's frames moved. .chronos files: format 2 opens its project, format 1 gives its settings to Main.
- Settings > Workspace: folder (shown, Open), Sync automatically, Kept versions. Strings in English and Italian.
- A capture (sample data without an engine) keeps editing the library.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit da47a580ba9db3ce2a1db2f11c30cf7344c8b394)
This commit is contained in:
Alby96 committed 2026-10-27 22:53:05 +01:00
1 parent 03d32f18d3
commit b9d1c396a1
37 files changed
+4547 -104

No files matched your search

+8 -4
View File
@@ -166,11 +166,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.
+21
View File
@@ -89,6 +89,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)
@@ -175,6 +176,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;
@@ -711,6 +729,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Shell.Services.Sync.Changed -= OnSyncChanged;
Shell.Services.SequenceReorganized -= OnSequenceReorganized;
foreach (var tab in Tabs) tab.Dispose();
_project?.Dispose();
base.Dispose();
await Session.DisposeAsync();
}
@@ -1134,6 +1153,8 @@ 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);
});
}
+23 -5
View File
@@ -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>
@@ -0,0 +1,342 @@
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). 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>A workspace project's read-only state is known when it opens.</summary>
public event Action? ReadOnlyChanged
{
add { }
remove { }
}
public event Action<Job>? JobChanged;
/// <exception cref="EditorException">The workspace holds no media for the project (copy them again), or the project is gone.</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);
}
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>
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 = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
if (ProjectMerge.SameValues(merged, stored)) return merged;
folder.WriteBundle(bundle with { Project = merged, Saved = DateTimeOffset.UtcNow });
return merged;
}
}, cancellationToken);
}
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 saved (an unsaved working state 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.
/// </summary>
private void Swap(WorkspaceSequence media, WorkspaceMedia index, BundleWorkspace workspace, bool readOnly)
{
var ids = media.Frames.Select(f => f.Id).ToArray();
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;
_readOnly = readOnly;
}
}
/// <summary>The last version saved: the newest one not sent yet, else the base; with its content hash.</summary>
private (Guid? Id, string? Hash) Tip()
{
try
{
if (_sync.Unpushed(ProjectId) is { Count: > 0 } unsent) return (unsent[^1].Id, unsent[^1].ContentHash);
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,91 @@
<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}" />
</ListBox.InputBindings>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ws:WorkspaceProjectItem}">
<Grid Height="40">
<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,7 @@ 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);
SearchOpenCommand = new AsyncRelayCommand(OpenFromSearchAsync);
ClearCommand = new RelayCommand(() => SearchText = string.Empty);
}
@@ -47,6 +58,28 @@ 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>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 +106,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 +153,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 +168,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)
@@ -194,6 +234,71 @@ 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;
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;
+58 -4
View File
@@ -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,37 @@
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.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 +163,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 +316,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>
+27 -2
View File
@@ -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)
{
+292 -26
View File
@@ -2,15 +2,19 @@ using System.ComponentModel;
using System.Net;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.App.Shell;
using Chronos.App.Workspace;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
using Chronos.Protocol.Client;
@@ -20,18 +24,24 @@ namespace Chronos.App.Sections;
/// <summary>
/// The Edit section (BRIEF §12.3; owner review 1, R7, formerly Sequence): opens the sequence the Library, Jobs, the
/// Server screen or its own picker chose into an <see cref="EditorViewModel"/> (from this PC's archive, or a server
/// sequence with this PC's proxies). The next sequence is read first; only then does the open one close, after its
/// last edit is stored. Without a sequence, or after Change sequence, it shows the picker (the editor stays open behind
/// it until another sequence opens). A server sequence whose proxies are missing or out of date fetches them first and
/// opens once they are here, the open sequence staying open meanwhile. A failed open is reported once and leaves the
/// open sequence open; an edit that cannot be saved is never dropped without the user's confirmation, and never written
/// after they chose to drop it. The step each sequence showed is kept for the rest of the run.
/// Server screen or its own picker chose into an <see cref="EditorViewModel"/>. A sequence of this PC's archive opens as a
/// project of the workspace (owner review 2, R8: editing never happens inside the library): the project of that sequence
/// opened last here; else, after "Open in workspace" asked which project (Main, another of its home, or a new one) and
/// which media, the project is checked out and its media copied by a job, and it opens once they are here. A server
/// sequence opens with this PC's proxies (the workspace takes server homes in phase 5b), and a capture (sample data
/// without an engine) opens the library as before. The next sequence is read first; only then does the open one close,
/// after its last edit is stored. Without a sequence, or after Change sequence, it shows the picker (the editor stays
/// open behind it until another sequence opens). A server sequence whose proxies are missing or out of date fetches them
/// first and opens once they are here, the open sequence staying open meanwhile; a workspace copy is followed the same
/// way. A failed open is reported once and leaves the open sequence open; an edit that cannot be saved is never dropped
/// without the user's confirmation, and never written after they chose to drop it. The step each sequence showed is
/// kept for the rest of the run. The section's in-window dialogs (Open in workspace, the project menu's) show over it.
/// </summary>
public sealed class SequenceViewModel : SectionViewModel
{
private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
private readonly Dictionary<Guid, StepMemory> _steps = [];
private readonly WorkspaceUi _workspaceUi;
private EditorViewModel? _editor;
private Guid? _openId;
private bool _isLoading;
@@ -41,16 +51,24 @@ 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>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 +115,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 +170,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 +190,80 @@ 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;
}
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 +295,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 +373,27 @@ public sealed class SequenceViewModel : SectionViewModel
{
Shell.PropertyChanged -= OnShellChanged;
StopFetch();
_dialog?.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>Closes <paramref name="dialog"/> if it is still the open one.</summary>
internal void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
}
protected override void OnActivated()
{
OpenRequested();
@@ -349,9 +467,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,6 +480,7 @@ 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);
@@ -386,20 +507,112 @@ 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),
};
if (entry is { HasMedia: true })
{
workspace.Remember(row.Id, entry.ProjectId);
return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(row.Id)).All(p => p.Id != wanted))
{
// A project file of a project this home does not have (another PC's workspace): its sequence's Main takes it.
Log.Info("workspace", $"Project {wanted} is not a project of sequence {row.Id} here; its Main opens instead");
projectId = null;
if (_afterOpen is { } pending && pending.Request.SequenceId == row.Id) _afterOpen = (ProjectRequest.MainOf(row.Id), pending.Action);
}
else if (entry is null && projectId is null && request is not { Main: true })
{
if (await AskProjectAsync(workspace, row) is not { } choice)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return null;
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
}
var checkout = await workspace.CheckoutAsync(row.Id, projectId, newName);
await FollowCopyAsync(row.Id, row.DisplayTitle, checkout.Project.Id, checkout.Copy);
return null;
}
/// <summary>"Open in workspace": the projects of the sequence's home and the media; null when closed without a choice.</summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row)
{
var projects = await workspace.HomeProjectsAsync(row.Id);
var dialog = new OpenInWorkspaceDialogViewModel(row.DisplayTitle, projects, d => CloseDialog(d));
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
IsLoading = false;
OpenDialog(dialog);
try
{
return await dialog.Choice;
}
finally
{
IsLoading = true;
}
}
/// <summary>The project the next open of <paramref name="sequenceId"/> takes, taken once; null when none was asked for.</summary>
private ProjectRequest? TakeRequest(Guid sequenceId)
{
if (_requested is not { } request || request.SequenceId != sequenceId) return null;
_requested = null;
return request;
}
/// <summary>Follows the workspace copy of a project's media (the picker's line, a toast): the project opens once it is done.</summary>
private async Task FollowCopyAsync(Guid sequenceId, string title, Guid projectId, Job copy)
{
var engine = Shell.Services.Engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
StopFetch();
var fetch = new PendingOpen(sequenceId, title, engine, "Editor.Workspace.Copying", projectId) { JobId = copy.Id };
fetch.Handler = job => _dispatcher.BeginInvoke(() => OnFetchChanged(fetch, job));
engine.JobChanged += fetch.Handler;
_fetch = fetch;
OnFetchingChanged();
Shell.Notify(Loc.L("Editor.Workspace.Copying"), title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
// A copy that ended before it was followed here is handled now.
if (Shell.Services.Database is { } db && await db.Jobs.GetAsync(copy.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
OnFetchChanged(fetch, ended);
}
/// <summary>
/// The proxy download or workspace copy an open waits on moved: opens the sequence (the project copied) once it is done,
/// says why not when it failed.
/// </summary>
private void OnFetchChanged(PendingOpen fetch, Job job)
{
if (!ReferenceEquals(fetch, _fetch) || job.Id != fetch.JobId || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
StopFetch();
switch (job.State)
{
// Opened only when it is still the sequence asked for; otherwise the next visit opens it from the cache.
// 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 +705,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 +732,65 @@ 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 void ShowDialog(ArchiveDialogViewModel dialog) => section.OpenDialog(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,30 @@
</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 and opened here; moving it (a plan and a confirmation) 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" />
</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" />
</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}">
+36 -1
View File
@@ -86,6 +86,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 +167,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);
// ---- Storage ----
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
{
@@ -718,6 +722,24 @@ 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);
}
}
// ---------------- Server ----------------
public EditableField DefaultServer { get; }
@@ -1176,7 +1198,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 +1556,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 +1636,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 +1670,7 @@ public sealed class SettingsViewModel : SectionViewModel
_interfacePriority?.Update();
foreach (var row in JobPriorities) row.Refresh();
Logs.Refresh();
WorkspaceRows.Refresh();
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
@@ -1656,6 +1685,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 +1719,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 +1751,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();
+10 -2
View File
@@ -165,9 +165,17 @@ 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.
/// </summary>
public static IReadOnlyList<string> Differences(IEnumerable<SettingsDifference> differences, int max, Func<string, string, string, string>? worded)
{
ArgumentNullException.ThrowIfNull(differences);
worded ??= (label, mine, server) => Loc.L("Server.Conflict.Difference", label, mine, server);
var lines = new List<string>();
var shown = new HashSet<string>(StringComparer.Ordinal);
foreach (var difference in differences)
@@ -178,7 +186,7 @@ public static class SyncText
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)
? worded(label, mine, server)
: Loc.L("Server.Conflict.Changed", label));
if (lines.Count == max) break;
}
+3
View File
@@ -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,67 @@
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; moving it, with its plan and
/// confirmation, 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) : 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);
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 (moving it is phase 5c).</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);
}
+4
View File
@@ -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;
@@ -44,6 +46,8 @@ public static class ErrorText
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => 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 => 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,521 @@
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
{
void ShowDialog(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), Save
/// version (Ctrl+S, an optional note; sent at once with Settings › Workspace › Sync automatically), Sync, History (Compare,
/// Restore as one undo step), 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 or a restore 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. Call from the UI thread.
/// </summary>
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
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;
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);
NewProjectCommand = new AsyncRelayCommand(OpenNewProjectAsync);
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
source.JobChanged += OnJobChanged;
}
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: the banner offers Update media.</summary>
public bool HasMediaUpdate => _homeFramesChanged;
/// <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");
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true };
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
: _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; }
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; a conflict found meanwhile is asked about.</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);
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.</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.Conflict is { } conflict) AskConflict(conflict);
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 a conflict as chosen, then brings the settled working state into the editor.</summary>
public async Task ResolveAsync(ConflictChoice choice)
{
await StoreEditAsync();
var result = await _host.ResolveAsync(ProjectId, choice);
if (_disposed) return;
Apply(result.Status);
await TakeAsync(result, force: true);
if (result.SavedAs is { } copy) _ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name);
if (result.Status.Conflict is { } again) AskConflict(again);
}
/// <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"/> (positions compared photo by photo).</summary>
public IReadOnlyList<string> Compare(ProjectVersion version, int max = 12)
{
ArgumentNullException.ThrowIfNull(version);
var now = ProjectContent.ToPortable(_session.Project, _source.Photos);
return WorkspaceText.CompareLines(SyncRules.Differences(now, version.SettingsJson, 64), max);
}
public override void Dispose()
{
_disposed = true;
_source.JobChanged -= OnJobChanged;
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);
}
}
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;
await _host.DeleteProjectAsync(projectId);
_ui.Notify(Loc.L("Editor.Workspace.Deleted", name));
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 = ProjectId;
_ui.ShowDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveAsync(projectId, discard), async () =>
{
await SaveAndSendAsync();
await RemoveAsync(projectId, discard: false);
}, _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.</summary>
/// <exception cref="WorkspaceException">Something could not be sent.</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);
if (result.Status is { Ahead: > 0 } or { Conflict: not null } 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);
}
private void AskConflict(WorkspaceConflict conflict)
{
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
_ui.ShowDialog(new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, ResolveAsync, _ui.CloseDialog));
}
/// <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,502 @@
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).</summary>
public sealed record ProjectOption(SequenceProject Project)
{
public string Label => WorkspaceText.ProjectName(Project.Name, Project.IsMain);
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: 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;
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close)
: base(close)
{
SequenceTitle = sequenceTitle;
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p))];
_selected = Projects.FirstOrDefault();
_isNew = Projects.Count == 0;
NewName = new EditableField(string.Empty, n => ProjectNames.Validate(n, projects.Select(p => p.Name)), _ => { }, () => 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; }
public string Heading => Loc.L("Editor.OpenWorkspace.Title");
public IReadOnlyList<ProjectOption> Projects { get; }
public bool HasProjects => Projects.Count > 0;
public ProjectOption? SelectedProject
{
get => _selected;
set
{
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 not null;
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.
/// </summary>
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ConflictChoice, Task> _resolve;
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
Action<ArchiveDialogViewModel> close)
: base(close)
{
ProjectName = projectName;
SiblingName = siblingName;
Differences = differences;
_resolve = resolve;
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy);
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy);
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
}
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("Editor.Workspace.Conflict.Message", ProjectName);
public IReadOnlyList<string> Differences { get; }
public ICommand KeepMineCommand { get; }
public ICommand TakeHomeCommand { get; }
public ICommand SaveBothCommand { get; }
public string SaveBothToolTip => Loc.L("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; the unsent
/// work is kept aside in the workspace's trash).
/// </summary>
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<bool, Task> _remove;
private readonly Func<Task> _sendFirst;
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Action<ArchiveDialogViewModel> close)
: base(close)
{
Plan = plan;
_remove = remove;
_sendFirst = sendFirst;
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);
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline);
DiscardCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(true)), () => !IsBusy && !plan.IsSafe);
}
public WorkspaceRemovalPlan Plan { get; }
public string Heading => Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false));
public IReadOnlyList<DialogFact> Facts { get; }
public bool HasUnsent => !Plan.IsSafe;
public ICommand RemoveCommand { get; }
public ICommand SendFirstCommand { get; }
public ICommand DiscardCommand { get; }
public string RemoveToolTip => Plan.IsSafe ? Plan.Offline ? Loc.L("Errors.Workspace.Offline") : Loc.L("Tooltips.Editor.RemoveCopy.Remove") : Loc.L("Errors.Workspace.Unsent");
public string SendFirstToolTip => 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");
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,254 @@
<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>
<!-- 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}"
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>
<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. -->
<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="{l:Loc Tooltips.Editor.Workspace.Differences}">
<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" />
<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" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.KeepMine}" Command="{Binding KeepMineCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="True" MinWidth="96" Margin="0,0,0,8" />
</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>
+640
View File
@@ -0,0 +1,640 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>A workspace operation was refused for a reason the user can act on; the message is one localized sentence.</summary>
public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner);
/// <summary>A project of this PC's workspace, as Edit's picker and the editor list it.</summary>
/// <param name="HasMedia">The workspace holds the project's media (a copy that ended); without them it cannot open.</param>
/// <param name="Saved">When its working state was last written.</param>
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
DateTimeOffset Saved);
/// <summary>A project brought into the workspace and the copy of its media that was queued.</summary>
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
/// <summary>What Save version did: the version (null when nothing changed), its sync when Sync automatically is on, where the project stands.</summary>
/// <param name="SyncError">Why the sync after it did not happen (the home out of reach, the project busy); the version waits here.</param>
public sealed record WorkspaceSaveResult(ProjectVersion? Version, WorkspaceSyncResult? Synced, WorkspaceStatus Status, Exception? SyncError);
/// <summary>A project's history as the History flyout lists it: newest first, the versions not sent yet on top.</summary>
/// <param name="Unsent">The ids among <paramref name="Versions"/> that wait to be sent to the home.</param>
/// <param name="Offline">The home could not be asked: only the versions this workspace keeps are listed.</param>
public sealed record WorkspaceHistory(IReadOnlyList<ProjectVersion> Versions, IReadOnlySet<Guid> Unsent, bool Offline);
/// <summary>
/// The plan of "Remove local copy": what the project's folder holds (files and bytes) and what would not be at the home
/// after it (versions not sent, changes not saved as a version, a conflict to settle).
/// </summary>
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline)
{
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
}
/// <summary>
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
/// <c>workspace</c> under the data folder: <c>%LOCALAPPDATA%\Chronos\workspace</c>, <c>.\data\workspace</c> for a portable
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and this PC's archive as the home of
/// its projects (<see cref="ArchiveProjectHome"/>; a server home comes in phase 5b). Every operation runs off the UI thread
/// and returns where the project stands. Nothing a workspace holds is lost: a version is sent before its copy goes, a copy
/// is removed only once the home verifiably holds its head, the work a user chose to discard is kept in
/// <c>&lt;workspace&gt;/.trash</c>, and versions the home holds are pruned past Settings › Workspace › Kept versions only
/// after the home was asked for each. A capture (sample data, no engine) has no workspace: Edit opens the library there.
/// </summary>
public sealed class WorkspaceHost
{
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
public const string TrashFolder = ".trash";
private readonly AppEnvironment _environment;
private readonly AppSettings _settings;
private readonly Action _savePreferences;
private readonly Func<ChronosDatabase?> _db;
private readonly Func<ArchiveService?> _archives;
private readonly Func<JobEngine?> _engine;
private readonly Lock _gate = new();
private readonly Dictionary<Guid, Guid> _copies = [];
private OpenWorkspace? _open;
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func<ChronosDatabase?> db, Func<ArchiveService?> archives,
Func<JobEngine?> engine)
{
_environment = environment;
_settings = settings;
_savePreferences = savePreferences;
_db = db;
_archives = archives;
_engine = engine;
}
/// <summary>The program and PC versions made here carry, as the archive's own versions do.</summary>
public static string ClientName { get; } = "Chronos on " + Environment.MachineName;
/// <summary>How long an operation waits for a project another writer holds (a copy job writing its media index).</summary>
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>The workspace folder of a data folder: <c>workspace</c> beside the index.</summary>
public static string DefaultRoot(AppEnvironment environment)
{
ArgumentNullException.ThrowIfNull(environment);
return Path.Combine(environment.DataDirectory, WorkspaceStore.DefaultFolderName);
}
/// <summary>The folder in use: Settings › Workspace › Folder, else <see cref="DefaultRoot"/>.</summary>
public string Root => _settings.WorkspaceFolder is { Length: > 0 } folder ? Path.GetFullPath(folder) : DefaultRoot(_environment);
/// <summary>Edit opens workspace projects (false in a capture, whose sample library has no engine to copy media).</summary>
public bool IsEnabled => !_environment.IsCapture;
/// <summary>The workspace can be used now: enabled, with the index and the archive engine open.</summary>
public bool IsAvailable => IsEnabled && _db() is not null && _archives() is not null;
public AppSettings Settings => _settings;
/// <summary>The sync over the workspace folder in use (made, with the folder and its manifest, at first use).</summary>
/// <exception cref="IOException">The folder cannot be made or read.</exception>
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
public WorkspaceSync Sync
{
get
{
var root = Root;
lock (_gate)
{
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
{
var store = new WorkspaceStore(root);
_open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
}
return open.Sync;
}
}
}
public WorkspaceStore Store => Sync.Store;
/// <summary>The home of a workspace project; null for a home this PC cannot reach in this phase (a server, phase 5b).</summary>
public IProjectHome? HomeOf(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
return home.IsArchive && _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
}
/// <summary>The home of a sequence of this PC's archive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public IProjectHome HomeOfSequence(Guid sequenceId) =>
HomeOf(new BundleHome(BundleHome.ArchiveKind, sequenceId)) ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
/// <summary>The projects of the workspace (one whose working state cannot be read is left out, and logged).</summary>
public Task<IReadOnlyList<WorkspaceEntry>> ListAsync(CancellationToken cancellationToken = default) =>
Task.Run(() => (IReadOnlyList<WorkspaceEntry>)[.. Store.ListBundles().Select(b => Entry(b.Project, b.Bundle))], cancellationToken);
/// <summary>The workspace projects of one sequence.</summary>
public async Task<IReadOnlyList<WorkspaceEntry>> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
[.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
/// <summary>A workspace project by id; null when the workspace has none (or it cannot be read).</summary>
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(() =>
{
if (Store.Find(projectId) is not { } project) return null;
try
{
return Entry(project, project.ReadBundle());
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
return null;
}
}, cancellationToken);
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var projects = await ProjectsOfAsync(sequenceId, cancellationToken).ConfigureAwait(false);
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var last) && projects.FirstOrDefault(p => p.ProjectId == last) is { } recent) return recent;
return projects.OrderByDescending(p => p.Saved).FirstOrDefault();
}
/// <summary>Remembers <paramref name="projectId"/> as the project of <paramref name="sequenceId"/> to open next time.</summary>
public void Remember(Guid sequenceId, Guid projectId)
{
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId) return;
_settings.WorkspaceRecent[sequenceId] = projectId;
_savePreferences();
}
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
}
/// <summary>
/// Brings a project of <paramref name="sequenceId"/> into the workspace and queues the copy of its media: the project
/// <paramref name="projectId"/>, else a new one named <paramref name="newName"/> (from Main's head), else Main. A
/// project already here keeps its working state; only its media are copied again.
/// </summary>
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The archive is offline or busy.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var checkout = await Task.Run(async () =>
{
SequenceProject project;
if (newName is not null)
{
project = await home.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
}
else
{
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
project = projectId is { } id
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
: listed.First(p => p.IsMain);
}
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
// Back on the caller's thread (the UI's): the settings are written there.
Remember(sequenceId, checkout.Project.Id);
return checkout;
}
/// <summary>
/// Queues the copy of a workspace project's media again ("Update media": the home's frames changed), unless one is
/// waiting or running already: that one is returned.
/// </summary>
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home.SequenceId, projectId, bundle.Workspace.Media.Kind, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached,
/// or that no longer has the project (deleted elsewhere), reads as offline.
/// </summary>
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var home = askHome ? HomeOf(project.ReadBundle().Workspace!.Home) : null;
try
{
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
{
Log.Info("workspace", $"The home of project {projectId} could not be asked: {ex.Message}");
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
return local with { Offline = true, State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Conflict ? local.State : WorkspaceState.Offline };
}
}, cancellationToken);
/// <summary>
/// "Save version": the working state as a new local version with <paramref name="note"/> (none when nothing changed
/// since the last), then, with Settings › Workspace › Sync automatically, the sync with the home
/// (<see cref="SyncAsync"/>); a home out of reach leaves the version waiting here.
/// </summary>
/// <exception cref="InvalidOperationException">The project is read-only, has a conflict to settle, or names frames the workspace has no media of.</exception>
public async Task<WorkspaceSaveResult> SaveVersionAsync(Guid projectId, string? note, CancellationToken cancellationToken = default)
{
var version = await Task.Run(async () =>
{
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
try
{
var synced = await SyncAsync(projectId, cancellationToken).ConfigureAwait(false);
return new WorkspaceSaveResult(version, synced, synced.Status, null);
}
catch (Exception ex) when (ex is HomeUnavailableException or LeaseUnavailableException or WorkspaceSyncException or WorkspaceException or ProjectException
or DatabaseException)
{
// The version is saved here all the same: it waits for the next sync.
Log.Info("workspace", $"Version of project {projectId} not sent yet: {ex.Message}");
return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), ex);
}
}
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// "Sync": the home's new versions taken (the working state and the local versions moved onto them), then the local
/// versions sent in order, then the versions past Kept versions pruned. A real conflict stops it before anything is
/// sent (<see cref="WorkspaceState.Conflict"/>).
/// </summary>
/// <exception cref="HomeUnavailableException">The home cannot be reached; nothing was lost.</exception>
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var home = HomeOfProject(projectId);
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
if (pulled.Status.State == WorkspaceState.Conflict) return pulled;
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
}, cancellationToken);
/// <summary>
/// Settles the conflict a sync stopped at, then sends what waits. <see cref="ConflictChoice.SaveBoth"/> sends this
/// workspace's versions to a sibling project named "&lt;name&gt; (&lt;this PC&gt;)" (a number added when that name is taken).
/// </summary>
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var home = HomeOfProject(projectId);
WorkspaceSyncResult resolved;
if (choice == ConflictChoice.SaveBoth)
{
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
try
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, cancellationToken).ConfigureAwait(false);
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, cancellationToken).ConfigureAwait(false);
}
}
else
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, cancellationToken).ConfigureAwait(false);
}
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
if (resolved.Status.State == WorkspaceState.Conflict) return resolved;
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs);
}, cancellationToken);
/// <summary>"<paramref name="name"/> (<c>PC</c>)", within the 60 characters of a project name.</summary>
public static string SiblingName(string name)
{
ArgumentNullException.ThrowIfNull(name);
var suffix = " (" + Environment.MachineName + ")";
if (suffix.Length >= ProjectService.MaxNameLength) suffix = suffix[..(ProjectService.MaxNameLength / 2)] + ")";
var room = ProjectService.MaxNameLength - suffix.Length;
return (name.Length > room ? name[..room].TrimEnd() : name) + suffix;
}
/// <summary>
/// Brings version <paramref name="versionId"/> back as the working state (uncommitted changes saved as a version first);
/// returns it, its positions on the media's frames.
/// </summary>
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
return restored;
}, cancellationToken);
/// <summary>The project's history, newest first: the versions not sent yet, then the home's (this workspace's own while the home is out of reach).</summary>
public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var unsent = Sync.Unpushed(projectId);
var home = HomeOf(project.ReadBundle().Workspace!.Home);
IReadOnlyList<ProjectVersion> stored;
var offline = false;
try
{
stored = home is null
? throw new HomeUnavailableException("The project's home cannot be reached from this PC.")
: await home.HistoryAsync(projectId, null, limit, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
Log.Info("workspace", $"The history of project {projectId} is read from the workspace: {ex.Message}");
offline = true;
stored = [.. project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).Take(limit)];
}
var ids = unsent.Select(v => v.Id).ToHashSet();
return new WorkspaceHistory([.. unsent.Reverse(), .. stored.Where(v => !ids.Contains(v.Id))], ids, offline);
}, cancellationToken);
/// <summary>A new project of the sequence named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version the home holds), else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(async () =>
{
var created = await home.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {sequenceId}");
return created;
}, cancellationToken);
}
/// <summary>Renames a project at its home, then its working state here.</summary>
/// <exception cref="ProjectException">The name is invalid or taken, or the project is gone.</exception>
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var renamed = await ArchiveProjects(project).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var bundle = project.ReadBundle();
project.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Name = renamed.Name } });
}
Log.Info("workspace", $"Project {projectId} renamed '{renamed.Name}'");
return renamed.Name;
}, cancellationToken);
/// <summary>
/// Deletes a project (never Main): the working state saved and sent first, so its home's trash
/// (<c>.chronos/projects/.trash</c>) holds every version; then the local copy goes.
/// </summary>
/// <exception cref="WorkspaceException">Something could not be sent (the home out of reach, a conflict): nothing was deleted.</exception>
/// <exception cref="ProjectException">Main, or the project is gone.</exception>
public async Task DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var sequenceId = await Task.Run(async () =>
{
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
var home = HomeOfProject(projectId);
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.Ahead > 0 || status.Conflict is not null || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
return workspace.Home.SequenceId;
}, cancellationToken);
Forget(sequenceId, projectId);
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
public Task<WorkspaceRemovalPlan> PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var name = project.ReadBundle().Workspace!.Name;
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
var (files, bytes) = Measure(project.Folder);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead, status.Modified, status.Conflict is not null, status.Offline);
}, cancellationToken);
/// <summary>
/// Removes a project's local copy. Without <paramref name="discard"/> it is refused while anything is not at the home,
/// and the home's head and the base this copy was made from are read back and checked against their hashes first.
/// With <paramref name="discard"/> (the user's explicit word) the versions not sent and the working state are moved to
/// <c>&lt;workspace&gt;/.trash</c> rather than erased. The media (copies the home can make again) are deleted.
/// </summary>
/// <exception cref="WorkspaceException">Something is not at the home yet, or the home's copy does not check out.</exception>
public async Task RemoveLocalCopyAsync(Guid projectId, bool discard, CancellationToken cancellationToken = default)
{
var sequenceId = await Task.Run(async () =>
{
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (!discard)
{
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Local copy of project {projectId} ('{workspace.Name}') removed{(discard ? ", its unsent work kept in " + TrashFolder : string.Empty)}");
return workspace.Home.SequenceId;
}, cancellationToken);
Forget(sequenceId, projectId);
}
/// <summary>
/// Drops the oldest versions this workspace took from the home, keeping Settings › Workspace › Kept versions of them
/// (the base among them), the versions not sent and the set-aside ones; a version goes only once the home was asked
/// and holds it with the same content.
/// </summary>
public async Task<int> PruneAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
var project = Existing(projectId);
var keep = Math.Max(1, _settings.WorkspaceKeptVersions);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var basis = project.ReadBundle().Workspace!.Base;
var stored = project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).ToList();
var kept = stored.Where(v => v.Id != basis?.VersionId).Take(keep - (basis is null ? 0 : 1)).Select(v => v.Id).ToHashSet();
var removed = 0;
foreach (var version in stored.Where(v => v.Id != basis?.VersionId && !kept.Contains(v.Id)))
{
if (await home.GetVersionAsync(projectId, version.Id, cancellationToken).ConfigureAwait(false) is not { } atHome
|| !string.Equals(atHome.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase)
|| !ProjectContent.Verifies(atHome.SettingsJson, atHome.ContentHash))
continue;
File.Delete(project.VersionPath(version));
removed++;
}
return removed;
}
}
private async Task PruneQuietlyAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
try
{
var removed = await PruneAsync(projectId, home, cancellationToken).ConfigureAwait(false);
if (removed > 0) Log.Info("workspace", $"{removed} older version(s) of project {projectId} dropped from the workspace (kept at the home)");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ProjectException)
{
Log.Warning("workspace", $"Older versions of project {projectId} could not be pruned", ex);
}
}
/// <summary>The local versions sent (after the home's new ones were taken), as one sync without the pruning.</summary>
private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return pulled.Status.State == WorkspaceState.Conflict ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
private async Task VerifyHomeAsync(Guid projectId, BundleWorkspace workspace, CancellationToken cancellationToken)
{
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
ProjectVersion head;
ProjectVersion? basis;
try
{
head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
basis = workspace.Base is { } b ? await home.GetVersionAsync(projectId, b.VersionId, cancellationToken).ConfigureAwait(false) : head;
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
}
if (!ProjectContent.Verifies(head.SettingsJson, head.ContentHash) || basis is null || !ProjectContent.Verifies(basis.SettingsJson, basis.ContentHash)
|| (workspace.Base is { } known && !string.Equals(known.ContentHash, basis.ContentHash, StringComparison.OrdinalIgnoreCase)))
throw new WorkspaceException(Loc.L("Errors.Workspace.HomeCheck"));
}
/// <summary>
/// The project's folder taken out of the workspace under its lease: the working state, the versions, the sync state and
/// the exports moved to <c>.trash/&lt;id&gt;-&lt;time&gt;</c> (kept: nothing a user made is erased), the media deleted; the
/// emptied folder goes once the lease is released.
/// </summary>
private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
// A copy of its media still under way would write them again behind the removal.
Guid copy;
lock (_gate) _copies.Remove(project.ProjectId, out copy);
if (copy != Guid.Empty && _engine() is { } engine && _db() is { } db && await db.Jobs.GetAsync(copy, cancellationToken).ConfigureAwait(false) is
{ State: JobState.Queued or JobState.Running or JobState.Paused })
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
var aside = Path.Combine(Store.Root, TrashFolder, project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture));
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
Directory.CreateDirectory(aside);
// The working state first: without it the folder is no project any more, whatever happens after.
File.Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile));
if (File.Exists(project.SyncPath)) File.Move(project.SyncPath, Path.Combine(aside, WorkspaceProject.SyncFile));
if (Directory.Exists(project.VersionsDirectory)) Directory.Move(project.VersionsDirectory, Path.Combine(aside, WorkspaceProject.VersionsFolder));
if (Directory.Exists(project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(project.ExportsDirectory).Any())
Directory.Move(project.ExportsDirectory, Path.Combine(aside, WorkspaceProject.ExportsFolder));
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
}
try
{
Directory.Delete(project.Folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Info("workspace", $"The emptied folder {project.Folder} stays: {ex.Message}");
}
}
/// <summary>A version can be saved: no conflict waits, the settings are this Chronos's, the media are here.</summary>
/// <exception cref="WorkspaceException">Why not.</exception>
private static void EnsureWritable(WorkspaceStatus status)
{
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
}
private void Forget(Guid sequenceId, Guid projectId)
{
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
_settings.WorkspaceRecent.Remove(sequenceId);
_savePreferences();
}
private async Task<Job> QueueCopyCoreAsync(Guid sequenceId, Guid projectId, string media, CancellationToken cancellationToken)
{
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
Guid known;
lock (_gate) _copies.TryGetValue(projectId, out known);
if (known != Guid.Empty && await db.Jobs.GetAsync(known, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running } running) return running;
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var job = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, Store.Root, projectId, media), cancellationToken: cancellationToken).ConfigureAwait(false);
lock (_gate) _copies[projectId] = job.Id;
return job;
}
private IProjectHome HomeOfProject(Guid projectId) =>
HomeOf(Existing(projectId).ReadBundle().Workspace!.Home) ?? throw new HomeUnavailableException("The project's home cannot be reached from this PC.");
private ProjectService ArchiveProjects(WorkspaceProject project) =>
project.ReadBundle().Workspace!.Home.IsArchive && _archives() is { } archives ? archives.Projects : throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
{
var workspace = bundle.Workspace!;
return new WorkspaceEntry(project.ProjectId, workspace.Home.SequenceId, workspace.Name, workspace.IsMain, workspace.Home,
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
}
/// <summary>Files and bytes under <paramref name="folder"/>, the lease left out.</summary>
private static (int Files, long Bytes) Measure(string folder)
{
var (files, bytes) = (0, 0L);
if (!Directory.Exists(folder)) return (files, bytes);
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
{
if (file.Name.EndsWith(".lease", StringComparison.OrdinalIgnoreCase)) continue;
files++;
bytes += file.Length;
}
return (files, bytes);
}
private sealed record OpenWorkspace(string Root, WorkspaceSync Sync);
}
@@ -0,0 +1,56 @@
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.
/// </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));
}
}
public string StateText => Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
public StatusKind StateKind => Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
public string StateToolTip => 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,83 @@
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,
_ => 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.</summary>
public static string Author(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
return version.Author ?? version.ClientName ?? string.Empty;
}
/// <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"/>.</summary>
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max) =>
SyncText.Differences(differences, 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,
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"),
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
_ => ArchiveFailures.Cause(ex),
};
}