Merge branch 'review2-p5a-fix3-desktop' into review2-p5a-int3

Conflict in WorkspaceFallbackTests: keeps desktop's new newer-copy test
and drops ACancelledFirstCopyLeavesNoHalfMedia, which the sync branch
removed along with WorkspaceHost.RemovePartialMediaAsync (the cancelled
first copy's clean-up now runs in the copy job, tested in Data).
ReplayAsync auto-merged with both intents: desktop's working-state
conflicts and silent paths, and sync's skip of no-change versions,
Settles journal flag and PruneReplaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-03 13:33:34 +01:00
commit c5ed31bced
21 files changed
+696 -54

No files matched your search

+6
View File
@@ -271,6 +271,8 @@
<data name="Editor.Remote.Outdated" xml:space="preserve"><value>{0} · proxies outdated</value></data>
<data name="Editor.Remote.ReadOnly" xml:space="preserve"><value>{0} · read-only</value></data>
<data name="Editor.RemoveCopy.Changed" xml:space="preserve"><value>Unsaved changes</value></data>
<data name="Editor.RemoveCopy.DamagedDiscard" xml:space="preserve"><value>Discard a damaged copy?</value></data>
<data name="Editor.RemoveCopy.DamagedTitle" xml:space="preserve"><value>Remove a damaged copy</value></data>
<data name="Editor.RemoveCopy.Discard" xml:space="preserve"><value>Discard changes</value></data>
<data name="Editor.RemoveCopy.DiscardMessage" xml:space="preserve"><value>The versions not sent and the unsaved changes go to the workspace's trash folder; Chronos does not bring them back.</value><comment>long</comment></data>
<data name="Editor.RemoveCopy.DiscardTitle" xml:space="preserve"><value>Discard the changes of {0}?</value></data>
@@ -281,6 +283,7 @@
<data name="Editor.RemoveCopy.SendFirst" xml:space="preserve"><value>Send first</value></data>
<data name="Editor.RemoveCopy.Size" xml:space="preserve"><value>Size</value></data>
<data name="Editor.RemoveCopy.Title" xml:space="preserve"><value>Remove local copy of {0}</value><comment>{0} project name</comment></data>
<data name="Editor.RemoveCopy.TypeFiles" xml:space="preserve"><value>Type the number of files, {0}, to confirm</value><comment>long; {0} number of files</comment></data>
<data name="Editor.RemoveCopy.TypeName" xml:space="preserve"><value>Type the project name to confirm</value><comment>long</comment></data>
<data name="Editor.RemoveCopy.Unsent" xml:space="preserve"><value>Versions not sent</value></data>
<data name="Editor.RemoveCopy.Yes" xml:space="preserve"><value>Yes</value></data>
@@ -389,6 +392,8 @@
<data name="Editor.Workspace.DeleteFailed" xml:space="preserve"><value>Project not deleted</value></data>
<data name="Editor.Workspace.Deleted" xml:space="preserve"><value>Project {0} deleted</value><comment>{0} project name</comment></data>
<data name="Editor.Workspace.Difference" xml:space="preserve"><value>{0} {1} here, {2} in the library</value><comment>long; {0} setting name, {1} value in this workspace, {2} value in the library</comment></data>
<data name="Editor.Workspace.EditSetAside" xml:space="preserve"><value>Edit kept aside</value></data>
<data name="Editor.Workspace.EditSetAsideMessage" xml:space="preserve"><value>A newer Chronos saved this project before your last edit was stored: that edit is kept aside in the project's folder, and the newer settings show read-only.</value><comment>long</comment></data>
<data name="Editor.Workspace.Edited.Message" xml:space="preserve"><value>{0} changed in the library while your edit waited to be saved. The settings below differ: keep your values, or take the library's.</value><comment>long</comment></data>
<data name="Editor.Workspace.InSync" xml:space="preserve"><value>Project in sync</value></data>
<data name="Editor.Workspace.MediaChanged" xml:space="preserve"><value>Library photos changed</value></data>
@@ -413,6 +418,7 @@
<data name="Editor.Workspace.State.InSync" xml:space="preserve"><value>In sync</value></data>
<data name="Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>No media</value></data>
<data name="Editor.Workspace.State.Modified" xml:space="preserve"><value>Changed</value><comment>the project has changes not saved as a version</comment></data>
<data name="Editor.Workspace.State.NewerCopy" xml:space="preserve"><value>Newer Chronos</value><comment>a newer Chronos saved this workspace copy; this one cannot open it</comment></data>
<data name="Editor.Workspace.State.Offline" xml:space="preserve"><value>Offline</value></data>
<data name="Editor.Workspace.State.Reading" xml:space="preserve"><value>Checking</value><comment>the project's state is being read from the library</comment></data>
<data name="Editor.Workspace.State.Syncing" xml:space="preserve"><value>Syncing</value></data>
+1
View File
@@ -67,6 +67,7 @@
<data name="Errors.Workspace.MediaChanged" xml:space="preserve"><value>The workspace's photos of this project changed; the editor reads them again.</value></data>
<data name="Errors.Workspace.MediaMissing" xml:space="preserve"><value>The workspace holds no photos of this project; open it again to copy them.</value></data>
<data name="Errors.Workspace.NameTaken" xml:space="preserve"><value>Another project of this sequence has that name.</value></data>
<data name="Errors.Workspace.NewerCopy" xml:space="preserve"><value>A newer Chronos saved this copy in the workspace; update Chronos to open it or remove it.</value></data>
<data name="Errors.Workspace.NoRoom" xml:space="preserve"><value>The drive of the workspace folder lacks room for this copy and the 0.5 GB the copy keeps free.</value></data>
<data name="Errors.Workspace.NotCheckedOut" xml:space="preserve"><value>The project is no longer in the workspace.</value></data>
<data name="Errors.Workspace.Offline" xml:space="preserve"><value>The library cannot be reached now; your work stays in the workspace and can be sent once it is back.</value></data>
+1
View File
@@ -344,6 +344,7 @@
<data name="Tooltips.Editor.Workspace.State.InSync" xml:space="preserve"><value>Every version of this project is in the library, and nothing changed since the last one</value></data>
<data name="Tooltips.Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>The workspace holds no photos of this project: opening it copies them again</value></data>
<data name="Tooltips.Editor.Workspace.State.Modified" xml:space="preserve"><value>Changes not saved as a version yet: Save version (Ctrl+S) keeps them in the history</value></data>
<data name="Tooltips.Editor.Workspace.State.NewerCopy" xml:space="preserve"><value>A newer Chronos saved this copy, so this one cannot open it; update Chronos: nothing in it is changed or removed here</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.State.Offline" xml:space="preserve"><value>The library cannot be reached now: your work stays here and is sent once it is back</value></data>
<data name="Tooltips.Editor.Workspace.State.OfflineAhead" xml:space="preserve"><value>The library cannot be reached now. Versions waiting to be sent once it is back: {0}</value><comment>{0} number of versions</comment></data>
<data name="Tooltips.Editor.Workspace.State.Reading" xml:space="preserve"><value>Asking the library where this project stands</value></data>
+6
View File
@@ -260,6 +260,8 @@
<data name="Editor.Remote.Outdated" xml:space="preserve"><value>{0} · proxy superati</value></data>
<data name="Editor.Remote.ReadOnly" xml:space="preserve"><value>{0} · sola lettura</value></data>
<data name="Editor.RemoveCopy.Changed" xml:space="preserve"><value>Modifiche non salvate</value></data>
<data name="Editor.RemoveCopy.DamagedDiscard" xml:space="preserve"><value>Scartare una copia danneggiata?</value></data>
<data name="Editor.RemoveCopy.DamagedTitle" xml:space="preserve"><value>Rimuovi una copia danneggiata</value></data>
<data name="Editor.RemoveCopy.Discard" xml:space="preserve"><value>Scarta modifiche</value></data>
<data name="Editor.RemoveCopy.DiscardMessage" xml:space="preserve"><value>Le versioni non inviate e le modifiche non salvate vanno nella cartella cestino dello spazio di lavoro; Chronos non le riporta indietro.</value></data>
<data name="Editor.RemoveCopy.DiscardTitle" xml:space="preserve"><value>Scartare le modifiche di {0}?</value></data>
@@ -270,6 +272,7 @@
<data name="Editor.RemoveCopy.SendFirst" xml:space="preserve"><value>Prima invia</value></data>
<data name="Editor.RemoveCopy.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Editor.RemoveCopy.Title" xml:space="preserve"><value>Rimuovi copia locale di {0}</value></data>
<data name="Editor.RemoveCopy.TypeFiles" xml:space="preserve"><value>Scrivi il numero di file, {0}, per confermare</value></data>
<data name="Editor.RemoveCopy.TypeName" xml:space="preserve"><value>Scrivi il nome del progetto per confermare</value></data>
<data name="Editor.RemoveCopy.Unsent" xml:space="preserve"><value>Versioni non inviate</value></data>
<data name="Editor.RemoveCopy.Yes" xml:space="preserve"><value>Sì</value></data>
@@ -364,6 +367,8 @@
<data name="Editor.Workspace.DeleteFailed" xml:space="preserve"><value>Progetto non eliminato</value></data>
<data name="Editor.Workspace.Deleted" xml:space="preserve"><value>Progetto {0} eliminato</value></data>
<data name="Editor.Workspace.Difference" xml:space="preserve"><value>{0} {1} qui, {2} nella libreria</value></data>
<data name="Editor.Workspace.EditSetAside" xml:space="preserve"><value>Modifica da parte</value></data>
<data name="Editor.Workspace.EditSetAsideMessage" xml:space="preserve"><value>Un Chronos più recente ha salvato questo progetto prima che la tua ultima modifica fosse memorizzata: quella modifica è tenuta da parte nella cartella del progetto, e le impostazioni più recenti si vedono in sola lettura.</value></data>
<data name="Editor.Workspace.Edited.Message" xml:space="preserve"><value>{0} è cambiato nella libreria mentre la tua modifica attendeva il salvataggio. Le impostazioni qui sotto sono diverse: tieni i tuoi valori o prendi quelli della libreria.</value></data>
<data name="Editor.Workspace.InSync" xml:space="preserve"><value>Progetto sincronizzato</value></data>
<data name="Editor.Workspace.MediaChanged" xml:space="preserve"><value>Foto della libreria cambiate</value></data>
@@ -388,6 +393,7 @@
<data name="Editor.Workspace.State.InSync" xml:space="preserve"><value>Sincronizzato</value></data>
<data name="Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>Senza media</value></data>
<data name="Editor.Workspace.State.Modified" xml:space="preserve"><value>Modificato</value></data>
<data name="Editor.Workspace.State.NewerCopy" xml:space="preserve"><value>Chronos più recente</value></data>
<data name="Editor.Workspace.State.Offline" xml:space="preserve"><value>Non in linea</value></data>
<data name="Editor.Workspace.State.Reading" xml:space="preserve"><value>Verifica</value></data>
<data name="Editor.Workspace.State.Syncing" xml:space="preserve"><value>Sincronizzazione</value></data>
+1
View File
@@ -67,6 +67,7 @@
<data name="Errors.Workspace.MediaChanged" xml:space="preserve"><value>Le foto di questo progetto nello spazio di lavoro sono cambiate; l'editor le rilegge.</value></data>
<data name="Errors.Workspace.MediaMissing" xml:space="preserve"><value>Lo spazio di lavoro non ha foto di questo progetto; riaprilo per copiarle.</value></data>
<data name="Errors.Workspace.NameTaken" xml:space="preserve"><value>Un altro progetto di questa sequenza ha già quel nome.</value></data>
<data name="Errors.Workspace.NewerCopy" xml:space="preserve"><value>Un Chronos più recente ha salvato questa copia nello spazio di lavoro; aggiorna Chronos per aprirla o rimuoverla.</value></data>
<data name="Errors.Workspace.NoRoom" xml:space="preserve"><value>All'unità della cartella dello spazio di lavoro manca lo spazio per questa copia e per gli 0,5 GB che la copia lascia liberi.</value></data>
<data name="Errors.Workspace.NotCheckedOut" xml:space="preserve"><value>Il progetto non è più nello spazio di lavoro.</value></data>
<data name="Errors.Workspace.Offline" xml:space="preserve"><value>La libreria ora non è raggiungibile; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando torna.</value></data>
+1
View File
@@ -343,6 +343,7 @@
<data name="Tooltips.Editor.Workspace.State.InSync" xml:space="preserve"><value>Ogni versione di questo progetto è nella libreria e nulla è cambiato dall'ultima</value></data>
<data name="Tooltips.Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>Lo spazio di lavoro non ha foto di questo progetto: aprirlo le copia di nuovo</value></data>
<data name="Tooltips.Editor.Workspace.State.Modified" xml:space="preserve"><value>Modifiche non ancora salvate come versione: Salva versione (Ctrl+S) le tiene nella cronologia</value></data>
<data name="Tooltips.Editor.Workspace.State.NewerCopy" xml:space="preserve"><value>Un Chronos più recente ha salvato questa copia, quindi questo non può aprirla; aggiorna Chronos: qui nulla viene cambiato o rimosso</value></data>
<data name="Tooltips.Editor.Workspace.State.Offline" xml:space="preserve"><value>La libreria ora non è raggiungibile: il tuo lavoro resta qui e viene inviato quando torna</value></data>
<data name="Tooltips.Editor.Workspace.State.OfflineAhead" xml:space="preserve"><value>La libreria ora non è raggiungibile. Versioni in attesa di essere inviate quando torna: {0}</value></data>
<data name="Tooltips.Editor.Workspace.State.Reading" xml:space="preserve"><value>Chiede alla libreria lo stato di questo progetto</value></data>
+74 -7
View File
@@ -69,6 +69,12 @@ public sealed class EditorSession : IAsyncDisposable
/// <summary>A save met settings changed on the server too (<see cref="Conflict"/> was null): the user picks a side.</summary>
public event Action<ProjectConflictException>? ConflictFound;
/// <summary>
/// An edit not stored yet met a newer Chronos's settings stored meanwhile, which this one never merges with: the edit
/// was kept aside at the path given (<see cref="ISequenceSource.SetAsideAsync"/>) and the newer settings shown read-only.
/// </summary>
public event Action<string>? EditSetAside;
public ISequenceSource Source { get; }
/// <summary>A server sequence edited with proxies: saved, analysed and rendered on the server.</summary>
@@ -204,8 +210,17 @@ public sealed class EditorSession : IAsyncDisposable
Conflict = null;
var basis = _basis;
_basis = theirs;
History.Replace(Source.Merge(basis, Project, theirs).Merged);
if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged);
try
{
History.Replace(Source.Merge(basis, Project, theirs).Merged);
if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged);
}
catch (NewerSettingsException ex)
{
// Never merged with a newer Chronos's settings: the edit is kept aside, those settings shown read-only.
_ = TakeNewerAsync(theirs, ex, CancellationToken.None);
return true;
}
// The change waiting for its retry goes now, on top of the server's settings.
_ = _saver.FlushAsync();
return true;
@@ -237,7 +252,9 @@ public sealed class EditorSession : IAsyncDisposable
/// <summary>
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken,
/// and a read waits for the one under way, so each follows the frames the one before it took.
/// and a read waits for the one under way, so each follows the frames the one before it took. A stored project of a
/// newer Chronos met with an edit not stored yet is never merged: the edit is kept aside and the newer settings shown
/// read-only (<see cref="EditSetAside"/>).
/// </summary>
public async Task ReloadAsync(CancellationToken cancellationToken = default)
{
@@ -249,7 +266,15 @@ public sealed class EditorSession : IAsyncDisposable
Follow(content);
// 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;
ProjectMergeResult? merge = null;
try
{
merge = Conflict is null ? Source.Merge(_basis, Project, content.Project) : null;
}
catch (NewerSettingsException ex)
{
await TakeNewerAsync(content.Project, ex, cancellationToken);
}
if (merge is not null && (!Source.AsksConflicts || !merge.HasConflicts))
{
_basis = content.Project;
@@ -283,9 +308,17 @@ public sealed class EditorSession : IAsyncDisposable
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);
try
{
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);
}
catch (NewerSettingsException ex)
{
_basis = basis;
await TakeNewerAsync(content.Project, ex, cancellationToken);
}
}
finally
{
@@ -343,6 +376,40 @@ public sealed class EditorSession : IAsyncDisposable
NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project;
}
/// <summary>
/// The stored project is a newer Chronos's (<paramref name="newer"/>) while the editor holds an edit not stored yet,
/// which this Chronos can neither merge with it nor store over it (<see cref="NewerSettingsException"/>): the edit is
/// kept aside by the source (<see cref="ISequenceSource.SetAsideAsync"/>, said by <see cref="EditSetAside"/>), never
/// dropped silently, and only then are the newer settings taken, read-only, the pending save dropped with it. A source
/// that keeps nothing aside, or a set-aside that fails, leaves the editor as it is (logged): the next read tries again.
/// Never throws.
/// </summary>
private async Task TakeNewerAsync(ProjectSettings newer, NewerSettingsException cause, CancellationToken cancellationToken)
{
var unsaved = Project;
string? kept;
try
{
kept = await Source.SetAsideAsync(unsaved, cancellationToken);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet could not be kept aside; it stays in the editor", ex);
return;
}
if (kept is null)
{
Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet meets newer settings and stays in the editor: {cause.Message}");
return;
}
Log.Info("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet was kept in {kept}: the stored project is a newer Chronos's ({cause.Message})");
_saver.Drop();
Conflict = null;
_basis = newer;
History.Replace(newer);
EditSetAside?.Invoke(kept);
}
/// <summary>
/// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new
/// one under way until the returned source is completed.
+12
View File
@@ -149,6 +149,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
session.ContentChanged += OnContentChanged;
session.SaveFailed += OnSaveFailed;
session.ConflictFound += OnConflictFound;
session.EditSetAside += OnEditSetAside;
session.Source.JobChanged += OnJobChanged;
session.Source.ReadOnlyChanged += OnReadOnlyChanged;
shell.Services.Sync.Changed += OnSyncChanged;
@@ -725,6 +726,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Session.ContentChanged -= OnContentChanged;
Session.SaveFailed -= OnSaveFailed;
Session.ConflictFound -= OnConflictFound;
Session.EditSetAside -= OnEditSetAside;
Session.Source.JobChanged -= OnJobChanged;
Session.Source.ReadOnlyChanged -= OnReadOnlyChanged;
Shell.Services.Sync.Changed -= OnSyncChanged;
@@ -1053,6 +1055,16 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
ActionCommand = new RelayCommand(() => _ = Session.FlushAsync()),
});
/// <summary>
/// An edit not stored yet met a newer Chronos's settings a sync took (owner review 2, R8): it was kept aside in the
/// project's folder, never dropped, and the toast says so; the newer settings show read-only.
/// </summary>
private void OnEditSetAside(string path) => _dispatcher.BeginInvoke(() =>
{
if (_disposed) return;
Shell.ShowToast(new Toast { Title = Loc.L("Editor.Workspace.EditSetAside"), Message = Loc.L("Editor.Workspace.EditSetAsideMessage") });
});
/// <summary>
/// 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
@@ -81,6 +81,13 @@ public interface ISequenceSource : IAsyncDisposable
/// </summary>
ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs);
/// <summary>
/// Keeps <paramref name="unsaved"/>, an edit that can no longer be stored (the stored project became a newer Chronos's,
/// which this one never merges with), where the user finds it and nothing sends it; returns where, or null when this
/// source keeps nothing aside (the edit then stays in the editor as it is).
/// </summary>
Task<string?> SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
+29 -1
View File
@@ -21,6 +21,9 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
private bool _flushRequested;
private bool _stopped;
private int _failures;
/// <summary>Changes dropped (<see cref="Drop"/>): a write that fails after one is not retried.</summary>
private int _drops;
private CancellationTokenSource? _wait;
/// <summary>No write starts until <see cref="Release"/> (or <see cref="Stop"/>): the user is being asked about the pending change.</summary>
@@ -103,6 +106,22 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
lock (_gate) ReleaseHold();
}
/// <summary>
/// Drops what is pending, a write under way included should it fail, and keeps saving what is scheduled from now on: the
/// change was kept elsewhere (set aside when the stored project became a newer Chronos's, where it can never be stored).
/// </summary>
public void Drop()
{
lock (_gate)
{
_pending = null;
_drops++;
_failures = 0;
LastError = null;
_wait?.Cancel();
}
}
/// <summary>Drops what is pending and stops retrying (the editor closed and the user chose to discard the change).</summary>
public void Stop()
{
@@ -153,8 +172,10 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
continue;
}
ProjectSettings next;
int drops;
lock (_gate)
{
drops = _drops;
_flushRequested = false;
if (_pending is null)
{
@@ -184,9 +205,16 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
}
catch (Exception ex)
{
LastError = ex;
lock (_gate)
{
if (_drops != drops)
{
// Dropped while it was written (kept elsewhere): not retried, and no failure to report.
EndWrite();
wait = TimeSpan.Zero;
continue;
}
LastError = ex;
// A newer change contains this one (projects are whole snapshots); otherwise this one waits for the retry.
if (!_stopped) _pending ??= next;
failures = ++_failures;
@@ -252,6 +252,43 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ProjectSettings.FromJson(ProjectContent.ToPortable(settings, photos), allowNewer: true);
}
/// <summary>
/// Keeps an edit the working state can no longer take (a sync brought a newer Chronos's settings) as a version file in
/// <c>versions/.replaced</c>, where a take of the library's values keeps the working state it replaces: outside the chain
/// of versions, so it is never sent, and never lost. Written under the project's lease, its positions parked by photo.
/// </summary>
/// <exception cref="Core.Archiving.LeaseUnavailableException">Another writer kept the project for longer than the sync waits.</exception>
public Task<string?> SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(unsaved);
var folder = Project;
var (photos, framesVersion, basis) = (Photos, MediaFramesVersion, Workspace?.Base);
return Task.Run<string?>(async () =>
{
using (await folder.LockAsync(_sync.LockWait, cancellationToken))
{
var portable = ProjectContent.ToPortable(unsaved, photos);
var version = new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = ProjectId,
ParentId = basis?.VersionId,
Number = (basis?.Number ?? 0) + 1,
Kind = ProjectVersionKind.Commit,
ClientName = Environment.MachineName,
SettingsJson = portable,
ContentHash = ProjectContent.Hash(portable),
SettingsFormat = ProjectContent.FormatOf(portable),
FramesVersion = Math.Max(0, framesVersion),
CreatedAt = DateTimeOffset.UtcNow,
};
var path = Path.Combine(folder.VersionsDirectory, WorkspaceProject.ReplacedFolder, Path.GetFileName(folder.VersionPath(version)));
ProjectSidecars.WriteVersion(path, version);
return path;
}
}, cancellationToken);
}
/// <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);
@@ -285,8 +285,8 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
foreach (var item in items)
{
if (generation != _generation) return;
// Its working state cannot be read: there is no state to ask for.
if (item.IsDamaged) continue;
// This Chronos cannot read its working state: there is no state to ask for.
if (!item.IsReadable) continue;
try
{
item.Status = await Shell.Services.Workspace.StatusAsync(item.ProjectId);
+10 -3
View File
@@ -232,6 +232,12 @@ public sealed class SequenceViewModel : SectionViewModel
KeepOpenSequence();
return;
}
// A copy a newer Chronos wrote neither opens nor goes from here: the toast says so, nothing is offered over it.
if (item.IsNewer)
{
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), Loc.L("Errors.Workspace.NewerCopy"), isError: true);
return;
}
// A copy whose working state cannot be read cannot open: its removal plan is what it offers.
if (item.IsDamaged)
{
@@ -441,7 +447,8 @@ public sealed class SequenceViewModel : SectionViewModel
{
await workspace.SendAllAsync(projectId);
await RemoveCopyAsync(projectId, name, discard: false);
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, name), d => CloseDialog(d)));
}, () => plan.Damaged ? RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, plan) : RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, name),
d => CloseDialog(d)));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -595,8 +602,8 @@ public sealed class SequenceViewModel : SectionViewModel
{ Main: true } => (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain),
_ => await workspace.LastUsedAsync(row.Id),
};
// Its working state cannot be read: nothing is checked out over it (the picker offers Remove local copy).
if (entry is { Damaged: true }) throw new WorkspaceException(Loc.L("Errors.Workspace.Damaged"));
// This Chronos cannot read its working state (damaged, or a newer Chronos's): nothing is checked out over it.
if (entry is { IsReadable: false } unreadable) throw WorkspaceHost.Unreadable(unreadable);
if (entry is { HasMedia: true })
{
workspace.Remember(row.Id, entry.ProjectId);
+30 -2
View File
@@ -503,7 +503,10 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
public WorkspaceRemovalPlan Plan { get; }
public string Heading => Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false));
/// <summary>"Remove local copy of Main"; a damaged copy by the name it is still known by, else as a damaged copy (never by its folder's id).</summary>
public string Heading => !Plan.Damaged ? Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false))
: Plan.KnownName is { Length: > 0 } known ? Loc.L("Editor.RemoveCopy.Title", known)
: Loc.L("Editor.RemoveCopy.DamagedTitle");
public IReadOnlyList<DialogFact> Facts { get; }
@@ -547,13 +550,38 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
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>
/// <summary>
/// The typed confirmation of discarding a damaged copy (<see cref="WorkspaceRemovalPlan.Damaged"/>): the name it is still
/// known by (<see cref="WorkspaceRemovalPlan.KnownName"/>), never its folder's id; with no name known, the number of its
/// files, as the plan shows it.
/// </summary>
public static ConfirmRequest DiscardRequest(WorkspaceRemovalPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.KnownName is { Length: > 0 } known) return DiscardRequest(known);
var files = Formatting.Count(plan.Files);
return DiscardRequest(string.Empty) with
{
Heading = Loc.L("Editor.RemoveCopy.DamagedDiscard"),
TypedConfirmation = files,
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeFiles", files),
};
}
/// <summary>Asks <see cref="DiscardRequest(string)"/> through <paramref name="ui"/>: true when the user typed the name and confirmed.</summary>
public static bool ConfirmDiscard(IWorkspaceUi ui, string projectName)
{
ArgumentNullException.ThrowIfNull(ui);
return ui.Confirm(DiscardRequest(projectName));
}
/// <summary>Asks <see cref="DiscardRequest(WorkspaceRemovalPlan)"/> through <paramref name="ui"/>: true when the user typed what it asks and confirmed.</summary>
public static bool ConfirmDiscard(IWorkspaceUi ui, WorkspaceRemovalPlan plan)
{
ArgumentNullException.ThrowIfNull(ui);
return ui.Confirm(DiscardRequest(plan));
}
private async Task DiscardAsync()
{
if (!_confirmDiscard()) return;
+155 -26
View File
@@ -1,4 +1,5 @@
using System.IO;
using System.Text.Json;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
@@ -25,11 +26,32 @@ public sealed class WorkspaceException(string message, Exception? inner = null)
/// <param name="HasMedia">The workspace holds the project's media (a copy that ended); without them it cannot open.</param>
/// <param name="Saved">When its working state was last written.</param>
/// <param name="Damaged">
/// Its working state (<c>project.chronos</c>) cannot be read: listed by its folder, it cannot open, and Remove local copy
/// can only keep its files aside in the workspace's trash (Discard).
/// Its working state (<c>project.chronos</c>) cannot be read: listed by the name it is still known by (else its folder), it
/// cannot open, and Remove local copy can only keep its files aside in the workspace's trash (Discard).
/// </param>
/// <remarks>
/// A copy this Chronos cannot read is no project of its sequence here (<see cref="SequenceId"/> is empty): nothing opens,
/// checks out or is copied over it.
/// </remarks>
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
DateTimeOffset Saved, bool Damaged = false);
DateTimeOffset Saved, bool Damaged = false)
{
/// <summary>
/// Its working state was written by a newer Chronos (a project file format this one does not know): listed as such,
/// it neither opens nor goes from here, and nothing in it is changed; a newer Chronos opens it.
/// </summary>
public bool Newer { get; init; }
/// <summary>
/// A copy this Chronos cannot read (<see cref="Damaged"/> or <see cref="Newer"/>): the name it is still known by (its
/// project's, else its sequence's), from what of its project file can be read or from the library's index; null when
/// neither knows it.
/// </summary>
public string? KnownName { get; init; }
/// <summary>This Chronos reads its working state: it can open.</summary>
public bool IsReadable => !Damaged && !Newer;
}
/// <summary>What changing the workspace folder to <see cref="Folder"/> does: Edit lists its projects from then on; nothing is moved.</summary>
/// <param name="Current">The folder in use, whose projects stay where they are (listed again once it is chosen back).</param>
@@ -73,6 +95,12 @@ public sealed record WorkspaceHistory(IReadOnlyList<ProjectVersion> Versions, IR
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline, bool Gone = false,
bool Damaged = false)
{
/// <summary>
/// A damaged copy: the name Discard asks to type (<see cref="WorkspaceEntry.KnownName"/>); null when no name is known,
/// and the number of its files is typed instead.
/// </summary>
public string? KnownName { get; init; }
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict && !Damaged;
}
@@ -176,25 +204,35 @@ public sealed class WorkspaceHost
/// <summary>
/// The projects of the workspace; one whose working state cannot be read is listed as damaged (<see cref="WorkspaceEntry.Damaged"/>),
/// never hidden, and logged. A workspace folder not made yet that lies inside a library is not made by listing it: it lists nothing.
/// one a newer Chronos wrote as such (<see cref="WorkspaceEntry.Newer"/>), never hidden, 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.List().Select(EntryOrDamaged)];
var entries = new List<WorkspaceEntry>();
foreach (var project in Store.List()) entries.Add(await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false));
return (IReadOnlyList<WorkspaceEntry>)entries;
}, 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 (damaged when its working state cannot be read); null when the workspace has none.</summary>
/// <summary>A workspace project by id (damaged or newer when this Chronos cannot read its working state); null when the workspace has none.</summary>
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
return Store.Find(projectId) is { } project ? EntryOrDamaged(project) : null;
return Store.Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
}, cancellationToken);
/// <summary>Why a copy this Chronos cannot read neither opens nor is checked out over: a newer Chronos wrote it, or it is damaged.</summary>
public static WorkspaceException Unreadable(WorkspaceEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return new WorkspaceException(Loc.L(entry.Newer ? "Errors.Workspace.NewerCopy" : "Errors.Workspace.Damaged"));
}
/// <summary>
/// What changing the workspace folder to <paramref name="folder"/> would do (Settings › Workspace › Change, and the
/// refusal of a folder inside a library): the projects the folder in use keeps where they are, those the new one holds
@@ -293,6 +331,9 @@ public sealed class WorkspaceHost
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
: listed.First(p => p.IsMain);
}
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
throw Unreadable(unreadable);
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false));
@@ -569,15 +610,18 @@ public sealed class WorkspaceHost
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
/// <exception cref="WorkspaceException">A newer Chronos wrote the copy: it goes from there, never from here.</exception>
public Task<WorkspaceRemovalPlan> PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
if (EntryOrDamaged(project) is { Damaged: true } damaged)
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
if (entry.Newer) throw Unreadable(entry);
if (entry.Damaged)
{
// What it holds is not known: every version file not marked sent, or not readable, counts as unsent work, kept aside by Discard.
var (count, size) = Measure(project.Folder);
var unsent = project.Versions().Count(v => v.StoredAt is null) + project.UnreadableVersions().Count;
return new WorkspaceRemovalPlan(projectId, damaged.Name, count, size, unsent, true, false, false, Damaged: true);
return new WorkspaceRemovalPlan(projectId, entry.Name, count, size, unsent, true, false, false, Damaged: true) { KnownName = entry.KnownName };
}
var name = project.ReadBundle().Workspace!.Name;
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -589,16 +633,21 @@ public sealed class WorkspaceHost
/// <summary>
/// Removes a project's local copy. Without <paramref name="discard"/> it is refused while anything is not at the home,
/// and the home's head and the base this copy was made from are read back and checked against their hashes first.
/// With <paramref name="discard"/> (the user's explicit word) the versions not sent and the working state are moved to
/// <c>&lt;workspace&gt;/.trash</c> rather than erased. The media (copies the home can make again) are deleted.
/// With <paramref name="discard"/> (the user's explicit word) every file of the folder but the media (the versions not
/// sent, the working state, whatever else it holds) is moved to <c>&lt;workspace&gt;/.trash</c> rather than erased. The
/// media (copies the home can make again) are deleted.
/// </summary>
/// <exception cref="WorkspaceException">Something is not at the home yet, or the home's copy does not check out.</exception>
/// <exception cref="WorkspaceException">
/// Something is not at the home yet, the home's copy does not check out, or a newer Chronos wrote the copy (it goes from there).
/// </exception>
public async Task RemoveLocalCopyAsync(Guid projectId, bool discard, CancellationToken cancellationToken = default)
{
var sequenceId = await Task.Run(async () =>
{
var project = Existing(projectId);
if (EntryOrDamaged(project) is { Damaged: true })
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
if (entry.Newer) throw Unreadable(entry);
if (entry.Damaged)
{
// Its working state cannot be read: only Discard, which keeps every file of it aside, takes it out.
if (!discard) throw new WorkspaceException(Loc.L("Errors.Workspace.Damaged"));
@@ -699,9 +748,10 @@ public sealed class WorkspaceHost
}
/// <summary>
/// The project's folder taken out of the workspace under its lease: the working state, the versions, the sync state and
/// the exports moved to <c>.trash/&lt;id&gt;-&lt;time&gt;</c> (kept: nothing a user made is erased), the media deleted; the
/// emptied folder goes once the lease is released.
/// The project's folder taken out of the workspace under its lease: every file and folder in it but the media and the
/// lease (the working state, the versions, the sync state, the exports, and whatever else a Chronos keeps there) moved
/// to <c>.trash/&lt;id&gt;-&lt;time&gt;</c> as it is (kept: nothing a user made is erased), the media deleted; the emptied
/// folder goes once the lease is released, only when nothing else came into it meanwhile.
/// </summary>
private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
@@ -717,20 +767,27 @@ public sealed class WorkspaceHost
Directory.CreateDirectory(aside);
// The working state first: without it the folder is no project any more, whatever happens after.
File.Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile));
if (File.Exists(project.SyncPath)) File.Move(project.SyncPath, Path.Combine(aside, WorkspaceProject.SyncFile));
if (Directory.Exists(project.VersionsDirectory)) Directory.Move(project.VersionsDirectory, Path.Combine(aside, WorkspaceProject.VersionsFolder));
if (Directory.Exists(project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(project.ExportsDirectory).Any())
Directory.Move(project.ExportsDirectory, Path.Combine(aside, WorkspaceProject.ExportsFolder));
foreach (var entry in Directory.EnumerateFileSystemEntries(project.Folder).ToList())
{
var name = Path.GetFileName(entry);
if (IsLease(name) || string.Equals(name, WorkspaceProject.MediaFolder, StringComparison.OrdinalIgnoreCase)) continue;
if (Directory.Exists(entry)) Directory.Move(entry, Path.Combine(aside, name));
else File.Move(entry, Path.Combine(aside, name));
}
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
}
try
{
Directory.Delete(project.Folder, recursive: true);
// Only the lease's leftovers may be left: anything else is kept where it is.
if (Directory.EnumerateFileSystemEntries(project.Folder).All(e => IsLease(Path.GetFileName(e)))) Directory.Delete(project.Folder, recursive: true);
else Log.Info("workspace", $"The folder {project.Folder} stays: files came into it while its copy was removed");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Info("workspace", $"The emptied folder {project.Folder} stays: {ex.Message}");
}
static bool IsLease(string name) => name.StartsWith(".lock.lease", StringComparison.OrdinalIgnoreCase);
}
/// <summary>A version can be saved: no conflict waits, the settings are this Chronos's, the media are here.</summary>
@@ -801,8 +858,12 @@ public sealed class WorkspaceHost
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
}
/// <summary>The project's entry; a damaged one, named by its folder, when its working state cannot be read (logged).</summary>
private static WorkspaceEntry EntryOrDamaged(WorkspaceProject project)
/// <summary>
/// The project's entry; when its working state cannot be read (logged), one written by a newer Chronos
/// (<see cref="WorkspaceEntry.Newer"/>) or a damaged one (<see cref="WorkspaceEntry.Damaged"/>), named as it is still
/// known (what of its project file reads, else the library's index), else by its folder.
/// </summary>
private async Task<WorkspaceEntry> EntryOrUnreadableAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
try
{
@@ -810,10 +871,78 @@ public sealed class WorkspaceHost
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
var peek = BundlePeek.Of(project);
if (peek.Newer) Log.Info("workspace", $"The project in {project.Folder} was saved by a newer Chronos (project file format {peek.Format}): it is left as it is");
else Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
var (name, isMain, title) = (peek.Name, peek.IsMain, peek.Title);
if ((name is null || title is null) && _db() is { } db)
{
try
{
if (await db.Projects.GetAsync(project.ProjectId, cancellationToken).ConfigureAwait(false) is { } known)
{
if (name is null) (name, isMain) = (known.Name, known.IsMain);
title ??= (await db.Sequences.GetAsync(known.SequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle;
}
}
catch (DatabaseException dbx)
{
Log.Info("workspace", $"The index could not name the project in {project.Folder}: {dbx.Message}");
}
}
var saved = File.Exists(project.BundlePath) ? new DateTimeOffset(File.GetLastWriteTimeUtc(project.BundlePath), TimeSpan.Zero) : DateTimeOffset.MinValue;
return new WorkspaceEntry(project.ProjectId, Guid.Empty, Path.GetFileName(project.Folder), false, new BundleHome(BundleHome.ArchiveKind, Guid.Empty),
project.Folder, false, saved, Damaged: true);
var shown = name is null ? null : WorkspaceText.ProjectName(name, isMain);
return new WorkspaceEntry(project.ProjectId, Guid.Empty, name ?? Path.GetFileName(project.Folder), isMain && name is not null,
new BundleHome(BundleHome.ArchiveKind, Guid.Empty), title ?? project.Folder, false, peek.Saved ?? saved, Damaged: !peek.Newer)
{
Newer = peek.Newer,
KnownName = shown ?? title,
};
}
}
/// <summary>
/// What a working state this Chronos cannot read still says, read as loosely as its JSON allows: whether a newer
/// Chronos wrote it (a format newer than <see cref="ProjectBundle.CurrentFormatVersion"/>), and the project's name,
/// its sequence's title and when it was saved, each when it is there.
/// </summary>
private sealed record BundlePeek(bool Newer, int Format, string? Name, bool IsMain, string? Title, DateTimeOffset? Saved)
{
private static readonly BundlePeek Nothing = new(false, 0, null, false, null, null);
public static BundlePeek Of(WorkspaceProject project)
{
try
{
var info = new FileInfo(project.BundlePath);
if (!info.Exists || info.Length > ProjectBundle.MaxBytes) return Nothing;
using var document = JsonDocument.Parse(File.ReadAllBytes(info.FullName), new JsonDocumentOptions { MaxDepth = 64 });
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != ProjectBundle.FormatName) return Nothing;
var format = root.TryGetProperty("formatVersion", out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n) ? n : 0;
string? name = null;
var isMain = false;
if (root.TryGetProperty("workspace", out var workspace) && workspace.ValueKind == JsonValueKind.Object
&& Text(workspace, "projectId") is { } id && Guid.TryParse(id, out var projectId) && projectId == project.ProjectId)
{
name = Text(workspace, "name") is { Length: > 0 } named ? named : null;
isMain = workspace.TryGetProperty("isMain", out var main) && main.ValueKind == JsonValueKind.True;
}
var title = root.TryGetProperty("sequence", out var sequence) && sequence.ValueKind == JsonValueKind.Object
? Text(sequence, "title") is { Length: > 0 } t ? t : Text(sequence, "folder") is { Length: > 0 } f ? f : null
: null;
DateTimeOffset? saved = root.TryGetProperty("saved", out var s) && s.ValueKind == JsonValueKind.String && s.TryGetDateTimeOffset(out var when)
? when
: null;
return new BundlePeek(format > ProjectBundle.CurrentFormatVersion, format, name, isMain, title, saved);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
{
return Nothing;
}
static string? Text(JsonElement element, string property) =>
element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
}
}
@@ -9,7 +9,7 @@ namespace Chronos.App.Workspace;
/// <summary>
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
/// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed
/// as damaged, by its folder.
/// as damaged, one a newer Chronos wrote as such, by the name each is still known by.
/// </summary>
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
{
@@ -45,12 +45,22 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
/// <summary>Its working state cannot be read: it cannot open, and Remove local copy keeps its files aside.</summary>
public bool IsDamaged => Entry.Damaged;
public string StateText => Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
/// <summary>A newer Chronos wrote its working state: it neither opens nor goes from here, and stays as it is.</summary>
public bool IsNewer => Entry.Newer;
/// <summary>This Chronos reads its working state: it opens, and its state is asked of its home.</summary>
public bool IsReadable => Entry.IsReadable;
public string StateText => Entry.Newer ? Loc.L("Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
public StatusKind StateKind => Entry.Damaged ? StatusKind.Error : Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
public StatusKind StateKind => Entry.Newer ? StatusKind.Warning
: Entry.Damaged ? StatusKind.Error
: Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
public string StateToolTip => Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")
public string StateToolTip => Entry.Newer ? Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
/// <summary>"Vertical social · Harbour sunset · In sync": what screen readers hear for the row.</summary>
+31 -9
View File
@@ -480,7 +480,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// only when they are those <paramref name="shown"/> lists (others are recorded and asked about first, as without a
/// choice). Taking the server's everywhere tells <paramref name="kept"/> the working state as keeping this side's values
/// would have left it (placed), and the working state it replaces is kept aside (<c>versions/.replaced</c>), never in the
/// chain. A conflict recorded before stays when the home holds no version after the base (it lost them: nothing to
/// chain. A conflict lists this side's value as the working state holds it, the base value it went back to included; where
/// the working state holds the home's value already there is nothing to ask, and the replayed versions take that value
/// too. A conflict recorded before stays when the home holds no version after the base (it lost them: nothing to
/// settle it against).
/// Written in steps a cut can stop at any point (<see cref="WorkspaceReplay"/>): the journal, the replayed versions, the
/// base with the merged working state (the commit point), then the old versions set aside and the held ones adopted.
@@ -534,6 +536,16 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var choice = takeTheirs is EveryPath ? null : takeTheirs;
List<ProjectSettings> mine = [.. locals.Select(v => ProjectMerge.Read(ProjectContent.Rebind(v.SettingsJson, photos)))];
var replay = ProjectMerge.Replay(basisSettings, mine, headSettings, choice);
// Where the working state holds the home's value already, the user has nothing to choose: the home's value is taken
// there, in the replayed versions too, so they and the working state agree (never asked, never listed).
var workingSide = WorkingConflicts(tip, working, basisSettings, headSettings);
var silent = replay.Conflicts.Concat(ProjectMerge.Conflicts(tip, working, replay.Commits.Count > 0 ? replay.Commits[^1] : headSettings))
.Select(d => d.Path).Where(p => !workingSide.Keys.Any(q => Overlaps(p, q))).ToHashSet(StringComparer.Ordinal);
if (silent.Count > 0)
{
choice = choice is null ? silent : new HashSet<string>(choice.Concat(silent), StringComparer.Ordinal);
replay = ProjectMerge.Replay(basisSettings, mine, headSettings, choice);
}
// This side's values wherever both changed: what taking the server's everywhere replaces (the editor's undo of it).
var keptTip = replay.Commits.Count > 0 ? replay.Commits[^1] : headSettings;
if (takeTheirs is EveryPath) replay = ProjectMerge.Replay(basisSettings, mine, headSettings, Paths(replay.Conflicts));
@@ -541,8 +553,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, choice);
var keptMine = takeTheirs is EveryPath ? ProjectMerge.MergeWithConflicts(tip, working, keptTip).Merged : merge.Merged;
if (takeTheirs is EveryPath) merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, Paths(merge.Conflicts));
var differences = AsInTheWorkingState(replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path),
ProjectMerge.Conflicts(basisSettings, working, headSettings));
var differences = AsInTheWorkingState(replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path).Where(d => !silent.Contains(d.Path)), workingSide);
if (differences.Count > 0 && (takeTheirs is null || (shown is not null && !SameDifferences(shown.Differences, differences))))
{
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], differences, DateTimeOffset.UtcNow);
@@ -1371,14 +1382,25 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// <summary>
/// The conflicts found as the user sees them: where the working state holds a value of its own against the home's
/// (<paramref name="working"/>: edited since the last local version), that value is this side's, not the version's.
/// (<paramref name="working"/>, <see cref="WorkingConflicts"/>), that value is this side's, not the version's.
/// Keeping mine keeps it, and taking the server's replaces it, so one answer settles what was listed.
/// </summary>
private static List<SettingsDifference> AsInTheWorkingState(IEnumerable<SettingsDifference> found, IReadOnlyList<SettingsDifference> working)
{
var now = working.DistinctBy(d => d.Path).ToDictionary(d => d.Path, StringComparer.Ordinal);
return [.. found.Select(d => now.TryGetValue(d.Path, out var held) ? held : d)];
}
private static List<SettingsDifference> AsInTheWorkingState(IEnumerable<SettingsDifference> found, IReadOnlyDictionary<string, SettingsDifference> working) =>
[.. found.Select(d => working.TryGetValue(d.Path, out var held) ? held : d)];
/// <summary>
/// The settings where the working state holds a value of its own against the home's head, by path: against the last
/// local version (<paramref name="tip"/>: edited since it, the base value it went back to included), else against the
/// base (the version's value, unchanged since). A conflict at a path neither lists has the home's value in the working
/// state already.
/// </summary>
private static Dictionary<string, SettingsDifference> WorkingConflicts(ProjectSettings tip, ProjectSettings working, ProjectSettings basis, ProjectSettings head) =>
ProjectMerge.Conflicts(tip, working, head).Concat(ProjectMerge.Conflicts(basis, working, head)).DistinctBy(d => d.Path)
.ToDictionary(d => d.Path, StringComparer.Ordinal);
/// <summary>Two merge paths name the same setting, or one lies inside the other ("camera" and "camera.aspect").</summary>
private static bool Overlaps(string a, string b) =>
a == b || a.StartsWith(b + ".", StringComparison.Ordinal) || b.StartsWith(a + ".", StringComparison.Ordinal);
/// <summary>Whether two conflicts list the same settings with the same values on each side (in any order).</summary>
private static bool SameDifferences(IReadOnlyList<SettingsDifference> shown, IReadOnlyList<SettingsDifference> found) =>
@@ -6,6 +6,7 @@ using Chronos.App.Settings;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
@@ -156,6 +157,8 @@ public sealed class WorkspaceFallbackTests(TestContext context)
var unsent = (await host.SaveVersionAsync(mainId, "Not sent")).Version!;
var project = host.Store.Find(mainId)!;
await File.WriteAllTextAsync(project.BundlePath, "{ this is not a project", bed.Ct);
// A file this Chronos does not know (a newer one's, the user's own): Discard keeps it too.
await File.WriteAllTextAsync(Path.Combine(project.Folder, "notes.txt"), "kept", bed.Ct);
var all = await host.ListAsync();
Assert.Count(1, all);
@@ -168,13 +171,27 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.Equal((Loc.L("Editor.Workspace.State.Damaged"), StatusKind.Error, Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")),
(item.StateText, item.StateKind, item.StateToolTip));
Assert.Equal(Loc.L("Editor.Project.Main"), listed.KnownName, "named as the library's index knows it, not by its folder's id");
var plan = await host.PlanRemovalAsync(mainId);
Assert.True(plan is { Damaged: true, IsSafe: false, Unsent: 1 });
Assert.Greater(plan.Files, 0);
Assert.Equal(Loc.L("Editor.Project.Main"), plan.KnownName);
var typed = RemoveCopyDialogViewModel.DiscardRequest(plan);
Assert.Equal((Loc.L("Editor.RemoveCopy.DiscardTitle", Loc.L("Editor.Project.Main")), Loc.L("Editor.Project.Main")), (typed.Heading, typed.TypedConfirmation),
"a readable name is typed");
var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => false, _ => { });
Assert.False(dialog.RemoveCommand.CanExecute(null) || dialog.SendFirstCommand.CanExecute(null));
Assert.True(dialog.DiscardCommand.CanExecute(null));
Assert.Equal((Loc.L("Errors.Workspace.Damaged"), Loc.L("Errors.Workspace.Damaged")), (dialog.RemoveToolTip, dialog.SendFirstToolTip));
Assert.Equal(Loc.L("Editor.RemoveCopy.Title", Loc.L("Editor.Project.Main")), dialog.Heading);
// Known by no name at all: the number of its files is typed instead, and the heading names no id.
var unnamed = plan with { KnownName = null };
var counted = RemoveCopyDialogViewModel.DiscardRequest(unnamed);
Assert.Equal((Loc.L("Editor.RemoveCopy.DamagedDiscard"), Formatting.Count(plan.Files), Loc.L("Editor.RemoveCopy.TypeFiles", Formatting.Count(plan.Files))),
(counted.Heading, counted.TypedConfirmation, counted.TypedPrompt));
Assert.True(counted.IsDestructive);
Assert.Equal(Loc.L("Editor.RemoveCopy.DamagedTitle"), new RemoveCopyDialogViewModel(unnamed, _ => Task.CompletedTask, () => Task.CompletedTask, () => false, _ => { }).Heading);
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Damaged"), refused.Message);
@@ -185,10 +202,59 @@ public sealed class WorkspaceFallbackTests(TestContext context)
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(mainId.ToString("N"), StringComparison.Ordinal));
Assert.Equal("{ this is not a project", await File.ReadAllTextAsync(Path.Combine(aside, WorkspaceProject.BundleFile), bed.Ct), "kept as it was");
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt"), bed.Ct), "every file of the folder is kept, not only the known ones");
Assert.False(Directory.Exists(Path.Combine(aside, WorkspaceProject.MediaFolder)), "the media, which the library makes again, are not kept");
Assert.False(Directory.Exists(project.Folder));
Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase)
|| f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept");
}
[Test]
public async Task ACopyANewerChronosSavedIsListedAsSuchAndNeitherOpensNorGoes()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
var project = host.Store.Find(mainId)!;
// A newer Chronos on this PC rewrote the working state in a format this one does not know (a downgrade since).
var json = System.Text.Json.Nodes.JsonNode.Parse(await File.ReadAllTextAsync(project.BundlePath, bed.Ct))!.AsObject();
json["formatVersion"] = ProjectBundle.CurrentFormatVersion + 1;
json["somethingNew"] = "of a newer Chronos";
var newer = json.ToJsonString();
await File.WriteAllTextAsync(project.BundlePath, newer, bed.Ct);
await File.WriteAllTextAsync(Path.Combine(project.Folder, "newer.dat"), "a newer Chronos's", bed.Ct);
Assert.Throws<InvalidDataException>(() => project.ReadBundle());
var listed = (await host.ListAsync()).Single();
Assert.True(listed is { Newer: true, Damaged: false, IsReadable: false, HasMedia: false });
Assert.Equal((mainId, ProjectService.MainName, true, Loc.L("Editor.Project.Main")), (listed.ProjectId, listed.Name, listed.IsMain, listed.KnownName),
"named from what of its file reads");
Assert.Equal("Synthetic", listed.SequenceTitle);
Assert.True((await host.FindAsync(mainId))!.Newer);
Assert.Empty(await host.ProjectsOfAsync(bed.SequenceId), "never taken as the sequence's project to open");
Assert.Null(await host.LastUsedAsync(bed.SequenceId));
var item = new WorkspaceProjectItem(listed, null);
Assert.Equal((Loc.L("Editor.Workspace.State.NewerCopy"), StatusKind.Warning, Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")),
(item.StateText, item.StateKind, item.StateToolTip));
Assert.True(item is { IsNewer: true, IsDamaged: false, IsReadable: false });
// Not offered as damaged: no plan, no discard, and nothing checked out over it.
var planned = await Assert.ThrowsAsync<WorkspaceException>(() => host.PlanRemovalAsync(mainId));
Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), planned.Message);
var discarded = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: true));
Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), discarded.Message);
var checkedOut = await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, mainId, null));
Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), checkedOut.Message);
await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, null, null));
Assert.Equal(newer, await File.ReadAllTextAsync(project.BundlePath, bed.Ct), "left exactly as the newer Chronos wrote it");
Assert.FileExists(Path.Combine(project.Folder, "newer.dat"));
Assert.True(Directory.Exists(project.MediaDirectory), "its media stay too");
// A damaged file is still damaged, not newer: a format number alone never makes one.
await File.WriteAllTextAsync(project.BundlePath, "{ \"format\": \"chronos-project\", \"formatVersion\": 9, ", bed.Ct);
Assert.True((await host.FindAsync(mainId)) is { Damaged: true, Newer: false });
}
[Test]
public async Task OpenInWorkspaceShowsTheCopysSizeAndTheFreeSpace()
{
@@ -1,4 +1,7 @@
using System.IO;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
@@ -46,4 +49,50 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv);
}
}
[Test]
public async Task AnEditNotStoredYetIsKeptAsideWhenANewerChronossSettingsArrive()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var host = bed.Host();
var projectId = await bed.CheckoutAsync(host);
var (source, session) = await bed.OpenAsync(host, projectId);
await using (session)
{
var kept = new List<string>();
session.EditSetAside += kept.Add;
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
Assert.NotNull(await host.CommitAsync(projectId, bed.Ct));
var folder = host.Store.Find(projectId)!;
var stored = folder.ReadBundle();
// A sync took a newer Chronos's settings while one more edit waited for its save (made during the sync).
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
Assert.True(session.Edit(p => p with { ExcludedFrames = [2] }));
Assert.False(await session.FlushAsync(), "the working state no longer takes it");
await session.ReloadAsync();
Assert.True(session.IsReadOnly);
Assert.True(session.Project.IsNewerFormat, "the newer settings are taken");
Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv);
Assert.True(await session.FlushAsync(), "nothing retried that could never be stored");
Assert.False(session.HasPendingSave);
Assert.Null(session.LastSaveError);
var path = Assert.NotNull(kept.SingleOrDefault(), "the edit is kept aside, and said");
Assert.Equal(Path.Combine(folder.VersionsDirectory, WorkspaceProject.ReplacedFolder), Path.GetDirectoryName(path));
var aside = ProjectSidecars.ReadVersion(path);
var placed = ProjectSettings.FromJson(ProjectContent.Place(aside.SettingsJson, source.Photos));
Assert.Equal(0.4, placed.Exposure.ExposureOffsetEv);
Assert.SequenceEqual([2], placed.ExcludedFrames, "the edit as it was, by photo");
Assert.False(folder.Versions().Any(v => v.Id == aside.Id), "outside the chain: never sent");
Assert.Empty(host.Sync.Unpushed(projectId).Where(v => v.Id == aside.Id));
// Read again: no throw, nothing more kept aside, the editor as it is.
await session.ReloadAsync();
Assert.Count(1, kept);
Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv);
Assert.True(await session.FlushAsync());
}
}
}
@@ -15,6 +15,7 @@ using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Workspaces;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
@@ -115,6 +116,91 @@ public sealed class WorkspaceSectionTests(TestContext context)
}
});
[Test]
public Task ARefusedFolderOffersAnotherFromItsToastAndCopiesThisChronosCannotReadAreNeverOpened() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-refused");
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
UiLanguage.Apply("en");
var settings = new AppSettings { Language = "en", FirstRunCompleted = true, CheckForUpdates = false };
var outside = Path.Combine(directory, "outside");
var dialogs = new ScriptedDialogs { Folder = outside };
var services = new AppServices(environment, settings, () => { }, dialogs);
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
var toasts = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
try
{
var library = Path.Combine(directory, "archive");
var sequenceId = await SequenceAsync(services, library);
var inside = Path.Combine(library, "workspace");
settings.WorkspaceFolder = inside;
var section = shell.Sequence;
// Open in workspace shows what the copy writes and the room there is, then the folder is refused with a way on.
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], ask.CopyFacts.Select(f => f.Label), "the copy's facts reach the dialog");
ask.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")), "the refusal is said");
var refused = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.OpenFailed"));
Assert.True(refused is { IsError: true, ActionCommand: not null }, "an error with its action");
Assert.Equal((Loc.L("Errors.Workspace.InsideLibraryEdit", Path.GetFullPath(inside)), Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder")),
(refused.Message, refused.ActionText, refused.ActionToolTip));
Assert.False(Directory.Exists(inside), "nothing was written inside the library");
Assert.Null(section.Editor);
// Its action picks another folder, shows the plan and uses it.
refused.ActionCommand!.Execute(null);
await WorkspaceTestBed.UntilAsync(() => string.Equals(services.Workspace.Root, Path.GetFullPath(outside), StringComparison.OrdinalIgnoreCase), "the folder chosen is used");
Assert.Count(1, dialogs.Asked);
Assert.Equal(Loc.L("Settings.Workspace.ChangeTitle"), dialogs.Asked[0].Heading);
// That workspace holds a copy a newer Chronos saved and a damaged one: listed, never opened.
var newerId = Guid.CreateVersion7();
var newer = Directory.CreateDirectory(Path.Combine(outside, newerId.ToString("N"))).FullName;
await File.WriteAllTextAsync(Path.Combine(newer, WorkspaceProject.BundleFile),
$$"""{ "format": "chronos-project", "formatVersion": 9, "sequence": { "title": "Harbour" }, "workspace": { "projectId": "{{newerId}}", "name": "Vertical" } }""");
var damagedId = Guid.CreateVersion7();
var damaged = Directory.CreateDirectory(Path.Combine(outside, damagedId.ToString("N"))).FullName;
await File.WriteAllTextAsync(Path.Combine(damaged, WorkspaceProject.BundleFile), "{ not a project");
await File.WriteAllTextAsync(Path.Combine(damaged, "notes.txt"), "kept");
await section.Picker.ReloadAsync();
await section.Picker.WorkspaceLoadedAsync();
var newerItem = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == newerId);
Assert.True(newerItem is { IsNewer: true, IsDamaged: false, IsReadable: false, Name: "Vertical", SequenceTitle: "Harbour" });
Assert.Null(newerItem.Status, "no state is asked of it");
await section.PickProjectAsync(newerItem);
Assert.Contains(toasts, t => t.Message == Loc.L("Errors.Workspace.NewerCopy") && t.IsError);
Assert.Null(section.Dialog, "nothing is offered over it");
Assert.FileExists(Path.Combine(newer, WorkspaceProject.BundleFile));
// The damaged one offers its removal, named as a damaged copy; Discard asks its files' number and keeps every file aside.
var damagedItem = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == damagedId);
await section.PickProjectAsync(damagedItem);
var remove = Assert.NotNull(section.Dialog as RemoveCopyDialogViewModel);
Assert.Equal(Loc.L("Editor.RemoveCopy.DamagedTitle"), remove.Heading);
dialogs.Answer = true;
remove.DiscardCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => !Directory.Exists(damaged), "the damaged copy goes");
var discard = dialogs.Asked[^1];
Assert.Equal((Loc.L("Editor.RemoveCopy.DamagedDiscard"), Formatting.Count(2), Loc.L("Editor.RemoveCopy.TypeFiles", Formatting.Count(2))),
(discard.Heading, discard.TypedConfirmation, discard.TypedPrompt));
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(outside, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(damagedId.ToString("N"), StringComparison.Ordinal));
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt")));
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
/// <summary>An archive with one sequence of six synthetic photos, indexed.</summary>
private async Task<Guid> SequenceAsync(AppServices services, string root)
{
@@ -133,6 +219,24 @@ public sealed class WorkspaceSectionTests(TestContext context)
return (await services.Database!.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
}
/// <summary>Dialogs that pick <see cref="Folder"/> and answer every confirmation with <see cref="Answer"/> (yes first), recording what they were asked.</summary>
private sealed class ScriptedDialogs : IAppDialogs
{
public string? Folder { get; set; }
public bool Answer { get; set; } = true;
public List<ConfirmRequest> Asked { get; } = [];
public string? PickFolder(string title, string? initialFolder = null) => Folder;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request)
{
Asked.Add(request);
return Answer;
}
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
/// <summary>Dialogs that pick nothing and decline every confirmation.</summary>
private sealed class DeclineDialogs : IAppDialogs
{
@@ -153,6 +153,66 @@ public abstract class WorkspaceConflictTests(TestContext context) : DatabaseTest
Assert.Equal(1.0, (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv, "the value listed as this side's is kept");
}
[Test]
public async Task AWorkingStateBackAtTheBaseValueIsListedAndKeptAsItIs()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
var basis = (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv;
await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
// This side saved 0.8 as a version, then went back to the base value without saving.
await EditAsync(two, id, s => Offset(s, 0.8), fx.Ct);
await two.CommitAsync(id, "warmer", cancellationToken: fx.Ct);
await EditAsync(two, id, s => Offset(s, basis), fx.Ct);
var shown = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict);
var difference = shown.Differences.Single();
Assert.Equal(("exposure.exposureOffsetEv", basis, 0.5), (difference.Path, Number(difference.Mine) ?? 0, Number(difference.Theirs)),
"this side's value is the working state's, not the version's 0.8");
var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: shown, cancellationToken: fx.Ct);
Assert.Null(settled.Status.Conflict, "one answer settles what was shown");
Assert.Equal(basis, (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv, "the value listed as this side's is the one kept");
Assert.True(settled.Status.Modified, "the saved version keeps its own value; the working state's is not saved yet");
Assert.Equal("warmer", two.Unpushed(id).Single().Note);
await two.CommitAsync(id, cancellationToken: fx.Ct);
await two.PushAsync(id, fx.Home, fx.Ct);
Assert.Equal(basis, ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson).Exposure.ExposureOffsetEv, "the library ends with the value kept");
}
[Test]
public async Task AWorkingStateHoldingTheLibrarysValueIsNoConflictAndItsVersionAgrees()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
// This side saved 0.8 and a stack as a version, then set the offset to the library's own 0.5 without saving.
await EditAsync(two, id, s => Stack(Offset(s, 0.8), StackSetting.Mean), fx.Ct);
await two.CommitAsync(id, "local", cancellationToken: fx.Ct);
await EditAsync(two, id, s => Offset(s, 0.5), fx.Ct);
var pulled = await two.PullAsync(id, fx.Home, fx.Ct);
Assert.Null(pulled.Status.Conflict, "nothing to choose: the working state holds the library's value");
var working = (await two.OpenAsync(id, fx.Ct)).Working;
Assert.Equal((0.5, StackSetting.Mean), (working.Exposure.ExposureOffsetEv, working.Stack.Mode), "the working state is unchanged");
var replayed = ProjectSettings.FromJson(two.Unpushed(id).Single().SettingsJson);
Assert.Equal((0.5, StackSetting.Mean), (replayed.Exposure.ExposureOffsetEv, replayed.Stack.Mode), "the replayed version agrees with the working state");
Assert.True(pulled.Status is { State: WorkspaceState.Ahead, Modified: false }, "nothing left unsaved");
await two.PushAsync(id, fx.Home, fx.Ct);
var head = ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson);
Assert.Equal((0.5, StackSetting.Mean), (head.Exposure.ExposureOffsetEv, head.Stack.Mode));
}
private static double? Number(string? json) => json is null ? null : double.Parse(json, System.Globalization.CultureInfo.InvariantCulture);
[Test]