feat(app): workspace projects whose home is a server, pushed and pulled like this PC's archive

Owner review 2, R8, phase 5b (client part), ported onto the final phase 5a.
A Chronos Server with the "projects" capability is now the home of
workspace projects. A server sequence is edited in the workspace like a
local one, not inside the library, and its versions sync with the server
"like git".

- Data: ServerProjectHome is an IProjectHome over ChronosClient.
  - These are HomeUnavailableException, so the workspace shows Offline: a
    server out of reach, an expired sign-in, a 503 (lease, offline archive,
    projects_unreadable), a 409 folder_in_use, and a server without projects.
  - 404 sequence/project/version and refused names are ProjectException;
    other refusals keep their meaning.
  - A deleted project's head is 404 project, so final 5a's HeadAsync NotFound
    rule reads it as Gone. The original 5b's IsLiveAsync and
    WorkspaceStatus.Gone are dropped. IProjectHome gains rename and delete.
- Data: WorkspaceJobs.CopyFromServer downloads into the workspace, through
  the desktop's session, the proxies of one frames version (or the
  thumbnails standing in for them), with the aliases of the server's
  conversions. It is rebuilt on final 5a's copy handler:
  - the copy:frame:fv:folder checkpoint, EnsureSpace (from the server's proxy
    sizes), WritingMedia, and the cancelled-copy clean-up;
  - the editor's current file is never overwritten;
  - each file is hashed as it arrives and checked on disk, four at a time.
  It never writes this PC's archive. Originals are still refused until 5c.
- Data: SyncAgent passes on the server's projectChanged events, and after a
  lost event stream it reports that changes may have been missed.
- App: SyncHost gives the server home over one session client. The Server
  screen offers Open in workspace, disabled with its reason on older
  servers, whose sequences keep opening with proxies.
- App: Edit opens or checks out server projects with final 5a's refusals:
  unreadable copies, a disabled damaged or newer Main, a refused folder. The
  "sequence left the index" refusal now applies only to projects of this
  PC's archive.
- App: the picker and the chip follow projectChanged (Server newer, Not on
  server). Every state, conflict, delete, remove and failure text uses its
  ".Server" form when one exists (WorkspaceText.ForHome). That includes 5a's
  newer-format conflict, the save conflict, the taken-values toast, Gone and
  version-too-large.
- App: a render of a server project first offers to send what is not on the
  server, then renders the version the server holds. Offline, Gone, Damaged
  and missing media hold the render. Analyses and renders run as server jobs
  (ServerJobs, shared with RemoteSequenceSource).
- Pruning keeps final 5a's rule: a version is pruned only after HoldsAsync
  reads it back.
- Strings in en and it; ARCHITECTURE, DECISIONS and CHANGELOG.

Tests:
- ServerProjectHome error mapping, using a fake handler.
- Against the in-process server:
  - two workspaces on one project: fast-forward, replay and merge, keep mine,
    take server, save both, restore;
  - the copy job verifying, resuming and following new frames;
  - a project deleted on the server (Gone from its head; a push sends
    nothing);
  - an offline server.
- SyncAgent project events.
- App tests for the host, the project menu and renders of a server home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 11:45:06 +01:00
1 parent e2ecc409a3
commit 26bab759fe
48 files changed
+3243 -409

No files matched your search

+14 -9
View File
@@ -625,6 +625,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// </summary>
public async Task RenderAsync(JobPriority priority, bool batch)
{
// A workspace project whose home is a server renders what the server holds: changes not sent are offered to be sent first (phase 5b).
if (Project is { } project && !await project.ReadyToRenderAsync()) return;
// The job embeds the project: its frame positions follow frames inserted since the editor read them first. A server
// sequence whose frames changed is outdated instead, and its toast says so and offers fresh proxies.
await Session.EnsureFramesAsync();
@@ -1074,22 +1076,25 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() =>
{
if (_disposed || Session.Conflict is null) return;
var request = Session.Source is WorkspaceSequenceSource ? LibraryConflictRequest(conflict, Title) : ConflictRequest(conflict, Title, ServerName ?? string.Empty);
var request = Session.Source is WorkspaceSequenceSource workspace ? LibraryConflictRequest(conflict, Title, workspace.IsServerHome) : ConflictRequest(conflict, Title, ServerName ?? string.Empty);
var keepMine = Shell.Services.Dialogs.Confirm(request);
if (!_disposed) Session.ResolveConflict(keepMine);
});
/// <summary>The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps.</summary>
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title) => new()
/// <summary>
/// The conflict prompt of a workspace project: what differs (the editor's value, then the home's) and what each choice
/// keeps, worded for a <paramref name="server"/> home (phase 5b) or the library.
/// </summary>
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title, bool server = false) => new()
{
Heading = Loc.L("Editor.Workspace.Conflict.Title"),
Message = Loc.L("Editor.Workspace.Edited.Message", title),
Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10)),
DetailToolTip = Loc.L("Tooltips.Editor.Workspace.Differences"),
SafeText = Loc.L("Editor.Workspace.Conflict.TakeHome"),
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.TakeHomeUndo"),
Message = WorkspaceText.ForHome("Editor.Workspace.Edited.Message", server, title),
Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10, server)),
DetailToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.Differences", server),
SafeText = WorkspaceText.ForHome("Editor.Workspace.Conflict.TakeHome", server),
SafeToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.TakeHomeUndo", server),
ActionText = Loc.L("Server.Sync.Action.KeepMine"),
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.KeepMine"),
ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.KeepMine", server),
IsDestructive = true,
};
+16 -144
View File
@@ -38,17 +38,12 @@ namespace Chronos.App.Editor;
public sealed class RemoteSequenceSource : ISequenceSource
{
private const int SaveAttempts = 3;
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
private readonly RemoteSequence _remote;
private readonly IRemoteSequenceApi _api;
private readonly IRenderFrameSource _frames;
private readonly IFrameSource _pixels;
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
private readonly CancellationTokenSource _stopping = new();
private readonly Task _listening;
private readonly ServerJobs _jobs;
private readonly bool _noEditRight;
private Stored? _stored;
private int _framesVersion = -1;
@@ -66,8 +61,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
_noEditRight = readOnly;
_frames = remote.OpenFrames(decoder);
_pixels = (IFrameSource)_frames;
var stopping = _stopping.Token;
_listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
_jobs = new ServerJobs(api, remote.Sequence.Id, remote.Sequence.DisplayTitle, job => JobChanged?.Invoke(job), OnEventAsync, OnReconnectedAsync);
}
public bool IsRemote => true;
@@ -190,126 +184,44 @@ public sealed class RemoteSequenceSource : ISequenceSource
/// The server queues every job at the user's priority; another priority ("Add to queue") is set right after. A
/// render embeds the project, whose frame positions mean nothing once the frames changed: refused while outdated.
/// </remarks>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
if (request.Kind == JobKind.Render && IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
var dto = await Call(() => _api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken));
if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken);
// The server's events may have reported the job already; its first state never replaces a later one.
if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) JobChanged?.Invoke(job);
return dto.Id;
return _jobs.SubmitAsync(request, cancellationToken);
}
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
{
var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken));
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
foreach (var job in mine) _jobs[job.Id] = job;
return mine;
}
public Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) => _jobs.ListAsync(cancellationToken);
public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await _api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.CancelAsync(jobId, cancellationToken);
public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await _api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.RetryAsync(jobId, cancellationToken);
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
try
{
await _stopping.CancelAsync();
await _listening;
// Stops following the events, and closes the connection.
await _jobs.DisposeAsync();
}
finally
{
_stopping.Dispose();
if (_frames is IAsyncDisposable frames) await frames.DisposeAsync();
_api.Dispose();
}
}
/// <summary>
/// Follows the server's events until the editor closes, reconnecting with a growing delay (job states lost meanwhile
/// are read back from the jobs, and the frames are compared again). Nothing that fails on the way ends it.
/// </summary>
private async Task ListenAsync(CancellationToken cancellationToken)
{
var failures = 0;
while (true)
{
try
{
await foreach (var e in _api.EventsAsync(cancellationToken).ConfigureAwait(false))
{
failures = 0;
await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Events of the server lost for {_remote.Sequence.DisplayTitle}: {ex.Message}");
}
try
{
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false);
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
// A frames change announced while the socket was down is found now rather than at the next save.
if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Jobs of {_remote.Sequence.DisplayTitle} could not be read again: {ex.Message}");
}
}
}
/// <summary>The server's events besides the jobs': frames added or removed on the server make the sequence outdated.</summary>
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
{
switch (e)
{
case SequenceChangedEvent changed when changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion):
await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
break;
// A late progress event never brings a finished job back to running.
case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running:
Publish(job with
{
State = JobState.Running,
ProgressDone = progress.Done,
ProgressTotal = progress.Total,
ItemsPerSecond = progress.ItemsPerSecond,
Eta = JobEta.FromSeconds(progress.EtaSeconds),
});
break;
case JobStateEvent state when !_foreign.ContainsKey(state.JobId):
await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false);
break;
}
if (e is SequenceChangedEvent changed && changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion))
await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
/// <summary>A frames change announced while the event socket was down is found now rather than at the next save.</summary>
private async Task OnReconnectedAsync(CancellationToken cancellationToken)
{
try
{
if (JobWire.FromDto(await _api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job);
else _foreign[jobId] = 0;
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}");
}
if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Frames added or removed on the server: whether this PC's frames are still the sequence's.</summary>
@@ -326,34 +238,6 @@ public sealed class RemoteSequenceSource : ISequenceSource
}
}
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
private async Task<JobDto> PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken)
{
try
{
return await _api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken);
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException)
{
// Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked.
Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}");
return dto;
}
}
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
private async Task RefreshTrackedAsync(CancellationToken cancellationToken)
{
foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList())
await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false);
}
private void Publish(Job job)
{
_jobs[job.Id] = job;
JobChanged?.Invoke(job);
}
/// <summary>
/// Takes the server's frames as <paramref name="manifest"/> lists them: their frames version when they are this PC's
/// (saves name it), outdated otherwise. Returns whether they are.
@@ -387,8 +271,6 @@ public sealed class RemoteSequenceSource : ISequenceSource
ReadOnlyChanged?.Invoke();
}
private bool Concerns(Job job) => job.TargetIds.Contains(Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
private Guid HeroFrameId(ProjectSettings project) =>
project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
@@ -424,17 +306,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
}
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
private static async Task<T> Call<T>(Func<Task<T>> call)
{
try
{
return await call();
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
}
}
private static Task<T> Call<T>(Func<Task<T>> call) => ServerJobs.Call(call);
/// <summary>The server's settings as last read or written, with the version a save must name.</summary>
private sealed record Stored(ProjectSettings Project, int Version);
+225
View File
@@ -0,0 +1,225 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.App.Editor;
/// <summary>
/// The analyses and renders of one server sequence as an editor follows them (BRIEF §14.5): queued through the API (the
/// server queues each at the user's priority, another one is set right after), their states and progress taken from the
/// server's events, the jobs followed read again whenever the event socket comes back after a loss (reconnecting with a
/// growing delay; nothing that fails on the way ends it). What a server sequence opened with proxies
/// (<see cref="RemoteSequenceSource"/>) and a workspace project whose home is a server (<see cref="WorkspaceSequenceSource"/>,
/// owner review 2, R8) run on the server. Events of other kinds go to <c>other</c>; <c>reconnected</c> runs after the jobs
/// were read again. Owns the connection: disposing stops listening and disposes it.
/// </summary>
internal sealed class ServerJobs : IAsyncDisposable
{
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
private readonly Guid _sequenceId;
private readonly string _title;
private readonly Action<Job> _changed;
private readonly Func<ServerEvent, CancellationToken, Task>? _other;
private readonly Func<CancellationToken, Task>? _reconnected;
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
private readonly CancellationTokenSource _stopping = new();
private readonly Task _listening;
private int _disposed;
/// <param name="changed">A job of the sequence changed (any thread).</param>
public ServerJobs(IRemoteSequenceApi api, Guid sequenceId, string title, Action<Job> changed, Func<ServerEvent, CancellationToken, Task>? other = null,
Func<CancellationToken, Task>? reconnected = null)
{
ArgumentNullException.ThrowIfNull(api);
ArgumentNullException.ThrowIfNull(changed);
Api = api;
_sequenceId = sequenceId;
_title = title;
_changed = changed;
_other = other;
_reconnected = reconnected;
var stopping = _stopping.Token;
_listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
}
/// <summary>The connection the jobs travel on (the source's other calls use it too).</summary>
public IRemoteSequenceApi Api { get; }
/// <summary>Queues <paramref name="request"/> on the server (its priority set after, when it is not the user's); returns the job id.</summary>
/// <exception cref="EditorException">The sequence is gone from the server.</exception>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
var dto = await Call(() => Api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken));
if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken);
// The server's events may have reported the job already; its first state never replaces a later one.
if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) _changed(job);
return dto.Id;
}
/// <summary>The analyses and renders of the sequence waiting, running or paused on the server, followed from now on.</summary>
public async Task<IReadOnlyList<Job>> ListAsync(CancellationToken cancellationToken)
{
var active = await Call(() => Api.ListActiveJobsAsync(cancellationToken));
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
foreach (var job in mine) _jobs[job.Id] = job;
return mine;
}
public async Task CancelAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await Api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public async Task RetryAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await Api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
try
{
await _stopping.CancelAsync();
await _listening;
}
finally
{
_stopping.Dispose();
Api.Dispose();
}
}
/// <summary>
/// Follows the server's events until disposed, reconnecting with a growing delay (job states lost meanwhile are read
/// back from the jobs, then <c>reconnected</c> runs). Nothing that fails on the way ends it.
/// </summary>
private async Task ListenAsync(CancellationToken cancellationToken)
{
var failures = 0;
while (true)
{
try
{
await foreach (var e in Api.EventsAsync(cancellationToken).ConfigureAwait(false))
{
failures = 0;
await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Events of the server lost for {_title}: {ex.Message}");
}
try
{
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false);
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
if (_reconnected is not null) await _reconnected(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Jobs of {_title} could not be read again: {ex.Message}");
}
}
}
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
{
switch (e)
{
// A late progress event never brings a finished job back to running.
case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running:
Publish(job with
{
State = JobState.Running,
ProgressDone = progress.Done,
ProgressTotal = progress.Total,
ItemsPerSecond = progress.ItemsPerSecond,
Eta = JobEta.FromSeconds(progress.EtaSeconds),
});
break;
case JobProgressEvent:
break;
case JobStateEvent state:
if (!_foreign.ContainsKey(state.JobId)) await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false);
break;
default:
if (_other is not null) await _other(e, cancellationToken).ConfigureAwait(false);
break;
}
}
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
{
try
{
if (JobWire.FromDto(await Api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job);
else _foreign[jobId] = 0;
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}");
}
}
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
private async Task<JobDto> PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken)
{
try
{
return await Api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken);
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException)
{
// Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked.
Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}");
return dto;
}
}
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
private async Task RefreshTrackedAsync(CancellationToken cancellationToken)
{
foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList())
await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false);
}
private void Publish(Job job)
{
_jobs[job.Id] = job;
_changed(job);
}
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
internal static async Task<T> Call<T>(Func<Task<T>> call)
{
try
{
return await call();
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
}
}
}
+248 -16
View File
@@ -19,6 +19,8 @@ using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.App.Editor;
@@ -29,6 +31,13 @@ public interface IProjectRenders
IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
}
/// <summary>
/// A workspace project's home when it is a server (owner review 2, R8, phase 5b): the connection its analyses and renders
/// travel on, which the source owns; null while this PC is not signed in to that server (the project still opens from the
/// workspace, its jobs are refused saying so).
/// </summary>
public sealed record WorkspaceServerHome(IRemoteSequenceApi? Api);
/// <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
@@ -42,6 +51,11 @@ public interface IProjectRenders
/// (<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.
/// A project whose home is a server (<see cref="WorkspaceServerHome"/>, phase 5b) is a remote one for the editor: its
/// analyses and renders are the server's jobs (<see cref="ServerJobs"/>), a render of the version the server holds when the
/// project is in step with it (else of the project's portable settings, recording the project), its deep report and renders
/// are read from the server when it can be reached (else the copy the workspace took), and "Update media" is offered when
/// the server's frames moved, or it has the proxy of a frame a thumbnail stands in for.
/// </summary>
public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
{
@@ -51,19 +65,23 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private readonly ChronosDatabase _db;
private readonly ImageDecoder _decoder;
private readonly JobEngine? _engine;
private readonly WorkspaceServerHome? _server;
private readonly Lock _gate = new();
private readonly List<IRenderFrameSource> _retired = [];
private IRenderFrameSource? _frames;
private IFrameSource? _pixels;
private ServerJobs? _serverJobs;
private int _frameCount;
private int _framesVersion = -1;
private Guid[] _frameIds = [];
private HashSet<Guid> _standIns = [];
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)
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null)
{
ArgumentNullException.ThrowIfNull(sync);
ArgumentNullException.ThrowIfNull(db);
@@ -72,7 +90,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_db = db;
_decoder = decoder;
_engine = engine;
_server = server;
ProjectId = projectId;
// This PC's engine runs the copies of the media (Update media), whatever the home.
if (engine is not null) engine.JobChanged += OnJobChanged;
}
@@ -90,7 +110,11 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <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>The project's home is a server (phase 5b): its analyses and renders run there.</summary>
public bool IsServerHome => _server is not null;
/// <summary>A server home's analyses and renders run on the server, as for a server sequence opened with proxies.</summary>
public bool IsRemote => _server is not null;
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
public bool IsReadOnly => Volatile.Read(ref _readOnly);
@@ -132,6 +156,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}
if (session is not { Sequence: { } media, Media: { } index }) throw new EditorException(Loc.L("Errors.Workspace.MediaMissing"));
var home = session.Bundle.Workspace!.Home;
if (_server is not null) return await LoadFromServerAsync(session, media, index, home, cancellationToken);
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);
@@ -160,6 +185,123 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}, cancellationToken);
}
/// <summary>
/// A project whose home is a server: the media's frames and the working state as for any workspace project, with what
/// the server says of its sequence when it can be reached (title, camera, tags, renders, and its deep report while its
/// frames are the media's); the copy the workspace took of the report otherwise. The server's jobs are followed from
/// the first read on.
/// </summary>
private async Task<SequenceContent> LoadFromServerAsync(WorkspaceSession session, WorkspaceSequence media, WorkspaceMedia index, BundleHome home,
CancellationToken cancellationToken)
{
var jobs = ServerJobsOf(home.SequenceId, session.Bundle.Sequence.Title ?? media.Sequence.DisplayTitle);
SequenceDto? dto = null;
SequenceManifest? manifest = null;
string? report = null;
if (jobs is not null)
{
try
{
dto = await jobs.Api.GetSequenceAsync(home.SequenceId, cancellationToken);
manifest = await jobs.Api.GetManifestAsync(home.SequenceId, cancellationToken);
// The server's report only while its frames are the ones this workspace holds.
if (manifest.FramesVersion == index.FramesVersion) report = await jobs.Api.GetAnalysisReportAsync(home.SequenceId, cancellationToken);
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException)
{
// Out of reach (or the sequence gone there): the workspace's own copy opens all the same.
Log.Info("editor", $"The server's view of workspace project {ProjectId} is not read now: {ex.Message}");
}
}
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();
var sequence = 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(),
};
if (dto is not null)
{
sequence = sequence with
{
Title = dto.Title,
CameraMake = dto.CameraMake,
CameraModel = dto.CameraModel,
Lens = dto.Lens,
MedianInterval = dto.MedianInterval,
Tags = dto.Tags,
Rating = dto.Rating,
Notes = dto.Notes,
Status = (SequenceStatus)dto.Status,
RenderedCount = dto.RenderedCount,
WarningCount = dto.WarningCount,
PreviewOnlyCount = dto.PreviewOnlyCount,
OwnerUserId = dto.OwnerUserId,
UpdatedAt = dto.UpdatedAt,
};
}
var renders = manifest?.Renders.OrderByDescending(r => r.Created).Select(r => new Render
{
Id = r.Id,
SequenceId = home.SequenceId,
PresetName = r.PresetName,
OutputPath = string.Empty,
Codec = r.Codec,
Width = r.Width,
Height = r.Height,
Fps = r.Fps,
DurationSeconds = r.DurationSeconds,
Bytes = r.Bytes,
Created = r.Created,
ProducedBy = r.ProducedBy,
}).ToList() ?? [];
var (deep, otherFrames) = ServerReport(report, 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, null, renders, [])
{
DeepOfOtherFrames = otherFrames,
};
}, cancellationToken);
}
/// <summary>The server's jobs of the sequence, followed from now on; null while this PC is not signed in to the server.</summary>
private ServerJobs? ServerJobsOf(Guid sequenceId, string title)
{
if (_server?.Api is not { } api) return null;
lock (_gate)
{
if (Volatile.Read(ref _disposed) == 1) return null;
return _serverJobs ??= new ServerJobs(api, sequenceId, title, job => JobChanged?.Invoke(job));
}
}
/// <summary>The server's deep report when it describes these frames, else the copy the workspace took; whether one of another number of frames was read instead.</summary>
private static (DeepAnalysisReport? Report, bool OtherFrames) ServerReport(string? json, string copied, int frameCount)
{
var otherFrames = false;
if (json is not null)
{
try
{
var report = DeepAnalysisReport.FromJson(json);
if (report.FrameCount == frameCount) return (report, false);
otherFrames = true;
}
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
Log.Warning("editor", "The server's deep report cannot be read; the workspace's copy is shown", ex);
}
}
var (deep, other) = ReadReport(null, false, copied, frameCount);
return (deep, deep is null && (other || otherFrames));
}
/// <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(() =>
{
@@ -175,11 +317,26 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}
}, cancellationToken);
/// <summary>Whether the home's frames moved past those the workspace holds (frames added or removed there): "Update media" copies them again.</summary>
/// <summary>
/// Whether the home's frames moved past those the workspace holds (frames added or removed there), or a server now has
/// the proxy of a frame a thumbnail stands in for here: "Update media" copies them again. A server out of reach says no.
/// </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;
if (_server is null) return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion;
if (_server.Api is not { } api) return false;
try
{
if ((await api.GetSequenceAsync(workspace.Home.SequenceId, cancellationToken)).FramesVersion != MediaFramesVersion) return true;
var standIns = Volatile.Read(ref _standIns);
return standIns.Count > 0 && (await api.GetManifestAsync(workspace.Home.SequenceId, cancellationToken)).Frames.Any(f => f.HasProxy && standIns.Contains(f.Id));
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException)
{
Log.Info("editor", $"The server's frames of workspace project {ProjectId} could not be compared: {ex.Message}");
return false;
}
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
@@ -293,27 +450,48 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private static bool NamesPosition(string path) =>
path is "excludedFrames" or "heroFrame" || path.StartsWith("camera.keyframes", StringComparison.Ordinal) || path.StartsWith("pendingFrames", StringComparison.Ordinal);
/// <remarks>A project whose home is a server queues its analyses and renders there; while this PC is not signed in to it, they are refused saying so.</remarks>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
if (_server is not null) return await ServerJobsOrThrow().SubmitAsync(request, 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;
/// <remarks>A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same).</remarks>
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
{
if (_server is null) return (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
if (Volatile.Read(ref _serverJobs) is not { } jobs) return [];
try
{
return await jobs.ListAsync(cancellationToken);
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException or EditorException)
{
Log.Info("editor", $"The server's jobs of workspace project {ProjectId} are not read now: {ex.Message}");
return [];
}
}
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) =>
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
? ServerJobsOrThrow().CancelAsync(jobId, 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);
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
? ServerJobsOrThrow().RetryAsync(jobId, cancellationToken)
: (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
/// <summary>
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job of this PC's
/// engine per preset, with the project's portable settings (positions parked by photo, placed on the home's frames by
/// the render) and the project recorded on the render; the version too when the settings are those of the last
/// version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is, without a version).
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset
/// (of this PC's engine, or the server's), with the project's portable settings (positions parked by photo, placed on
/// the home's frames by the render) and the project recorded on the render; the version too when the settings are those
/// of the last version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is,
/// without a version). A server home (phase 5b) renders the version it holds when the project is in step with it
/// (nothing saved or sent since its base): the jobs name that version alone and the server renders its settings with
/// the jobs' export; a project out of step renders its portable settings, recording the project only, as a server knows
/// no version of this workspace's that it was not sent.
/// </summary>
public IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight)
{
@@ -322,8 +500,18 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable);
if (_server is not null)
{
if (InStepWithHome(project) is { } basis)
{
var version = new ProjectVersion { Id = basis.VersionId, ProjectId = ProjectId, Number = basis.Number, SettingsJson = portable, ContentHash = hash };
return [.. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => r with { ParametersJson = WithoutSettings(r.ParametersJson) })];
}
var unsent = new ProjectVersion { Id = Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash };
return [.. ProcessingJobs.RenderVersion(sequence, unsent, export, sourceWidth, sourceHeight).Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
var (tipId, tipHash) = Tip();
var version = new ProjectVersion
var tip = new ProjectVersion
{
Id = tipId ?? Guid.Empty,
ProjectId = ProjectId,
@@ -331,29 +519,65 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
SettingsJson = portable,
ContentHash = hash,
};
var requests = ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight);
var requests = ProcessingJobs.RenderVersion(sequence, tip, 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) })];
}
/// <summary>
/// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project
/// (<paramref name="project"/>) holds what the base holds; null otherwise.
/// </summary>
public BundleBase? InStepWithHome(ProjectSettings project)
{
ArgumentNullException.ThrowIfNull(project);
try
{
if (_sync.Unpushed(ProjectId).Count > 0 || Project.ReadBundle().Workspace?.Base is not { } basis) return null;
var working = ProjectContent.ToPortable(project, Photos);
if (string.Equals(ProjectContent.Hash(working), basis.ContentHash, StringComparison.OrdinalIgnoreCase)) return basis;
// Saved before a hash or a conversion at the home named its photos anew: the same choices are in step too.
return Project.Versions().FirstOrDefault(v => v.Id == basis.VersionId) is { } version && ProjectContent.SameChoices(version.SettingsJson, working, Photos)
? basis
: 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;
}
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
List<IRenderFrameSource> sources;
ServerJobs? jobs;
lock (_gate)
{
sources = [.. _retired];
if (_frames is not null) sources.Add(_frames);
_retired.Clear();
(_frames, _pixels) = (null, null);
(jobs, _serverJobs) = (_serverJobs, null);
}
// The server's connection is the source's: it closes with it, also when no read made the jobs' listener.
if (jobs is not null) await jobs.DisposeAsync();
else _server?.Api?.Dispose();
foreach (var source in sources)
{
if (source is IAsyncDisposable disposable) await disposable.DisposeAsync();
}
}
/// <summary>The server's jobs of the project's sequence, or why there are none.</summary>
/// <exception cref="EditorException">This PC is not signed in to the server of the project.</exception>
private ServerJobs ServerJobsOrThrow() =>
Volatile.Read(ref _serverJobs)
?? (Workspace is { } workspace ? ServerJobsOf(workspace.Home.SequenceId, Project.ReadBundle().Sequence.Title ?? string.Empty) : null)
?? throw new EditorException(Loc.L("Editor.Error.SignedOut"));
/// <summary>
/// Takes the media read now: a frame source over them when they differ from those read before (the old one is disposed
/// with this source, as a decode may still read it), their frames and photos, the project's workspace section, and
@@ -375,6 +599,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_frameIds = ids;
_framesVersion = index.FramesVersion;
_photos = index.Photos;
_standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)];
_workspace = workspace;
changed = _readOnly != readOnly;
_readOnly = readOnly;
@@ -407,6 +632,13 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
return JsonSerializer.Serialize(parameters with { ProjectVersionId = null }, ProtocolJson.Default.RenderJobParameters);
}
/// <summary>A job of a version the home holds: the home renders that version's settings (with the job's export), so none travel with it.</summary>
private static string? WithoutSettings(string? parametersJson)
{
if (parametersJson is null || JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters) is not { } parameters) return parametersJson;
return JsonSerializer.Serialize(parameters with { SettingsJson = 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.
@@ -74,6 +74,9 @@ public sealed class AppServices : IAsyncDisposable
Sync = new SyncHost(this);
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine);
// A server that keeps projects is the home of the workspace projects of its sequences (owner review 2, R8, phase 5b).
Workspace.ServerHomes = Sync.ProjectHome;
Sync.ProjectChanged += Workspace.OnServerProjectChanged;
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
Formats = new WicFormatInventory(() => _wic);
@@ -120,7 +123,7 @@ 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>
/// <summary>The workspace where Edit opens projects (owner review 2, R8), with this PC's archive or the signed-in server as their home.</summary>
public WorkspaceHost Workspace { get; }
public IEncoderInventory Encoders { get; set; }
@@ -175,12 +178,13 @@ 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). The workspace copy is the desktop's alone: it writes into this PC's workspace.</summary>
/// queued (it is never claimed here). The workspace copy is the desktop's alone: it writes into this PC's workspace, from
/// this PC's archive or, through the signed-in session, from a server.</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) : [],
.. services.Database is { } db && services.Archives is { } archives ? WorkspaceJobs.CreateHandlers(db, archives, services.Sync) : [],
];
/// <summary>
@@ -26,6 +26,7 @@ namespace Chronos.App.Sections;
public sealed class SequencePickerViewModel : LocalizedViewModel
{
private readonly SequenceViewModel _section;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _searchDelay;
private readonly RemoteMerge _merge = new();
private readonly AsyncRelayCommand _open;
@@ -46,8 +47,10 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
public SequencePickerViewModel(SequenceViewModel section)
{
_section = section;
_dispatcher = Dispatcher.CurrentDispatcher;
_searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
_searchDelay.Tick += (_, _) => _ = ReloadAsync();
section.Shell.Services.Workspace.HomeChanged += OnHomeChanged;
_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);
@@ -172,11 +175,34 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
{
_searchDelay.Stop();
_pager?.Cancel();
_section.Shell.Services.Workspace.HomeChanged -= OnHomeChanged;
// The projects' states still being read stop asking.
_generation++;
base.Dispose();
}
/// <summary>
/// A project's home told it changed there (any thread; phase 5b: a server's <c>projectChanged</c>), or that changes may
/// have been missed: the listed projects it concerns read their state again (Server newer, Deleted).
/// </summary>
private void OnHomeChanged(WorkspaceHomeChange change) => _dispatcher.BeginInvoke(async () =>
{
var generation = _generation;
foreach (var item in WorkspaceItems.Where(i => change.ProjectId is { } id ? i.ProjectId == id
: i.Entry.IsServerHome && string.Equals(i.Entry.Home.Server, change.Server, StringComparison.OrdinalIgnoreCase)).ToList())
{
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 async Task OpenFromSearchAsync()
{
await SettleAsync();
@@ -271,8 +297,13 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
{
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));
var row = entry.IsServerHome ? null : await db.Sequences.GetAsync(entry.SequenceId);
// A server's sequence as the Library lists it (phase 5b), with the server's thumbnail; none while signed out.
var remote = row is null ? Shell.Library.RemoteSequences.FirstOrDefault(s => s.Id == entry.SequenceId) : null;
var sequence = row is not null ? new SequenceItem(row, services.Thumbnails)
: remote is not null ? new SequenceItem(remote, Shell.Library.RemoteThumbnails)
: null;
var item = new WorkspaceProjectItem(entry, sequence);
if (text.Length > 0 && !item.Name.Contains(text, StringComparison.CurrentCultureIgnoreCase)
&& !item.SequenceTitle.Contains(text, StringComparison.CurrentCultureIgnoreCase))
continue;
+5 -5
View File
@@ -123,11 +123,11 @@
<Separator />
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Rename}" />
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{Binding Project.RenameToolTip}" />
<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}" />
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{Binding Project.RemoveCopyToolTip}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
@@ -164,13 +164,13 @@
</StackPanel>
</Grid>
<!-- Owner review 2, R8: the library's frames moved past the workspace's; Update media copies them again (positions follow their photos). -->
<!-- Owner review 2, R8: the home's frames (the library's or the server's) 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"
ToolTip="{Binding Project.UpdateMediaToolTip}" ToolTipService.ShowOnDisabled="True" />
<ui:StatusGlyph Kind="Warning" Text="{Binding Project.MediaUpdateText}" ToolTip="{Binding Project.MediaChangedToolTip}" VerticalAlignment="Center"
infra:LiveRegion.Text="{Binding Project.MediaUpdateText}" AutomationProperties.LiveSetting="Polite" />
</DockPanel>
</Border>
+145 -24
View File
@@ -14,8 +14,10 @@ using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol.Client;
using Chronos.Ui.Mvvm;
@@ -27,9 +29,11 @@ namespace Chronos.App.Sections;
/// 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,
/// which media, the project is checked out and its media copied by a job, and it opens once they are here. A sequence of
/// a server that keeps projects opens the same way as a project whose home is that server (phase 5b: its media downloaded
/// into the workspace; a project already there opens from it, the server reachable or not); one of an older server opens
/// with this PC's proxies, and a capture (sample data without an engine) opens the library as before. The next sequence
/// is read first; only then does the open one close,
/// after its last edit is stored. Without a sequence, or after Change sequence, it shows the picker (the editor stays
/// open behind it until another sequence opens). A server sequence whose proxies are missing or out of date fetches them
/// first and opens once they are here, the open sequence staying open meanwhile; a workspace copy is followed the same
@@ -540,9 +544,10 @@ public sealed class SequenceViewModel : SectionViewModel
/// <summary>
/// Where <paramref name="sequenceId"/> lives: this PC's index (opened as a workspace project,
/// <see cref="OpenWorkspaceAsync"/>; in a capture, the library itself), else a sequence of the signed-in server whose
/// proxies this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only shown
/// when the account may not change it. Null when it cannot open yet: its proxies are being fetched
/// <see cref="OpenWorkspaceAsync"/>; in a capture, the library itself), else a server's sequence: a workspace project
/// whose home is that server (<see cref="OpenServerWorkspaceAsync"/>), or, for a server that keeps no projects, one
/// whose proxies this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only
/// shown when the account may not change it. Null when it cannot open yet: its proxies are being fetched
/// (<see cref="FetchProxiesAsync"/>), its workspace copy runs, or the user closed "Open in workspace".
/// </summary>
private async Task<(ISequenceSource Source, string Title)?> OpenSourceAsync(AppServices services, Guid sequenceId)
@@ -557,14 +562,19 @@ public sealed class SequenceViewModel : SectionViewModel
local.HeroChanged += OnHeroChanged;
return (local, row.DisplayTitle);
}
// A workspace project whose sequence left the index (its trash emptied, its folder gone): not a server's sequence to
// fetch; its local copy can only be removed (the picker's Remove local copy).
// A workspace project of this PC's archive whose sequence left the index (its trash emptied, its folder gone): not a
// server's sequence to fetch; its local copy can only be removed (the picker's Remove local copy).
if (_requested is { ProjectId: { } projectId } asked && asked.SequenceId == sequenceId && services.Workspace.IsEnabled
&& await services.Workspace.FindAsync(projectId) is not null)
&& await services.Workspace.FindAsync(projectId) is { IsServerHome: false })
{
_requested = null;
throw new InvalidOperationException(Loc.L("Errors.Workspace.SequenceGone"));
}
// A server sequence (owner review 2, R8, phase 5b): a project of it in the workspace opens from there, the server
// reachable or not; one of a server that keeps projects is checked out (asked which); an older server's opens with
// proxies as before.
if (services.Workspace.IsEnabled && await OpenServerWorkspaceAsync(services, services.Workspace, db, decoder, sequenceId) is { } project)
return project.Opened;
var sync = services.Sync;
if (sync.Server is not { } server || sync.Service is not { } service || sync.ConnectEditor() is not { } api)
throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
@@ -610,7 +620,7 @@ public sealed class SequenceViewModel : SectionViewModel
// with Remove local copy for a damaged one, when nothing else could be chosen (Main asked for, or the home has no
// other project); otherwise "Open in workspace" lists Main as it is, disabled, and offers the others.
WorkspaceEntry? unreadableMain = null;
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, row.Id) is { } main)
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, WorkspaceHost.ArchiveHome(row.Id)) is { } main)
{
if (request is { Main: true } || (await workspace.HomeProjectsAsync(row.Id)).All(p => p.IsMain))
{
@@ -664,10 +674,10 @@ public sealed class SequenceViewModel : SectionViewModel
return null;
}
/// <summary>The workspace's copy of the sequence's Main when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, Guid sequenceId)
/// <summary>The workspace's copy of the Main of <paramref name="home"/>'s sequence when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, BundleHome home)
{
if ((await workspace.HomeProjectsAsync(sequenceId)).FirstOrDefault(p => p.IsMain) is not { } main) return null;
if ((await workspace.HomeProjectsAsync(home)).FirstOrDefault(p => p.IsMain) is not { } main) return null;
return await workspace.FindAsync(main.Id) is { IsReadable: false } copy ? copy : null;
}
@@ -689,22 +699,130 @@ public sealed class SequenceViewModel : SectionViewModel
}
/// <summary>
/// "Open in workspace": the projects of the sequence's home, the media, what their copy writes and the room the
/// workspace's drive has; null when closed without a choice. <paramref name="unreadableMain"/>, the copy of Main here
/// this Chronos cannot read, is listed disabled, why in its tooltip.
/// A sequence of a server opens as a project of the workspace whose home is that server (phase 5b): the project asked
/// for, else the one of the sequence opened last here. One the workspace holds the media of opens from there, whether
/// this PC can reach the server or not (its sync, analyses and renders wait for it). Otherwise, signed in to a server
/// that keeps projects, the project is checked out, after "Open in workspace" asked which (when the sequence has none
/// here), and its media downloaded by a job; it opens once they are here. A copy this Chronos cannot read is refused as
/// for this PC's archive. Null when the server keeps no projects, or this PC is not signed in to it: the sequence then
/// opens with proxies as before (or says to connect).
/// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row, WorkspaceEntry? unreadableMain = null)
private async Task<ServerOpen?> OpenServerWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db, ImageDecoder decoder, Guid remoteId)
{
var projects = await workspace.HomeProjectsAsync(row.Id);
WorkspaceCopyFacts? copy = null;
var request = _requested is { } asked && asked.SequenceId == remoteId ? asked : null;
var entry = request switch
{
{ ProjectId: { } id } => await workspace.FindAsync(id) is { IsServerHome: true } found && found.SequenceId == remoteId ? found : null,
{ Main: true } => (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true }),
_ => await workspace.LastUsedAsync(remoteId) is { IsServerHome: true } last ? last : null,
};
var sync = services.Sync;
if (entry is { IsReadable: false } unreadable)
{
TakeRequest(remoteId);
throw WorkspaceHost.Unreadable(unreadable);
}
if (entry is { HasMedia: true })
{
TakeRequest(remoteId);
workspace.Remember(remoteId, entry.ProjectId);
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server.
var api = string.Equals(sync.Server, entry.Home.Server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null;
return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, new WorkspaceServerHome(api)),
entry.SequenceTitle));
}
if (sync.ServerHome(remoteId) is not { } home) return null;
TakeRequest(remoteId);
try
{
copy = await workspace.CopyFactsAsync(row.Id);
var reached = workspace.Reachable(home);
var title = (await Task.Run(() => reached.SequenceAsync(CancellationToken.None))).Sequence.Title ?? entry?.SequenceTitle ?? string.Empty;
// No project of the sequence here opens and its Main here cannot be read: refused, or listed disabled, as for this PC's archive.
WorkspaceEntry? unreadableMain = null;
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, home) is { } main)
{
if (request is { Main: true } || (await workspace.HomeProjectsAsync(home)).All(p => p.IsMain))
{
RefuseUnreadable(main);
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
unreadableMain = main;
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(home)).All(p => p.Id != wanted))
{
// A project the server does not have (deleted there, or another server's): the sequence's Main opens instead.
Log.Info("workspace", $"Project {wanted} is not a project of server sequence {remoteId}; its Main opens instead");
projectId = null;
if (_afterOpen is { } pending && pending.Request.SequenceId == remoteId) _afterOpen = (ProjectRequest.MainOf(remoteId), pending.Action);
}
else if (entry is null && projectId is null && request is not { Main: true })
{
if (await AskProjectAsync(workspace, home, title, unreadableMain) is not { } choice)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(home, projectId, newName);
}
catch (WorkspaceException ex) when (ex.FolderRefused)
{
// Nothing was written: the way on is another workspace folder, offered from the refusal.
Log.Info("workspace", $"Server sequence {remoteId} not checked out: {ex.Message}");
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), ex.Message, Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder"),
() => _ = WorkspaceFolderChange.ChooseAsync(Shell), isError: true);
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
await FollowCopyAsync(remoteId, title, checkout.Project.Id, checkout.Copy);
return new ServerOpen(null);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
catch (ProjectException ex) when (ex.Reason == ProjectError.SequenceNotFound)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {row.Id} could not be measured: {ex.Message}");
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
}
catch (HomeUnavailableException ex)
{
// Said of the server, not of this PC's library.
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server: true), ex);
}
}
/// <summary>"Open in workspace" for a sequence of this PC's archive; null when closed without a choice.</summary>
private Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row, WorkspaceEntry? unreadableMain = null) =>
AskProjectAsync(workspace, WorkspaceHost.ArchiveHome(row.Id), row.DisplayTitle, unreadableMain);
/// <summary>
/// "Open in workspace" for a sequence of <paramref name="home"/> (this PC's archive, or a server): its projects, the
/// media, and for this PC's archive what their copy writes and the room the workspace's drive has; null when closed
/// without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed
/// disabled, why in its tooltip.
/// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, BundleHome home, string title, WorkspaceEntry? unreadableMain)
{
var projects = await workspace.HomeProjectsAsync(home);
WorkspaceCopyFacts? copy = null;
if (home.IsArchive)
{
try
{
copy = await workspace.CopyFactsAsync(home.SequenceId);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
}
}
var unreadable = unreadableMain is { } main
? new Dictionary<Guid, string>
@@ -712,7 +830,7 @@ public sealed class SequenceViewModel : SectionViewModel
[main.ProjectId] = Loc.L(main.Newer ? "Tooltips.Editor.Workspace.State.NewerCopy" : "Tooltips.Editor.Workspace.State.DamagedCopy"),
}
: null;
var dialog = new OpenInWorkspaceDialogViewModel(row.DisplayTitle, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable);
var dialog = new OpenInWorkspaceDialogViewModel(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive);
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
IsLoading = false;
OpenDialog(dialog);
@@ -888,6 +1006,9 @@ public sealed class SequenceViewModel : SectionViewModel
}
}
/// <summary>What the open of a server sequence as a workspace project came to: its source, or null while it waits (its copy runs, the dialog was closed).</summary>
private sealed record ServerOpen((ISequenceSource Source, string Title)? Opened);
/// <summary>
/// A job an open waits on, with its engine subscription: a server sequence's proxy download, or the workspace copy of a
/// project's media (<see cref="ProjectId"/>: the project that opens when it is done).
+1 -1
View File
@@ -260,7 +260,7 @@
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type srv:SyncRowAction}">
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
AutomationProperties.Name="{Binding AccessibleName}" FontSize="12" Margin="0,2,6,2" />
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding AccessibleName}" FontSize="12" Margin="0,2,6,2" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
+74 -6
View File
@@ -3,9 +3,12 @@ using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.App.Server;
@@ -15,23 +18,28 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
/// <summary>
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
/// connection of upload and download jobs (<see cref="ISyncConnector"/>), a <see cref="SyncAgent"/> that keeps the
/// table current while a session is open, started and stopped in order as the session changes, the
/// <see cref="UploadHold"/> for metered connections, the connections of editors of server sequences
/// (<see cref="ConnectEditor"/>) and the Export "Sync" of finished renders (<see cref="ExportSync"/>). Options come from
/// <see cref="AppSettings.SyncSettingsAutomatically"/>, <see cref="AppSettings.KeepProxiesOffline"/> and
/// <see cref="AppSettings.PauseUploadsOnMetered"/>.
/// connection of upload and download jobs (<see cref="ISyncConnector"/>, also the workspace copies of server projects), a
/// <see cref="SyncAgent"/> that keeps the table current while a session is open, started and stopped in order as the
/// session changes, the <see cref="UploadHold"/> for metered connections, the connections of editors of server sequences
/// (<see cref="ConnectEditor"/>), the server as the home of workspace projects when it keeps projects (owner review 2, R8,
/// phase 5b: <see cref="ProjectHome"/>, <see cref="ProjectChanged"/>) and the Export "Sync" of finished renders
/// (<see cref="ExportSync"/>). Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>,
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>.
/// </summary>
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
{
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
private readonly Lock _gate = new();
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private Running? _running;
private JobEngine? _renders;
/// <summary>The client project homes of the session share, made at first use for the credentials it holds.</summary>
private SharedClient? _projects;
/// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
@@ -40,6 +48,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
new ChronosRemoteSequenceApi(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token });
/// <summary>The client the session's project homes share (<see cref="ProjectHome"/>); tests substitute one of their own.</summary>
public Func<Uri, string, IReadOnlyCollection<string>, ChronosClient> ProjectClientFactory { get; set; } = (address, token, trusted) =>
new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token };
/// <summary>The engine; null until the index is open.</summary>
public SyncService? Service { get; private set; }
@@ -61,6 +73,37 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>The signed-in account may queue renders on the server.</summary>
public bool CanRender => Allows(Permissions.Render);
/// <summary>
/// The signed-in server keeps its sequences' projects (owner review 2, R8: the <c>projects</c> capability), so Edit opens
/// its sequences as workspace projects; false while signed out and for an older server, whose sequences Edit opens with
/// proxies as before.
/// </summary>
public bool HasProjects =>
services.Server.IsConnected && services.Server.Flow.Info?.Capabilities is { } capabilities && capabilities.Contains(ServerCapabilities.Projects);
/// <summary>The home of a workspace project of server sequence <paramref name="remoteId"/>; null while signed out or when the server keeps no projects.</summary>
public BundleHome? ServerHome(Guid remoteId) => Server is { } server && HasProjects ? new BundleHome(BundleHome.ServerKind, remoteId, null, server) : null;
/// <summary>
/// The project home of a workspace project whose home is a server (<see cref="ServerProjectHome"/> over the session's
/// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then
/// shows the project offline and its work waits.
/// </summary>
public IProjectHome? ProjectHome(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials
|| !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
return null;
return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName);
}
/// <summary>
/// A project of a sequence of the signed-in server changed there (the server's key, and its <c>projectChanged</c>), or,
/// with null, changes may have been missed while its events were lost (any thread).
/// </summary>
public event Action<string, ProjectChangedEvent?>? ProjectChanged;
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
public UploadHold Uploads { get; } = new(services);
@@ -146,10 +189,31 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
await _switch.ConfigureAwait(false);
await StopAsync().ConfigureAwait(false);
lock (_gate)
{
_projects?.Client.Dispose();
_projects = null;
}
}
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
/// <summary>
/// The client of <paramref name="credentials"/>' session, made once for its address and token: another sign-in replaces
/// it (a call still on the old one fails as a server out of reach, and is tried again on the new one).
/// </summary>
private ChronosClient SessionClient(Credentials credentials)
{
lock (_gate)
{
if (_projects is { } current && current.Address == credentials.Address && current.Token == credentials.Token) return current.Client;
_projects?.Client.Dispose();
var client = ProjectClientFactory(credentials.Address, credentials.Token, credentials.Fingerprints);
_projects = new SharedClient(credentials.Address, credentials.Token, client);
return client;
}
}
/// <summary>
/// Export "Sync": a render of this PC that asked for it is sent to the server once done (<see cref="ExportSync"/>),
/// also when it ends while the session is down: the send is queued for the saved session's server and waits for it.
@@ -205,6 +269,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
agent.Start();
Volatile.Write(ref _running, new Running(agent, remote, start));
Log.Info("sync", $"Comparing with {remote.Server}");
@@ -221,6 +286,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
/// <summary>The client project homes share, and the session it was made for.</summary>
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
/// <summary>The agent of the signed-in session: one reference, so the UI thread never reads half of a switch.</summary>
private sealed record Running(SyncAgent Agent, ISyncRemote Remote, Credentials Credentials);
}
+27 -6
View File
@@ -8,14 +8,22 @@ using Chronos.Ui.Mvvm;
namespace Chronos.App.Server;
/// <summary>A row button: "Upload", "Keep mine", …; kept while the row offers it, so focus, tooltips and clicks survive updates.</summary>
public sealed class SyncRowAction(SyncAction action, ICommand command) : ObservableObject
public sealed class SyncRowAction : ObservableObject
{
private readonly AsyncRelayCommand _command;
private string _toolTip = string.Empty;
private string _sequence = string.Empty;
private bool _isEnabled = true;
public SyncAction Action { get; } = action;
public SyncRowAction(SyncAction action, Func<Task> execute)
{
Action = action;
_command = new AsyncRelayCommand(execute, () => _isEnabled);
}
public SyncAction Action { get; }
public string Text => Loc.L("Server.Sync.Action." + Action);
public ICommand Command { get; } = command;
public ICommand Command => _command;
public string ToolTip
{
@@ -23,6 +31,16 @@ public sealed class SyncRowAction(SyncAction action, ICommand command) : Observa
set => Set(ref _toolTip, value);
}
/// <summary>The button can be pressed (Open in workspace cannot on a server that keeps no projects; its tooltip says why).</summary>
public bool IsEnabled
{
get => _isEnabled;
set
{
if (Set(ref _isEnabled, value)) _command.RaiseCanExecuteChanged();
}
}
/// <summary>The title of the row's sequence.</summary>
public string Sequence
{
@@ -49,6 +67,7 @@ public sealed class SyncRow : ObservableObject
{
private readonly Func<SyncRow, SyncAction, Task> _act;
private SyncEntry _entry;
private SyncRights _rights;
private IReadOnlyList<SyncRowAction> _actions = [];
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
@@ -103,22 +122,24 @@ public sealed class SyncRow : ObservableObject
foreach (var action in _actions)
{
action.Relabel();
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, _rights);
}
RaiseTexts();
}
private void UpdateActions(SyncRights rights)
{
_rights = rights;
var wanted = SyncText.Actions(_entry, rights);
if (!wanted.SequenceEqual(_actions.Select(a => a.Action)))
{
var kept = _actions.ToDictionary(a => a.Action);
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, new AsyncRelayCommand(() => _act(this, action))))];
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, () => _act(this, action)))];
}
foreach (var action in _actions)
{
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, rights);
action.IsEnabled = SyncText.IsEnabled(action.Action, rights);
action.Sequence = Title;
}
}
+7 -1
View File
@@ -171,7 +171,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
private SyncHost Host => _shell.Services.Sync;
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) with { KeepsProjects = Host.HasProjects } : default;
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
@@ -326,6 +326,12 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
case SyncAction.GetExports:
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
break;
// Edit opens it as a workspace project of the server: the project opened last, else "Open in workspace" asks (phase 5b).
case SyncAction.OpenInWorkspace when Host.HasProjects:
_shell.OpenSequence(entry.Id);
return;
case SyncAction.OpenInWorkspace:
return;
case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
_shell.OpenSequence(entry.Id);
return;
+22 -4
View File
@@ -33,13 +33,20 @@ public enum SyncAction
SendExports,
Pause,
Resume,
/// <summary>
/// Edit a project of the server's sequence in the workspace (owner review 2, R8, phase 5b): offered disabled by a server
/// that keeps no projects, whose sequences open with proxies as before.
/// </summary>
OpenInWorkspace,
}
/// <summary>What the signed-in account may do (server permission bits).</summary>
/// <summary>What the signed-in account may do (server permission bits), and whether its server keeps projects.</summary>
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
/// <param name="CanEdit">Change the server's copy of a sequence's settings, title, tags, rating and notes.</param>
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit)
/// <param name="KeepsProjects">The server keeps its sequences' projects (the <c>projects</c> capability): they open in the workspace.</param>
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit, bool KeepsProjects = false)
{
public static SyncRights Of(long permissions) => new(
(permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0,
@@ -227,9 +234,16 @@ public static class SyncText
case SyncStatus.LocalOnly when rights.CanUpload:
actions.Add(SyncAction.Upload);
break;
// A server that keeps projects edits its sequences in the workspace; an older one's open with proxies, the
// workspace offered disabled with the reason (phase 5b).
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly when rights.KeepsProjects:
actions.Add(SyncAction.OpenInWorkspace);
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
break;
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly:
actions.Add(SyncAction.OpenWithProxies);
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
actions.Add(SyncAction.OpenInWorkspace);
break;
case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }:
if (rights.CanUpload) actions.Add(SyncAction.Upload);
@@ -265,12 +279,16 @@ public static class SyncText
_ => 0,
};
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action) => action switch
/// <summary>Whether a row button can be pressed: all can, but Open in workspace on a server that keeps no projects.</summary>
public static bool IsEnabled(SyncAction action, SyncRights rights) => action != SyncAction.OpenInWorkspace || rights.KeepsProjects;
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves; why not, for one disabled.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action, SyncRights rights = default) => action switch
{
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))),
SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))),
SyncAction.SendExports => Loc.Plural("Tooltips.Server.Sync.SendExports", entry.Link!.ExportsToSend, Formatting.Bytes(Size(entry, action))),
SyncAction.OpenInWorkspace when !rights.KeepsProjects => Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects"),
_ => Loc.L("Tooltips.Server.Sync." + action),
};
+154 -36
View File
@@ -9,6 +9,7 @@ using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
@@ -54,13 +55,19 @@ public interface IWorkspaceUi
/// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a
/// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A
/// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict
/// shown; one an automatic sync met waits for the dialog open to close. Call from the UI thread.
/// shown; one an automatic sync met waits for the dialog open to close. A project whose home is a server (phase 5b) words
/// its texts for the server, follows what the server tells of it (<see cref="WorkspaceHost.HomeChanged"/>: the chip reads
/// Server newer, or that the server no longer has it, its copy kept here), and renders only what the server holds
/// (<see cref="ReadyToRenderAsync"/>). Call from the UI thread.
/// </summary>
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
/// <summary>How long after the last edit the chip reads the working state again (a little after the editor's save).</summary>
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
/// <summary>How long after an analysis ended a change the home tells is taken as its Auto values reaching Main.</summary>
private static readonly TimeSpan AnalysisTake = TimeSpan.FromMinutes(2);
private readonly WorkspaceHost _host;
private readonly WorkspaceSequenceSource _source;
private readonly EditorSession _session;
@@ -82,6 +89,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <summary>The conflict dialog asked in the background, until it is closed (one is asked at a time).</summary>
private ConflictDialogViewModel? _asking;
/// <summary>
/// When an analysis of the sequence ended while Sync automatically is on and the home had not told its new Main yet
/// (a server catches up a moment later): the change it tells next is taken.
/// </summary>
private DateTime? _analysisEnded;
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
{
_host = host;
@@ -99,6 +112,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
host.HomeChanged += OnHomeChanged;
}
public Guid ProjectId => _source.ProjectId;
@@ -107,6 +121,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public bool IsMain => _source.Workspace?.IsMain == true;
/// <summary>The project's home is a server (phase 5b): its texts name the server, its renders are of what the server holds.</summary>
public bool IsServerHome => _source.IsServerHome;
/// <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;
@@ -114,11 +131,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public bool IsSyncing => _isSyncing;
public string StateText => WorkspaceText.State(_status, _isSyncing);
public string StateText => WorkspaceText.State(_status, _isSyncing, IsServerHome);
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing, IsServerHome);
/// <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);
@@ -136,17 +153,25 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <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 string MediaUpdateText => IsUpdatingMedia ? Loc.L("Editor.Workspace.Updating") : WorkspaceText.ForHome("Editor.Workspace.MediaChanged", IsServerHome);
public string MediaChangedToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.MediaChanged", IsServerHome);
public string UpdateMediaToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.UpdateMedia", IsServerHome);
/// <summary>A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project.</summary>
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone };
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
: _status?.State == WorkspaceState.Gone ? Loc.L("Errors.Workspace.DeletedAtHome")
: _status?.State == WorkspaceState.Gone ? WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome)
: _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");
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : WorkspaceText.ForHome("Tooltips.Editor.Project.Delete", IsServerHome);
public string RenameToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.Rename", IsServerHome);
public string RemoveCopyToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.RemoveCopy", IsServerHome);
/// <summary>Save version… (Ctrl+S): the note dialog.</summary>
public ICommand SaveVersionCommand { get; }
@@ -195,6 +220,55 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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);
// A server writes the Auto values into Main a moment after its analysis ends: what it tells next is taken then.
else if (IsServerHome) _analysisEnded = DateTime.UtcNow;
}
/// <summary>
/// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a
/// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here,
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive
/// renders as it is: true.
/// </summary>
public async Task<bool> ReadyToRenderAsync()
{
if (!IsServerHome) return true;
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
Apply(status);
if (status.State is WorkspaceState.Gone or WorkspaceState.Offline or WorkspaceState.Damaged or WorkspaceState.MediaRemoved)
{
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.StateToolTip(status, server: true), isError: status.State != WorkspaceState.Offline);
return false;
}
if (status.Conflict is not null)
{
AskConflict(status.Conflict);
return false;
}
if (status.Ahead == 0 && !status.Modified && _source.InStepWithHome(_session.Project) is not null) return true;
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Workspace.SendFirst.Title"),
Message = Loc.L("Editor.Workspace.SendFirst.Message", Name),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Keep"),
ActionText = Loc.L("Editor.Workspace.SendFirst.Action"),
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Action"),
}))
return false;
try
{
await SaveAndSendAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be sent before its render", ex);
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, server: true), isError: ex is not HomeUnavailableException);
return false;
}
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
}
/// <summary>
@@ -222,7 +296,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
_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.SyncError is { } error)
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
// Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here.
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
else if (result.Status.Conflict is { } conflict) AskConflict(conflict);
@@ -250,8 +325,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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);
_ui.Notify(ex is HomeUnavailableException ? WorkspaceText.ForHome("Editor.Workspace.Offline", IsServerHome) : Loc.L("Editor.Workspace.SyncFailed"),
WorkspaceText.Failure(ex, IsServerHome), isError: ex is not HomeUnavailableException);
await RefreshAsync();
}
finally
@@ -288,7 +363,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (result.Kept is { } kept)
{
if (await _session.TakeOverAsync(kept) is { } step)
_ui.Notify(Loc.L("Editor.Workspace.TookLibrary"), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.UndoTake"), () => step.Undo());
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.TookLibrary", IsServerHome), Name, Loc.L("Editor.Workspace.Undo"),
WorkspaceText.ForHome("Tooltips.Editor.Workspace.UndoTake", IsServerHome), () => step.Undo());
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
else
@@ -307,8 +383,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
() => _ = _ui.OpenProjectAsync(sequenceId, copy.Id));
}
/// <summary>The library no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
private void NotifyGone() => _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome"));
/// <summary>The home no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
private void NotifyGone() =>
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.State.Gone", IsServerHome), WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
/// <summary>
/// Restores <paramref name="version"/> as the project, as one undo step (uncommitted changes are saved as a version
@@ -355,6 +432,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
_disposed = true;
_source.JobChanged -= OnJobChanged;
_session.ProjectChanged -= OnProjectChanged;
_host.HomeChanged -= OnHomeChanged;
// A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time).
if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose();
base.Dispose();
@@ -369,12 +447,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private void OpenSaveVersion()
{
if (!CanSaveVersion) return;
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog));
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog, IsServerHome));
}
private async Task OpenHistoryAsync()
{
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog);
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog, IsServerHome);
_ui.ShowDialog(dialog);
try
{
@@ -389,8 +467,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
}
}
/// <summary>The project's home (this PC's archive, or a server).</summary>
private BundleHome Home => _source.Workspace?.Home ?? WorkspaceHost.ArchiveHome(SequenceId);
/// <summary>
/// Open project…: "Open in workspace" over the library's projects of the sequence but the open one (a Save both
/// Open project…: "Open in workspace" over the home's projects of the sequence but the open one (a Save both
/// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not
/// here yet).
/// </summary>
@@ -399,32 +480,34 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
try
{
await StoreEditAsync();
var projects = (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != ProjectId).ToList();
var home = Home;
var projects = (await _host.HomeProjectsAsync(home)).Where(p => p.Id != ProjectId).ToList();
var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog,
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)]);
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)], server: IsServerHome);
_ui.ShowDialog(dialog);
if (await dialog.Choice is not { } choice || _disposed) return;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(SequenceId, choice.NewName!, _status?.Base?.VersionId)).Id;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(home, choice.NewName!, _status?.Base?.VersionId)).Id;
await _ui.OpenProjectAsync(SequenceId, id);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
private async Task OpenNewProjectAsync()
{
var names = await OtherNamesAsync(null);
var home = Home;
_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);
var created = await _host.CreateProjectAsync(home, name, _status?.Base?.VersionId);
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
}, _ui.CloseDialog));
}, _ui.CloseDialog, IsServerHome));
}
private async Task OpenRenameAsync()
@@ -436,7 +519,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await _session.ReloadAsync();
_ui.Notify(Loc.L("Editor.Workspace.Renamed"), name);
RaiseState();
}, _ui.CloseDialog));
}, _ui.CloseDialog, IsServerHome));
}
private async Task DeleteAsync()
@@ -446,11 +529,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Project.DeleteTitle", name),
Message = Loc.L("Editor.Project.DeleteMessage"),
Message = WorkspaceText.ForHome("Editor.Project.DeleteMessage", IsServerHome),
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"),
ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Project.DeleteAction", IsServerHome),
IsDestructive = true,
}))
return;
@@ -468,7 +551,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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);
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -483,12 +566,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
await SaveAndSendAsync();
await RemoveAsync(projectId, discard: false);
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog));
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog, IsServerHome));
}
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);
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -504,14 +587,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
var result = await _host.SyncAsync(ProjectId);
Apply(result.Status);
await TakeAsync(result);
// Nothing can be sent to a project the library no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
// Nothing can be sent to a project the home no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
if (result.Status.Conflict is { } conflict)
{
AskConflict(conflict);
throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
}
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false })
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
}
private async Task RemoveAsync(Guid projectId, bool discard)
@@ -520,7 +604,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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"));
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false })
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
}
var name = Name;
if (!await _ui.CloseProjectAsync()) return;
@@ -532,7 +617,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
try
{
return [.. (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != except).Select(p => p.Name)];
return [.. (await _host.HomeProjectsAsync(Home)).Where(p => p.Id != except).Select(p => p.Name)];
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -555,7 +640,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -582,9 +667,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private void AskConflict(WorkspaceConflict conflict, bool background = false)
{
if (background && _asking is { IsClosed: false }) return;
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10, IsServerHome);
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
_ui.CloseDialog, conflict.NewerFormat);
_ui.CloseDialog, conflict.NewerFormat, IsServerHome);
if (!background)
{
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
@@ -669,6 +754,34 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
else _ = CopyEndedAsync(job);
}
/// <summary>
/// The home told that this project changed there, or that changes may have been missed (any thread; phase 5b): where it
/// stands is read again on the menu's thread, so the chip says Server newer, or that the server no longer has it.
/// </summary>
private void OnHomeChanged(WorkspaceHomeChange change)
{
if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase)))
return;
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
else _ = HomeChangedAsync(change);
}
private async Task HomeChangedAsync(WorkspaceHomeChange change)
{
if (_disposed || _isSyncing) return;
await RefreshAsync();
// An analysis's Auto values reached Main at the server: with Sync automatically they are taken, as after an analysis here.
if (_disposed || _analysisEnded is not { } ended || change.Change != ProjectChanges.Pushed) return;
if (DateTime.UtcNow - ended > AnalysisTake)
{
_analysisEnded = null;
return;
}
if (_status is not { State: WorkspaceState.Behind } || !_host.Settings.WorkspaceAutoSync) return;
_analysisEnded = null;
await SyncAsync(quiet: true);
}
/// <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)
{
@@ -682,7 +795,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
await RefreshAsync();
RaiseState();
@@ -718,6 +831,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
OnPropertyChanged(nameof(CanSaveVersion));
OnPropertyChanged(nameof(SaveVersionToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
OnPropertyChanged(nameof(IsServerHome));
OnPropertyChanged(nameof(RenameToolTip));
OnPropertyChanged(nameof(RemoveCopyToolTip));
OnPropertyChanged(nameof(MediaChangedToolTip));
OnPropertyChanged(nameof(UpdateMediaToolTip));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
+74 -28
View File
@@ -53,6 +53,7 @@ public static class ProjectNames
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
private readonly TaskCompletionSource<OpenChoice?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly bool _server;
private ProjectOption? _selected;
private bool _isNew;
@@ -61,10 +62,12 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// <param name="unreadable">
/// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen.
/// </param>
/// <param name="server">The sequence's home is a server (phase 5b): the texts name the server.</param>
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null)
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false)
: base(close)
{
_server = server;
SequenceTitle = sequenceTitle;
Copy = copy;
CopyFacts = copy is null ? []
@@ -138,6 +141,12 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public EditableField NewName { get; }
public string ExistingToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Existing", _server);
public string ProjectsToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Projects", _server);
public string ProxiesToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Proxies", _server);
/// <summary>The proxies, the only media this phase copies.</summary>
public bool IsProxies => true;
@@ -176,13 +185,17 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<string, Task> _save;
private readonly bool _server;
/// <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)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close,
bool server = false)
: base(close)
{
IsRename = rename;
_save = save;
_server = server;
var taken = others.ToList();
Name = new EditableField(name, n => ProjectNames.Validate(n, taken), _ => { }, () => Loc.L("Tooltips.Editor.ProjectName.Name"));
Name.PropertyChanged += (_, _) =>
@@ -203,7 +216,7 @@ public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
public ICommand SaveCommand { get; }
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create");
public string SaveToolTip => Name.Error ?? WorkspaceText.ForHome(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create", _server);
private async Task SaveAsync()
{
@@ -217,7 +230,7 @@ public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Naming a project failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
finally
{
@@ -233,13 +246,16 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
public const int MaxNoteLength = 200;
private readonly Func<string?, Task> _save;
private readonly bool _server;
private string _note = string.Empty;
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close, bool server = false)
: base(close)
{
ProjectName = projectName;
_save = save;
_server = server;
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy);
}
@@ -247,6 +263,8 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
public string Heading => Loc.L("Editor.SaveVersion.Title", ProjectName);
public string SaveToolTip => WorkspaceText.ForHome("Tooltips.Editor.SaveVersion.Save", _server);
public string Note
{
get => _note;
@@ -267,7 +285,7 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Saving a version failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
finally
{
@@ -277,10 +295,13 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
}
/// <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 sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore, bool server = false) : ObservableObject
{
public ProjectVersion Version { get; } = version;
/// <summary>"Saved here, waiting to be sent to the library" (the server, for a server's project).</summary>
public string NotSentToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.NotSent", server);
public string Number => Formatting.Count(Version.Number);
public string Author => WorkspaceText.Author(Version);
@@ -317,17 +338,20 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ProjectVersion, Task<IReadOnlyList<string>>> _compare;
private readonly Func<ProjectVersion, Task> _restore;
private readonly bool _server;
private string? _comparedTitle;
private IReadOnlyList<string> _compared = [];
private bool _isLoaded;
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public HistoryDialogViewModel(string projectName, Func<ProjectVersion, Task<IReadOnlyList<string>>> compare, Func<ProjectVersion, Task> restore,
Action<ArchiveDialogViewModel> close)
Action<ArchiveDialogViewModel> close, bool server = false)
: base(close)
{
ProjectName = projectName;
_compare = compare;
_restore = restore;
_server = server;
}
public string ProjectName { get; }
@@ -339,6 +363,11 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
/// <summary>The home could not be asked: only this PC's versions are listed.</summary>
public bool IsOffline { get; private set; }
/// <summary>"Library offline", or "Server offline" for a server's project.</summary>
public string OfflineText => WorkspaceText.ForHome("Editor.History.Offline", _server);
public string OfflineToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.Offline", _server);
public bool IsEmpty => _isLoaded && Rows.Count == 0;
/// <summary>"Version 3 → now" over the comparison; null before one.</summary>
@@ -355,7 +384,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
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)));
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy), _server));
}
IsOffline = history.Offline;
_isLoaded = true;
@@ -369,7 +398,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
ArgumentNullException.ThrowIfNull(ex);
_isLoaded = true;
OnPropertyChanged(nameof(IsEmpty));
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
public async Task CompareAsync(ProjectVersion version)
@@ -385,7 +414,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
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);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
}
@@ -403,7 +432,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
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);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
@@ -418,10 +447,12 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ConflictChoice, Task> _resolve;
private readonly bool _server;
/// <param name="newerFormat">The library holds a newer Chronos's settings: nothing is merged, Save both is the only choice.</param>
/// <param name="server">The project's home is a server (phase 5b): "Take server's", and the texts name the server.</param>
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
Action<ArchiveDialogViewModel> close, bool newerFormat = false)
Action<ArchiveDialogViewModel> close, bool newerFormat = false, bool server = false)
: base(close)
{
ProjectName = projectName;
@@ -430,6 +461,7 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
// The format's number says nothing to the user: the line names the cause.
Differences = newerFormat ? [Loc.L("Editor.Workspace.Conflict.NewerFormat")] : differences;
_resolve = resolve;
_server = server;
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy && CanMerge);
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy && CanMerge);
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
@@ -446,13 +478,13 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
/// <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 Heading => WorkspaceText.ForHome("Editor.Workspace.Conflict.Title", _server);
public string Message => Loc.L(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", ProjectName);
public string Message => WorkspaceText.ForHome(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", _server, ProjectName);
public IReadOnlyList<string> Differences { get; }
public string DifferencesToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences");
public string DifferencesToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences", _server);
public ICommand KeepMineCommand { get; }
@@ -460,7 +492,14 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
public ICommand SaveBothCommand { get; }
public string SaveBothToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", SiblingName);
/// <summary>"Take library's", or "Take server's" for a server's project.</summary>
public string TakeHomeText => WorkspaceText.ForHome("Editor.Workspace.Conflict.TakeHome", _server);
public string TakeHomeToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.TakeHome", _server);
public string KeepMineToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.KeepMine", _server);
public string SaveBothToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", _server, SiblingName);
private async Task ResolveAsync(ConflictChoice choice)
{
@@ -475,7 +514,7 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
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);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
@@ -493,15 +532,19 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
private readonly Func<bool, Task> _remove;
private readonly Func<Task> _sendFirst;
private readonly Func<bool> _confirmDiscard;
private readonly bool _server;
/// <param name="confirmDiscard">The typed confirmation Discard changes asks first (<see cref="ConfirmDiscard"/>); true when the user confirmed.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close,
bool server = false)
: base(close)
{
Plan = plan;
_remove = remove;
_sendFirst = sendFirst;
_confirmDiscard = confirmDiscard;
_server = server;
Facts =
[
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
@@ -532,19 +575,22 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
public ICommand DiscardCommand { get; }
/// <summary>What happens to the copy and the project, worded for the project's home.</summary>
public string Message => WorkspaceText.ForHome("Editor.RemoveCopy.Message", _server);
public string RemoveToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: !Plan.IsSafe ? Loc.L("Errors.Workspace.Unsent")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.Remove");
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
: !Plan.IsSafe ? WorkspaceText.ForHome("Errors.Workspace.Unsent", _server)
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Remove", _server);
public string SendFirstToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
: Plan.Conflict ? Loc.L("Errors.Workspace.Conflict")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.SendFirst", _server);
public string DiscardToolTip => Loc.L("Tooltips.Editor.RemoveCopy.Discard");
public string DiscardToolTip => WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Discard", _server);
/// <summary>
/// The typed confirmation of Discard changes (the plan's cross-cutting rule for what Chronos cannot bring back): the
@@ -614,7 +660,7 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
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);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
+10 -10
View File
@@ -45,9 +45,9 @@
</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" />
ToolTip="{Binding ExistingToolTip}" VerticalAlignment="Center" Margin="0,0,12,0" />
<ComboBox Grid.Column="2" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label" IsEnabled="{Binding HasProjects}"
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Projects}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{Binding ProjectsToolTip}" 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}"
@@ -55,7 +55,7 @@
<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" />
ToolTip="{Binding ProxiesToolTip}" 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>
@@ -127,7 +127,7 @@
</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" />
ToolTip="{Binding SaveToolTip}" 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>
@@ -146,7 +146,7 @@
<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"
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{Binding OfflineText}" ToolTip="{Binding OfflineToolTip}" FontSize="12"
VerticalAlignment="Center" Visibility="{Binding IsOffline, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
</DockPanel>
@@ -171,7 +171,7 @@
<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"
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{Binding NotSentToolTip}" 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}}" />
@@ -214,7 +214,7 @@
</Border>
</DataTemplate>
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's, Save both, or Later (only Save both and Later for a newer Chronos's project). -->
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's (the server's), Save both, or Later (only Save both and Later for a newer Chronos's project). -->
<DataTemplate DataType="{x:Type ws:ConflictDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="560">
<StackPanel>
@@ -234,10 +234,10 @@
MinWidth="96" Margin="0,0,8,8" />
<Button Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}" MinWidth="96" Margin="0,0,8,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Editor.Workspace.Conflict.TakeHome}" Command="{Binding TakeHomeCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.TakeHome}"
<Button Content="{Binding TakeHomeText}" Command="{Binding TakeHomeCommand}" ToolTip="{Binding TakeHomeToolTip}"
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.KeepMine}" Command="{Binding KeepMineCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
ToolTip="{Binding KeepMineToolTip}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<!-- A conflict of format: Save both is the only choice that settles it. -->
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}"
@@ -254,7 +254,7 @@
<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" />
<TextBlock Text="{Binding 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}">
+162 -44
View File
@@ -9,9 +9,11 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
namespace Chronos.App.Workspace;
@@ -51,6 +53,9 @@ public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name
/// <summary>This Chronos reads its working state: it can open.</summary>
public bool IsReadable => !Damaged && !Newer;
/// <summary>The project's home is a server (phase 5b), not this PC's archive.</summary>
public bool IsServerHome => !Home.IsArchive;
}
/// <summary>What changing the workspace folder to <see cref="Folder"/> does: Edit lists its projects from then on; nothing is moved.</summary>
@@ -71,6 +76,13 @@ public sealed record WorkspaceCopyFacts(long Bytes, long? Free)
public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
}
/// <summary>
/// A workspace project's home told that the project changed there (owner review 2, R8, phase 5b: a server's
/// <c>projectChanged</c>): <see cref="Change"/> is one of <c>Protocol.ProjectChanges</c>; null for every project of
/// <see cref="Server"/> when changes may have been missed (its events were lost for a while).
/// </summary>
public sealed record WorkspaceHomeChange(string Server, Guid? ProjectId, string? Change);
/// <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);
@@ -108,12 +120,14 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// <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.
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and the homes of its projects: this PC's
/// archive (<see cref="ArchiveProjectHome"/>) or, from phase 5b, the signed-in server (<see cref="ServerHomes"/>, a
/// <see cref="ServerProjectHome"/>; a project of a server this PC is not signed in to reads as offline, its work waiting
/// here). 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 returned each, a page of its history at a time. A capture (sample data, no
/// engine) has no workspace: Edit opens the library there.
/// </summary>
public sealed class WorkspaceHost
{
@@ -190,17 +204,64 @@ public sealed class WorkspaceHost
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>
/// <summary>
/// The project home of a server home (phase 5b; the desktop's <c>SyncHost.ProjectHome</c>): null while this PC is not
/// signed in to that server, or it keeps no projects. Without it every server home reads as out of reach.
/// </summary>
public Func<BundleHome, IProjectHome?>? ServerHomes { get; set; }
/// <summary>A workspace project's home told that it changed there (any thread): its state is read again.</summary>
public event Action<WorkspaceHomeChange>? HomeChanged;
/// <summary>The home of a workspace project; null for a home this PC cannot reach now (the index not open, a server it is not signed in to).</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;
if (!home.IsArchive) return ServerHomes?.Invoke(home);
return _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 (<paramref name="sequenceId"/> is in its index).</summary>
public static BundleHome ArchiveHome(Guid sequenceId) => new(BundleHome.ArchiveKind, sequenceId);
/// <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"));
public IProjectHome HomeOfSequence(Guid sequenceId) => Reachable(ArchiveHome(sequenceId));
/// <summary>The home <paramref name="home"/> names, which must be reachable now.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open (this PC's archive).</exception>
/// <exception cref="HomeUnavailableException">This PC is not signed in to the server, or it keeps no projects.</exception>
public IProjectHome Reachable(BundleHome home) =>
HomeOf(home) ?? (home.IsArchive
? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"))
: throw new HomeUnavailableException("This PC is not signed in to the server of the project, or it keeps no projects."));
/// <summary>
/// The signed-in server told that a project changed there (phase 5b), or (<paramref name="change"/> null) that changes
/// may have been missed: projects of this workspace whose home it is are told (<see cref="HomeChanged"/>).
/// </summary>
public void OnServerProjectChanged(string server, ProjectChangedEvent? change)
{
ArgumentNullException.ThrowIfNull(server);
if (change is null)
{
HomeChanged?.Invoke(new WorkspaceHomeChange(server, null, null));
return;
}
// The folder is named by the project's id: only a project this workspace holds, of that server and sequence, is told.
try
{
if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } home || home.SequenceId != change.SequenceId
|| !string.Equals(home.Server, server, StringComparison.OrdinalIgnoreCase))
return;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("workspace", $"A change of project {change.ProjectId} on {server} could not be matched: {ex.Message}");
return;
}
HomeChanged?.Invoke(new WorkspaceHomeChange(server, change.ProjectId, change.Change));
}
/// <summary>
/// The projects of the workspace; one whose working state cannot be read is listed as damaged (<see cref="WorkspaceEntry.Damaged"/>),
@@ -307,10 +368,15 @@ public sealed class WorkspaceHost
}
/// <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)
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
HomeProjectsAsync(ArchiveHome(sequenceId), cancellationToken);
/// <summary>The live projects of <paramref name="home"/>'s sequence, Main first (made from the sequence's settings when it has none yet).</summary>
/// <exception cref="HomeUnavailableException">A server home this PC cannot reach now.</exception>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(BundleHome home, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
var reached = Reachable(home);
return Task.Run(() => reached.ListAsync(cancellationToken), cancellationToken);
}
/// <summary>
@@ -321,10 +387,22 @@ public sealed class WorkspaceHost
/// <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>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
public Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default) =>
CheckoutAsync(ArchiveHome(sequenceId), projectId, newName, media, cancellationToken);
/// <summary>
/// Brings a project of <paramref name="home"/>'s sequence (this PC's archive, or the signed-in server) into the workspace
/// and queues the copy of its media, as <see cref="CheckoutAsync(Guid, Guid?, string?, string, CancellationToken)"/>.
/// </summary>
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(BundleHome home, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var reached = Reachable(home);
var sequenceId = home.SequenceId;
var checkout = await Task.Run(async () =>
{
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
@@ -333,11 +411,11 @@ public sealed class WorkspaceHost
SequenceProject project;
if (newName is not null)
{
project = await home.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
project = await reached.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
}
else
{
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
var listed = await reached.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);
@@ -345,9 +423,10 @@ public sealed class WorkspaceHost
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
throw Unreadable(unreadable);
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
var folder = await Sync.CheckoutAsync(reached, 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));
var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
// Back on the caller's thread (the UI's): the settings are written there.
Remember(sequenceId, checkout.Project.Id);
@@ -361,20 +440,24 @@ public sealed class WorkspaceHost
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);
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, bundle.Workspace.Media.Kind, bundle.Sequence.Title ?? string.Empty, 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
/// reads as offline; one that answers it no longer has the project or its sequence (the sequence left the index) reads
/// as <see cref="WorkspaceState.Gone"/>, whose local copy can then only be removed (nothing is removed by itself).
/// (a server this PC is not signed in to among them) reads as offline; one that answers it no longer has the project or
/// its sequence (the sequence left the index, the project was deleted there) reads as <see cref="WorkspaceState.Gone"/>,
/// whose local copy can then only be removed (nothing is removed by itself).
/// </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;
var named = project.ReadBundle().Workspace!.Home;
var home = askHome ? HomeOf(named) : null;
try
{
if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
@@ -392,6 +475,13 @@ public sealed class WorkspaceHost
Conflict = gone ? null : local.Conflict,
};
}
static WorkspaceStatus Offline(WorkspaceStatus local) =>
local with
{
Offline = true,
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Damaged or WorkspaceState.Conflict ? local.State : WorkspaceState.Offline,
};
}, cancellationToken);
/// <summary>
@@ -542,23 +632,30 @@ public sealed class WorkspaceHost
/// <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)
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default) =>
CreateProjectAsync(ArchiveHome(sequenceId), name, fromVersionId, cancellationToken);
/// <summary>A new project of <paramref name="home"/>'s sequence named <paramref name="name"/> from <paramref name="fromVersionId"/>, else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
public Task<SequenceProject> CreateProjectAsync(BundleHome home, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var reached = Reachable(home);
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}");
var created = await reached.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {home.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>
/// <exception cref="HomeUnavailableException">The home cannot be reached now: the name stays.</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);
var renamed = await HomeOfProject(projectId).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var bundle = project.ReadBundle();
@@ -592,8 +689,8 @@ public sealed class WorkspaceHost
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(workspace.Home));
await home.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
try
{
@@ -624,7 +721,7 @@ public sealed class WorkspaceHost
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(Existing(projectId).ReadBundle().Workspace!.Home));
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
@@ -682,7 +779,7 @@ public sealed class WorkspaceHost
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
throw new WorkspaceException(Unsent(workspace.Home));
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
@@ -742,7 +839,8 @@ public sealed class WorkspaceHost
/// <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"));
var server = !workspace.Home.IsArchive;
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server));
ProjectVersion head;
ProjectVersion? basis;
bool held;
@@ -761,13 +859,16 @@ public sealed class WorkspaceHost
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server), ex);
}
if (!held || !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"));
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.HomeCheck", server));
}
/// <summary>"Some work is not in the library (on the server) yet": worded for the project's home.</summary>
private static string Unsent(BundleHome home) => WorkspaceText.ForHome("Errors.Workspace.Unsent", !home.IsArchive);
/// <summary>
/// The project's folder taken out of the workspace under its lease: every file and folder in it but the media and the
/// lease (the working state, the versions, the sync state, the exports, and whatever else a Chronos keeps there) moved
@@ -889,25 +990,42 @@ public sealed class WorkspaceHost
_savePreferences();
}
private async Task<Job> QueueCopyCoreAsync(Guid sequenceId, Guid projectId, string media, CancellationToken cancellationToken)
/// <summary>
/// The copy of a project's media from its home, unless one is waiting or running: a sequence of this PC's archive copied
/// from there, a server's downloaded from it (<paramref name="title"/> labels that job: the index has no row for it).
/// </summary>
private async Task<Job> QueueCopyCoreAsync(BundleHome home, Guid projectId, string media, string title, 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);
ArchiveJobRequest request;
if (home.IsArchive)
{
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index.");
request = WorkspaceJobs.Copy(sequence, Store.Root, projectId, media);
}
else
{
request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."), Store.Root,
projectId, media);
}
var job = await engine.EnqueueAsync(request, 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"));
/// <exception cref="HomeUnavailableException">The project's home cannot be reached now.</exception>
private IProjectHome HomeOfProject(Guid projectId)
{
var home = Existing(projectId).ReadBundle().Workspace!.Home;
return HomeOf(home) ?? throw new HomeUnavailableException(home.IsArchive
? "The project's home cannot be reached from this PC."
: "This PC is not signed in to the server of the project, or it keeps no projects.");
}
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
@@ -7,9 +7,10 @@ using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
/// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed
/// as damaged, one a newer Chronos wrote as such, by the name each is still known by.
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail; a server's
/// as the Library lists it, phase 5b) and where it stands, a chip read from its home after the list shows and again when
/// the home tells it changed. A copy whose working state cannot be read is listed as damaged, one a newer Chronos wrote
/// as such, by the name each is still known by.
/// </summary>
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
{
@@ -53,7 +54,7 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
public string StateText => Entry.Newer ? Loc.L("Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status, server: Entry.IsServerHome) : Loc.L("Editor.Workspace.State.MediaRemoved");
public StatusKind StateKind => Entry.Newer ? StatusKind.Warning
: Entry.Damaged ? StatusKind.Error
@@ -61,7 +62,7 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
public string StateToolTip => Entry.Newer ? Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status, server: Entry.IsServerHome) : 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);
+52 -19
View File
@@ -1,27 +1,53 @@
using System.IO;
using System.Net;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Shell;
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.Protocol.Client;
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>
/// <summary>
/// How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free. A text that
/// names the project's home has a form for each: "the library" (this PC's archive) and, with <c>server</c>, "the server"
/// (phase 5b: its key with <see cref="ServerSuffix"/>).
/// </summary>
public static class WorkspaceText
{
/// <summary>The suffix of a text's key in its form for a project whose home is a server.</summary>
public const string ServerSuffix = ".Server";
/// <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);
/// <summary>
/// The text of <paramref name="key"/> worded for the project's home: its server form (<see cref="ServerSuffix"/>) when
/// <paramref name="server"/>, the key itself for a text that names no home.
/// </summary>
public static string ForHome(string key, bool server, params object?[] args)
{
ArgumentNullException.ThrowIfNull(key);
var worded = server && Loc.Get(key + ServerSuffix, Loc.Culture) is not null ? key + ServerSuffix : key;
return args.Length == 0 ? Loc.L(worded) : Loc.L(worded, args);
}
/// <summary>
/// The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs; worded for a server's project where
/// the state names the home ("Server newer", "Not on server").
/// </summary>
public static string State(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Editor.Workspace.State.Reading")
: ForHome("Editor.Workspace.State." + status.State, server);
public static StatusKind Kind(WorkspaceStatus? status, bool syncing = false) => syncing ? StatusKind.Running : status?.State switch
{
@@ -36,15 +62,16 @@ public static class WorkspaceText
_ => 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")
/// <summary>What the state means and what to do, with the counts behind it, worded for the project's home.</summary>
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? ForHome("Tooltips.Editor.Workspace.State.Syncing", server)
: status is null ? ForHome("Tooltips.Editor.Workspace.State.Reading", server)
: 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),
WorkspaceState.Ahead => ForHome("Tooltips.Editor.Workspace.State.Ahead", server, Formatting.Count(status.Ahead)),
WorkspaceState.Behind => ForHome("Tooltips.Editor.Workspace.State.Behind", server, Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => ForHome("Tooltips.Editor.Workspace.State.OfflineAhead", server, Formatting.Count(status.Ahead)),
var state => ForHome("Tooltips.Editor.Workspace.State." + state, server),
};
/// <summary>"Saved", "Merged", "Restored", "Imported", "Outside change".</summary>
@@ -76,34 +103,40 @@ public static class WorkspaceText
/// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most <paramref name="max"/>.
/// A conflict of format (<see cref="ProjectMerge.FormatPath"/>) reads as its cause, never as the format's numbers.
/// </summary>
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max)
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max, bool server = false)
{
ArgumentNullException.ThrowIfNull(differences);
var list = differences.ToList();
if (list.Any(d => d.Path == ProjectMerge.FormatPath)) return [Loc.L("Editor.Workspace.Conflict.NewerFormat")];
return SyncText.Differences(list, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
return SyncText.Differences(list, max, (label, mine, theirs) => ForHome("Editor.Workspace.Difference", server, 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
/// <summary>
/// Why a workspace operation stopped, as one localized sentence chosen by cause and worded for the project's home; the
/// exception's own text goes to the log.
/// </summary>
public static string Failure(Exception ex, bool server = false) => ex switch
{
WorkspaceException or LeaseUnavailableException => ex.Message,
// A library that can be read but not written (a read-only share, a write-protected disk): the work waits here as offline.
HomeUnavailableException { InnerException: ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } }
or ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } => Loc.L("Errors.Workspace.ReadOnlyHome"),
HomeUnavailableException or ArchiveOfflineException => Loc.L("Errors.Workspace.Offline"),
HomeUnavailableException or ArchiveOfflineException => ForHome("Errors.Workspace.Offline", server),
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"),
ProjectException => ForHome("Errors.Workspace.ProjectGone", server),
// A version over the size one may be: saved here (refused before anything was written) or sent (the home stored nothing).
ProjectVersionTooLargeException or WorkspaceSyncException { Outcome: PushOutcome.TooLarge } =>
Loc.L("Errors.Workspace.VersionTooLarge", ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
ForHome("Errors.Workspace.VersionTooLarge", server, ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => ForHome("Errors.Workspace.Refused", server),
// A server's refusal that keeps its meaning: an account that may not change projects there, above all.
ChronosApiException { Status: HttpStatusCode.Forbidden } => Loc.L("Errors.Workspace.Forbidden"),
ChronosApiException api => ErrorText.ForServer(api),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
_ => ArchiveFailures.Cause(ex),