merge: review2-p5a-fix-desktop into phase 5a fix round 1 integration

# Conflicts:
#	src/Chronos.Data/Workspaces/WorkspaceSync.cs
This commit is contained in:
Alby96 committed 2026-11-03 10:40:02 +01:00
commit 1a35fcdb27
28 files changed
+1328 -139

No files matched your search

+195 -27
View File
@@ -17,8 +17,18 @@ namespace Chronos.App.Workspace;
/// <summary>What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project.</summary>
public interface IWorkspaceUi
{
/// <summary>The dialog open now; null when none is.</summary>
ArchiveDialogViewModel? Dialog { get; }
/// <summary>Shows <paramref name="dialog"/> now, in place of an open one (the dialog the user acted in leads to it).</summary>
void ShowDialog(ArchiveDialogViewModel dialog);
/// <summary>
/// Shows <paramref name="dialog"/> now when no dialog is open, else once the open one closes: something found in the
/// background (a conflict an automatic sync met) never replaces what the user is doing.
/// </summary>
void ShowDialogWhenFree(ArchiveDialogViewModel dialog);
void CloseDialog(ArchiveDialogViewModel dialog);
/// <summary>True when the user chose the action (a destructive confirmation).</summary>
@@ -37,15 +47,20 @@ public interface IWorkspaceUi
}
/// <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.
/// The project menu of the editor's title (▾, owner review 2, R8) for a workspace project: where it stands (the chip, read
/// again a moment after each edit), Save version (Ctrl+S, an optional note; sent at once with Settings › Workspace › Sync
/// automatically), Sync, History (Compare, Restore as one undo step), Open project (another project of the sequence, at
/// the library or here), New project, Rename, Delete project (never Main) and Remove local copy, and the "Update media"
/// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a
/// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A
/// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict
/// shown; one an automatic sync met waits for the dialog open to close. Call from the UI thread.
/// </summary>
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
/// <summary>How long after the last edit the chip reads the working state again (a little after the editor's save).</summary>
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
private readonly WorkspaceHost _host;
private readonly WorkspaceSequenceSource _source;
private readonly EditorSession _session;
@@ -61,6 +76,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private Guid _copyJob;
private bool _disposed;
/// <summary>Counts the editor's changes, so only the last one's state read applies.</summary>
private int _changes;
/// <summary>The conflict dialog asked in the background, until it is closed (one is asked at a time).</summary>
private ConflictDialogViewModel? _asking;
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
{
_host = host;
@@ -71,11 +92,13 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
_updateMedia = new AsyncRelayCommand(UpdateMediaAsync, () => _copyJob == Guid.Empty);
SaveVersionCommand = new RelayCommand(OpenSaveVersion, () => CanSaveVersion);
HistoryCommand = new AsyncRelayCommand(OpenHistoryAsync);
OpenProjectCommand = new AsyncRelayCommand(OpenOtherProjectAsync);
NewProjectCommand = new AsyncRelayCommand(OpenNewProjectAsync);
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
}
public Guid ProjectId => _source.ProjectId;
@@ -126,6 +149,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public ICommand HistoryCommand { get; }
/// <summary>Open project…: another project of the sequence, one of the library's (a Save both sibling, another PC's) or a new one.</summary>
public ICommand OpenProjectCommand { get; }
public ICommand NewProjectCommand { get; }
public ICommand RenameCommand { get; }
@@ -136,7 +162,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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>
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
public async Task RefreshAsync()
{
try
@@ -194,7 +220,10 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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>
/// <summary>
/// Sync: the home's new versions taken into the editor, the local ones sent; a conflict is asked about (once the open
/// dialog closes when <paramref name="quiet"/>: the sync ran in the background).
/// </summary>
public async Task SyncAsync(bool quiet = false)
{
if (_isSyncing) return;
@@ -206,7 +235,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (_disposed) return;
Apply(result.Status);
await TakeAsync(result);
if (result.Status.Conflict is { } conflict) AskConflict(conflict);
if (result.Status.Conflict is { } conflict) AskConflict(conflict, background: quiet);
else if (!quiet) _ui.Notify(Loc.L(result.Status.State == WorkspaceState.InSync ? "Editor.Workspace.InSync" : "Editor.Workspace.Synced"), Name);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
@@ -222,16 +251,39 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
}
}
/// <summary>Settles a conflict as chosen, then brings the settled working state into the editor.</summary>
public async Task ResolveAsync(ConflictChoice choice)
/// <summary>
/// Settles the conflict <paramref name="shown"/> listed (else the one recorded) as chosen, then brings the settled
/// working state into the editor: the library's values taken as one undo step (the toast's Undo, Ctrl+Z), what Save
/// both made offered by its toast. When what differs changed since it was shown, nothing is settled and it is asked again.
/// </summary>
public async Task ResolveAsync(ConflictChoice choice, WorkspaceConflict? shown = null)
{
await StoreEditAsync();
var result = await _host.ResolveAsync(ProjectId, choice);
var result = await _host.ResolveAsync(ProjectId, choice, shown: shown);
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);
if (result.Status.Conflict is { } again)
{
await TakeAsync(result);
AskConflict(again);
return;
}
if (result.Kept is { } kept)
{
if (await _session.TakeOverAsync(kept) is { } step)
_ui.Notify(Loc.L("Editor.Workspace.TookLibrary"), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.UndoTake"), () => step.Undo());
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
else
{
await TakeAsync(result, force: true);
}
if (result.SavedAs is { } copy)
{
var sequenceId = SequenceId;
_ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name, Loc.L("Editor.Workspace.OpenCopy"), Loc.L("Tooltips.Editor.Workspace.OpenCopy", copy.Name),
() => _ = _ui.OpenProjectAsync(sequenceId, copy.Id));
}
}
/// <summary>
@@ -259,18 +311,28 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await RefreshAsync();
}
/// <summary>The settings that differ between the project now and <paramref name="version"/> (positions compared photo by photo).</summary>
/// <summary>
/// The settings that differ between the project now and <paramref name="version"/>, the version placed on the media's
/// frames first: exclusions, the hero and keyframes compare as the settings they are (a photo the media lack stays
/// parked, and reads as such).
/// </summary>
public IReadOnlyList<string> Compare(ProjectVersion version, int max = 12)
{
ArgumentNullException.ThrowIfNull(version);
var now = ProjectContent.ToPortable(_session.Project, _source.Photos);
return WorkspaceText.CompareLines(SyncRules.Differences(now, version.SettingsJson, 64), max);
var photos = _source.Photos;
if (_session.Project.IsNewerFormat || ProjectContent.FormatOf(version.SettingsJson) > ProjectSettings.CurrentVersion)
return WorkspaceText.CompareLines(SyncRules.Differences(ProjectContent.ToPortable(_session.Project, photos), version.SettingsJson, 64), max);
var then = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Rebind(version.SettingsJson, photos), photos), allowNewer: true);
return WorkspaceText.CompareLines(SyncRules.Differences(_session.Project.ToJson(), then.ToJson(), 64), max);
}
public override void Dispose()
{
_disposed = true;
_source.JobChanged -= OnJobChanged;
_session.ProjectChanged -= OnProjectChanged;
// A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time).
if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose();
base.Dispose();
}
@@ -303,6 +365,31 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
}
}
/// <summary>
/// Open project…: "Open in workspace" over the library's projects of the sequence but the open one (a Save both
/// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not
/// here yet).
/// </summary>
private async Task OpenOtherProjectAsync()
{
try
{
await StoreEditAsync();
var projects = (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != ProjectId).ToList();
var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog,
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)]);
_ui.ShowDialog(dialog);
if (await dialog.Choice is not { } choice || _disposed) return;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(SequenceId, choice.NewName!, _status?.Base?.VersionId)).Id;
await _ui.OpenProjectAsync(SequenceId, id);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex), isError: true);
}
}
private async Task OpenNewProjectAsync()
{
var names = await OtherNamesAsync(null);
@@ -349,8 +436,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await SaveAndSendAsync();
var (sequenceId, projectId) = (SequenceId, ProjectId);
if (!await _ui.CloseProjectAsync()) return;
await _host.DeleteProjectAsync(projectId);
_ui.Notify(Loc.L("Editor.Workspace.Deleted", name));
// The library's delete stands even when the local copy could not go with it: it is said, and Remove local copy takes it later.
if (await _host.DeleteProjectAsync(projectId)) _ui.Notify(Loc.L("Editor.Workspace.Deleted", name));
else _ui.Notify(Loc.L("Editor.Workspace.Deleted", name), Loc.L("Errors.Workspace.CopyKept"), isError: true);
await _ui.SequenceChangedAsync(sequenceId);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
@@ -366,12 +454,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
await StoreEditAsync();
var plan = await _host.PlanRemovalAsync(ProjectId);
var projectId = ProjectId;
var (projectId, name) = (ProjectId, Name);
_ui.ShowDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveAsync(projectId, discard), async () =>
{
await SaveAndSendAsync();
await RemoveAsync(projectId, discard: false);
}, _ui.CloseDialog));
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -380,8 +468,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
}
}
/// <summary>The working state saved as a version and everything sent, for Send first.</summary>
/// <exception cref="WorkspaceException">Something could not be sent.</exception>
/// <summary>
/// The working state saved as a version and everything sent, for Send first and Delete project. A conflict the sync
/// meets is asked about at once (in place of the dialog that asked for it), never left behind a reason to discard.
/// </summary>
/// <exception cref="WorkspaceException">Something could not be sent: a conflict to settle first, or the work not in the library yet.</exception>
private async Task SaveAndSendAsync()
{
await StoreEditAsync();
@@ -389,7 +480,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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"));
if (result.Status.Conflict is { } conflict)
{
AskConflict(conflict);
throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
}
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
private async Task RemoveAsync(Guid projectId, bool discard)
@@ -452,10 +548,82 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
private void AskConflict(WorkspaceConflict conflict)
/// <summary>
/// Asks how to settle <paramref name="conflict"/>, the choice applying to it as listed. One a sync met in the
/// <paramref name="background"/> (after an analysis) waits for the open dialog to close, and is asked once: the chip
/// says Conflict meanwhile, and Sync asks again.
/// </summary>
private void AskConflict(WorkspaceConflict conflict, bool background = false)
{
if (background && _asking is { IsClosed: false }) return;
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
_ui.ShowDialog(new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, ResolveAsync, _ui.CloseDialog));
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
_ui.CloseDialog);
if (!background)
{
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
_asking?.Dispose();
_asking = null;
_ui.ShowDialog(dialog);
return;
}
_asking = dialog;
_ui.ShowDialogWhenFree(dialog);
}
/// <summary>The editor's project changed (an edit, undo, a merge; the UI thread): the chip reads the working state again a moment later.</summary>
private void OnProjectChanged()
{
if (_disposed) return;
_ = RefreshLocalAsync(++_changes);
}
/// <summary>
/// After the last change's save: where the working state stands now (changed, saved as versions), the library's facts
/// (newer, out of reach) kept from the last time it was asked; no read of the home on every edit.
/// </summary>
private async Task RefreshLocalAsync(int change)
{
try
{
// The save follows the change after a moment (and is retried after a failure): read once it is stored.
for (var wait = 0; wait == 0 || (_session.HasPendingSave && wait < 10); wait++)
{
await Task.Delay(StateRefreshDelay);
if (_disposed || change != _changes) return;
}
if (_isSyncing || _session.HasPendingSave) return;
var local = await _host.StatusAsync(ProjectId, askHome: false);
if (_disposed || change != _changes || _isSyncing) return;
Apply(WithLocal(_status, local));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Debug("workspace", $"The state of project {ProjectId} could not be read after an edit: {ex.Message}");
}
}
/// <summary>
/// The state read without the home (<paramref name="local"/>) with what the last read of the home said (how far the
/// library is ahead, whether it could be reached, whether it still has the project), in the order the sync ranks them.
/// </summary>
internal static WorkspaceStatus WithLocal(WorkspaceStatus? last, WorkspaceStatus local)
{
ArgumentNullException.ThrowIfNull(local);
if (last is null) return local;
var gone = last.State == WorkspaceState.Gone;
// A base that moved since (a sync) leaves how far the library is ahead unknown until it is asked again.
var behind = last.Base?.VersionId == local.Base?.VersionId ? last.Behind : 0;
var status = local with { Behind = behind, Offline = last.Offline, HomeHead = last.HomeHead };
var state = gone ? WorkspaceState.Gone
: status.MediaRemoved ? WorkspaceState.MediaRemoved
: status.Conflict is not null ? WorkspaceState.Conflict
: status.Offline ? WorkspaceState.Offline
: status.Behind > 0 ? WorkspaceState.Behind
: status.Ahead > 0 ? WorkspaceState.Ahead
: status.Modified ? WorkspaceState.Modified
: WorkspaceState.InSync;
return status with { State = state };
}
/// <summary>A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread.</summary>
+59 -14
View File
@@ -37,9 +37,10 @@ public static class ProjectNames
}
/// <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.
/// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet, and by the project
/// menu's Open project: which project of its home (Main, made from the sequence's settings as they are, or another) or a
/// new one with its name, and the media to copy (proxies; the originals come in phase 5c). Open queues the copy; the
/// sequence opens once it is done.
/// </summary>
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
@@ -47,14 +48,17 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private ProjectOption? _selected;
private bool _isNew;
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close)
/// <param name="taken">The names a new project cannot take (default: those of <paramref name="projects"/>).</param>
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
IReadOnlyList<string>? taken = null)
: 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"));
var names = taken ?? [.. projects.Select(p => p.Name)];
NewName = new EditableField(string.Empty, n => ProjectNames.Validate(n, names), _ => { }, () => Loc.L("Tooltips.Editor.OpenWorkspace.Name"));
NewName.PropertyChanged += (_, _) => Refresh();
OpenCommand = new RelayCommand(Open, () => CanOpen);
}
@@ -436,20 +440,24 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
/// <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).
/// (only when everything is at the library), Send first (sends, then removes), or Discard changes (removes once the
/// user typed the project's name; the unsent work is kept aside in the workspace's trash). A project the library no
/// longer has (<see cref="WorkspaceRemovalPlan.Gone"/>) can only be discarded that way.
/// </summary>
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<bool, Task> _remove;
private readonly Func<Task> _sendFirst;
private readonly Func<bool> _confirmDiscard;
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Action<ArchiveDialogViewModel> close)
/// <param name="confirmDiscard">The typed confirmation Discard changes asks first (<see cref="ConfirmDiscard"/>); true when the user confirmed.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close)
: base(close)
{
Plan = plan;
_remove = remove;
_sendFirst = sendFirst;
_confirmDiscard = confirmDiscard;
Facts =
[
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
@@ -457,9 +465,9 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
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);
RemoveCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(false)), () => !IsBusy && plan.IsSafe && !plan.Offline && !plan.Gone);
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone);
DiscardCommand = new AsyncRelayCommand(DiscardAsync, () => !IsBusy && HasUnsent);
}
public WorkspaceRemovalPlan Plan { get; }
@@ -468,7 +476,8 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
public IReadOnlyList<DialogFact> Facts { get; }
public bool HasUnsent => !Plan.IsSafe;
/// <summary>Something would not be at the library after the removal (or the library no longer has the project): Discard changes shows.</summary>
public bool HasUnsent => !Plan.IsSafe || Plan.Gone;
public ICommand RemoveCommand { get; }
@@ -476,12 +485,48 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
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 RemoveToolTip => Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: !Plan.IsSafe ? Loc.L("Errors.Workspace.Unsent")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.Remove");
public string SendFirstToolTip => Plan.Conflict ? Loc.L("Errors.Workspace.Conflict") : Plan.Offline ? Loc.L("Errors.Workspace.Offline") : Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
public string SendFirstToolTip => Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: Plan.Conflict ? Loc.L("Errors.Workspace.Conflict")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
public string DiscardToolTip => Loc.L("Tooltips.Editor.RemoveCopy.Discard");
/// <summary>
/// The typed confirmation of Discard changes (the plan's cross-cutting rule for what Chronos cannot bring back): the
/// project's name, as shown, typed before Discard enables.
/// </summary>
public static ConfirmRequest DiscardRequest(string projectName) => new()
{
Heading = Loc.L("Editor.RemoveCopy.DiscardTitle", projectName),
Message = Loc.L("Editor.RemoveCopy.DiscardMessage"),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Keep"),
ActionText = Loc.L("Editor.RemoveCopy.Discard"),
ActionToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Discard"),
IsDestructive = true,
TypedConfirmation = projectName,
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeName"),
};
/// <summary>Asks <see cref="DiscardRequest"/> through <paramref name="ui"/>: true when the user typed the name and confirmed.</summary>
public static bool ConfirmDiscard(IWorkspaceUi ui, string projectName)
{
ArgumentNullException.ThrowIfNull(ui);
return ui.Confirm(DiscardRequest(projectName));
}
private async Task DiscardAsync()
{
if (!_confirmDiscard()) return;
await RunAsync(() => _remove(true));
}
private async Task RunAsync(Func<Task> action)
{
ClearError();
+111 -25
View File
@@ -2,6 +2,7 @@ using System.IO;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
@@ -38,7 +39,11 @@ public sealed record WorkspaceHistory(IReadOnlyList<ProjectVersion> Versions, IR
/// 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)
/// <param name="Gone">
/// The home answered it no longer has the project or its sequence: nothing can be sent or checked there, so the copy can
/// only go with its work kept aside (Discard).
/// </param>
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline, bool Gone = false)
{
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
@@ -80,8 +85,11 @@ public sealed class WorkspaceHost
_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>
/// The PC versions made here carry ("STUDIO-PC"): data, shown as it is by History (no words of the UI in it, so every
/// language reads it alike).
/// </summary>
public static string ClientName { get; } = 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);
@@ -138,17 +146,24 @@ public sealed class WorkspaceHost
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 projects of the workspace (one whose working state cannot be read is left out, and logged). A workspace folder
/// not made yet that lies inside a library is not made by listing it: it lists nothing.
/// </summary>
public Task<IReadOnlyList<WorkspaceEntry>> ListAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
return (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(() =>
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
if (Store.Find(projectId) is not { } project) return null;
try
{
@@ -191,12 +206,15 @@ public sealed class WorkspaceHost
/// </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>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var checkout = await Task.Run(async () =>
{
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root));
SequenceProject project;
if (newName is not null)
{
@@ -229,8 +247,9 @@ public sealed class WorkspaceHost
}, 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.
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached
/// reads as offline; one that answers it no longer has the project or its sequence (the sequence left the index) reads
/// as <see cref="WorkspaceState.Gone"/>, whose local copy can then only be removed (nothing is removed by itself).
/// </summary>
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
@@ -242,9 +261,16 @@ public sealed class WorkspaceHost
}
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 gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound };
Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"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 };
return local with
{
Offline = true,
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Conflict && !gone ? local.State
: gone ? WorkspaceState.Gone
: WorkspaceState.Offline,
};
}
}, cancellationToken);
@@ -303,11 +329,13 @@ public sealed class WorkspaceHost
}, cancellationToken);
/// <summary>
/// Settles the conflict a sync stopped at, then sends what waits. <see cref="ConflictChoice.SaveBoth"/> sends this
/// Settles the conflict a sync stopped at, as <paramref name="shown"/> listed it to the user (else as recorded), then
/// sends what waits. When what differs now is not what was shown, nothing is settled: the conflict found now comes back
/// (<see cref="WorkspaceState.Conflict"/>) to be asked again. <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 () =>
WorkspaceConflict? shown = null, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var home = HomeOfProject(projectId);
WorkspaceSyncResult resolved;
@@ -316,21 +344,28 @@ public sealed class WorkspaceHost
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
try
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, cancellationToken).ConfigureAwait(false);
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, shown, 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);
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
}
else
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, cancellationToken).ConfigureAwait(false);
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
if (resolved.Status.State == WorkspaceState.Conflict)
{
Log.Info("workspace", $"Conflict of project {projectId} not settled ({choice}): what differs changed since it was shown");
return resolved;
}
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);
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs)
{
Kept = resolved.Kept,
};
}, cancellationToken);
/// <summary>"<paramref name="name"/> (<c>PC</c>)", within the 60 characters of a project name.</summary>
@@ -414,27 +449,56 @@ public sealed class WorkspaceHost
/// 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>
/// <returns>
/// False when the home deleted the project but its local copy could not be removed (a file in use): the copy stays,
/// and Remove local copy takes it later.
/// </returns>
/// <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)
public async Task<bool> DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var sequenceId = await Task.Run(async () =>
var (sequenceId, removed) = 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.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
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"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
return workspace.Home.SequenceId;
try
{
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
return (workspace.Home.SequenceId, true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or LeaseUnavailableException)
{
// The home's delete stands (its trash holds every version); the copy, all of it sent, waits for Remove local copy.
Log.Warning("workspace", $"Project {projectId} was deleted at its home, but its local copy stays", ex);
return (workspace.Home.SequenceId, false);
}
}, cancellationToken);
Forget(sequenceId, projectId);
return removed;
}
/// <summary>
/// "Send first" for a project not open in the editor (the picker's Remove local copy): its working state saved as a
/// version when it can be, then the sync.
/// </summary>
/// <exception cref="WorkspaceException">A conflict waits (open the project and Sync to settle it), or something is still not at the home.</exception>
public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false);
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
@@ -444,7 +508,8 @@ public sealed class WorkspaceHost
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);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead, status.Modified, status.Conflict is not null, status.Offline,
status.State == WorkspaceState.Gone);
}, cancellationToken);
/// <summary>
@@ -588,6 +653,27 @@ public sealed class WorkspaceHost
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
}
/// <summary>
/// The workspace folder lies inside a library this index knows (a portable copy's <c>data</c> folder under a library
/// at a drive's root): editing happens outside every library, so nothing is checked out or copied there.
/// </summary>
private async Task<bool> InsideALibraryAsync(CancellationToken cancellationToken)
{
if (_db() is not { } db) return false;
var root = Plain(Path.GetFullPath(Root));
foreach (var archive in await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (DataLocation.IsUnder(root, Plain(Path.GetFullPath(archive.RootPath)))) return true;
}
return false;
// Without the long-path prefix, which only one of the two may carry.
static string Plain(string path) =>
path.StartsWith(@"\\?\UNC\", StringComparison.Ordinal) ? @"\\" + path[8..]
: path.StartsWith(@"\\?\", StringComparison.Ordinal) ? path[4..]
: path;
}
private void Forget(Guid sequenceId, Guid projectId)
{
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
+15 -2
View File
@@ -31,6 +31,7 @@ public static class WorkspaceText
WorkspaceState.Conflict => StatusKind.Error,
WorkspaceState.Offline => StatusKind.Offline,
WorkspaceState.MediaRemoved => StatusKind.NoProxies,
WorkspaceState.Gone => StatusKind.Warning,
_ => StatusKind.Queued,
};
@@ -48,13 +49,25 @@ public static class WorkspaceText
/// <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>
/// <summary>
/// Who made a version: its author, else the PC it was made on ("STUDIO-PC"), however the program that made it named
/// itself ("chronos@STUDIO-PC" for the archive's own versions, "Chronos on STUDIO-PC" for those of test builds).
/// </summary>
public static string Author(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
return version.Author ?? version.ClientName ?? string.Empty;
if (version.Author is { Length: > 0 } author) return author;
var client = version.ClientName?.Trim() ?? string.Empty;
foreach (var prefix in ClientPrefixes)
{
if (client.Length > prefix.Length && client.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return client[prefix.Length..];
}
return client;
}
/// <summary>What programs put before the PC's name in a version's client name (not words of the UI: the PC alone is shown).</summary>
private static readonly string[] ClientPrefixes = ["chronos@", "server@", "workspace@", "Chronos on "];
/// <summary>"28/10/2026 18:02".</summary>
public static string When(DateTimeOffset at) => $"{Formatting.Date(at)} {Formatting.TimeOfDay(at)}";