feat: owner review 2 phase 5b: the server as a project home (#17)
CI / Build and test (push) Successful in 9m58s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 14m8s
CI / PostgreSQL 16 integration (push) Successful in 8m55s
CI / PostgreSQL 17 integration (push) Successful in 8m50s
CI / Docker image (push) Successful in 57s
Release / Server image (push) Successful in 1m22s

A Chronos Server keeps its sequences' projects, as a PC's archive does: Main and named projects with versions under /api/v1/sequences/{id}/projects, the projects capability and the projectChanged event. The desktop opens a server's sequences in the workspace (proxies downloaded, hash-checked, resumable) with Save version, Sync, conflicts, History, Restore and the project actions against the server. Renders can be of a project version. The admin panel lists a sequence's projects and versions. Strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #17.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 14:58:11 +01:00
1 parent 255e149087
commit 81c303f484
325 files changed
+11477 -516

No files matched your search

+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}">
+185 -45
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,85 @@ 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.
BundleHome home;
try
{
if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
|| !string.Equals(held.Server, server, StringComparison.OrdinalIgnoreCase))
return;
home = held;
}
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;
}
if (change.Change != ProjectChanges.Renamed)
{
HomeChanged?.Invoke(new WorkspaceHomeChange(server, change.ProjectId, change.Change));
return;
}
// A rename at the server is written to the copy here before it is told, so the state read again shows the new name.
_ = FollowNameThenTellAsync(server, home, change);
}
private async Task FollowNameThenTellAsync(string server, BundleHome home, ProjectChangedEvent change)
{
try
{
if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} could not be followed: {ex.Message}");
}
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 +389,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 +408,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,21 +432,23 @@ 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);
// A server's sequence with no photo yet has no projects at all.
: listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet.");
}
// 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 +462,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 +497,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 +654,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 +711,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 +743,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 +801,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 +861,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 +881,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 +1012,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),