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

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

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

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

No files matched your search

@@ -0,0 +1,521 @@
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project.</summary>
public interface IWorkspaceUi
{
void ShowDialog(ArchiveDialogViewModel dialog);
void CloseDialog(ArchiveDialogViewModel dialog);
/// <summary>True when the user chose the action (a destructive confirmation).</summary>
bool Confirm(ConfirmRequest request);
void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false);
/// <summary>Opens project <paramref name="projectId"/> of <paramref name="sequenceId"/> in the editor (checked out and copied first when it is not here).</summary>
Task OpenProjectAsync(Guid sequenceId, Guid projectId);
/// <summary>Closes the open project (its last edit stored first); the picker shows. False when the user kept it open.</summary>
Task<bool> CloseProjectAsync();
/// <summary>The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again.</summary>
Task SequenceChangedAsync(Guid sequenceId);
}
/// <summary>
/// The project menu of the editor's title (▾, owner review 2, R8) for a workspace project: where it stands (the chip), Save
/// version (Ctrl+S, an optional note; sent at once with Settings › Workspace › Sync automatically), Sync, History (Compare,
/// Restore as one undo step), New project, Rename, Delete project (never Main) and Remove local copy, and the "Update
/// media" banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit;
/// what a pull or a restore changed comes back into the editor (merged, or as an undo step). A conflict is asked about
/// only when the merge met settings both sides changed. Call from the UI thread.
/// </summary>
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
private readonly WorkspaceHost _host;
private readonly WorkspaceSequenceSource _source;
private readonly EditorSession _session;
private readonly IWorkspaceUi _ui;
private readonly AsyncRelayCommand _sync;
private readonly AsyncRelayCommand _updateMedia;
/// <summary>The thread the menu was made on (the UI's); null where there is none (tests run inline).</summary>
private readonly SynchronizationContext? _context = SynchronizationContext.Current;
private WorkspaceStatus? _status;
private bool _isSyncing;
private bool _homeFramesChanged;
private Guid _copyJob;
private bool _disposed;
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
{
_host = host;
_source = source;
_session = session;
_ui = ui;
_sync = new AsyncRelayCommand(() => SyncAsync(), () => !_isSyncing);
_updateMedia = new AsyncRelayCommand(UpdateMediaAsync, () => _copyJob == Guid.Empty);
SaveVersionCommand = new RelayCommand(OpenSaveVersion, () => CanSaveVersion);
HistoryCommand = new AsyncRelayCommand(OpenHistoryAsync);
NewProjectCommand = new AsyncRelayCommand(OpenNewProjectAsync);
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
source.JobChanged += OnJobChanged;
}
public Guid ProjectId => _source.ProjectId;
public Guid SequenceId => _session.Content.Sequence.Id;
public bool IsMain => _source.Workspace?.IsMain == true;
/// <summary>The project's name (Main in the UI language).</summary>
public string Name => _source.Workspace is { } workspace ? WorkspaceText.ProjectName(workspace.Name, workspace.IsMain) : string.Empty;
public WorkspaceStatus? Status => _status;
public bool IsSyncing => _isSyncing;
public string StateText => WorkspaceText.State(_status, _isSyncing);
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing);
/// <summary>The ▾ button: its name, then where the project stands, then what the menu holds.</summary>
public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText);
/// <summary>The button's accessible name: the project and its state.</summary>
public string MenuName => string.Join(Loc.Separator, Name, StateText);
/// <summary>The home's frames moved past those the workspace holds: the banner offers Update media.</summary>
public bool HasMediaUpdate => _homeFramesChanged;
/// <summary>A copy of the media runs (Update media): the banner says so.</summary>
public bool IsUpdatingMedia => _copyJob != Guid.Empty;
public string MediaUpdateText => Loc.L(IsUpdatingMedia ? "Editor.Workspace.Updating" : "Editor.Workspace.MediaChanged");
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true };
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
: _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict")
: Loc.L("Tooltips.Editor.Project.SaveVersion");
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : Loc.L("Tooltips.Editor.Project.Delete");
/// <summary>Save version… (Ctrl+S): the note dialog.</summary>
public ICommand SaveVersionCommand { get; }
public ICommand SyncCommand => _sync;
public ICommand HistoryCommand { get; }
public ICommand NewProjectCommand { get; }
public ICommand RenameCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand RemoveCopyCommand { get; }
public ICommand UpdateMediaCommand => _updateMedia;
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved; a conflict found meanwhile is asked about.</summary>
public async Task RefreshAsync()
{
try
{
var status = await _host.StatusAsync(ProjectId);
var moved = await _source.HomeFramesChangedAsync(CancellationToken.None);
if (_disposed) return;
_homeFramesChanged = moved;
Apply(status);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The state of project {ProjectId} could not be read", ex);
}
}
/// <summary>
/// A job of the sequence ended: where the project stands is read again; after an analysis, which writes its Auto
/// values into the library's settings (Main's), the project takes them at once with Sync automatically.
/// </summary>
public async Task JobEndedAsync(Job job)
{
ArgumentNullException.ThrowIfNull(job);
await RefreshAsync();
if (_disposed || !_host.Settings.WorkspaceAutoSync || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse)) return;
if (_status is { State: WorkspaceState.Behind }) await SyncAsync(quiet: true);
}
/// <summary>
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about.
/// </summary>
/// <exception cref="WorkspaceException">Why no version could be saved (the edit could not be stored, a conflict, read-only).</exception>
public async Task SaveVersionAsync(string? note)
{
await StoreEditAsync();
var result = await _host.SaveVersionAsync(ProjectId, note);
if (_disposed) return;
Apply(result.Status);
if (result.Synced is { } taken) await TakeAsync(taken);
if (result.Version is null)
{
_ui.Notify(Loc.L("Editor.Workspace.NothingNew"), Name);
}
else if (result.Synced is { Pushed.Count: > 0 } synced)
{
// The home numbers what it stores: the last one sent is this version.
_ui.Notify(Loc.L("Editor.Workspace.SavedSent", Formatting.Count(synced.Pushed[^1].Number)), Name);
}
else
{
_ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name);
}
if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error), isError: error is not HomeUnavailableException);
if (result.Status.Conflict is { } conflict) AskConflict(conflict);
}
/// <summary>Sync: the home's new versions taken into the editor, the local ones sent; a conflict is asked about.</summary>
public async Task SyncAsync(bool quiet = false)
{
if (_isSyncing) return;
SetSyncing(true);
try
{
await StoreEditAsync();
var result = await _host.SyncAsync(ProjectId);
if (_disposed) return;
Apply(result.Status);
await TakeAsync(result);
if (result.Status.Conflict is { } conflict) AskConflict(conflict);
else if (!quiet) _ui.Notify(Loc.L(result.Status.State == WorkspaceState.InSync ? "Editor.Workspace.InSync" : "Editor.Workspace.Synced"), Name);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be synced", ex);
_ui.Notify(Loc.L(ex is HomeUnavailableException ? "Editor.Workspace.Offline" : "Editor.Workspace.SyncFailed"), WorkspaceText.Failure(ex),
isError: ex is not HomeUnavailableException);
await RefreshAsync();
}
finally
{
SetSyncing(false);
}
}
/// <summary>Settles a conflict as chosen, then brings the settled working state into the editor.</summary>
public async Task ResolveAsync(ConflictChoice choice)
{
await StoreEditAsync();
var result = await _host.ResolveAsync(ProjectId, choice);
if (_disposed) return;
Apply(result.Status);
await TakeAsync(result, force: true);
if (result.SavedAs is { } copy) _ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name);
if (result.Status.Conflict is { } again) AskConflict(again);
}
/// <summary>
/// Restores <paramref name="version"/> as the project, as one undo step (uncommitted changes are saved as a version
/// first, so nothing is lost); the toast's Undo takes it back while it is the last change.
/// </summary>
public async Task RestoreAsync(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
await StoreEditAsync();
var restored = await _host.RestoreAsync(ProjectId, version.Id);
if (_disposed) return;
var before = _session.Project;
if (_session.Edit(_ => restored))
{
_session.EndEditRun();
var undo = new ProjectRestore(_session, before, _session.Project);
_ui.Notify(Loc.L("Editor.Workspace.Restored", Formatting.Count(version.Number)), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.Undo"),
() => undo.Undo());
}
else
{
_ui.Notify(Loc.L("Editor.Copy.Same"), Name);
}
await RefreshAsync();
}
/// <summary>The settings that differ between the project now and <paramref name="version"/> (positions compared photo by photo).</summary>
public IReadOnlyList<string> Compare(ProjectVersion version, int max = 12)
{
ArgumentNullException.ThrowIfNull(version);
var now = ProjectContent.ToPortable(_session.Project, _source.Photos);
return WorkspaceText.CompareLines(SyncRules.Differences(now, version.SettingsJson, 64), max);
}
public override void Dispose()
{
_disposed = true;
_source.JobChanged -= OnJobChanged;
base.Dispose();
}
protected override void OnLanguageChanged()
{
base.OnLanguageChanged();
RaiseState();
}
private void OpenSaveVersion()
{
if (!CanSaveVersion) return;
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog));
}
private async Task OpenHistoryAsync()
{
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog);
_ui.ShowDialog(dialog);
try
{
await StoreEditAsync();
var history = await _host.HistoryAsync(ProjectId, Math.Max(50, _host.Settings.WorkspaceKeptVersions));
dialog.Show(history, ProjectContent.Hash(ProjectContent.ToPortable(_session.Project, _source.Photos)));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The history of project {ProjectId} could not be read", ex);
dialog.ShowFailure(ex);
}
}
private async Task OpenNewProjectAsync()
{
var names = await OtherNamesAsync(null);
_ui.ShowDialog(new ProjectNameDialogViewModel(false, string.Empty, names, async name =>
{
await StoreEditAsync();
// From the open project's last version at the home, so the new one starts where this one is there.
var created = await _host.CreateProjectAsync(SequenceId, name, _status?.Base?.VersionId);
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
}, _ui.CloseDialog));
}
private async Task OpenRenameAsync()
{
var names = await OtherNamesAsync(ProjectId);
_ui.ShowDialog(new ProjectNameDialogViewModel(true, _source.Workspace?.Name ?? string.Empty, names, async name =>
{
await _host.RenameAsync(ProjectId, name);
await _session.ReloadAsync();
_ui.Notify(Loc.L("Editor.Workspace.Renamed"), name);
RaiseState();
}, _ui.CloseDialog));
}
private async Task DeleteAsync()
{
if (IsMain) return;
var name = Name;
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Project.DeleteTitle", name),
Message = Loc.L("Editor.Project.DeleteMessage"),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"),
ActionText = Loc.L("Editor.Project.DeleteAction"),
ActionToolTip = Loc.L("Tooltips.Editor.Project.DeleteAction"),
IsDestructive = true,
}))
return;
try
{
// Everything sent first, while the project is still open: a delete that cannot happen leaves it as it was.
await SaveAndSendAsync();
var (sequenceId, projectId) = (SequenceId, ProjectId);
if (!await _ui.CloseProjectAsync()) return;
await _host.DeleteProjectAsync(projectId);
_ui.Notify(Loc.L("Editor.Workspace.Deleted", name));
await _ui.SequenceChangedAsync(sequenceId);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} was not deleted", ex);
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
private async Task OpenRemoveCopyAsync()
{
try
{
await StoreEditAsync();
var plan = await _host.PlanRemovalAsync(ProjectId);
var projectId = ProjectId;
_ui.ShowDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveAsync(projectId, discard), async () =>
{
await SaveAndSendAsync();
await RemoveAsync(projectId, discard: false);
}, _ui.CloseDialog));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The removal of project {ProjectId} could not be planned", ex);
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
/// <summary>The working state saved as a version and everything sent, for Send first.</summary>
/// <exception cref="WorkspaceException">Something could not be sent.</exception>
private async Task SaveAndSendAsync()
{
await StoreEditAsync();
if (CanSaveVersion) await _host.CommitAsync(ProjectId);
var result = await _host.SyncAsync(ProjectId);
Apply(result.Status);
await TakeAsync(result);
if (result.Status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
private async Task RemoveAsync(Guid projectId, bool discard)
{
// Checked before the editor closes, so a copy that cannot go leaves it open.
if (!discard)
{
var status = await _host.StatusAsync(projectId, askHome: false);
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
var name = Name;
if (!await _ui.CloseProjectAsync()) return;
await _host.RemoveLocalCopyAsync(projectId, discard);
_ui.Notify(Loc.L("Editor.Workspace.Removed"), name);
}
private async Task<IReadOnlyList<string>> OtherNamesAsync(Guid? except)
{
try
{
return [.. (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != except).Select(p => p.Name)];
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The home checks the name again when the project is made.
Log.Info("workspace", $"The projects of sequence {SequenceId} could not be listed: {ex.Message}");
return [];
}
}
private async Task UpdateMediaAsync()
{
try
{
await StoreEditAsync();
var job = await _host.QueueCopyAsync(ProjectId);
_copyJob = job.Id;
RaiseState();
_ui.Notify(Loc.L("Editor.Workspace.Copying"), _session.Content.Sequence.DisplayTitle);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The media of project {ProjectId} could not be copied again", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
/// <summary>The editor's last edit stored in the working state before an operation reads it.</summary>
/// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception>
private async Task StoreEditAsync()
{
if (await _session.FlushAsync()) return;
throw new WorkspaceException(Loc.L("Errors.Workspace.EditNotStored"), _session.LastSaveError);
}
/// <summary>What a sync, resolve or restore took from the home comes into the editor, merged with what was edited meanwhile.</summary>
private async Task TakeAsync(WorkspaceSyncResult result, bool force = false)
{
if (force || result.Pulled.Count > 0) await _session.ReloadAsync();
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
private void AskConflict(WorkspaceConflict conflict)
{
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
_ui.ShowDialog(new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, ResolveAsync, _ui.CloseDialog));
}
/// <summary>A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread.</summary>
private void OnJobChanged(Job job)
{
if (job.Id != _copyJob || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
if (_context is { } context) context.Post(_ => _ = CopyEndedAsync(job), null);
else _ = CopyEndedAsync(job);
}
/// <summary>The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not.</summary>
private async Task CopyEndedAsync(Job job)
{
if (_disposed || job.Id != _copyJob) return;
_copyJob = Guid.Empty;
if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true);
try
{
if (job.State == JobState.Done) await _session.ReloadAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The new media of project {ProjectId} could not be read", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
}
await RefreshAsync();
RaiseState();
}
private void Apply(WorkspaceStatus status)
{
_status = status;
RaiseState();
}
private void SetSyncing(bool syncing)
{
_isSyncing = syncing;
_sync.RaiseCanExecuteChanged();
RaiseState();
}
private void RaiseState()
{
OnPropertyChanged(nameof(Status));
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(IsMain));
OnPropertyChanged(nameof(IsSyncing));
OnPropertyChanged(nameof(StateText));
OnPropertyChanged(nameof(StateKind));
OnPropertyChanged(nameof(StateToolTip));
OnPropertyChanged(nameof(MenuToolTip));
OnPropertyChanged(nameof(MenuName));
OnPropertyChanged(nameof(HasMediaUpdate));
OnPropertyChanged(nameof(IsUpdatingMedia));
OnPropertyChanged(nameof(MediaUpdateText));
OnPropertyChanged(nameof(CanSaveVersion));
OnPropertyChanged(nameof(SaveVersionToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
}
@@ -0,0 +1,502 @@
using System.Collections.ObjectModel;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>What "Open in workspace" chose: an existing project of the home (<see cref="ProjectId"/>) or a new one (<see cref="NewName"/>), and the media.</summary>
public sealed record OpenChoice(Guid? ProjectId, string? NewName, string Media);
/// <summary>A project of the home offered by "Open in workspace" (Main in the UI language).</summary>
public sealed record ProjectOption(SequenceProject Project)
{
public string Label => WorkspaceText.ProjectName(Project.Name, Project.IsMain);
public override string ToString() => Label;
}
/// <summary>Project names as the home takes them: 1 to 60 characters, no control character, each once per sequence (case does not count).</summary>
public static class ProjectNames
{
/// <summary>The problem of <paramref name="name"/>, or null when the home takes it.</summary>
public static string? Validate(string name, IEnumerable<string> others)
{
var trimmed = name?.Trim() ?? string.Empty;
if (trimmed.Length is 0 or > ProjectService.MaxNameLength || trimmed.Any(char.IsControl)) return Loc.L("Errors.Workspace.InvalidName");
return others.Any(o => string.Equals(o, trimmed, StringComparison.OrdinalIgnoreCase)) ? Loc.L("Errors.Workspace.NameTaken") : null;
}
}
/// <summary>
/// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet: which project of
/// its home (Main, made from the sequence's settings as they are, or another) or a new one with its name, and the media
/// to copy (proxies; the originals come in phase 5c). Open queues the copy; the sequence opens once it is done.
/// </summary>
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
private readonly TaskCompletionSource<OpenChoice?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
private ProjectOption? _selected;
private bool _isNew;
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close)
: base(close)
{
SequenceTitle = sequenceTitle;
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p))];
_selected = Projects.FirstOrDefault();
_isNew = Projects.Count == 0;
NewName = new EditableField(string.Empty, n => ProjectNames.Validate(n, projects.Select(p => p.Name)), _ => { }, () => Loc.L("Tooltips.Editor.OpenWorkspace.Name"));
NewName.PropertyChanged += (_, _) => Refresh();
OpenCommand = new RelayCommand(Open, () => CanOpen);
}
/// <summary>Completes with the user's choice, or null when the dialog was closed without one.</summary>
public Task<OpenChoice?> Choice => _choice.Task;
public string SequenceTitle { get; }
public string Heading => Loc.L("Editor.OpenWorkspace.Title");
public IReadOnlyList<ProjectOption> Projects { get; }
public bool HasProjects => Projects.Count > 0;
public ProjectOption? SelectedProject
{
get => _selected;
set
{
if (Set(ref _selected, value) && value is not null) IsExisting = true;
}
}
/// <summary>A project the home has.</summary>
public bool IsExisting
{
get => !_isNew;
set
{
if (value) IsNew = false;
}
}
/// <summary>A new project, named in <see cref="NewName"/>.</summary>
public bool IsNew
{
get => _isNew;
set
{
if (!Set(ref _isNew, value || !HasProjects)) return;
OnPropertyChanged(nameof(IsExisting));
Refresh();
}
}
public EditableField NewName { get; }
/// <summary>The proxies, the only media this phase copies.</summary>
public bool IsProxies => true;
/// <summary>The originals: offered from phase 5c, to render on this PC.</summary>
public bool CanCopyOriginals => false;
public ICommand OpenCommand { get; }
public bool CanOpen => _isNew ? !NewName.HasErrors : _selected is not null;
public string OpenToolTip => _isNew && NewName.Error is { } error ? error : Loc.L("Tooltips.Editor.OpenWorkspace.Open");
public override void Dispose()
{
// Closed without a choice (Cancel, Esc, another sequence asked for).
_choice.TrySetResult(null);
base.Dispose();
}
private void Open()
{
if (!CanOpen) return;
_choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), BundleMedia.Proxies) : new OpenChoice(_selected!.Project.Id, null, BundleMedia.Proxies));
Close();
}
private void Refresh()
{
OnPropertyChanged(nameof(CanOpen));
OnPropertyChanged(nameof(OpenToolTip));
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>Names a project: "New project" (made from the open project's last version at the home) or "Rename".</summary>
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<string, Task> _save;
/// <param name="others">The names of the sequence's other projects (each name is used once).</param>
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close)
: base(close)
{
IsRename = rename;
_save = save;
var taken = others.ToList();
Name = new EditableField(name, n => ProjectNames.Validate(n, taken), _ => { }, () => Loc.L("Tooltips.Editor.ProjectName.Name"));
Name.PropertyChanged += (_, _) =>
{
OnPropertyChanged(nameof(SaveToolTip));
CommandManager.InvalidateRequerySuggested();
};
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy && !Name.HasErrors);
}
public bool IsRename { get; }
public string Heading => Loc.L(IsRename ? "Editor.ProjectName.Rename" : "Editor.ProjectName.New");
public string SaveText => Loc.L(IsRename ? "Editor.ProjectName.Apply" : "Editor.ProjectName.Create");
public EditableField Name { get; }
public ICommand SaveCommand { get; }
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create");
private async Task SaveAsync()
{
ClearError();
IsBusy = true;
try
{
await _save(Name.Text.Trim());
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Naming a project failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
finally
{
IsBusy = false;
}
}
}
/// <summary>"Save version" (Ctrl+S): an optional note, then the version is saved (and sent when Sync automatically is on).</summary>
public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
{
/// <summary>A note is a line of the history: longer text is cut there.</summary>
public const int MaxNoteLength = 200;
private readonly Func<string?, Task> _save;
private string _note = string.Empty;
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close)
: base(close)
{
ProjectName = projectName;
_save = save;
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy);
}
public string ProjectName { get; }
public string Heading => Loc.L("Editor.SaveVersion.Title", ProjectName);
public string Note
{
get => _note;
set => Set(ref _note, (value ?? string.Empty).Length > MaxNoteLength ? value![..MaxNoteLength] : value ?? string.Empty);
}
public ICommand SaveCommand { get; }
private async Task SaveAsync()
{
ClearError();
IsBusy = true;
try
{
await _save(string.IsNullOrWhiteSpace(_note) ? null : _note.Trim());
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Saving a version failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
finally
{
IsBusy = false;
}
}
}
/// <summary>A version in the History flyout: number, author, time, note, what made it, and Compare and Restore.</summary>
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore) : ObservableObject
{
public ProjectVersion Version { get; } = version;
public string Number => Formatting.Count(Version.Number);
public string Author => WorkspaceText.Author(Version);
public string When => WorkspaceText.When(Version.CreatedAt);
public string Note => Version.Note ?? string.Empty;
public string KindText => WorkspaceText.VersionKind(Version.Kind);
/// <summary>Saved here, waiting to be sent.</summary>
public bool IsUnsent { get; } = unsent;
/// <summary>The version the working state was last saved as (nothing differs).</summary>
public bool IsCurrent { get; } = isCurrent;
/// <summary>"Version 3 · Saved · STUDIO-PC · 28/10/2026 18:02 · note": the row for screen readers and its tooltip.</summary>
public string Description => string.Join(Loc.Separator, new[] { Loc.L("Editor.History.Version", Number), KindText, Author, When, Note }.Where(s => s.Length > 0));
public ICommand CompareCommand { get; } = compare;
public ICommand RestoreCommand { get; } = restore;
public string CompareToolTip => Loc.L("Tooltips.Editor.History.Compare", Number);
public string RestoreToolTip => Loc.L("Tooltips.Editor.History.Restore", Number);
}
/// <summary>
/// The History flyout of a workspace project: its versions newest first (those not sent yet marked), Compare (the
/// settings that differ from the project now) and Restore (the version as the project again, one undo step).
/// </summary>
public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ProjectVersion, Task<IReadOnlyList<string>>> _compare;
private readonly Func<ProjectVersion, Task> _restore;
private string? _comparedTitle;
private IReadOnlyList<string> _compared = [];
private bool _isLoaded;
public HistoryDialogViewModel(string projectName, Func<ProjectVersion, Task<IReadOnlyList<string>>> compare, Func<ProjectVersion, Task> restore,
Action<ArchiveDialogViewModel> close)
: base(close)
{
ProjectName = projectName;
_compare = compare;
_restore = restore;
}
public string ProjectName { get; }
public string Heading => Loc.L("Editor.History.Title", ProjectName);
public ObservableCollection<HistoryRowViewModel> Rows { get; } = [];
/// <summary>The home could not be asked: only this PC's versions are listed.</summary>
public bool IsOffline { get; private set; }
public bool IsEmpty => _isLoaded && Rows.Count == 0;
/// <summary>"Version 3 → now" over the comparison; null before one.</summary>
public string? ComparedTitle { get => _comparedTitle; private set => Set(ref _comparedTitle, value); }
public IReadOnlyList<string> Compared { get => _compared; private set => Set(ref _compared, value); }
/// <summary>Lists <paramref name="history"/>; <paramref name="currentHash"/> marks the version the project is now.</summary>
public void Show(WorkspaceHistory history, string? currentHash)
{
ArgumentNullException.ThrowIfNull(history);
Rows.Clear();
foreach (var version in history.Versions)
{
var current = currentHash is not null && string.Equals(version.ContentHash, currentHash, StringComparison.OrdinalIgnoreCase);
Rows.Add(new HistoryRowViewModel(version, history.Unsent.Contains(version.Id), current,
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy)));
}
IsOffline = history.Offline;
_isLoaded = true;
OnPropertyChanged(nameof(IsOffline));
OnPropertyChanged(nameof(IsEmpty));
}
/// <summary>A failure of the read that lists the versions, shown in the flyout.</summary>
public void ShowFailure(Exception ex)
{
ArgumentNullException.ThrowIfNull(ex);
_isLoaded = true;
OnPropertyChanged(nameof(IsEmpty));
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
public async Task CompareAsync(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
ClearError();
try
{
var lines = await _compare(version);
ComparedTitle = Loc.L("Editor.History.Compared", Formatting.Count(version.Number));
Compared = lines.Count == 0 ? [Loc.L("Editor.History.Same")] : lines;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be compared", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
}
}
public async Task RestoreAsync(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
ClearError();
IsBusy = true;
try
{
await _restore(version);
IsBusy = false;
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be restored", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
}
}
}
/// <summary>
/// A sync that met settings both sides changed (owner review 2, R8: asked only on real conflicts): what differs, then
/// Keep mine, Take the library's, or Save both (this workspace's versions go to a sibling project). Later leaves the
/// conflict for the next Sync; editing goes on meanwhile.
/// </summary>
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ConflictChoice, Task> _resolve;
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
Action<ArchiveDialogViewModel> close)
: base(close)
{
ProjectName = projectName;
SiblingName = siblingName;
Differences = differences;
_resolve = resolve;
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy);
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy);
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
}
public string ProjectName { get; }
/// <summary>The project Save both makes for this workspace's versions.</summary>
public string SiblingName { get; }
public string Heading => Loc.L("Editor.Workspace.Conflict.Title");
public string Message => Loc.L("Editor.Workspace.Conflict.Message", ProjectName);
public IReadOnlyList<string> Differences { get; }
public ICommand KeepMineCommand { get; }
public ICommand TakeHomeCommand { get; }
public ICommand SaveBothCommand { get; }
public string SaveBothToolTip => Loc.L("Tooltips.Editor.Workspace.SaveBoth", SiblingName);
private async Task ResolveAsync(ConflictChoice choice)
{
ClearError();
IsBusy = true;
try
{
await _resolve(choice);
IsBusy = false;
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The conflict of '{ProjectName}' could not be settled ({choice})", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
}
}
}
/// <summary>
/// "Remove local copy": the plan (files and size of the copy; versions not sent and changes not saved), then Remove
/// (only when everything is at the library), Send first (sends, then removes), or Discard changes (removes; the unsent
/// work is kept aside in the workspace's trash).
/// </summary>
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<bool, Task> _remove;
private readonly Func<Task> _sendFirst;
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Action<ArchiveDialogViewModel> close)
: base(close)
{
Plan = plan;
_remove = remove;
_sendFirst = sendFirst;
Facts =
[
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
new DialogFact(Loc.L("Editor.RemoveCopy.Size"), Formatting.Bytes(plan.Bytes)),
new DialogFact(Loc.L("Editor.RemoveCopy.Unsent"), Formatting.Count(plan.Unsent)),
new DialogFact(Loc.L("Editor.RemoveCopy.Changed"), Loc.L(plan.Modified ? "Editor.RemoveCopy.Yes" : "Editor.RemoveCopy.No")),
];
RemoveCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(false)), () => !IsBusy && plan.IsSafe && !plan.Offline);
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline);
DiscardCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(true)), () => !IsBusy && !plan.IsSafe);
}
public WorkspaceRemovalPlan Plan { get; }
public string Heading => Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false));
public IReadOnlyList<DialogFact> Facts { get; }
public bool HasUnsent => !Plan.IsSafe;
public ICommand RemoveCommand { get; }
public ICommand SendFirstCommand { get; }
public ICommand DiscardCommand { get; }
public string RemoveToolTip => Plan.IsSafe ? Plan.Offline ? Loc.L("Errors.Workspace.Offline") : Loc.L("Tooltips.Editor.RemoveCopy.Remove") : Loc.L("Errors.Workspace.Unsent");
public string SendFirstToolTip => Plan.Conflict ? Loc.L("Errors.Workspace.Conflict") : Plan.Offline ? Loc.L("Errors.Workspace.Offline") : Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
public string DiscardToolTip => Loc.L("Tooltips.Editor.RemoveCopy.Discard");
private async Task RunAsync(Func<Task> action)
{
ClearError();
IsBusy = true;
try
{
await action();
IsBusy = false;
Close();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The local copy of project {Plan.ProjectId} was not removed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
}
}
}
@@ -0,0 +1,254 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:ar="clr-namespace:Chronos.App.Archiving"
xmlns:ws="clr-namespace:Chronos.App.Workspace"
xmlns:infra="clr-namespace:Chronos.App.Infrastructure">
<!-- The in-window dialogs of Edit's workspace (owner review 2, R8), with the dialog kit of the Archive screen. -->
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- A history row: focusable for the arrow keys; screen readers hear the version, what made it, who, when and the note. -->
<Style x:Key="ListBoxItem.History" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding Description}" />
<Setter Property="ToolTip" Value="{Binding Description}" />
</Style>
<!-- Open in workspace: which project of the sequence's home, or a new one, and the media to copy. -->
<DataTemplate DataType="{x:Type ws:OpenInWorkspaceDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Text="{Binding SequenceTitle}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" TextTrimming="CharacterEllipsis" ToolTip="{Binding SequenceTitle}" />
<Grid Margin="0,16,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Editor.OpenWorkspace.Project}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<RadioButton Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.Existing}" IsChecked="{Binding IsExisting}" IsEnabled="{Binding HasProjects}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Existing}" VerticalAlignment="Center" Margin="0,0,12,0" />
<ComboBox Grid.Column="2" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label" IsEnabled="{Binding HasProjects}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Projects}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
<RadioButton Grid.Row="1" Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.New}" IsChecked="{Binding IsNew}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.New}" VerticalAlignment="Center" Margin="0,8,12,0" />
<TextBox Grid.Row="1" Grid.Column="2" Margin="0,8,0,0" Text="{Binding NewName.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
IsEnabled="{Binding IsNew}" ToolTip="{Binding NewName.ToolTip}" MaxLength="60" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.New}" />
<TextBlock Grid.Row="2" Text="{l:Loc Editor.OpenWorkspace.Media}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,14,0,0" />
<StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,14,0,0">
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies, Mode=OneWay}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Proxies}" Margin="0,0,16,0" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="False"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" />
</StackPanel>
</Grid>
<DockPanel Margin="0,20,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.OpenWorkspace.Open}" Command="{Binding OpenCommand}"
ToolTip="{Binding OpenToolTip}" ToolTipService.ShowOnDisabled="True" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- New project and Rename: the name, checked as it is typed. -->
<DataTemplate DataType="{x:Type ws:ProjectNameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Editor.ProjectName.Name}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Name.ToolTip}"
MaxLength="60" AutomationProperties.Name="{l:Loc Editor.ProjectName.Name}" />
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{Binding SaveText}" Command="{Binding SaveCommand}" ToolTip="{Binding SaveToolTip}"
ToolTipService.ShowOnDisabled="True" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- Save version (Ctrl+S): an optional note; Enter saves. -->
<DataTemplate DataType="{x:Type ws:SaveVersionDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Editor.SaveVersion.Note}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding Note, UpdateSourceTrigger=PropertyChanged}" ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Note}" MaxLength="200"
AutomationProperties.Name="{l:Loc Editor.SaveVersion.Note}" />
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.SaveVersion.Save}" Command="{Binding SaveCommand}"
ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Save}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- History: a flyout under the title, newest first; Compare shows what differs from now below the list, Restore brings a version back. -->
<DataTemplate DataType="{x:Type ws:HistoryDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="620" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="40,40,0,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DockPanel>
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{l:Loc Editor.History.Offline}" ToolTip="{l:Loc Tooltips.Editor.History.Offline}" FontSize="12"
VerticalAlignment="Center" Visibility="{Binding IsOffline, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
</DockPanel>
<Grid Grid.Row="1" Margin="0,12,0,0" MinHeight="120">
<ListBox ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.History}" Grid.IsSharedSizeScope="True"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" AutomationProperties.Name="{l:Loc Editor.History.List}" KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ws:HistoryRowViewModel}">
<Grid Height="36">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="36" SharedSizeGroup="HistoryNumber" />
<ColumnDefinition Width="Auto" SharedSizeGroup="HistoryKind" />
<ColumnDefinition Width="Auto" MaxWidth="160" SharedSizeGroup="HistoryAuthor" />
<ColumnDefinition Width="Auto" SharedSizeGroup="HistoryWhen" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.CellNumber}" Text="{Binding Number}" FontWeight="SemiBold" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding KindText}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Author}" Margin="12,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding When}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
Typography.NumeralAlignment="Tabular" />
<DockPanel Grid.Column="4" Margin="12,0,0,0">
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{l:Loc Tooltips.Editor.History.NotSent}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsUnsent, Converter={StaticResource BoolToVisibility}}" />
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Done" Text="{l:Loc Editor.History.Current}" ToolTip="{l:Loc Tooltips.Editor.History.Current}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsCurrent, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Note}" />
</DockPanel>
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Content="{l:Loc Editor.History.Compare}" Command="{Binding CompareCommand}"
ToolTip="{Binding CompareToolTip}" Margin="12,0,0,0" />
<Button Grid.Column="6" Style="{StaticResource Button.Row}" Content="{l:Loc Editor.History.Restore}" Command="{Binding RestoreCommand}"
ToolTip="{Binding RestoreToolTip}" Margin="8,0,0,0" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Style="{StaticResource Text.Secondary}" Text="{l:Loc Editor.History.Empty}" HorizontalAlignment="Center" VerticalAlignment="Center"
Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<!-- What differs between now and the version compared. -->
<Border Grid.Row="2" Style="{StaticResource Border.Card}" Margin="0,12,0,0" Padding="12,10" MaxHeight="160"
Visibility="{Binding ComparedTitle, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{Binding ComparedTitle}" FontWeight="SemiBold" infra:LiveRegion.Text="{Binding ComparedTitle}"
AutomationProperties.LiveSetting="Polite" />
<ScrollViewer Margin="0,6,0,0" VerticalScrollBarVisibility="Auto" Focusable="False">
<ItemsControl ItemsSource="{Binding Compared}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" TextWrapping="Wrap" Margin="0,0,0,4" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</DockPanel>
</Border>
<DockPanel Grid.Row="3" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Editor.History.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" IsDefault="True"
MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's, Save both, or Later. -->
<DataTemplate DataType="{x:Type ws:ConflictDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="560">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" TextTrimming="None" />
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<Border Style="{StaticResource Border.Card}" Margin="0,14,0,0" Padding="12,10" ToolTip="{l:Loc Tooltips.Editor.Workspace.Differences}">
<ItemsControl ItemsSource="{Binding Differences}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" TextWrapping="Wrap" Margin="0,0,0,4" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<WrapPanel HorizontalAlignment="Right" Margin="0,20,0,0">
<Button Content="{l:Loc Editor.Workspace.Conflict.Later}" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.Later}" IsCancel="True"
MinWidth="96" Margin="0,0,8,8" />
<Button Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}" MinWidth="96" Margin="0,0,8,8" />
<Button Content="{l:Loc Editor.Workspace.Conflict.TakeHome}" Command="{Binding TakeHomeCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.TakeHome}"
MinWidth="96" Margin="0,0,8,8" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.KeepMine}" Command="{Binding KeepMineCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="True" MinWidth="96" Margin="0,0,0,8" />
</WrapPanel>
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" HorizontalAlignment="Right" />
</StackPanel>
</Border>
</DataTemplate>
<!-- Remove local copy: the plan, then Remove (all at the library), Send first, or Discard changes. -->
<DataTemplate DataType="{x:Type ws:RemoveCopyDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Text="{l:Loc Editor.RemoveCopy.Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<ItemsControl ItemsSource="{Binding Facts}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="FactLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
<TextBlock Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" Typography.NumeralAlignment="Tabular" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<WrapPanel HorizontalAlignment="Right" Margin="0,18,0,0">
<Button Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" IsDefault="True" MinWidth="96"
Margin="0,0,8,8" />
<Button Style="{StaticResource Button.Destructive}" Content="{l:Loc Editor.RemoveCopy.Discard}" Command="{Binding DiscardCommand}" ToolTip="{Binding DiscardToolTip}"
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,8,8" Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Editor.RemoveCopy.SendFirst}" Command="{Binding SendFirstCommand}" ToolTip="{Binding SendFirstToolTip}" ToolTipService.ShowOnDisabled="True"
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Destructive}" Content="{l:Loc Editor.RemoveCopy.Remove}" Command="{Binding RemoveCommand}" ToolTip="{Binding RemoveToolTip}"
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,0,8" />
</WrapPanel>
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" HorizontalAlignment="Right" />
</StackPanel>
</Border>
</DataTemplate>
</ResourceDictionary>
+640
View File
@@ -0,0 +1,640 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>A workspace operation was refused for a reason the user can act on; the message is one localized sentence.</summary>
public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner);
/// <summary>A project of this PC's workspace, as Edit's picker and the editor list it.</summary>
/// <param name="HasMedia">The workspace holds the project's media (a copy that ended); without them it cannot open.</param>
/// <param name="Saved">When its working state was last written.</param>
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
DateTimeOffset Saved);
/// <summary>A project brought into the workspace and the copy of its media that was queued.</summary>
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
/// <summary>What Save version did: the version (null when nothing changed), its sync when Sync automatically is on, where the project stands.</summary>
/// <param name="SyncError">Why the sync after it did not happen (the home out of reach, the project busy); the version waits here.</param>
public sealed record WorkspaceSaveResult(ProjectVersion? Version, WorkspaceSyncResult? Synced, WorkspaceStatus Status, Exception? SyncError);
/// <summary>A project's history as the History flyout lists it: newest first, the versions not sent yet on top.</summary>
/// <param name="Unsent">The ids among <paramref name="Versions"/> that wait to be sent to the home.</param>
/// <param name="Offline">The home could not be asked: only the versions this workspace keeps are listed.</param>
public sealed record WorkspaceHistory(IReadOnlyList<ProjectVersion> Versions, IReadOnlySet<Guid> Unsent, bool Offline);
/// <summary>
/// The plan of "Remove local copy": what the project's folder holds (files and bytes) and what would not be at the home
/// after it (versions not sent, changes not saved as a version, a conflict to settle).
/// </summary>
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline)
{
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
}
/// <summary>
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
/// <c>workspace</c> under the data folder: <c>%LOCALAPPDATA%\Chronos\workspace</c>, <c>.\data\workspace</c> for a portable
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and this PC's archive as the home of
/// its projects (<see cref="ArchiveProjectHome"/>; a server home comes in phase 5b). Every operation runs off the UI thread
/// and returns where the project stands. Nothing a workspace holds is lost: a version is sent before its copy goes, a copy
/// is removed only once the home verifiably holds its head, the work a user chose to discard is kept in
/// <c>&lt;workspace&gt;/.trash</c>, and versions the home holds are pruned past Settings › Workspace › Kept versions only
/// after the home was asked for each. A capture (sample data, no engine) has no workspace: Edit opens the library there.
/// </summary>
public sealed class WorkspaceHost
{
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
public const string TrashFolder = ".trash";
private readonly AppEnvironment _environment;
private readonly AppSettings _settings;
private readonly Action _savePreferences;
private readonly Func<ChronosDatabase?> _db;
private readonly Func<ArchiveService?> _archives;
private readonly Func<JobEngine?> _engine;
private readonly Lock _gate = new();
private readonly Dictionary<Guid, Guid> _copies = [];
private OpenWorkspace? _open;
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func<ChronosDatabase?> db, Func<ArchiveService?> archives,
Func<JobEngine?> engine)
{
_environment = environment;
_settings = settings;
_savePreferences = savePreferences;
_db = db;
_archives = archives;
_engine = engine;
}
/// <summary>The program and PC versions made here carry, as the archive's own versions do.</summary>
public static string ClientName { get; } = "Chronos on " + Environment.MachineName;
/// <summary>How long an operation waits for a project another writer holds (a copy job writing its media index).</summary>
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>The workspace folder of a data folder: <c>workspace</c> beside the index.</summary>
public static string DefaultRoot(AppEnvironment environment)
{
ArgumentNullException.ThrowIfNull(environment);
return Path.Combine(environment.DataDirectory, WorkspaceStore.DefaultFolderName);
}
/// <summary>The folder in use: Settings › Workspace › Folder, else <see cref="DefaultRoot"/>.</summary>
public string Root => _settings.WorkspaceFolder is { Length: > 0 } folder ? Path.GetFullPath(folder) : DefaultRoot(_environment);
/// <summary>Edit opens workspace projects (false in a capture, whose sample library has no engine to copy media).</summary>
public bool IsEnabled => !_environment.IsCapture;
/// <summary>The workspace can be used now: enabled, with the index and the archive engine open.</summary>
public bool IsAvailable => IsEnabled && _db() is not null && _archives() is not null;
public AppSettings Settings => _settings;
/// <summary>The sync over the workspace folder in use (made, with the folder and its manifest, at first use).</summary>
/// <exception cref="IOException">The folder cannot be made or read.</exception>
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
public WorkspaceSync Sync
{
get
{
var root = Root;
lock (_gate)
{
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
{
var store = new WorkspaceStore(root);
_open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
}
return open.Sync;
}
}
}
public WorkspaceStore Store => Sync.Store;
/// <summary>The home of a workspace project; null for a home this PC cannot reach in this phase (a server, phase 5b).</summary>
public IProjectHome? HomeOf(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
return home.IsArchive && _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
}
/// <summary>The home of a sequence of this PC's archive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public IProjectHome HomeOfSequence(Guid sequenceId) =>
HomeOf(new BundleHome(BundleHome.ArchiveKind, sequenceId)) ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
/// <summary>The projects of the workspace (one whose working state cannot be read is left out, and logged).</summary>
public Task<IReadOnlyList<WorkspaceEntry>> ListAsync(CancellationToken cancellationToken = default) =>
Task.Run(() => (IReadOnlyList<WorkspaceEntry>)[.. Store.ListBundles().Select(b => Entry(b.Project, b.Bundle))], cancellationToken);
/// <summary>The workspace projects of one sequence.</summary>
public async Task<IReadOnlyList<WorkspaceEntry>> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
[.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
/// <summary>A workspace project by id; null when the workspace has none (or it cannot be read).</summary>
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(() =>
{
if (Store.Find(projectId) is not { } project) return null;
try
{
return Entry(project, project.ReadBundle());
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
return null;
}
}, cancellationToken);
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var projects = await ProjectsOfAsync(sequenceId, cancellationToken).ConfigureAwait(false);
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var last) && projects.FirstOrDefault(p => p.ProjectId == last) is { } recent) return recent;
return projects.OrderByDescending(p => p.Saved).FirstOrDefault();
}
/// <summary>Remembers <paramref name="projectId"/> as the project of <paramref name="sequenceId"/> to open next time.</summary>
public void Remember(Guid sequenceId, Guid projectId)
{
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId) return;
_settings.WorkspaceRecent[sequenceId] = projectId;
_savePreferences();
}
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
}
/// <summary>
/// Brings a project of <paramref name="sequenceId"/> into the workspace and queues the copy of its media: the project
/// <paramref name="projectId"/>, else a new one named <paramref name="newName"/> (from Main's head), else Main. A
/// project already here keeps its working state; only its media are copied again.
/// </summary>
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The archive is offline or busy.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var checkout = await Task.Run(async () =>
{
SequenceProject project;
if (newName is not null)
{
project = await home.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
}
else
{
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
project = projectId is { } id
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
: listed.First(p => p.IsMain);
}
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
// Back on the caller's thread (the UI's): the settings are written there.
Remember(sequenceId, checkout.Project.Id);
return checkout;
}
/// <summary>
/// Queues the copy of a workspace project's media again ("Update media": the home's frames changed), unless one is
/// waiting or running already: that one is returned.
/// </summary>
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home.SequenceId, projectId, bundle.Workspace.Media.Kind, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached,
/// or that no longer has the project (deleted elsewhere), reads as offline.
/// </summary>
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var home = askHome ? HomeOf(project.ReadBundle().Workspace!.Home) : null;
try
{
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
{
Log.Info("workspace", $"The home of project {projectId} could not be asked: {ex.Message}");
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
return local with { Offline = true, State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Conflict ? local.State : WorkspaceState.Offline };
}
}, cancellationToken);
/// <summary>
/// "Save version": the working state as a new local version with <paramref name="note"/> (none when nothing changed
/// since the last), then, with Settings › Workspace › Sync automatically, the sync with the home
/// (<see cref="SyncAsync"/>); a home out of reach leaves the version waiting here.
/// </summary>
/// <exception cref="InvalidOperationException">The project is read-only, has a conflict to settle, or names frames the workspace has no media of.</exception>
public async Task<WorkspaceSaveResult> SaveVersionAsync(Guid projectId, string? note, CancellationToken cancellationToken = default)
{
var version = await Task.Run(async () =>
{
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
try
{
var synced = await SyncAsync(projectId, cancellationToken).ConfigureAwait(false);
return new WorkspaceSaveResult(version, synced, synced.Status, null);
}
catch (Exception ex) when (ex is HomeUnavailableException or LeaseUnavailableException or WorkspaceSyncException or WorkspaceException or ProjectException
or DatabaseException)
{
// The version is saved here all the same: it waits for the next sync.
Log.Info("workspace", $"Version of project {projectId} not sent yet: {ex.Message}");
return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), ex);
}
}
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// "Sync": the home's new versions taken (the working state and the local versions moved onto them), then the local
/// versions sent in order, then the versions past Kept versions pruned. A real conflict stops it before anything is
/// sent (<see cref="WorkspaceState.Conflict"/>).
/// </summary>
/// <exception cref="HomeUnavailableException">The home cannot be reached; nothing was lost.</exception>
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var home = HomeOfProject(projectId);
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
if (pulled.Status.State == WorkspaceState.Conflict) return pulled;
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
}, cancellationToken);
/// <summary>
/// Settles the conflict a sync stopped at, then sends what waits. <see cref="ConflictChoice.SaveBoth"/> sends this
/// workspace's versions to a sibling project named "&lt;name&gt; (&lt;this PC&gt;)" (a number added when that name is taken).
/// </summary>
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var home = HomeOfProject(projectId);
WorkspaceSyncResult resolved;
if (choice == ConflictChoice.SaveBoth)
{
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
try
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, cancellationToken).ConfigureAwait(false);
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, cancellationToken).ConfigureAwait(false);
}
}
else
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, cancellationToken).ConfigureAwait(false);
}
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
if (resolved.Status.State == WorkspaceState.Conflict) return resolved;
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs);
}, cancellationToken);
/// <summary>"<paramref name="name"/> (<c>PC</c>)", within the 60 characters of a project name.</summary>
public static string SiblingName(string name)
{
ArgumentNullException.ThrowIfNull(name);
var suffix = " (" + Environment.MachineName + ")";
if (suffix.Length >= ProjectService.MaxNameLength) suffix = suffix[..(ProjectService.MaxNameLength / 2)] + ")";
var room = ProjectService.MaxNameLength - suffix.Length;
return (name.Length > room ? name[..room].TrimEnd() : name) + suffix;
}
/// <summary>
/// Brings version <paramref name="versionId"/> back as the working state (uncommitted changes saved as a version first);
/// returns it, its positions on the media's frames.
/// </summary>
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
return restored;
}, cancellationToken);
/// <summary>The project's history, newest first: the versions not sent yet, then the home's (this workspace's own while the home is out of reach).</summary>
public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var unsent = Sync.Unpushed(projectId);
var home = HomeOf(project.ReadBundle().Workspace!.Home);
IReadOnlyList<ProjectVersion> stored;
var offline = false;
try
{
stored = home is null
? throw new HomeUnavailableException("The project's home cannot be reached from this PC.")
: await home.HistoryAsync(projectId, null, limit, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
Log.Info("workspace", $"The history of project {projectId} is read from the workspace: {ex.Message}");
offline = true;
stored = [.. project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).Take(limit)];
}
var ids = unsent.Select(v => v.Id).ToHashSet();
return new WorkspaceHistory([.. unsent.Reverse(), .. stored.Where(v => !ids.Contains(v.Id))], ids, offline);
}, cancellationToken);
/// <summary>A new project of the sequence named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version the home holds), else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(async () =>
{
var created = await home.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {sequenceId}");
return created;
}, cancellationToken);
}
/// <summary>Renames a project at its home, then its working state here.</summary>
/// <exception cref="ProjectException">The name is invalid or taken, or the project is gone.</exception>
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var renamed = await ArchiveProjects(project).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var bundle = project.ReadBundle();
project.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Name = renamed.Name } });
}
Log.Info("workspace", $"Project {projectId} renamed '{renamed.Name}'");
return renamed.Name;
}, cancellationToken);
/// <summary>
/// Deletes a project (never Main): the working state saved and sent first, so its home's trash
/// (<c>.chronos/projects/.trash</c>) holds every version; then the local copy goes.
/// </summary>
/// <exception cref="WorkspaceException">Something could not be sent (the home out of reach, a conflict): nothing was deleted.</exception>
/// <exception cref="ProjectException">Main, or the project is gone.</exception>
public async Task DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var sequenceId = await Task.Run(async () =>
{
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
var home = HomeOfProject(projectId);
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.Ahead > 0 || status.Conflict is not null || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
return workspace.Home.SequenceId;
}, cancellationToken);
Forget(sequenceId, projectId);
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
public Task<WorkspaceRemovalPlan> PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var name = project.ReadBundle().Workspace!.Name;
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
var (files, bytes) = Measure(project.Folder);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead, status.Modified, status.Conflict is not null, status.Offline);
}, cancellationToken);
/// <summary>
/// Removes a project's local copy. Without <paramref name="discard"/> it is refused while anything is not at the home,
/// and the home's head and the base this copy was made from are read back and checked against their hashes first.
/// With <paramref name="discard"/> (the user's explicit word) the versions not sent and the working state are moved to
/// <c>&lt;workspace&gt;/.trash</c> rather than erased. The media (copies the home can make again) are deleted.
/// </summary>
/// <exception cref="WorkspaceException">Something is not at the home yet, or the home's copy does not check out.</exception>
public async Task RemoveLocalCopyAsync(Guid projectId, bool discard, CancellationToken cancellationToken = default)
{
var sequenceId = await Task.Run(async () =>
{
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (!discard)
{
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Local copy of project {projectId} ('{workspace.Name}') removed{(discard ? ", its unsent work kept in " + TrashFolder : string.Empty)}");
return workspace.Home.SequenceId;
}, cancellationToken);
Forget(sequenceId, projectId);
}
/// <summary>
/// Drops the oldest versions this workspace took from the home, keeping Settings › Workspace › Kept versions of them
/// (the base among them), the versions not sent and the set-aside ones; a version goes only once the home was asked
/// and holds it with the same content.
/// </summary>
public async Task<int> PruneAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
var project = Existing(projectId);
var keep = Math.Max(1, _settings.WorkspaceKeptVersions);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var basis = project.ReadBundle().Workspace!.Base;
var stored = project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).ToList();
var kept = stored.Where(v => v.Id != basis?.VersionId).Take(keep - (basis is null ? 0 : 1)).Select(v => v.Id).ToHashSet();
var removed = 0;
foreach (var version in stored.Where(v => v.Id != basis?.VersionId && !kept.Contains(v.Id)))
{
if (await home.GetVersionAsync(projectId, version.Id, cancellationToken).ConfigureAwait(false) is not { } atHome
|| !string.Equals(atHome.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase)
|| !ProjectContent.Verifies(atHome.SettingsJson, atHome.ContentHash))
continue;
File.Delete(project.VersionPath(version));
removed++;
}
return removed;
}
}
private async Task PruneQuietlyAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
try
{
var removed = await PruneAsync(projectId, home, cancellationToken).ConfigureAwait(false);
if (removed > 0) Log.Info("workspace", $"{removed} older version(s) of project {projectId} dropped from the workspace (kept at the home)");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ProjectException)
{
Log.Warning("workspace", $"Older versions of project {projectId} could not be pruned", ex);
}
}
/// <summary>The local versions sent (after the home's new ones were taken), as one sync without the pruning.</summary>
private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return pulled.Status.State == WorkspaceState.Conflict ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
private async Task VerifyHomeAsync(Guid projectId, BundleWorkspace workspace, CancellationToken cancellationToken)
{
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
ProjectVersion head;
ProjectVersion? basis;
try
{
head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
basis = workspace.Base is { } b ? await home.GetVersionAsync(projectId, b.VersionId, cancellationToken).ConfigureAwait(false) : head;
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
}
if (!ProjectContent.Verifies(head.SettingsJson, head.ContentHash) || basis is null || !ProjectContent.Verifies(basis.SettingsJson, basis.ContentHash)
|| (workspace.Base is { } known && !string.Equals(known.ContentHash, basis.ContentHash, StringComparison.OrdinalIgnoreCase)))
throw new WorkspaceException(Loc.L("Errors.Workspace.HomeCheck"));
}
/// <summary>
/// The project's folder taken out of the workspace under its lease: the working state, the versions, the sync state and
/// the exports moved to <c>.trash/&lt;id&gt;-&lt;time&gt;</c> (kept: nothing a user made is erased), the media deleted; the
/// emptied folder goes once the lease is released.
/// </summary>
private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
// A copy of its media still under way would write them again behind the removal.
Guid copy;
lock (_gate) _copies.Remove(project.ProjectId, out copy);
if (copy != Guid.Empty && _engine() is { } engine && _db() is { } db && await db.Jobs.GetAsync(copy, cancellationToken).ConfigureAwait(false) is
{ State: JobState.Queued or JobState.Running or JobState.Paused })
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
var aside = Path.Combine(Store.Root, TrashFolder, project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture));
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
Directory.CreateDirectory(aside);
// The working state first: without it the folder is no project any more, whatever happens after.
File.Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile));
if (File.Exists(project.SyncPath)) File.Move(project.SyncPath, Path.Combine(aside, WorkspaceProject.SyncFile));
if (Directory.Exists(project.VersionsDirectory)) Directory.Move(project.VersionsDirectory, Path.Combine(aside, WorkspaceProject.VersionsFolder));
if (Directory.Exists(project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(project.ExportsDirectory).Any())
Directory.Move(project.ExportsDirectory, Path.Combine(aside, WorkspaceProject.ExportsFolder));
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
}
try
{
Directory.Delete(project.Folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Info("workspace", $"The emptied folder {project.Folder} stays: {ex.Message}");
}
}
/// <summary>A version can be saved: no conflict waits, the settings are this Chronos's, the media are here.</summary>
/// <exception cref="WorkspaceException">Why not.</exception>
private static void EnsureWritable(WorkspaceStatus status)
{
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
}
private void Forget(Guid sequenceId, Guid projectId)
{
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
_settings.WorkspaceRecent.Remove(sequenceId);
_savePreferences();
}
private async Task<Job> QueueCopyCoreAsync(Guid sequenceId, Guid projectId, string media, CancellationToken cancellationToken)
{
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
Guid known;
lock (_gate) _copies.TryGetValue(projectId, out known);
if (known != Guid.Empty && await db.Jobs.GetAsync(known, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running } running) return running;
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var job = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, Store.Root, projectId, media), cancellationToken: cancellationToken).ConfigureAwait(false);
lock (_gate) _copies[projectId] = job.Id;
return job;
}
private IProjectHome HomeOfProject(Guid projectId) =>
HomeOf(Existing(projectId).ReadBundle().Workspace!.Home) ?? throw new HomeUnavailableException("The project's home cannot be reached from this PC.");
private ProjectService ArchiveProjects(WorkspaceProject project) =>
project.ReadBundle().Workspace!.Home.IsArchive && _archives() is { } archives ? archives.Projects : throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
{
var workspace = bundle.Workspace!;
return new WorkspaceEntry(project.ProjectId, workspace.Home.SequenceId, workspace.Name, workspace.IsMain, workspace.Home,
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
}
/// <summary>Files and bytes under <paramref name="folder"/>, the lease left out.</summary>
private static (int Files, long Bytes) Measure(string folder)
{
var (files, bytes) = (0, 0L);
if (!Directory.Exists(folder)) return (files, bytes);
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
{
if (file.Name.EndsWith(".lease", StringComparison.OrdinalIgnoreCase)) continue;
files++;
bytes += file.Length;
}
return (files, bytes);
}
private sealed record OpenWorkspace(string Root, WorkspaceSync Sync);
}
@@ -0,0 +1,56 @@
using Chronos.App.Library;
using Chronos.Core.Localization;
using Chronos.Data.Workspaces;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
/// where it stands, a chip read from its home after the list shows.
/// </summary>
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
{
private WorkspaceStatus? _status;
public WorkspaceEntry Entry { get; } = entry;
/// <summary>The sequence's row of the library, for its thumbnail; null when the index no longer has it.</summary>
public SequenceItem? Sequence { get; } = sequence;
public Guid ProjectId => Entry.ProjectId;
public Guid SequenceId => Entry.SequenceId;
/// <summary>The project's name (Main in the UI language).</summary>
public string Name => WorkspaceText.ProjectName(Entry.Name, Entry.IsMain);
public string SequenceTitle => Sequence?.Title ?? Entry.SequenceTitle;
public WorkspaceStatus? Status
{
get => _status;
set
{
if (!Set(ref _status, value)) return;
OnPropertyChanged(nameof(StateText));
OnPropertyChanged(nameof(StateKind));
OnPropertyChanged(nameof(StateToolTip));
OnPropertyChanged(nameof(Description));
}
}
public string StateText => Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
public StatusKind StateKind => Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
public string StateToolTip => Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
/// <summary>"Vertical social · Harbour sunset · In sync": what screen readers hear for the row.</summary>
public string Description => string.Join(Loc.Separator, Name, SequenceTitle, StateText);
public override string ToString() => Name;
internal void Refresh() => OnAllPropertiesChanged();
}
@@ -0,0 +1,83 @@
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Ui.Controls;
namespace Chronos.App.Workspace;
/// <summary>How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free.</summary>
public static class WorkspaceText
{
/// <summary>The project's name; the Main project in the UI language.</summary>
public static string ProjectName(string name, bool isMain) =>
isMain && string.Equals(name, ProjectService.MainName, StringComparison.Ordinal) ? Loc.L("Editor.Project.Main") : name;
/// <summary>The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs.</summary>
public static string State(WorkspaceStatus? status, bool syncing = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing") : status is null ? Loc.L("Editor.Workspace.State.Reading") : Loc.L("Editor.Workspace.State." + status.State);
public static StatusKind Kind(WorkspaceStatus? status, bool syncing = false) => syncing ? StatusKind.Running : status?.State switch
{
WorkspaceState.InSync => StatusKind.Synced,
WorkspaceState.Modified or WorkspaceState.Ahead => StatusKind.Queued,
WorkspaceState.Behind => StatusKind.Remote,
WorkspaceState.Conflict => StatusKind.Error,
WorkspaceState.Offline => StatusKind.Offline,
WorkspaceState.MediaRemoved => StatusKind.NoProxies,
_ => StatusKind.Queued,
};
/// <summary>What the state means and what to do, with the counts behind it.</summary>
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false) => syncing ? Loc.L("Tooltips.Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Tooltips.Editor.Workspace.State.Reading")
: status.State switch
{
WorkspaceState.Ahead => Loc.L("Tooltips.Editor.Workspace.State.Ahead", Formatting.Count(status.Ahead)),
WorkspaceState.Behind => Loc.L("Tooltips.Editor.Workspace.State.Behind", Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => Loc.L("Tooltips.Editor.Workspace.State.OfflineAhead", Formatting.Count(status.Ahead)),
var state => Loc.L("Tooltips.Editor.Workspace.State." + state),
};
/// <summary>"Saved", "Merged", "Restored", "Imported", "Outside change".</summary>
public static string VersionKind(ProjectVersionKind kind) => Loc.L("Editor.History.Kind." + kind);
/// <summary>Who made a version: its author, else the PC it was made on.</summary>
public static string Author(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
return version.Author ?? version.ClientName ?? string.Empty;
}
/// <summary>"28/10/2026 18:02".</summary>
public static string When(DateTimeOffset at) => $"{Formatting.Date(at)} {Formatting.TimeOfDay(at)}";
/// <summary>One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most <paramref name="max"/>.</summary>
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max) =>
SyncText.Differences(differences, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
/// <summary>One line per setting that differs between now and a version ("Deflicker window 41 now, 33 in that version").</summary>
public static IReadOnlyList<string> CompareLines(IEnumerable<SettingsDifference> differences, int max) =>
SyncText.Differences(differences, max, (label, now, then) => Loc.L("Editor.History.Difference", label, now, then));
/// <summary>Why a workspace operation stopped, as one localized sentence chosen by cause; the exception's own text goes to the log.</summary>
public static string Failure(Exception ex) => ex switch
{
WorkspaceException or LeaseUnavailableException => ex.Message,
HomeUnavailableException or ArchiveOfflineException => Loc.L("Errors.Workspace.Offline"),
ProjectException { Reason: ProjectError.NameTaken } => Loc.L("Errors.Workspace.NameTaken"),
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
ProjectException { Reason: ProjectError.MainCannotBeDeleted } => Loc.L("Errors.Workspace.MainKept"),
ProjectException => Loc.L("Errors.Workspace.ProjectGone"),
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
_ => ArchiveFailures.Cause(ex),
};
}