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

@@ -94,6 +94,15 @@ public abstract class ArchiveDialogViewModel : LocalizedViewModel
ErrorText = null;
ErrorToolTip = null;
}
/// <summary>The dialog was closed (disposed): one still waiting to be shown no longer is.</summary>
public bool IsClosed { get; private set; }
public override void Dispose()
{
IsClosed = true;
base.Dispose();
}
}
/// <summary>A fact of the rebuild dialog ("Sidecars · 412"); a path stays left to right, a missing value says why in its tooltip.</summary>
+50 -14
View File
@@ -46,7 +46,8 @@ public sealed class EditorSession : IAsyncDisposable
Source = source;
_codecs = codecs ?? [];
_basis = content.Project;
History = new ProjectHistory(content.Project);
// Undo steps take outside changes as the source merges them (a workspace project: positions photo by photo).
History = new ProjectHistory(content.Project, merge: (basis, ours, theirs) => source.Merge(basis, ours, theirs).Merged);
History.Changed += OnProjectChanged;
_saver = new ProjectSaver(SaveAsync, saveDelay ?? DefaultSaveDelay);
_saver.Failed += OnSaveFailed;
@@ -190,10 +191,11 @@ public sealed class EditorSession : IAsyncDisposable
}
/// <summary>
/// Settles <see cref="Conflict"/> against the server's settings as the last save read them. Both choices first take
/// in what only the server changed (like any merge, without an undo step). <paramref name="keepMine"/> then saves
/// the editor's values of the settings both changed; otherwise the server's values become the project as one
/// undoable step, so Ctrl+Z brings the editor's back (and saves them).
/// Settles <see cref="Conflict"/> against the settings stored meanwhile (the server's, a workspace's working state a sync
/// wrote) as the last save read them. Both choices first take in what only the other side changed (like any merge,
/// without an undo step). <paramref name="keepMine"/> then saves the editor's values of the settings both changed;
/// otherwise the other side's values become the project as one undoable step, so Ctrl+Z brings the editor's back (and
/// saves them).
/// </summary>
/// <returns>False when there is no conflict to settle (a later save already went through).</returns>
public bool ResolveConflict(bool keepMine)
@@ -202,8 +204,8 @@ public sealed class EditorSession : IAsyncDisposable
Conflict = null;
var basis = _basis;
_basis = theirs;
History.Replace(ProjectMerge.Merge(basis, Project, theirs));
if (!keepMine) History.Apply(ProjectMerge.Merge(basis, theirs, Project));
History.Replace(Source.Merge(basis, Project, theirs).Merged);
if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged);
// The change waiting for its retry goes now, on top of the server's settings.
_ = _saver.FlushAsync();
return true;
@@ -245,13 +247,13 @@ public sealed class EditorSession : IAsyncDisposable
{
var content = await Source.LoadAsync(cancellationToken);
Follow(content);
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
// retry meets them and asks (Conflict).
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
// Settings a server or a sync stored that conflict with the editor's waiting change are not merged over it: that
// change's retry meets them and asks (Conflict).
var merge = Conflict is null ? Source.Merge(_basis, Project, content.Project) : null;
if (merge is not null && (!Source.AsksConflicts || !merge.HasConflicts))
{
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
_basis = content.Project;
History.Replace(merged);
History.Replace(merge.Merged);
}
}
finally
@@ -261,6 +263,38 @@ public sealed class EditorSession : IAsyncDisposable
ContentChanged?.Invoke();
}
/// <summary>
/// Reads the project again after the user took the other side's values of the settings both changed (a workspace
/// project's "Take the library's", settled by its sync): what only the other side changed comes in as any merge does,
/// without an undo step (<paramref name="kept"/>: the stored project as keeping the editor's values would have left
/// it), then the values taken become the project as one undoable step, so Ctrl+Z brings the editor's back (and saves
/// them), as <see cref="ResolveConflict"/> does for a server's.
/// </summary>
/// <returns>That step, which a toast's Undo can take back while it is the last change; null when it changed nothing.</returns>
public async Task<ProjectRestore?> TakeOverAsync(ProjectSettings kept, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(kept);
await _saver.FlushAsync();
var taken = await BeginReadAsync();
ProjectRestore? step = null;
try
{
var content = await Source.LoadAsync(cancellationToken);
Follow(content);
var basis = _basis;
_basis = content.Project;
History.Replace(Source.Merge(basis, Project, kept).Merged);
var before = Project;
if (!IsReadOnly && History.Apply(Source.Merge(kept, Project, content.Project).Merged)) step = new ProjectRestore(this, before, Project);
}
finally
{
taken.SetResult();
}
ContentChanged?.Invoke();
return step;
}
/// <summary>Stores pending changes now; false when the save failed (the change stays pending and is retried).</summary>
public Task<bool> FlushAsync() => _saver.FlushAsync();
@@ -357,7 +391,9 @@ public sealed class EditorSession : IAsyncDisposable
private void OnProjectChanged()
{
_saver.Schedule(Project);
// A read-only project takes what is read again (a workspace pull of a newer Chronos's settings) without a save that
// could never be stored and would be retried for ever.
if (!IsReadOnly) _saver.Schedule(Project);
ProjectChanged?.Invoke();
}
@@ -410,7 +446,7 @@ public sealed class EditorSession : IAsyncDisposable
Conflict = null;
_basis = stored;
// Someone else's change was merged in: show it without an undo step (edits made since the save are kept).
if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored));
if (!ProjectMerge.SameValues(stored, project)) History.Replace(Source.Merge(project, Project, stored).Merged);
}
}
+31 -7
View File
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.App.Workspace;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics;
@@ -480,7 +481,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>Why the controls that change the project are disabled; null while they are not.</summary>
public string? LockedToolTip => IsOutdated ? Loc.L("Tooltips.Editor.Outdated", ServerName)
: IsReadOnly ? Loc.L("Tooltips.Editor.ReadOnly")
: IsReadOnly ? Loc.L(Session.Source is WorkspaceSequenceSource ? "Errors.Workspace.ReadOnly" : "Tooltips.Editor.ReadOnly")
: IsBusy ? Loc.L("Tooltips.Editor.Busy")
: null;
@@ -1053,17 +1054,33 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
});
/// <summary>
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"): the
/// dialog lists them; Keep mine overwrites the server's, Take server (the safe default, also on Esc) shows theirs as
/// one undoable step. Saving waits until then.
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"), or, for
/// a workspace project, that a sync took from the library while the edit waited (owner review 2, R8): the dialog lists
/// them; Keep mine overwrites the other side's, Take server or the library's (the safe default, also on Esc) shows theirs
/// as one undoable step. Saving waits until then.
/// </summary>
private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() =>
{
if (_disposed || Session.Conflict is null) return;
var keepMine = Shell.Services.Dialogs.Confirm(ConflictRequest(conflict, Title, ServerName ?? string.Empty));
var request = Session.Source is WorkspaceSequenceSource ? LibraryConflictRequest(conflict, Title) : ConflictRequest(conflict, Title, ServerName ?? string.Empty);
var keepMine = Shell.Services.Dialogs.Confirm(request);
if (!_disposed) Session.ResolveConflict(keepMine);
});
/// <summary>The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps.</summary>
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title) => new()
{
Heading = Loc.L("Editor.Workspace.Conflict.Title"),
Message = Loc.L("Editor.Workspace.Edited.Message", title),
Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10)),
DetailToolTip = Loc.L("Tooltips.Editor.Workspace.Differences"),
SafeText = Loc.L("Editor.Workspace.Conflict.TakeHome"),
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.TakeHomeUndo"),
ActionText = Loc.L("Server.Sync.Action.KeepMine"),
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.KeepMine"),
IsDestructive = true,
};
/// <summary>The conflict prompt: what differs (the editor's value, then the server's) and what each choice replaces.</summary>
internal static ConfirmRequest ConflictRequest(ProjectConflictException conflict, string title, string server) => new()
{
@@ -1160,8 +1177,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
}
/// <summary>
/// The frames of the server sequence changed while it is open (any thread): everything that changes the project is
/// disabled and says why, and a toast offers to fetch the proxies again.
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's
/// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
/// server sequence, offering to fetch the proxies again).
/// </summary>
private void OnReadOnlyChanged() => _dispatcher.BeginInvoke(() =>
{
@@ -1173,6 +1191,12 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
OnPropertyChanged(nameof(RenderChoiceToolTip));
OnRenderStateChanged();
OnBusyChanged();
// A workspace project a sync turned read-only (a newer Chronos saved it): said once, the controls say why too.
if (IsReadOnly && Session.Source is WorkspaceSequenceSource)
{
Shell.ShowToast(new Toast { Title = Loc.L("Editor.Workspace.ReadOnly"), Message = Loc.L("Errors.Workspace.ReadOnly") });
return;
}
if (!IsOutdated) return;
var (id, title) = (Session.Content.Sequence.Id, Title);
Shell.ShowToast(new Toast
+13
View File
@@ -35,6 +35,12 @@ public interface ISequenceSource : IAsyncDisposable
/// </summary>
bool IsOutdated { get; }
/// <summary>
/// A change stored meanwhile by someone else to settings the editor changed too is asked about
/// (<see cref="ProjectConflictException"/>), never merged over the editor's: a server sequence, a workspace project.
/// </summary>
bool AsksConflicts => IsRemote;
/// <summary><see cref="IsReadOnly"/> changed (any thread).</summary>
event Action? ReadOnlyChanged;
@@ -68,6 +74,13 @@ public interface ISequenceSource : IAsyncDisposable
/// <exception cref="EditorException">The editor's own reason the project was not stored, worded for the user.</exception>
Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken);
/// <summary>
/// The three-way merge of the editor's projects, all three naming this source's frames (<see cref="ProjectMerge"/>): member
/// by member, a member both sides changed listed as a conflict and settled for <paramref name="ours"/>. A workspace
/// project merges its frame positions photo by photo, as its sync does.
/// </summary>
ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs);
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
+9 -4
View File
@@ -9,7 +9,11 @@ namespace Chronos.App.Editor;
/// <see cref="EndRun"/> (the drag or key press ended); any other edit, undo or redo also ends the run. The oldest steps
/// are dropped beyond <see cref="Capacity"/>.
/// </summary>
public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
/// <param name="merge">
/// The three-way merge (basis, ours, theirs) that gives each step an outside change (<see cref="Replace"/>): the source's,
/// which merges a workspace project's frame positions photo by photo; <see cref="ProjectMerge.Merge"/> when null.
/// </param>
public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200, Func<ProjectSettings, ProjectSettings, ProjectSettings, ProjectSettings>? merge = null)
{
private readonly LinkedList<ProjectSettings> _undo = new();
private readonly LinkedList<ProjectSettings> _redo = new();
@@ -71,7 +75,8 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
{
ArgumentNullException.ThrowIfNull(current);
if (ProjectMerge.SameValues(current, Current)) return;
var rebase = new ProjectMerge.Rebase(Current, current);
var (basis, theirs) = (Current, current);
Func<ProjectSettings, ProjectSettings> rebase = merge is null ? new ProjectMerge.Rebase(basis, theirs).Apply : step => merge(basis, step, theirs);
Rebase(_undo, rebase);
Rebase(_redo, rebase);
_runKey = null;
@@ -98,9 +103,9 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
Changed?.Invoke();
}
private static void Rebase(LinkedList<ProjectSettings> steps, ProjectMerge.Rebase rebase)
private static void Rebase(LinkedList<ProjectSettings> steps, Func<ProjectSettings, ProjectSettings> rebase)
{
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value);
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase(node.Value);
}
private bool Move(ProjectSettings target)
@@ -34,7 +34,10 @@ public interface IProjectRenders
/// library): the frames and pixels of the media the workspace holds (<c>media/media.json</c>, the proxies), the project
/// from its working state (<c>project.chronos</c>, positions placed on those frames), saved there atomically under the
/// project's lease and merged against the basis like <see cref="LocalSequenceSource"/> (a pull or a copy job writes it
/// too). Jobs run on this PC's engine against the home's sequence (same id): an analysis reads the home's originals, a
/// too): frame positions photo by photo as the sync merges them (<see cref="Merge"/>), and settings the editor changed to
/// other values than those stored meanwhile asked about (<see cref="ProjectConflictException"/>), never decided for the
/// editor. A pull that brings a newer Chronos's settings turns it read-only (<see cref="ReadOnlyChanged"/>). Jobs run on
/// this PC's engine against the home's sequence (same id): an analysis reads the home's originals, a
/// render renders the home's originals with the project's portable settings and records the project and the version
/// (<see cref="RenderRequests"/>). The deep report is the home's while its frames are the media's, else the copy the
/// workspace took. A copy job that changed the media (Update media) makes saves made against the frames read before refused
@@ -94,12 +97,11 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
public bool IsOutdated => false;
/// <summary>A workspace project's read-only state is known when it opens.</summary>
public event Action? ReadOnlyChanged
{
add { }
remove { }
}
/// <summary>The library's values and the editor's are asked about where both changed a setting, as a sync asks.</summary>
public bool AsksConflicts => true;
/// <summary>The working state read again holds a newer Chronos's settings (a pull took them), or no longer does.</summary>
public event Action? ReadOnlyChanged;
public event Action<Job>? JobChanged;
@@ -183,6 +185,10 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <exception cref="EditorException">The project is read-only, or its media are gone.</exception>
/// <exception cref="FramesChangedException">The media changed since they were read (a copy job): read them again first.</exception>
/// <exception cref="ProjectConflictException">
/// The working state stored meanwhile (a sync took the library's versions) holds other values of settings this edit
/// changed too: nothing is stored until the user keeps theirs or takes the library's.
/// </exception>
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
@@ -200,7 +206,13 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
// A copy job moved the working state onto other frames: the editor reads them and moves its positions first.
if (media.FramesVersion != framesVersion) throw new FramesChangedException(Loc.L("Errors.Workspace.MediaChanged"));
var stored = ProjectSettings.FromJson(ProjectContent.Place(bundle.Project.ToJson(), media.Photos), allowNewer: true);
var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
var merged = project;
if (!ProjectMerge.SameValues(stored, basis))
{
var merge = Merge(basis, project, stored, media.Photos);
if (merge.HasConflicts) throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, merge.Conflicts);
merged = merge.Merged;
}
if (ProjectMerge.SameValues(merged, stored)) return merged;
folder.WriteBundle(bundle with { Project = merged, Saved = DateTimeOffset.UtcNow });
return merged;
@@ -208,6 +220,33 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}, cancellationToken);
}
/// <summary>
/// The editor's merges as the sync merges (owner review 2, R8): member by member, and frame positions photo by photo and
/// flag by flag in the portable form, so an exclusion or a keyframe a sync wrote meanwhile stays beside the editor's own
/// (positional arrays would take one side whole). All three name the frames of the media read last.
/// </summary>
public ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => Merge(basis, ours, theirs, Photos);
private static ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, FramePhotos photos)
{
ArgumentNullException.ThrowIfNull(basis);
ArgumentNullException.ThrowIfNull(ours);
ArgumentNullException.ThrowIfNull(theirs);
var merge = ProjectMerge.MergeWithConflicts(basis, ours, theirs);
// Positions only one side moved, or none, merge alike either way; the portable form is needed where both did.
if (photos.Count == 0 || !merge.Conflicts.Any(c => NamesPosition(c.Path)) || basis.IsNewerFormat || ours.IsNewerFormat || theirs.IsNewerFormat) return merge;
var portable = ProjectMerge.MergeWithConflicts(Portable(basis, photos), Portable(ours, photos), Portable(theirs, photos));
var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(portable.Merged.ToJson()), photos), allowNewer: true);
return portable with { Merged = placed };
static ProjectSettings Portable(ProjectSettings settings, FramePhotos photos) =>
ProjectSettings.FromJson(ProjectContent.ToPortable(settings, photos), allowNewer: true);
}
/// <summary>A merge path of a frame position (an exclusion, the hero, a camera keyframe, a frame waiting for its photo).</summary>
private static bool NamesPosition(string path) =>
path is "excludedFrames" or "heroFrame" || path.StartsWith("camera.keyframes", StringComparison.Ordinal) || path.StartsWith("pendingFrames", StringComparison.Ordinal);
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
@@ -271,11 +310,13 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <summary>
/// Takes the media read now: a frame source over them when they differ from those read before (the old one is disposed
/// with this source, as a decode may still read it), their frames and photos, the project's workspace section.
/// with this source, as a decode may still read it), their frames and photos, the project's workspace section, and
/// whether the settings are a newer Chronos's (said by <see cref="ReadOnlyChanged"/> when that changed).
/// </summary>
private void Swap(WorkspaceSequence media, WorkspaceMedia index, BundleWorkspace workspace, bool readOnly)
{
var ids = media.Frames.Select(f => f.Id).ToArray();
bool changed;
lock (_gate)
{
if (_frames is null || index.FramesVersion != _framesVersion || !ids.AsSpan().SequenceEqual(_frameIds))
@@ -289,8 +330,10 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_framesVersion = index.FramesVersion;
_photos = index.Photos;
_workspace = workspace;
changed = _readOnly != readOnly;
_readOnly = readOnly;
}
if (changed) ReadOnlyChanged?.Invoke();
}
/// <summary>
@@ -80,10 +80,18 @@
Grid.IsSharedSizeScope="True" Visibility="{Binding Picker.HasWorkspaceItems, Converter={StaticResource BoolToVisibility}}">
<ListBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding Picker.OpenProjectCommand}" />
<KeyBinding Key="Delete" Command="{Binding Picker.RemoveCopyCommand}" />
</ListBox.InputBindings>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ws:WorkspaceProjectItem}">
<Grid Height="40">
<!-- Remove local copy also for a project that cannot open (its copy failed, or the library no longer has it). -->
<Grid Height="40" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding PlacementTarget.Tag.Picker.RemoveCopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Editor.Project.RemoveCopy}" />
</ContextMenu>
</Grid.ContextMenu>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MinWidth="120" />
@@ -51,6 +51,7 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
_open = new AsyncRelayCommand(() => (Selected ?? Items.FirstOrDefault()) is { } item ? _section.PickAsync(item) : Task.CompletedTask, () => Items.Count > 0);
OpenItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _section.PickAsync(item) : Task.CompletedTask);
OpenProjectCommand = new AsyncRelayCommand((p, _) => (p as WorkspaceProjectItem ?? SelectedProject) is { } item ? _section.PickProjectAsync(item) : Task.CompletedTask);
RemoveCopyCommand = new AsyncRelayCommand((p, _) => (p as WorkspaceProjectItem ?? SelectedProject) is { } item ? _section.RemoveProjectCopyAsync(item) : Task.CompletedTask);
SearchOpenCommand = new AsyncRelayCommand(OpenFromSearchAsync);
ClearCommand = new RelayCommand(() => SearchText = string.Empty);
}
@@ -73,6 +74,9 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
/// <summary>Opens a project of the Workspace group (double-click, Enter in its list), else the selected one.</summary>
public ICommand OpenProjectCommand { get; }
/// <summary>"Remove local copy…" of a project of the Workspace group (its menu, Delete in its list), also one that cannot open.</summary>
public ICommand RemoveCopyCommand { get; }
/// <summary>The Workspace group read last, then its projects' states (tests wait for it).</summary>
public async Task WorkspaceLoadedAsync()
{
@@ -121,6 +121,7 @@
<MenuItem Header="{l:Loc Editor.Project.Sync}" Command="{Binding Project.SyncCommand}" ToolTip="{Binding Project.StateToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.History}" Command="{Binding Project.HistoryCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.History}" />
<Separator />
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Rename}" />
<MenuItem Header="{l:Loc Editor.Project.Delete}" Command="{Binding Project.DeleteCommand}" ToolTip="{Binding Project.DeleteToolTip}"
+70 -1
View File
@@ -54,6 +54,9 @@ public sealed class SequenceViewModel : SectionViewModel
private PendingOpen? _fetch;
private ArchiveDialogViewModel? _dialog;
/// <summary>Dialogs that show once the open one closes (<see cref="OpenDialogWhenFree"/>), oldest first.</summary>
private readonly Queue<ArchiveDialogViewModel> _waiting = new();
/// <summary>The project the next open of its sequence takes (the picker's Workspace group, a project file, the project menu).</summary>
private ProjectRequest? _requested;
@@ -374,6 +377,7 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.PropertyChanged -= OnShellChanged;
StopFetch();
_dialog?.Dispose();
while (_waiting.TryDequeue(out var waiting)) waiting.Dispose();
Editor?.Dispose();
Picker.Dispose();
base.Dispose();
@@ -386,12 +390,65 @@ public sealed class SequenceViewModel : SectionViewModel
Dialog = dialog;
}
/// <summary>Closes <paramref name="dialog"/> if it is still the open one.</summary>
/// <summary>
/// Shows <paramref name="dialog"/> now when no dialog is open, else once the open one (and those waiting before it)
/// closed: what the background found (a conflict an automatic sync met) never replaces what the user is doing.
/// </summary>
internal void OpenDialogWhenFree(ArchiveDialogViewModel dialog)
{
if (_dialog is null) OpenDialog(dialog);
else _waiting.Enqueue(dialog);
}
/// <summary>Closes <paramref name="dialog"/> if it is still the open one; the next one waiting shows (one closed meanwhile is skipped).</summary>
internal void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
while (_waiting.TryDequeue(out var next))
{
if (next.IsClosed) continue;
OpenDialog(next);
break;
}
}
/// <summary>
/// "Remove local copy" of a project of the picker's Workspace group: the open project's goes through its menu; another,
/// even one that cannot open (its copy failed, or the library no longer has it), gets the same plan and choices here.
/// </summary>
public async Task RemoveProjectCopyAsync(WorkspaceProjectItem item)
{
ArgumentNullException.ThrowIfNull(item);
if (_editor?.Project is { } menu && menu.ProjectId == item.ProjectId)
{
menu.RemoveCopyCommand.Execute(null);
return;
}
var workspace = Shell.Services.Workspace;
var (projectId, name) = (item.ProjectId, item.Name);
try
{
var plan = await workspace.PlanRemovalAsync(projectId);
OpenDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveCopyAsync(projectId, name, discard), async () =>
{
await workspace.SendAllAsync(projectId);
await RemoveCopyAsync(projectId, name, discard: false);
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, name), d => CloseDialog(d)));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The removal of project {projectId} could not be planned", ex);
Shell.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true);
}
async Task RemoveCopyAsync(Guid id, string project, bool discard)
{
await workspace.RemoveLocalCopyAsync(id, discard);
Shell.Notify(Loc.L("Editor.Workspace.Removed"), project);
_ = Picker.ReloadAsync();
}
}
protected override void OnActivated()
@@ -485,6 +542,14 @@ public sealed class SequenceViewModel : SectionViewModel
local.HeroChanged += OnHeroChanged;
return (local, row.DisplayTitle);
}
// A workspace project whose sequence left the index (its trash emptied, its folder gone): not a server's sequence to
// fetch; its local copy can only be removed (the picker's Remove local copy).
if (_requested is { ProjectId: { } projectId } asked && asked.SequenceId == sequenceId && services.Workspace.IsEnabled
&& await services.Workspace.FindAsync(projectId) is not null)
{
_requested = null;
throw new InvalidOperationException(Loc.L("Errors.Workspace.SequenceGone"));
}
var sync = services.Sync;
if (sync.Server is not { } server || sync.Service is not { } service || sync.ConnectEditor() is not { } api)
throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
@@ -758,8 +823,12 @@ public sealed class SequenceViewModel : SectionViewModel
/// <summary>What the project menu of an editor of this section asks of it: its dialogs, the shell's confirmations and toasts, opening and closing projects.</summary>
private sealed class WorkspaceUi(SequenceViewModel section) : IWorkspaceUi
{
public ArchiveDialogViewModel? Dialog => section.Dialog;
public void ShowDialog(ArchiveDialogViewModel dialog) => section.OpenDialog(dialog);
public void ShowDialogWhenFree(ArchiveDialogViewModel dialog) => section.OpenDialogWhenFree(dialog);
public void CloseDialog(ArchiveDialogViewModel dialog) => section.CloseDialog(dialog);
public bool Confirm(ConfirmRequest request) => section.Shell.Services.Dialogs.Confirm(request);
+18
View File
@@ -4,6 +4,7 @@ using System.Text.Json.Nodes;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Ui.Controls;
@@ -90,6 +91,9 @@ public static class SyncText
["heroFrame"] = "Server.Setting.HeroFrame",
};
/// <summary>The paths of positions parked by photo: "pendingFrames.&lt;photo&gt;.&lt;flag&gt;".</summary>
private const string PendingPrefix = "pendingFrames.";
/// <summary>"originals · proxies", "proxies" (cached server proxies) or "—".</summary>
public static string Local(SyncEntry entry)
{
@@ -267,9 +271,23 @@ public static class SyncText
/// <summary>
/// The label key of a difference path and the member below the setting it reaches ("isAuto", "manual", … of an
/// Auto parameter; null for the setting itself): "exposure.deflickerWindow.manual" is the deflicker window's manual value.
/// Positions parked by photo (a workspace project's portable form, owner review 2, R8) read as the setting they hold:
/// "hero" (two heroes chosen), "pendingFrames.&lt;photo&gt;.keyframes" or ".excluded".
/// </summary>
private static (string Key, string? Field) Setting(string path)
{
if (path == ProjectMerge.HeroPath) return ("Server.Setting.HeroFrame", null);
if (path.StartsWith(PendingPrefix, StringComparison.Ordinal))
{
// The flag is the last segment: the photo's key between may hold dots of its own.
return path[(path.LastIndexOf('.') + 1)..] switch
{
"excluded" => ("Server.Setting.ExcludedFrames", null),
"hero" => ("Server.Setting.HeroFrame", null),
"keyframes" => ("Server.Setting.Keyframes", null),
_ => ("Server.Setting.Other", null),
};
}
var segments = path.Split('.');
for (var length = segments.Length; length > 0; length--)
{
+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)}";