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

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

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

No files matched your search

@@ -0,0 +1,724 @@
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project.</summary>
public interface IWorkspaceUi
{
/// <summary>The dialog open now; null when none is.</summary>
ArchiveDialogViewModel? Dialog { get; }
/// <summary>Shows <paramref name="dialog"/> now, in place of an open one (the dialog the user acted in leads to it).</summary>
void ShowDialog(ArchiveDialogViewModel dialog);
/// <summary>
/// Shows <paramref name="dialog"/> now when no dialog is open, else once the open one closes: something found in the
/// background (a conflict an automatic sync met) never replaces what the user is doing.
/// </summary>
void ShowDialogWhenFree(ArchiveDialogViewModel dialog);
void CloseDialog(ArchiveDialogViewModel dialog);
/// <summary>True when the user chose the action (a destructive confirmation).</summary>
bool Confirm(ConfirmRequest request);
void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false);
/// <summary>Opens project <paramref name="projectId"/> of <paramref name="sequenceId"/> in the editor (checked out and copied first when it is not here).</summary>
Task OpenProjectAsync(Guid sequenceId, Guid projectId);
/// <summary>Closes the open project (its last edit stored first); the picker shows. False when the user kept it open.</summary>
Task<bool> CloseProjectAsync();
/// <summary>The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again.</summary>
Task SequenceChangedAsync(Guid sequenceId);
}
/// <summary>
/// The project menu of the editor's title (▾, owner review 2, R8) for a workspace project: where it stands (the chip, read
/// again a moment after each edit), Save version (Ctrl+S, an optional note; sent at once with Settings › Workspace › Sync
/// automatically), Sync, History (Compare, Restore as one undo step), Open project (another project of the sequence, at
/// the library or here), New project, Rename, Delete project (never Main) and Remove local copy, and the "Update media"
/// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a
/// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A
/// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict
/// shown; one an automatic sync met waits for the dialog open to close. Call from the UI thread.
/// </summary>
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
/// <summary>How long after the last edit the chip reads the working state again (a little after the editor's save).</summary>
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
private readonly WorkspaceHost _host;
private readonly WorkspaceSequenceSource _source;
private readonly EditorSession _session;
private readonly IWorkspaceUi _ui;
private readonly AsyncRelayCommand _sync;
private readonly AsyncRelayCommand _updateMedia;
/// <summary>The thread the menu was made on (the UI's); null where there is none (tests run inline).</summary>
private readonly SynchronizationContext? _context = SynchronizationContext.Current;
private WorkspaceStatus? _status;
private bool _isSyncing;
private bool _homeFramesChanged;
private Guid _copyJob;
private bool _disposed;
/// <summary>Counts the editor's changes, so only the last one's state read applies.</summary>
private int _changes;
/// <summary>The conflict dialog asked in the background, until it is closed (one is asked at a time).</summary>
private ConflictDialogViewModel? _asking;
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
{
_host = host;
_source = source;
_session = session;
_ui = ui;
_sync = new AsyncRelayCommand(() => SyncAsync(), () => !_isSyncing);
_updateMedia = new AsyncRelayCommand(UpdateMediaAsync, () => _copyJob == Guid.Empty);
SaveVersionCommand = new RelayCommand(OpenSaveVersion, () => CanSaveVersion);
HistoryCommand = new AsyncRelayCommand(OpenHistoryAsync);
OpenProjectCommand = new AsyncRelayCommand(OpenOtherProjectAsync);
NewProjectCommand = new AsyncRelayCommand(OpenNewProjectAsync);
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
}
public Guid ProjectId => _source.ProjectId;
public Guid SequenceId => _session.Content.Sequence.Id;
public bool IsMain => _source.Workspace?.IsMain == true;
/// <summary>The project's name (Main in the UI language).</summary>
public string Name => _source.Workspace is { } workspace ? WorkspaceText.ProjectName(workspace.Name, workspace.IsMain) : string.Empty;
public WorkspaceStatus? Status => _status;
public bool IsSyncing => _isSyncing;
public string StateText => WorkspaceText.State(_status, _isSyncing);
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing);
/// <summary>The ▾ button: its name, then where the project stands, then what the menu holds.</summary>
public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText);
/// <summary>The button's accessible name: the project and its state.</summary>
public string MenuName => string.Join(Loc.Separator, Name, StateText);
/// <summary>
/// The home's frames moved past those the workspace holds, or the library names photos otherwise since the copy (hashed,
/// converted) and the media could not learn it yet (the last read of the library says so; a later one that taught them
/// clears it): the banner offers Update media.
/// </summary>
public bool HasMediaUpdate => _homeFramesChanged || _status is { MediaOutdated: true };
/// <summary>A copy of the media runs (Update media): the banner says so.</summary>
public bool IsUpdatingMedia => _copyJob != Guid.Empty;
public string MediaUpdateText => Loc.L(IsUpdatingMedia ? "Editor.Workspace.Updating" : "Editor.Workspace.MediaChanged");
/// <summary>A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project.</summary>
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone };
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
: _status?.State == WorkspaceState.Gone ? Loc.L("Errors.Workspace.DeletedAtHome")
: _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict")
: Loc.L("Tooltips.Editor.Project.SaveVersion");
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : Loc.L("Tooltips.Editor.Project.Delete");
/// <summary>Save version… (Ctrl+S): the note dialog.</summary>
public ICommand SaveVersionCommand { get; }
public ICommand SyncCommand => _sync;
public ICommand HistoryCommand { get; }
/// <summary>Open project…: another project of the sequence, one of the library's (a Save both sibling, another PC's) or a new one.</summary>
public ICommand OpenProjectCommand { get; }
public ICommand NewProjectCommand { get; }
public ICommand RenameCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand RemoveCopyCommand { get; }
public ICommand UpdateMediaCommand => _updateMedia;
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
public async Task RefreshAsync()
{
try
{
var status = await _host.StatusAsync(ProjectId);
var moved = await _source.HomeFramesChangedAsync(CancellationToken.None);
if (_disposed) return;
_homeFramesChanged = moved;
Apply(status);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The state of project {ProjectId} could not be read", ex);
}
}
/// <summary>
/// A job of the sequence ended: where the project stands is read again; after an analysis, which writes its Auto
/// values into the library's settings (Main's), the project takes them at once with Sync automatically.
/// </summary>
public async Task JobEndedAsync(Job job)
{
ArgumentNullException.ThrowIfNull(job);
await RefreshAsync();
if (_disposed || !_host.Settings.WorkspaceAutoSync || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse)) return;
if (_status is { State: WorkspaceState.Behind }) await SyncAsync(quiet: true);
}
/// <summary>
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about.
/// </summary>
/// <exception cref="WorkspaceException">Why no version could be saved (the edit could not be stored, a conflict, read-only).</exception>
public async Task SaveVersionAsync(string? note)
{
await StoreEditAsync();
var result = await _host.SaveVersionAsync(ProjectId, note);
if (_disposed) return;
Apply(result.Status);
if (result.Synced is { } taken) await TakeAsync(taken);
if (result.Version is null)
{
_ui.Notify(Loc.L("Editor.Workspace.NothingNew"), Name);
}
else if (result.Synced is { Pushed.Count: > 0 } synced)
{
// The home numbers what it stores: the last one sent is this version.
_ui.Notify(Loc.L("Editor.Workspace.SavedSent", Formatting.Count(synced.Pushed[^1].Number)), Name);
}
else
{
_ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name);
}
if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error), isError: error is not HomeUnavailableException);
// Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here.
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
else if (result.Status.Conflict is { } conflict) AskConflict(conflict);
}
/// <summary>
/// Sync: the home's new versions taken into the editor, the local ones sent; a conflict is asked about (once the open
/// dialog closes when <paramref name="quiet"/>: the sync ran in the background).
/// </summary>
public async Task SyncAsync(bool quiet = false)
{
if (_isSyncing) return;
SetSyncing(true);
try
{
await StoreEditAsync();
var result = await _host.SyncAsync(ProjectId);
if (_disposed) return;
Apply(result.Status);
await TakeAsync(result);
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
else if (result.Status.Conflict is { } conflict) AskConflict(conflict, background: quiet);
else if (!quiet) _ui.Notify(Loc.L(result.Status.State == WorkspaceState.InSync ? "Editor.Workspace.InSync" : "Editor.Workspace.Synced"), Name);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be synced", ex);
_ui.Notify(Loc.L(ex is HomeUnavailableException ? "Editor.Workspace.Offline" : "Editor.Workspace.SyncFailed"), WorkspaceText.Failure(ex),
isError: ex is not HomeUnavailableException);
await RefreshAsync();
}
finally
{
SetSyncing(false);
}
}
/// <summary>
/// Settles the conflict <paramref name="shown"/> listed (else the one recorded) as chosen, then brings the settled
/// working state into the editor: the library's values taken as one undo step (the toast's Undo, Ctrl+Z), what Save
/// both made offered by its toast. When what differs changed since it was shown, nothing is settled and it is asked again.
/// A project deleted in the library meanwhile is said so once, nothing asked again: its work stays here (the copy Save
/// both made holding it too, offered by its toast).
/// </summary>
public async Task ResolveAsync(ConflictChoice choice, WorkspaceConflict? shown = null)
{
await StoreEditAsync();
var result = await _host.ResolveAsync(ProjectId, choice, shown: shown);
if (_disposed) return;
Apply(result.Status);
if (result.Status.State == WorkspaceState.Gone)
{
NotifyGone();
NotifySavedAs(result);
return;
}
if (result.Status.Conflict is { } again)
{
await TakeAsync(result);
AskConflict(again);
return;
}
if (result.Kept is { } kept)
{
if (await _session.TakeOverAsync(kept) is { } step)
_ui.Notify(Loc.L("Editor.Workspace.TookLibrary"), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.UndoTake"), () => step.Undo());
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
else
{
await TakeAsync(result, force: true);
}
NotifySavedAs(result);
}
/// <summary>The project Save both made, offered by its toast.</summary>
private void NotifySavedAs(WorkspaceSyncResult result)
{
if (result.SavedAs is not { } copy) return;
var sequenceId = SequenceId;
_ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name, Loc.L("Editor.Workspace.OpenCopy"), Loc.L("Tooltips.Editor.Workspace.OpenCopy", copy.Name),
() => _ = _ui.OpenProjectAsync(sequenceId, copy.Id));
}
/// <summary>The library no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
private void NotifyGone() => _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome"));
/// <summary>
/// Restores <paramref name="version"/> as the project, as one undo step (uncommitted changes are saved as a version
/// first, so nothing is lost); the toast's Undo takes it back while it is the last change.
/// </summary>
public async Task RestoreAsync(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
await StoreEditAsync();
var restored = await _host.RestoreAsync(ProjectId, version.Id);
if (_disposed) return;
var before = _session.Project;
if (_session.Edit(_ => restored))
{
_session.EndEditRun();
var undo = new ProjectRestore(_session, before, _session.Project);
_ui.Notify(Loc.L("Editor.Workspace.Restored", Formatting.Count(version.Number)), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.Undo"),
() => undo.Undo());
}
else
{
_ui.Notify(Loc.L("Editor.Copy.Same"), Name);
}
await RefreshAsync();
}
/// <summary>
/// The settings that differ between the project now and <paramref name="version"/>, the version placed on the media's
/// frames first: exclusions, the hero and keyframes compare as the settings they are (a photo the media lack stays
/// parked, and reads as such).
/// </summary>
public IReadOnlyList<string> Compare(ProjectVersion version, int max = 12)
{
ArgumentNullException.ThrowIfNull(version);
var photos = _source.Photos;
if (_session.Project.IsNewerFormat || ProjectContent.FormatOf(version.SettingsJson) > ProjectSettings.CurrentVersion)
return WorkspaceText.CompareLines(SyncRules.Differences(ProjectContent.ToPortable(_session.Project, photos), version.SettingsJson, 64), max);
var then = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Rebind(version.SettingsJson, photos), photos), allowNewer: true);
return WorkspaceText.CompareLines(SyncRules.Differences(_session.Project.ToJson(), then.ToJson(), 64), max);
}
public override void Dispose()
{
_disposed = true;
_source.JobChanged -= OnJobChanged;
_session.ProjectChanged -= OnProjectChanged;
// A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time).
if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose();
base.Dispose();
}
protected override void OnLanguageChanged()
{
base.OnLanguageChanged();
RaiseState();
}
private void OpenSaveVersion()
{
if (!CanSaveVersion) return;
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog));
}
private async Task OpenHistoryAsync()
{
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog);
_ui.ShowDialog(dialog);
try
{
await StoreEditAsync();
var history = await _host.HistoryAsync(ProjectId, Math.Max(50, _host.Settings.WorkspaceKeptVersions));
dialog.Show(history, ProjectContent.Hash(ProjectContent.ToPortable(_session.Project, _source.Photos)));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The history of project {ProjectId} could not be read", ex);
dialog.ShowFailure(ex);
}
}
/// <summary>
/// Open project…: "Open in workspace" over the library's projects of the sequence but the open one (a Save both
/// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not
/// here yet).
/// </summary>
private async Task OpenOtherProjectAsync()
{
try
{
await StoreEditAsync();
var projects = (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != ProjectId).ToList();
var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog,
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)]);
_ui.ShowDialog(dialog);
if (await dialog.Choice is not { } choice || _disposed) return;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(SequenceId, choice.NewName!, _status?.Base?.VersionId)).Id;
await _ui.OpenProjectAsync(SequenceId, id);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
private async Task OpenNewProjectAsync()
{
var names = await OtherNamesAsync(null);
_ui.ShowDialog(new ProjectNameDialogViewModel(false, string.Empty, names, async name =>
{
await StoreEditAsync();
// From the open project's last version at the home, so the new one starts where this one is there.
var created = await _host.CreateProjectAsync(SequenceId, name, _status?.Base?.VersionId);
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
}, _ui.CloseDialog));
}
private async Task OpenRenameAsync()
{
var names = await OtherNamesAsync(ProjectId);
_ui.ShowDialog(new ProjectNameDialogViewModel(true, _source.Workspace?.Name ?? string.Empty, names, async name =>
{
await _host.RenameAsync(ProjectId, name);
await _session.ReloadAsync();
_ui.Notify(Loc.L("Editor.Workspace.Renamed"), name);
RaiseState();
}, _ui.CloseDialog));
}
private async Task DeleteAsync()
{
if (IsMain) return;
var name = Name;
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Project.DeleteTitle", name),
Message = Loc.L("Editor.Project.DeleteMessage"),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"),
ActionText = Loc.L("Editor.Project.DeleteAction"),
ActionToolTip = Loc.L("Tooltips.Editor.Project.DeleteAction"),
IsDestructive = true,
}))
return;
try
{
// Everything sent first, while the project is still open: a delete that cannot happen leaves it as it was.
await SaveAndSendAsync();
var (sequenceId, projectId) = (SequenceId, ProjectId);
if (!await _ui.CloseProjectAsync()) return;
// The library's delete stands even when the local copy could not go with it: it is said, and Remove local copy takes it later.
if (await _host.DeleteProjectAsync(projectId)) _ui.Notify(Loc.L("Editor.Workspace.Deleted", name));
else _ui.Notify(Loc.L("Editor.Workspace.Deleted", name), Loc.L("Errors.Workspace.CopyKept"), isError: true);
await _ui.SequenceChangedAsync(sequenceId);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} was not deleted", ex);
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
private async Task OpenRemoveCopyAsync()
{
try
{
await StoreEditAsync();
var plan = await _host.PlanRemovalAsync(ProjectId);
var (projectId, name) = (ProjectId, Name);
_ui.ShowDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveAsync(projectId, discard), async () =>
{
await SaveAndSendAsync();
await RemoveAsync(projectId, discard: false);
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The removal of project {ProjectId} could not be planned", ex);
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
/// <summary>
/// The working state saved as a version and everything sent, for Send first and Delete project. A conflict the sync
/// meets is asked about at once (in place of the dialog that asked for it), never left behind a reason to discard.
/// </summary>
/// <exception cref="WorkspaceException">Something could not be sent: a conflict to settle first, or the work not in the library yet.</exception>
private async Task SaveAndSendAsync()
{
await StoreEditAsync();
if (CanSaveVersion) await _host.CommitAsync(ProjectId);
var result = await _host.SyncAsync(ProjectId);
Apply(result.Status);
await TakeAsync(result);
// Nothing can be sent to a project the library no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (result.Status.Conflict is { } conflict)
{
AskConflict(conflict);
throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
}
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
private async Task RemoveAsync(Guid projectId, bool discard)
{
// Checked before the editor closes, so a copy that cannot go leaves it open.
if (!discard)
{
var status = await _host.StatusAsync(projectId, askHome: false);
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
var name = Name;
if (!await _ui.CloseProjectAsync()) return;
await _host.RemoveLocalCopyAsync(projectId, discard);
_ui.Notify(Loc.L("Editor.Workspace.Removed"), name);
}
private async Task<IReadOnlyList<string>> OtherNamesAsync(Guid? except)
{
try
{
return [.. (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != except).Select(p => p.Name)];
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The home checks the name again when the project is made.
Log.Info("workspace", $"The projects of sequence {SequenceId} could not be listed: {ex.Message}");
return [];
}
}
private async Task UpdateMediaAsync()
{
try
{
await StoreEditAsync();
var job = await _host.QueueCopyAsync(ProjectId);
_copyJob = job.Id;
RaiseState();
_ui.Notify(Loc.L("Editor.Workspace.Copying"), _session.Content.Sequence.DisplayTitle);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The media of project {ProjectId} could not be copied again", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
/// <summary>The editor's last edit stored in the working state before an operation reads it.</summary>
/// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception>
private async Task StoreEditAsync()
{
if (await _session.FlushAsync()) return;
throw new WorkspaceException(Loc.L("Errors.Workspace.EditNotStored"), _session.LastSaveError);
}
/// <summary>What a sync, resolve or restore took from the home comes into the editor, merged with what was edited meanwhile.</summary>
private async Task TakeAsync(WorkspaceSyncResult result, bool force = false)
{
if (force || result.Pulled.Count > 0) await _session.ReloadAsync();
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
/// <summary>
/// Asks how to settle <paramref name="conflict"/>, the choice applying to it as listed. One a sync met in the
/// <paramref name="background"/> (after an analysis) waits for the open dialog to close, and is asked once: the chip
/// says Conflict meanwhile, and Sync asks again.
/// </summary>
private void AskConflict(WorkspaceConflict conflict, bool background = false)
{
if (background && _asking is { IsClosed: false }) return;
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
_ui.CloseDialog, conflict.NewerFormat);
if (!background)
{
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
_asking?.Dispose();
_asking = null;
_ui.ShowDialog(dialog);
return;
}
_asking = dialog;
_ui.ShowDialogWhenFree(dialog);
}
/// <summary>The editor's project changed (an edit, undo, a merge; the UI thread): the chip reads the working state again a moment later.</summary>
private void OnProjectChanged()
{
if (_disposed) return;
_ = RefreshLocalAsync(++_changes);
}
/// <summary>
/// After the last change's save: where the working state stands now (changed, saved as versions), the library's facts
/// (newer, out of reach) kept from the last time it was asked; no read of the home on every edit.
/// </summary>
private async Task RefreshLocalAsync(int change)
{
try
{
// The save follows the change after a moment (and is retried after a failure): read once it is stored.
for (var wait = 0; wait == 0 || (_session.HasPendingSave && wait < 10); wait++)
{
await Task.Delay(StateRefreshDelay);
if (_disposed || change != _changes) return;
}
if (_isSyncing || _session.HasPendingSave) return;
var local = await _host.StatusAsync(ProjectId, askHome: false);
if (_disposed || change != _changes || _isSyncing) return;
Apply(WithLocal(_status, local));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Debug("workspace", $"The state of project {ProjectId} could not be read after an edit: {ex.Message}");
}
}
/// <summary>
/// The state read without the home (<paramref name="local"/>) with what the last read of the home said (how far the
/// library is ahead, whether it could be reached, whether it still has the project), in the order the sync ranks them.
/// </summary>
internal static WorkspaceStatus WithLocal(WorkspaceStatus? last, WorkspaceStatus local)
{
ArgumentNullException.ThrowIfNull(local);
if (last is null) return local;
var gone = last.State == WorkspaceState.Gone;
// A base that moved since (a sync) leaves how far the library is ahead unknown until it is asked again.
var behind = last.Base?.VersionId == local.Base?.VersionId ? last.Behind : 0;
// A project the library no longer has holds no conflict to answer (the one recorded stays for the record).
var status = local with
{
Behind = behind,
Offline = last.Offline,
HomeHead = last.HomeHead,
MediaOutdated = last.MediaOutdated,
Conflict = gone ? null : local.Conflict,
};
var state = gone ? WorkspaceState.Gone
: status.MediaRemoved ? WorkspaceState.MediaRemoved
: status.Damaged > 0 ? WorkspaceState.Damaged
: status.Conflict is not null ? WorkspaceState.Conflict
: status.Offline ? WorkspaceState.Offline
: status.Behind > 0 ? WorkspaceState.Behind
: status.Ahead > 0 ? WorkspaceState.Ahead
: status.Modified ? WorkspaceState.Modified
: WorkspaceState.InSync;
return status with { State = state };
}
/// <summary>A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread.</summary>
private void OnJobChanged(Job job)
{
if (job.Id != _copyJob || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
if (_context is { } context) context.Post(_ => _ = CopyEndedAsync(job), null);
else _ = CopyEndedAsync(job);
}
/// <summary>The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not.</summary>
private async Task CopyEndedAsync(Job job)
{
if (_disposed || job.Id != _copyJob) return;
_copyJob = Guid.Empty;
if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true);
try
{
if (job.State == JobState.Done) await _session.ReloadAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The new media of project {ProjectId} could not be read", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
}
await RefreshAsync();
RaiseState();
}
private void Apply(WorkspaceStatus status)
{
_status = status;
RaiseState();
}
private void SetSyncing(bool syncing)
{
_isSyncing = syncing;
_sync.RaiseCanExecuteChanged();
RaiseState();
}
private void RaiseState()
{
OnPropertyChanged(nameof(Status));
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(IsMain));
OnPropertyChanged(nameof(IsSyncing));
OnPropertyChanged(nameof(StateText));
OnPropertyChanged(nameof(StateKind));
OnPropertyChanged(nameof(StateToolTip));
OnPropertyChanged(nameof(MenuToolTip));
OnPropertyChanged(nameof(MenuName));
OnPropertyChanged(nameof(HasMediaUpdate));
OnPropertyChanged(nameof(IsUpdatingMedia));
OnPropertyChanged(nameof(MediaUpdateText));
OnPropertyChanged(nameof(CanSaveVersion));
OnPropertyChanged(nameof(SaveVersionToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
}
@@ -0,0 +1,621 @@
using System.Collections.ObjectModel;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>What "Open in workspace" chose: an existing project of the home (<see cref="ProjectId"/>) or a new one (<see cref="NewName"/>), and the media.</summary>
public sealed record OpenChoice(Guid? ProjectId, string? NewName, string Media);
/// <summary>
/// A project of the home offered by "Open in workspace" (Main in the UI language). One whose copy here this Chronos cannot
/// read (<paramref name="Unreadable"/>: why) is shown, disabled, its reason in the tooltip.
/// </summary>
public sealed record ProjectOption(SequenceProject Project, string? Unreadable = null)
{
public string Label => WorkspaceText.ProjectName(Project.Name, Project.IsMain);
/// <summary>It can be chosen: its copy here, if any, is one this Chronos reads.</summary>
public bool IsAvailable => Unreadable is null;
public string ToolTip => Unreadable ?? Loc.L("Tooltips.Editor.OpenWorkspace.Projects");
public override string ToString() => Label;
}
/// <summary>Project names as the home takes them: 1 to 60 characters, no control character, each once per sequence (case does not count).</summary>
public static class ProjectNames
{
/// <summary>The problem of <paramref name="name"/>, or null when the home takes it.</summary>
public static string? Validate(string name, IEnumerable<string> others)
{
var trimmed = name?.Trim() ?? string.Empty;
if (trimmed.Length is 0 or > ProjectService.MaxNameLength || trimmed.Any(char.IsControl)) return Loc.L("Errors.Workspace.InvalidName");
return others.Any(o => string.Equals(o, trimmed, StringComparison.OrdinalIgnoreCase)) ? Loc.L("Errors.Workspace.NameTaken") : null;
}
}
/// <summary>
/// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet, and by the project
/// menu's Open project: which project of its home (Main, made from the sequence's settings as they are, or another) or a
/// new one with its name, and the media to copy (proxies; the originals come in phase 5c). Open queues the copy; the
/// sequence opens once it is done.
/// </summary>
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
private readonly TaskCompletionSource<OpenChoice?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
private ProjectOption? _selected;
private bool _isNew;
/// <param name="taken">The names a new project cannot take (default: those of <paramref name="projects"/>).</param>
/// <param name="copy">What the copy of the media writes and the free space of the workspace's drive; null when not measured (shown as nothing).</param>
/// <param name="unreadable">
/// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen.
/// </param>
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null)
: base(close)
{
SequenceTitle = sequenceTitle;
Copy = copy;
CopyFacts = copy is null ? []
:
[
new DialogFact(Loc.L("Editor.OpenWorkspace.Size"), Formatting.Bytes(copy.Bytes), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.Size")),
new DialogFact(Loc.L("Editor.OpenWorkspace.Free"), copy.Free is { } free ? Formatting.Bytes(free) : Loc.L("Server.Sync.None"),
Reason: Loc.L(copy.TooLittleSpace ? "Errors.Workspace.NoRoom" : "Tooltips.Editor.OpenWorkspace.Free")),
];
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))];
_selected = Projects.FirstOrDefault(p => p.IsAvailable);
_isNew = !HasProjects;
var names = taken ?? [.. projects.Select(p => p.Name)];
NewName = new EditableField(string.Empty, n => ProjectNames.Validate(n, names), _ => { }, () => Loc.L("Tooltips.Editor.OpenWorkspace.Name"));
NewName.PropertyChanged += (_, _) => Refresh();
OpenCommand = new RelayCommand(Open, () => CanOpen);
}
/// <summary>Completes with the user's choice, or null when the dialog was closed without one.</summary>
public Task<OpenChoice?> Choice => _choice.Task;
public string SequenceTitle { get; }
/// <summary>The copy's bytes and the drive's free space, when measured.</summary>
public WorkspaceCopyFacts? Copy { get; }
/// <summary>"Copy size" and "Free space", under the media.</summary>
public IReadOnlyList<DialogFact> CopyFacts { get; }
/// <summary>The drive lacks room for the copy: the free space says so (the copy would stop saying how much is missing).</summary>
public bool IsShortOfSpace => Copy?.TooLittleSpace == true;
public string Heading => Loc.L("Editor.OpenWorkspace.Title");
public IReadOnlyList<ProjectOption> Projects { get; }
/// <summary>A project of the home can be chosen (one this Chronos cannot read here is only listed).</summary>
public bool HasProjects => Projects.Any(p => p.IsAvailable);
public ProjectOption? SelectedProject
{
get => _selected;
set
{
if (value is { IsAvailable: false }) return;
if (Set(ref _selected, value) && value is not null) IsExisting = true;
}
}
/// <summary>A project the home has.</summary>
public bool IsExisting
{
get => !_isNew;
set
{
if (value) IsNew = false;
}
}
/// <summary>A new project, named in <see cref="NewName"/>.</summary>
public bool IsNew
{
get => _isNew;
set
{
if (!Set(ref _isNew, value || !HasProjects)) return;
OnPropertyChanged(nameof(IsExisting));
Refresh();
}
}
public EditableField NewName { get; }
/// <summary>The proxies, the only media this phase copies.</summary>
public bool IsProxies => true;
/// <summary>The originals: offered from phase 5c, to render on this PC.</summary>
public bool CanCopyOriginals => false;
public ICommand OpenCommand { get; }
public bool CanOpen => _isNew ? !NewName.HasErrors : _selected is { IsAvailable: true };
public string OpenToolTip => _isNew && NewName.Error is { } error ? error : Loc.L("Tooltips.Editor.OpenWorkspace.Open");
public override void Dispose()
{
// Closed without a choice (Cancel, Esc, another sequence asked for).
_choice.TrySetResult(null);
base.Dispose();
}
private void Open()
{
if (!CanOpen) return;
_choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), BundleMedia.Proxies) : new OpenChoice(_selected!.Project.Id, null, BundleMedia.Proxies));
Close();
}
private void Refresh()
{
OnPropertyChanged(nameof(CanOpen));
OnPropertyChanged(nameof(OpenToolTip));
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>Names a project: "New project" (made from the open project's last version at the home) or "Rename".</summary>
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<string, Task> _save;
/// <param name="others">The names of the sequence's other projects (each name is used once).</param>
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close)
: base(close)
{
IsRename = rename;
_save = save;
var taken = others.ToList();
Name = new EditableField(name, n => ProjectNames.Validate(n, taken), _ => { }, () => Loc.L("Tooltips.Editor.ProjectName.Name"));
Name.PropertyChanged += (_, _) =>
{
OnPropertyChanged(nameof(SaveToolTip));
CommandManager.InvalidateRequerySuggested();
};
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy && !Name.HasErrors);
}
public bool IsRename { get; }
public string Heading => Loc.L(IsRename ? "Editor.ProjectName.Rename" : "Editor.ProjectName.New");
public string SaveText => Loc.L(IsRename ? "Editor.ProjectName.Apply" : "Editor.ProjectName.Create");
public EditableField Name { get; }
public ICommand SaveCommand { get; }
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create");
private async Task SaveAsync()
{
ClearError();
IsBusy = true;
try
{
await _save(Name.Text.Trim());
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Naming a project failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
finally
{
IsBusy = false;
}
}
}
/// <summary>"Save version" (Ctrl+S): an optional note, then the version is saved (and sent when Sync automatically is on).</summary>
public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
{
/// <summary>A note is a line of the history: longer text is cut there.</summary>
public const int MaxNoteLength = 200;
private readonly Func<string?, Task> _save;
private string _note = string.Empty;
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close)
: base(close)
{
ProjectName = projectName;
_save = save;
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy);
}
public string ProjectName { get; }
public string Heading => Loc.L("Editor.SaveVersion.Title", ProjectName);
public string Note
{
get => _note;
set => Set(ref _note, (value ?? string.Empty).Length > MaxNoteLength ? value![..MaxNoteLength] : value ?? string.Empty);
}
public ICommand SaveCommand { get; }
private async Task SaveAsync()
{
ClearError();
IsBusy = true;
try
{
await _save(string.IsNullOrWhiteSpace(_note) ? null : _note.Trim());
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Saving a version failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
finally
{
IsBusy = false;
}
}
}
/// <summary>A version in the History flyout: number, author, time, note, what made it, and Compare and Restore.</summary>
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore) : ObservableObject
{
public ProjectVersion Version { get; } = version;
public string Number => Formatting.Count(Version.Number);
public string Author => WorkspaceText.Author(Version);
public string When => WorkspaceText.When(Version.CreatedAt);
public string Note => Version.Note ?? string.Empty;
public string KindText => WorkspaceText.VersionKind(Version.Kind);
/// <summary>Saved here, waiting to be sent.</summary>
public bool IsUnsent { get; } = unsent;
/// <summary>The version the working state was last saved as (nothing differs).</summary>
public bool IsCurrent { get; } = isCurrent;
/// <summary>"Version 3 · Saved · STUDIO-PC · 28/10/2026 18:02 · note": the row for screen readers and its tooltip.</summary>
public string Description => string.Join(Loc.Separator, new[] { Loc.L("Editor.History.Version", Number), KindText, Author, When, Note }.Where(s => s.Length > 0));
public ICommand CompareCommand { get; } = compare;
public ICommand RestoreCommand { get; } = restore;
public string CompareToolTip => Loc.L("Tooltips.Editor.History.Compare", Number);
public string RestoreToolTip => Loc.L("Tooltips.Editor.History.Restore", Number);
}
/// <summary>
/// The History flyout of a workspace project: its versions newest first (those not sent yet marked), Compare (the
/// settings that differ from the project now) and Restore (the version as the project again, one undo step).
/// </summary>
public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ProjectVersion, Task<IReadOnlyList<string>>> _compare;
private readonly Func<ProjectVersion, Task> _restore;
private string? _comparedTitle;
private IReadOnlyList<string> _compared = [];
private bool _isLoaded;
public HistoryDialogViewModel(string projectName, Func<ProjectVersion, Task<IReadOnlyList<string>>> compare, Func<ProjectVersion, Task> restore,
Action<ArchiveDialogViewModel> close)
: base(close)
{
ProjectName = projectName;
_compare = compare;
_restore = restore;
}
public string ProjectName { get; }
public string Heading => Loc.L("Editor.History.Title", ProjectName);
public ObservableCollection<HistoryRowViewModel> Rows { get; } = [];
/// <summary>The home could not be asked: only this PC's versions are listed.</summary>
public bool IsOffline { get; private set; }
public bool IsEmpty => _isLoaded && Rows.Count == 0;
/// <summary>"Version 3 → now" over the comparison; null before one.</summary>
public string? ComparedTitle { get => _comparedTitle; private set => Set(ref _comparedTitle, value); }
public IReadOnlyList<string> Compared { get => _compared; private set => Set(ref _compared, value); }
/// <summary>Lists <paramref name="history"/>; <paramref name="currentHash"/> marks the version the project is now.</summary>
public void Show(WorkspaceHistory history, string? currentHash)
{
ArgumentNullException.ThrowIfNull(history);
Rows.Clear();
foreach (var version in history.Versions)
{
var current = currentHash is not null && string.Equals(version.ContentHash, currentHash, StringComparison.OrdinalIgnoreCase);
Rows.Add(new HistoryRowViewModel(version, history.Unsent.Contains(version.Id), current,
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy)));
}
IsOffline = history.Offline;
_isLoaded = true;
OnPropertyChanged(nameof(IsOffline));
OnPropertyChanged(nameof(IsEmpty));
}
/// <summary>A failure of the read that lists the versions, shown in the flyout.</summary>
public void ShowFailure(Exception ex)
{
ArgumentNullException.ThrowIfNull(ex);
_isLoaded = true;
OnPropertyChanged(nameof(IsEmpty));
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
public async Task CompareAsync(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
ClearError();
try
{
var lines = await _compare(version);
ComparedTitle = Loc.L("Editor.History.Compared", Formatting.Count(version.Number));
Compared = lines.Count == 0 ? [Loc.L("Editor.History.Same")] : lines;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be compared", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
}
public async Task RestoreAsync(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
ClearError();
IsBusy = true;
try
{
await _restore(version);
IsBusy = false;
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be restored", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
}
}
}
/// <summary>
/// A sync that met settings both sides changed (owner review 2, R8: asked only on real conflicts): what differs, then
/// Keep mine, Take the library's, or Save both (this workspace's versions go to a sibling project). Later leaves the
/// conflict for the next Sync; editing goes on meanwhile. A conflict of format (the library's project saved by a newer
/// Chronos, <see cref="WorkspaceConflict.NewerFormat"/>) cannot be merged either way: only Save both and Later are offered.
/// </summary>
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ConflictChoice, Task> _resolve;
/// <param name="newerFormat">The library holds a newer Chronos's settings: nothing is merged, Save both is the only choice.</param>
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
Action<ArchiveDialogViewModel> close, bool newerFormat = false)
: base(close)
{
ProjectName = projectName;
SiblingName = siblingName;
IsNewerFormat = newerFormat;
// The format's number says nothing to the user: the line names the cause.
Differences = newerFormat ? [Loc.L("Editor.Workspace.Conflict.NewerFormat")] : differences;
_resolve = resolve;
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy && CanMerge);
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy && CanMerge);
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
}
/// <summary>The library's project was saved by a newer Chronos.</summary>
public bool IsNewerFormat { get; }
/// <summary>Keep mine and Take the library's are offered (not for a conflict of format, which neither can settle).</summary>
public bool CanMerge => !IsNewerFormat;
public string ProjectName { get; }
/// <summary>The project Save both makes for this workspace's versions.</summary>
public string SiblingName { get; }
public string Heading => Loc.L("Editor.Workspace.Conflict.Title");
public string Message => Loc.L(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", ProjectName);
public IReadOnlyList<string> Differences { get; }
public string DifferencesToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences");
public ICommand KeepMineCommand { get; }
public ICommand TakeHomeCommand { get; }
public ICommand SaveBothCommand { get; }
public string SaveBothToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", SiblingName);
private async Task ResolveAsync(ConflictChoice choice)
{
ClearError();
IsBusy = true;
try
{
await _resolve(choice);
IsBusy = false;
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The conflict of '{ProjectName}' could not be settled ({choice})", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
}
}
}
/// <summary>
/// "Remove local copy": the plan (files and size of the copy; versions not sent and changes not saved), then Remove
/// (only when everything is at the library), Send first (sends, then removes), or Discard changes (removes once the
/// user typed the project's name; the unsent work is kept aside in the workspace's trash). A project the library no
/// longer has (<see cref="WorkspaceRemovalPlan.Gone"/>), or a copy whose working state cannot be read
/// (<see cref="WorkspaceRemovalPlan.Damaged"/>), can only be discarded that way.
/// </summary>
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<bool, Task> _remove;
private readonly Func<Task> _sendFirst;
private readonly Func<bool> _confirmDiscard;
/// <param name="confirmDiscard">The typed confirmation Discard changes asks first (<see cref="ConfirmDiscard"/>); true when the user confirmed.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close)
: base(close)
{
Plan = plan;
_remove = remove;
_sendFirst = sendFirst;
_confirmDiscard = confirmDiscard;
Facts =
[
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
new DialogFact(Loc.L("Editor.RemoveCopy.Size"), Formatting.Bytes(plan.Bytes)),
new DialogFact(Loc.L("Editor.RemoveCopy.Unsent"), Formatting.Count(plan.Unsent)),
new DialogFact(Loc.L("Editor.RemoveCopy.Changed"), Loc.L(plan.Modified ? "Editor.RemoveCopy.Yes" : "Editor.RemoveCopy.No")),
];
RemoveCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(false)), () => !IsBusy && plan.IsSafe && !plan.Offline && !plan.Gone);
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone && !plan.Damaged);
DiscardCommand = new AsyncRelayCommand(DiscardAsync, () => !IsBusy && HasUnsent);
}
public WorkspaceRemovalPlan Plan { get; }
/// <summary>"Remove local copy of Main"; a damaged copy by the name it is still known by, else as a damaged copy (never by its folder's id).</summary>
public string Heading => !Plan.Damaged ? Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false))
: Plan.KnownName is { Length: > 0 } known ? Loc.L("Editor.RemoveCopy.Title", known)
: Loc.L("Editor.RemoveCopy.DamagedTitle");
public IReadOnlyList<DialogFact> Facts { get; }
/// <summary>Something would not be at the library after the removal (or the library no longer has the project): Discard changes shows.</summary>
public bool HasUnsent => !Plan.IsSafe || Plan.Gone;
public ICommand RemoveCommand { get; }
public ICommand SendFirstCommand { get; }
public ICommand DiscardCommand { get; }
public string RemoveToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: !Plan.IsSafe ? Loc.L("Errors.Workspace.Unsent")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.Remove");
public string SendFirstToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: Plan.Conflict ? Loc.L("Errors.Workspace.Conflict")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
public string DiscardToolTip => Loc.L("Tooltips.Editor.RemoveCopy.Discard");
/// <summary>
/// The typed confirmation of Discard changes (the plan's cross-cutting rule for what Chronos cannot bring back): the
/// project's name, as shown, typed before Discard enables.
/// </summary>
public static ConfirmRequest DiscardRequest(string projectName) => new()
{
Heading = Loc.L("Editor.RemoveCopy.DiscardTitle", projectName),
Message = Loc.L("Editor.RemoveCopy.DiscardMessage"),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Keep"),
ActionText = Loc.L("Editor.RemoveCopy.Discard"),
ActionToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Discard"),
IsDestructive = true,
TypedConfirmation = projectName,
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeName"),
};
/// <summary>
/// The typed confirmation of discarding a damaged copy (<see cref="WorkspaceRemovalPlan.Damaged"/>): the name it is still
/// known by (<see cref="WorkspaceRemovalPlan.KnownName"/>), never its folder's id; with no name known, the number of its
/// files, as the plan shows it.
/// </summary>
public static ConfirmRequest DiscardRequest(WorkspaceRemovalPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.KnownName is { Length: > 0 } known) return DiscardRequest(known);
var files = Formatting.Count(plan.Files);
return DiscardRequest(string.Empty) with
{
Heading = Loc.L("Editor.RemoveCopy.DamagedDiscard"),
TypedConfirmation = files,
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeFiles", files),
};
}
/// <summary>Asks <see cref="DiscardRequest(string)"/> through <paramref name="ui"/>: true when the user typed the name and confirmed.</summary>
public static bool ConfirmDiscard(IWorkspaceUi ui, string projectName)
{
ArgumentNullException.ThrowIfNull(ui);
return ui.Confirm(DiscardRequest(projectName));
}
/// <summary>Asks <see cref="DiscardRequest(WorkspaceRemovalPlan)"/> through <paramref name="ui"/>: true when the user typed what it asks and confirmed.</summary>
public static bool ConfirmDiscard(IWorkspaceUi ui, WorkspaceRemovalPlan plan)
{
ArgumentNullException.ThrowIfNull(ui);
return ui.Confirm(DiscardRequest(plan));
}
private async Task DiscardAsync()
{
if (!_confirmDiscard()) return;
await RunAsync(() => _remove(true));
}
private async Task RunAsync(Func<Task> action)
{
ClearError();
IsBusy = true;
try
{
await action();
IsBusy = false;
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The local copy of project {Plan.ProjectId} was not removed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
}
}
}
@@ -0,0 +1,286 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:ar="clr-namespace:Chronos.App.Archiving"
xmlns:ws="clr-namespace:Chronos.App.Workspace"
xmlns:infra="clr-namespace:Chronos.App.Infrastructure">
<!-- The in-window dialogs of Edit's workspace (owner review 2, R8), with the dialog kit of the Archive screen. -->
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- A history row: focusable for the arrow keys; screen readers hear the version, what made it, who, when and the note. -->
<Style x:Key="ListBoxItem.History" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding Description}" />
<Setter Property="ToolTip" Value="{Binding Description}" />
</Style>
<!-- A project of Open in workspace: one whose copy here this Chronos cannot read is disabled, its reason in the tooltip. -->
<Style x:Key="ComboBoxItem.Project" TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
<Setter Property="IsEnabled" Value="{Binding IsAvailable}" />
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
<Setter Property="AutomationProperties.Name" Value="{Binding Label}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding ToolTip}" />
</Style>
<!-- Open in workspace: which project of the sequence's home, or a new one, and the media to copy. -->
<DataTemplate DataType="{x:Type ws:OpenInWorkspaceDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Text="{Binding SequenceTitle}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" TextTrimming="CharacterEllipsis" ToolTip="{Binding SequenceTitle}" />
<Grid Margin="0,16,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Editor.OpenWorkspace.Project}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<RadioButton Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.Existing}" IsChecked="{Binding IsExisting}" IsEnabled="{Binding HasProjects}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Existing}" VerticalAlignment="Center" Margin="0,0,12,0" />
<ComboBox Grid.Column="2" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label" IsEnabled="{Binding HasProjects}"
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Projects}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
<RadioButton Grid.Row="1" Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.New}" IsChecked="{Binding IsNew}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.New}" VerticalAlignment="Center" Margin="0,8,12,0" />
<TextBox Grid.Row="1" Grid.Column="2" Margin="0,8,0,0" Text="{Binding NewName.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
IsEnabled="{Binding IsNew}" ToolTip="{Binding NewName.ToolTip}" MaxLength="60" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.New}" />
<TextBlock Grid.Row="2" Text="{l:Loc Editor.OpenWorkspace.Media}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,14,0,0" />
<StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,14,0,0">
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies, Mode=OneWay}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Proxies}" Margin="0,0,16,0" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="False"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" />
</StackPanel>
</Grid>
<!-- What the copy writes and the room the workspace's drive has for it. -->
<ItemsControl ItemsSource="{Binding CopyFacts}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
<Grid Margin="0,0,0,6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="CopyFactLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
<TextBlock Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" Typography.NumeralAlignment="Tabular" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ui:StatusGlyph Kind="Warning" Text="{l:Loc Editor.OpenWorkspace.NoRoom}" ToolTip="{l:Loc Errors.Workspace.NoRoom}" FontSize="12" HorizontalAlignment="Left"
Margin="116,2,0,0" Visibility="{Binding IsShortOfSpace, Converter={StaticResource BoolToVisibility}}" />
<DockPanel Margin="0,20,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.OpenWorkspace.Open}" Command="{Binding OpenCommand}"
ToolTip="{Binding OpenToolTip}" ToolTipService.ShowOnDisabled="True" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- New project and Rename: the name, checked as it is typed. -->
<DataTemplate DataType="{x:Type ws:ProjectNameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Editor.ProjectName.Name}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Name.ToolTip}"
MaxLength="60" AutomationProperties.Name="{l:Loc Editor.ProjectName.Name}" />
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{Binding SaveText}" Command="{Binding SaveCommand}" ToolTip="{Binding SaveToolTip}"
ToolTipService.ShowOnDisabled="True" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- Save version (Ctrl+S): an optional note; Enter saves. -->
<DataTemplate DataType="{x:Type ws:SaveVersionDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Editor.SaveVersion.Note}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding Note, UpdateSourceTrigger=PropertyChanged}" ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Note}" MaxLength="200"
AutomationProperties.Name="{l:Loc Editor.SaveVersion.Note}" />
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.SaveVersion.Save}" Command="{Binding SaveCommand}"
ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Save}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- History: a flyout under the title, newest first; Compare shows what differs from now below the list, Restore brings a version back. -->
<DataTemplate DataType="{x:Type ws:HistoryDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="620" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="40,40,0,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DockPanel>
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{l:Loc Editor.History.Offline}" ToolTip="{l:Loc Tooltips.Editor.History.Offline}" FontSize="12"
VerticalAlignment="Center" Visibility="{Binding IsOffline, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
</DockPanel>
<Grid Grid.Row="1" Margin="0,12,0,0" MinHeight="120">
<ListBox ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.History}" Grid.IsSharedSizeScope="True"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" AutomationProperties.Name="{l:Loc Editor.History.List}" KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ws:HistoryRowViewModel}">
<Grid Height="36">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="36" SharedSizeGroup="HistoryNumber" />
<ColumnDefinition Width="Auto" SharedSizeGroup="HistoryKind" />
<ColumnDefinition Width="Auto" MaxWidth="160" SharedSizeGroup="HistoryAuthor" />
<ColumnDefinition Width="Auto" SharedSizeGroup="HistoryWhen" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.CellNumber}" Text="{Binding Number}" FontWeight="SemiBold" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding KindText}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Author}" Margin="12,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding When}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
Typography.NumeralAlignment="Tabular" />
<DockPanel Grid.Column="4" Margin="12,0,0,0">
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{l:Loc Tooltips.Editor.History.NotSent}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsUnsent, Converter={StaticResource BoolToVisibility}}" />
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Done" Text="{l:Loc Editor.History.Current}" ToolTip="{l:Loc Tooltips.Editor.History.Current}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsCurrent, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Note}" />
</DockPanel>
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Content="{l:Loc Editor.History.Compare}" Command="{Binding CompareCommand}"
ToolTip="{Binding CompareToolTip}" Margin="12,0,0,0" />
<Button Grid.Column="6" Style="{StaticResource Button.Row}" Content="{l:Loc Editor.History.Restore}" Command="{Binding RestoreCommand}"
ToolTip="{Binding RestoreToolTip}" Margin="8,0,0,0" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Style="{StaticResource Text.Secondary}" Text="{l:Loc Editor.History.Empty}" HorizontalAlignment="Center" VerticalAlignment="Center"
Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<!-- What differs between now and the version compared. -->
<Border Grid.Row="2" Style="{StaticResource Border.Card}" Margin="0,12,0,0" Padding="12,10" MaxHeight="160"
Visibility="{Binding ComparedTitle, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{Binding ComparedTitle}" FontWeight="SemiBold" infra:LiveRegion.Text="{Binding ComparedTitle}"
AutomationProperties.LiveSetting="Polite" />
<ScrollViewer Margin="0,6,0,0" VerticalScrollBarVisibility="Auto" Focusable="False">
<ItemsControl ItemsSource="{Binding Compared}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" TextWrapping="Wrap" Margin="0,0,0,4" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</DockPanel>
</Border>
<DockPanel Grid.Row="3" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Editor.History.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" IsDefault="True"
MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's, Save both, or Later (only Save both and Later for a newer Chronos's project). -->
<DataTemplate DataType="{x:Type ws:ConflictDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="560">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" TextTrimming="None" />
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<Border Style="{StaticResource Border.Card}" Margin="0,14,0,0" Padding="12,10" ToolTip="{Binding DifferencesToolTip}">
<ItemsControl ItemsSource="{Binding Differences}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" TextWrapping="Wrap" Margin="0,0,0,4" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<WrapPanel HorizontalAlignment="Right" Margin="0,20,0,0">
<Button Content="{l:Loc Editor.Workspace.Conflict.Later}" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.Later}" IsCancel="True"
MinWidth="96" Margin="0,0,8,8" />
<Button Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}" MinWidth="96" Margin="0,0,8,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Editor.Workspace.Conflict.TakeHome}" Command="{Binding TakeHomeCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.TakeHome}"
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.KeepMine}" Command="{Binding KeepMineCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<!-- A conflict of format: Save both is the only choice that settles it. -->
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}"
IsDefault="{Binding IsNewerFormat, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
Visibility="{Binding CanMerge, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
</WrapPanel>
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" HorizontalAlignment="Right" />
</StackPanel>
</Border>
</DataTemplate>
<!-- Remove local copy: the plan, then Remove (all at the library), Send first, or Discard changes. -->
<DataTemplate DataType="{x:Type ws:RemoveCopyDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Text="{l:Loc Editor.RemoveCopy.Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<ItemsControl ItemsSource="{Binding Facts}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="FactLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
<TextBlock Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" Typography.NumeralAlignment="Tabular" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<WrapPanel HorizontalAlignment="Right" Margin="0,18,0,0">
<Button Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" IsDefault="True" MinWidth="96"
Margin="0,0,8,8" />
<Button Style="{StaticResource Button.Destructive}" Content="{l:Loc Editor.RemoveCopy.Discard}" Command="{Binding DiscardCommand}" ToolTip="{Binding DiscardToolTip}"
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,8,8" Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Editor.RemoveCopy.SendFirst}" Command="{Binding SendFirstCommand}" ToolTip="{Binding SendFirstToolTip}" ToolTipService.ShowOnDisabled="True"
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Destructive}" Content="{l:Loc Editor.RemoveCopy.Remove}" Command="{Binding RemoveCommand}" ToolTip="{Binding RemoveToolTip}"
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,0,8" />
</WrapPanel>
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" HorizontalAlignment="Right" />
</StackPanel>
</Border>
</DataTemplate>
</ResourceDictionary>
@@ -0,0 +1,86 @@
using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
namespace Chronos.App.Workspace;
/// <summary>
/// Choosing another workspace folder (owner review 2, R8): Settings › Workspace › Change, and the refusal of a folder
/// inside a library, where Edit cannot be used until one is chosen. The folder is picked, its plan shown and confirmed
/// (the projects the folder in use keeps, those the new one holds), a workspace project open in the editor closes (its
/// last edit stored first), and only then does the setting change. Nothing is moved or deleted: the projects of the
/// folder left stay there, listed again once it is chosen back. Moving a workspace with its projects comes in phase 5c.
/// </summary>
public static class WorkspaceFolderChange
{
/// <summary>The shell's flow: its folder picker and confirmation, its editor, its toasts.</summary>
public static async Task<bool> ChooseAsync(ShellViewModel shell)
{
ArgumentNullException.ThrowIfNull(shell);
var changed = await ChooseAsync(shell.Services.Workspace, shell.Services.Dialogs, async () =>
{
if (shell.Sequence.Editor?.Session.Source is not WorkspaceSequenceSource) return true;
if (!await shell.Sequence.ConfirmCloseAsync()) return false;
await shell.Sequence.CloseAsync();
shell.KeepSequence(null);
return true;
}, message => shell.Notify(Loc.L("Settings.Workspace.NotChanged"), message, isError: true));
if (changed) shell.Notify(Loc.L("Settings.Workspace.Changed"), shell.Services.Workspace.Root);
return changed;
}
/// <summary>
/// Picks a folder through <paramref name="dialogs"/>, confirms its plan, lets <paramref name="closeProject"/> close a
/// workspace project open in the editor (false keeps everything as it is), then makes it the workspace's folder.
/// <paramref name="failed"/> hears why a folder was refused. True when the folder changed.
/// </summary>
public static async Task<bool> ChooseAsync(WorkspaceHost host, IAppDialogs dialogs, Func<Task<bool>> closeProject, Action<string> failed)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(dialogs);
ArgumentNullException.ThrowIfNull(closeProject);
ArgumentNullException.ThrowIfNull(failed);
if (dialogs.PickFolder(Loc.L("Settings.Workspace.ChooseTitle"), Directory.Exists(host.Root) ? host.Root : null) is not { } folder) return false;
try
{
var plan = await host.PlanFolderAsync(folder);
if (plan.IsSame) return false;
if (plan.InsideLibrary)
{
failed(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder));
return false;
}
if (!dialogs.Confirm(Request(plan))) return false;
if (!await closeProject()) return false;
await host.UseFolderAsync(plan.Folder);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException or WorkspaceException)
{
Log.Warning("workspace", $"The workspace folder was not changed to {folder}", ex);
failed(ex is WorkspaceException ? ex.Message : Loc.L("Errors.Workspace.FolderUnusable", folder));
return false;
}
}
/// <summary>The plan as a confirmation: where Edit's projects come from now, and what stays where it is.</summary>
public static ConfirmRequest Request(WorkspaceFolderPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
return new ConfirmRequest
{
Heading = Loc.L("Settings.Workspace.ChangeTitle"),
Message = Loc.L("Settings.Workspace.ChangeMessage", plan.Folder, plan.Current),
Detail = string.Join(Environment.NewLine, Loc.L("Settings.Workspace.ProjectsLeft", Formatting.Count(plan.ProjectsLeft)),
Loc.L("Settings.Workspace.ProjectsFound", Formatting.Count(plan.ProjectsFound))),
IsDetailMonospaced = false,
SafeText = Loc.L("Archive.Dialog.Cancel"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepWorkspace"),
ActionText = Loc.L("Settings.Workspace.Use"),
ActionToolTip = Loc.L("Tooltips.Settings.UseWorkspace"),
};
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,72 @@
using Chronos.App.Library;
using Chronos.Core.Localization;
using Chronos.Data.Workspaces;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
/// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed
/// as damaged, one a newer Chronos wrote as such, by the name each is still known by.
/// </summary>
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
{
private WorkspaceStatus? _status;
public WorkspaceEntry Entry { get; } = entry;
/// <summary>The sequence's row of the library, for its thumbnail; null when the index no longer has it.</summary>
public SequenceItem? Sequence { get; } = sequence;
public Guid ProjectId => Entry.ProjectId;
public Guid SequenceId => Entry.SequenceId;
/// <summary>The project's name (Main in the UI language).</summary>
public string Name => WorkspaceText.ProjectName(Entry.Name, Entry.IsMain);
public string SequenceTitle => Sequence?.Title ?? Entry.SequenceTitle;
public WorkspaceStatus? Status
{
get => _status;
set
{
if (!Set(ref _status, value)) return;
OnPropertyChanged(nameof(StateText));
OnPropertyChanged(nameof(StateKind));
OnPropertyChanged(nameof(StateToolTip));
OnPropertyChanged(nameof(Description));
}
}
/// <summary>Its working state cannot be read: it cannot open, and Remove local copy keeps its files aside.</summary>
public bool IsDamaged => Entry.Damaged;
/// <summary>A newer Chronos wrote its working state: it neither opens nor goes from here, and stays as it is.</summary>
public bool IsNewer => Entry.Newer;
/// <summary>This Chronos reads its working state: it opens, and its state is asked of its home.</summary>
public bool IsReadable => Entry.IsReadable;
public string StateText => Entry.Newer ? Loc.L("Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
public StatusKind StateKind => Entry.Newer ? StatusKind.Warning
: Entry.Damaged ? StatusKind.Error
: Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
public string StateToolTip => Entry.Newer ? Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
/// <summary>"Vertical social · Harbour sunset · In sync": what screen readers hear for the row.</summary>
public string Description => string.Join(Loc.Separator, Name, SequenceTitle, StateText);
public override string ToString() => Name;
internal void Refresh() => OnAllPropertiesChanged();
}
+111
View File
@@ -0,0 +1,111 @@
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Ui.Controls;
namespace Chronos.App.Workspace;
/// <summary>How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free.</summary>
public static class WorkspaceText
{
/// <summary>The project's name; the Main project in the UI language.</summary>
public static string ProjectName(string name, bool isMain) =>
isMain && string.Equals(name, ProjectService.MainName, StringComparison.Ordinal) ? Loc.L("Editor.Project.Main") : name;
/// <summary>The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs.</summary>
public static string State(WorkspaceStatus? status, bool syncing = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing") : status is null ? Loc.L("Editor.Workspace.State.Reading") : Loc.L("Editor.Workspace.State." + status.State);
public static StatusKind Kind(WorkspaceStatus? status, bool syncing = false) => syncing ? StatusKind.Running : status?.State switch
{
WorkspaceState.InSync => StatusKind.Synced,
WorkspaceState.Modified or WorkspaceState.Ahead => StatusKind.Queued,
WorkspaceState.Behind => StatusKind.Remote,
WorkspaceState.Conflict => StatusKind.Error,
WorkspaceState.Offline => StatusKind.Offline,
WorkspaceState.MediaRemoved => StatusKind.NoProxies,
WorkspaceState.Gone => StatusKind.Warning,
WorkspaceState.Damaged => StatusKind.Error,
_ => StatusKind.Queued,
};
/// <summary>What the state means and what to do, with the counts behind it.</summary>
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false) => syncing ? Loc.L("Tooltips.Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Tooltips.Editor.Workspace.State.Reading")
: status.State switch
{
WorkspaceState.Ahead => Loc.L("Tooltips.Editor.Workspace.State.Ahead", Formatting.Count(status.Ahead)),
WorkspaceState.Behind => Loc.L("Tooltips.Editor.Workspace.State.Behind", Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => Loc.L("Tooltips.Editor.Workspace.State.OfflineAhead", Formatting.Count(status.Ahead)),
var state => Loc.L("Tooltips.Editor.Workspace.State." + state),
};
/// <summary>"Saved", "Merged", "Restored", "Imported", "Outside change".</summary>
public static string VersionKind(ProjectVersionKind kind) => Loc.L("Editor.History.Kind." + kind);
/// <summary>
/// Who made a version: its author, else the PC it was made on ("STUDIO-PC"), however the program that made it named
/// itself ("chronos@STUDIO-PC" for the archive's own versions, "Chronos on STUDIO-PC" for those of test builds).
/// </summary>
public static string Author(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
if (version.Author is { Length: > 0 } author) return author;
var client = version.ClientName?.Trim() ?? string.Empty;
foreach (var prefix in ClientPrefixes)
{
if (client.Length > prefix.Length && client.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return client[prefix.Length..];
}
return client;
}
/// <summary>What programs put before the PC's name in a version's client name (not words of the UI: the PC alone is shown).</summary>
private static readonly string[] ClientPrefixes = ["chronos@", "server@", "workspace@", "Chronos on "];
/// <summary>"28/10/2026 18:02".</summary>
public static string When(DateTimeOffset at) => $"{Formatting.Date(at)} {Formatting.TimeOfDay(at)}";
/// <summary>
/// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most <paramref name="max"/>.
/// A conflict of format (<see cref="ProjectMerge.FormatPath"/>) reads as its cause, never as the format's numbers.
/// </summary>
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max)
{
ArgumentNullException.ThrowIfNull(differences);
var list = differences.ToList();
if (list.Any(d => d.Path == ProjectMerge.FormatPath)) return [Loc.L("Editor.Workspace.Conflict.NewerFormat")];
return SyncText.Differences(list, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
}
/// <summary>One line per setting that differs between now and a version ("Deflicker window 41 now, 33 in that version").</summary>
public static IReadOnlyList<string> CompareLines(IEnumerable<SettingsDifference> differences, int max) =>
SyncText.Differences(differences, max, (label, now, then) => Loc.L("Editor.History.Difference", label, now, then));
/// <summary>Why a workspace operation stopped, as one localized sentence chosen by cause; the exception's own text goes to the log.</summary>
public static string Failure(Exception ex) => ex switch
{
WorkspaceException or LeaseUnavailableException => ex.Message,
// A library that can be read but not written (a read-only share, a write-protected disk): the work waits here as offline.
HomeUnavailableException { InnerException: ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } }
or ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } => Loc.L("Errors.Workspace.ReadOnlyHome"),
HomeUnavailableException or ArchiveOfflineException => Loc.L("Errors.Workspace.Offline"),
ProjectException { Reason: ProjectError.NameTaken } => Loc.L("Errors.Workspace.NameTaken"),
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
ProjectException { Reason: ProjectError.MainCannotBeDeleted } => Loc.L("Errors.Workspace.MainKept"),
ProjectException => Loc.L("Errors.Workspace.ProjectGone"),
// A version over the size one may be: saved here (refused before anything was written) or sent (the home stored nothing).
ProjectVersionTooLargeException or WorkspaceSyncException { Outcome: PushOutcome.TooLarge } =>
Loc.L("Errors.Workspace.VersionTooLarge", ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
_ => ArchiveFailures.Cause(ex),
};
}