diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx
index 3369c389..b371aa79 100644
--- a/i18n/en/Editor.resx
+++ b/i18n/en/Editor.resx
@@ -241,6 +241,7 @@
Keep
Mainthe name of every sequence's first project, holding the sequence's own settings
New project…
+ Open project…
Remove local copy…
Rename…
Save version…
@@ -268,6 +269,8 @@
{0} · read-only
Unsaved changes
Discard changes
+ The versions not sent and the unsaved changes go to the workspace's trash folder; Chronos does not bring them back.long
+ Discard the changes of {0}?
Files
The photos copied to this PC are deleted; the project stays in the library and opens again from there.long
None
@@ -275,6 +278,7 @@
Send first
Size
Remove local copy of {0}{0} project name
+ Type the project name to confirmlong
Versions not sent
Yes
Render · {0}
@@ -379,11 +383,15 @@
Project not deleted
Project {0} deleted{0} project name
{0} {1} here, {2} in the librarylong; {0} setting name, {1} value in this workspace, {2} value in the library
+ {0} changed in the library while your edit waited to be saved. The settings below differ: keep your values, or take the library's.long
Project in sync
Library photos changed
Version not sent yet
Nothing new to save
Library offline
+ Open
+ Project not opened
+ Project read-only
Local copy not removed
Local copy removed
Project renamed
@@ -394,6 +402,7 @@
Not sentversions saved here wait to be sent to the library
Library newerthe library has versions the workspace has not taken
Conflict
+ Not in library
In sync
No media
Changedthe project has changes not saved as a version
@@ -402,6 +411,7 @@
Syncing
Sync failed
Project synced
+ Library's values taken
Undo
Update media
Updating media
diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index 2c90826f..c1581591 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -50,12 +50,14 @@
The closing brace at position {1} has no opening one; double it for a literal brace.
Something went wrong.
Settle the conflict first: Sync shows which settings differ.
+ Its local copy could not be removed now: Remove local copy takes it later.long
{0} did not match its source after it was copied.{0} file path
A file of this project in the workspace cannot be read; the log names it.
The workspace drive needs {0} GB more for this copy.{0} gigabytes missing
The last edit could not be stored yet; it is tried again, try once more in a moment.
The library's copy of this project does not match what was sent; nothing was removed.
The workspace folder is inside a library; nothing is copied into it.
+ The workspace folder {0} is inside a library, where Edit copies nothing: keep Chronos's data folder outside your libraries.long
A project name has 1 to 60 characters.
The Main project holds the sequence's own settings: it cannot be deleted.
The workspace's photos of this project changed; the editor reads them again.
@@ -69,5 +71,6 @@
This project is no longer in the library.
This project was saved by a newer Chronos: it opens read-only.
The library refused a version of this project; the log says why.
+ This project's sequence is no longer in the library: only its local copy can be removed, from the picker's menu.long
Some work is not in the library yet: send it first, or discard it.
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index 75e98a54..b48b5abb 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -261,6 +261,7 @@
Keep the project as it is
Project {0} ({1}): save a version, sync, history, other projects and the local copy{0} project name, {1} its state
Make another project of this sequence, starting from this one (for example a vertical cut for social media)
+ Open another project of this sequence: one in the library, or a new onelong
Free this PC's space: delete the photos copied to the workspace; the project stays in the library
Give this project another name, here and in the library
Keep the project as it is now as a version of its history, with an optional note (Ctrl+S)
@@ -275,6 +276,7 @@
Edited with proxies on this PC; changes are saved on {0} and analyses and renders run there
Shown from {0}; your account can look at this sequence but not change it
Remove the copy without sending what is not in the library; that work is kept aside in the workspace's trash
+ Keep the local copy as it is
Delete the workspace copy; every version is in the library
Save and send what is not in the library yet, then remove the copy
Render with the selected preset; progress in the job bar · Ctrl+R
@@ -326,10 +328,12 @@
Keep your values of these settings; they are sent to the library
Decide later and keep editing; Sync asks again
Photos were added to or removed from this sequence in the library after the workspace copied it
+ Open project {0}, which holds your versionslong
Keep the library's values in this project, and send yours to a new project “{0}”{0} the new project's name
Versions saved here that wait to be sent to the library: {0}. Sync sends them{0} number of versions
Versions in the library this workspace has not taken yet: {0}. Sync takes them{0} number of versions
You and the library changed the same settings: Sync to choose which to keep
+ The library no longer has this project or its sequence: nothing more can be sent; remove the local copy (its work is kept aside)long
Every version of this project is in the library, and nothing changed since the last one
The workspace holds no photos of this project: opening it copies them again
Changes not saved as a version yet: Save version (Ctrl+S) keeps them in the history
@@ -338,7 +342,9 @@
Asking the library where this project stands
Taking the library's new versions and sending yours
Use the library's values of these settings in the editor
+ Use the library's values of these settings; Ctrl+Z brings yours backlong
Bring back the project as it was before the restore
+ Bring back your values of the settings the library's replacedlong
Copy the library's frames into the workspace again; the frames you excluded or keyed follow their photos
Import photos already in the archive again; nothing is overwritten
Copy into this PC's archive with the naming templates · {0}
diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx
index 980e5388..dcc5a09f 100644
--- a/i18n/it/Editor.it.resx
+++ b/i18n/it/Editor.it.resx
@@ -230,6 +230,7 @@
Mantieni
Principale
Nuovo progetto…
+ Apri progetto…
Rimuovi copia locale…
Rinomina…
Salva versione…
@@ -257,6 +258,8 @@
{0} · sola lettura
Modifiche non salvate
Scarta modifiche
+ Le versioni non inviate e le modifiche non salvate vanno nella cartella cestino dello spazio di lavoro; Chronos non le riporta indietro.
+ Scartare le modifiche di {0}?
File
Le foto copiate su questo PC vengono eliminate; il progetto resta nella libreria e si riapre da lì.
Nessuna
@@ -264,6 +267,7 @@
Prima invia
Dimensione
Rimuovi copia locale di {0}
+ Scrivi il nome del progetto per confermare
Versioni non inviate
Sì
Renderizza · {0}
@@ -354,11 +358,15 @@
Progetto non eliminato
Progetto {0} eliminato
{0} {1} qui, {2} nella libreria
+ {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.
Progetto sincronizzato
Foto della libreria cambiate
Versione non ancora inviata
Niente di nuovo da salvare
Libreria non in linea
+ Apri
+ Progetto non aperto
+ Progetto in sola lettura
Copia locale non rimossa
Copia locale rimossa
Progetto rinominato
@@ -369,6 +377,7 @@
Da inviare
Libreria più nuova
Conflitto
+ Non in libreria
Sincronizzato
Senza media
Modificato
@@ -377,6 +386,7 @@
Sincronizzazione
Sincronizzazione non riuscita
Sincronizzazione eseguita
+ Valori della libreria presi
Annulla
Aggiorna media
Aggiornamento media
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index e6671d4d..84954535 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -50,12 +50,14 @@
La parentesi graffa chiusa alla posizione {1} non ha un'apertura; raddoppiala per una graffa letterale.
Si è verificato un problema.
Risolvi prima il conflitto: Sincronizza mostra quali impostazioni sono diverse.
+ La sua copia locale ora non è stata rimossa: Rimuovi copia locale la toglie più tardi.
{0} non corrispondeva all'originale dopo la copia.
Un file di questo progetto nello spazio di lavoro non è leggibile; il log lo indica.
Al disco dello spazio di lavoro servono altri {0} GB per questa copia.
L'ultima modifica non è ancora stata memorizzata; viene ritentata, riprova tra un momento.
La copia di questo progetto nella libreria non corrisponde a quanto inviato; non è stato rimosso nulla.
La cartella dello spazio di lavoro è dentro una libreria; non vi viene copiato nulla.
+ La cartella dello spazio di lavoro {0} è dentro una libreria, dove Modifica non copia nulla: tieni la cartella dei dati di Chronos fuori dalle tue librerie.
Il nome di un progetto ha da 1 a 60 caratteri.
Il progetto Principale contiene le impostazioni della sequenza: non può essere eliminato.
Le foto di questo progetto nello spazio di lavoro sono cambiate; l'editor le rilegge.
@@ -69,5 +71,6 @@
Questo progetto non è più nella libreria.
Questo progetto è stato salvato da un Chronos più recente: si apre in sola lettura.
La libreria ha rifiutato una versione di questo progetto; il log spiega il motivo.
+ La sequenza di questo progetto non è più nella libreria: si può solo rimuoverne la copia locale, dal menu del selettore.
Parte del lavoro non è ancora nella libreria: prima inviala oppure scartala.
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 57626515..d3b216a5 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -261,6 +261,7 @@
Tieni il progetto com'è
Progetto {0} ({1}): salva una versione, sincronizza, cronologia, altri progetti e copia locale
Crea un altro progetto di questa sequenza a partire da questo (per esempio un taglio verticale per i social)
+ Apri un altro progetto di questa sequenza: uno della libreria o uno nuovo
Libera spazio su questo PC: elimina le foto copiate nello spazio di lavoro; il progetto resta nella libreria
Dai un altro nome a questo progetto, qui e nella libreria
Tieni il progetto com'è ora come versione della sua cronologia, con una nota facoltativa (Ctrl+S)
@@ -275,6 +276,7 @@
Modificata con i proxy su questo PC; le modifiche si salvano su {0} e analisi e render vengono eseguiti lì
Mostrata da {0}; il tuo account può vedere questa sequenza ma non modificarla
Rimuovi la copia senza inviare ciò che non è nella libreria; quel lavoro resta da parte nel cestino dello spazio di lavoro
+ Mantieni la copia locale com'è
Elimina la copia di lavoro; ogni versione è nella libreria
Salva e invia ciò che non è ancora nella libreria, poi rimuovi la copia
Renderizza con il preset scelto; avanzamento nella barra dei lavori · Ctrl+R
@@ -325,10 +327,12 @@
Tieni i tuoi valori di queste impostazioni; vengono inviati alla libreria
Decidi più tardi e continua a modificare; Sincronizza lo chiede di nuovo
Sono state aggiunte o tolte foto a questa sequenza nella libreria dopo che lo spazio di lavoro l'ha copiata
+ Apri il progetto {0}, che contiene le tue versioni
Tieni i valori della libreria in questo progetto e invia i tuoi a un nuovo progetto «{0}»
Versioni salvate qui in attesa di essere inviate alla libreria: {0}. Sincronizza le invia
Versioni nella libreria non ancora prese da questo spazio di lavoro: {0}. Sincronizza le prende
Tu e la libreria avete modificato le stesse impostazioni: sincronizza per scegliere quali tenere
+ La libreria non ha più questo progetto o la sua sequenza: non si può più inviare nulla; rimuovi la copia locale (il suo lavoro resta da parte)
Ogni versione di questo progetto è nella libreria e nulla è cambiato dall'ultima
Lo spazio di lavoro non ha foto di questo progetto: aprirlo le copia di nuovo
Modifiche non ancora salvate come versione: Salva versione (Ctrl+S) le tiene nella cronologia
@@ -337,7 +341,9 @@
Chiede alla libreria lo stato di questo progetto
Prende le nuove versioni della libreria e invia le tue
Usa nell'editor i valori della libreria per queste impostazioni
+ Usa i valori della libreria per queste impostazioni; Ctrl+Z riporta i tuoi
Riporta il progetto com'era prima del ripristino
+ Riporta i tuoi valori delle impostazioni sostituite da quelli della libreria
Copia di nuovo i fotogrammi della libreria nello spazio di lavoro; i fotogrammi esclusi o con keyframe seguono le loro foto
Importa di nuovo le foto già in archivio; nulla viene sovrascritto
Copia nell'archivio di questo PC con i modelli dei nomi · {0}
diff --git a/src/Chronos.App/Archive/ArchiveDialogViewModels.cs b/src/Chronos.App/Archive/ArchiveDialogViewModels.cs
index f7f8f186..a5fa4e11 100644
--- a/src/Chronos.App/Archive/ArchiveDialogViewModels.cs
+++ b/src/Chronos.App/Archive/ArchiveDialogViewModels.cs
@@ -94,6 +94,15 @@ public abstract class ArchiveDialogViewModel : LocalizedViewModel
ErrorText = null;
ErrorToolTip = null;
}
+
+ /// The dialog was closed (disposed): one still waiting to be shown no longer is.
+ public bool IsClosed { get; private set; }
+
+ public override void Dispose()
+ {
+ IsClosed = true;
+ base.Dispose();
+ }
}
/// A fact of the rebuild dialog ("Sidecars · 412"); a path stays left to right, a missing value says why in its tooltip.
diff --git a/src/Chronos.App/Editor/EditorSession.cs b/src/Chronos.App/Editor/EditorSession.cs
index f0dbc2a8..c23dbd7b 100644
--- a/src/Chronos.App/Editor/EditorSession.cs
+++ b/src/Chronos.App/Editor/EditorSession.cs
@@ -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
}
///
- /// Settles 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). 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 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). 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).
///
/// False when there is no conflict to settle (a later save already went through).
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();
}
+ ///
+ /// 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 (: 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 does for a server's.
+ ///
+ /// That step, which a toast's Undo can take back while it is the last change; null when it changed nothing.
+ public async Task 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;
+ }
+
/// Stores pending changes now; false when the save failed (the change stays pending and is retried).
public Task 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);
}
}
diff --git a/src/Chronos.App/Editor/EditorViewModel.cs b/src/Chronos.App/Editor/EditorViewModel.cs
index d31f2f84..e92d6b23 100644
--- a/src/Chronos.App/Editor/EditorViewModel.cs
+++ b/src/Chronos.App/Editor/EditorViewModel.cs
@@ -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
/// Why the controls that change the project are disabled; null while they are not.
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
});
///
- /// 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.
///
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);
});
+ /// The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps.
+ 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,
+ };
+
/// The conflict prompt: what differs (the editor's value, then the server's) and what each choice replaces.
internal static ConfirmRequest ConflictRequest(ProjectConflictException conflict, string title, string server) => new()
{
@@ -1160,8 +1177,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
}
///
- /// 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).
///
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
diff --git a/src/Chronos.App/Editor/ISequenceSource.cs b/src/Chronos.App/Editor/ISequenceSource.cs
index 46be0566..a1709a2d 100644
--- a/src/Chronos.App/Editor/ISequenceSource.cs
+++ b/src/Chronos.App/Editor/ISequenceSource.cs
@@ -35,6 +35,12 @@ public interface ISequenceSource : IAsyncDisposable
///
bool IsOutdated { get; }
+ ///
+ /// A change stored meanwhile by someone else to settings the editor changed too is asked about
+ /// (), never merged over the editor's: a server sequence, a workspace project.
+ ///
+ bool AsksConflicts => IsRemote;
+
/// changed (any thread).
event Action? ReadOnlyChanged;
@@ -68,6 +74,13 @@ public interface ISequenceSource : IAsyncDisposable
/// The editor's own reason the project was not stored, worded for the user.
Task SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken);
+ ///
+ /// The three-way merge of the editor's projects, all three naming this source's frames (): member
+ /// by member, a member both sides changed listed as a conflict and settled for . A workspace
+ /// project merges its frame positions photo by photo, as its sync does.
+ ///
+ ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs);
+
/// Queues an analysis or render job for the sequence; returns the job id.
Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
diff --git a/src/Chronos.App/Editor/ProjectHistory.cs b/src/Chronos.App/Editor/ProjectHistory.cs
index de7d5ca8..fc396f9f 100644
--- a/src/Chronos.App/Editor/ProjectHistory.cs
+++ b/src/Chronos.App/Editor/ProjectHistory.cs
@@ -9,7 +9,11 @@ namespace Chronos.App.Editor;
/// (the drag or key press ended); any other edit, undo or redo also ends the run. The oldest steps
/// are dropped beyond .
///
-public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
+///
+/// The three-way merge (basis, ours, theirs) that gives each step an outside change (): the source's,
+/// which merges a workspace project's frame positions photo by photo; when null.
+///
+public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200, Func? merge = null)
{
private readonly LinkedList _undo = new();
private readonly LinkedList _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 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 steps, ProjectMerge.Rebase rebase)
+ private static void Rebase(LinkedList steps, Func 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)
diff --git a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs
index 87426f32..492c573d 100644
--- a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs
+++ b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs
@@ -34,7 +34,10 @@ public interface IProjectRenders
/// library): the frames and pixels of the media the workspace holds (media/media.json, the proxies), the project
/// from its working state (project.chronos, positions placed on those frames), saved there atomically under the
/// project's lease and merged against the basis like (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 (), and settings the editor changed to
+/// other values than those stored meanwhile asked about (), never decided for the
+/// editor. A pull that brings a newer Chronos's settings turns it read-only (). 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
/// (). 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;
- /// A workspace project's read-only state is known when it opens.
- public event Action? ReadOnlyChanged
- {
- add { }
- remove { }
- }
+ /// The library's values and the editor's are asked about where both changed a setting, as a sync asks.
+ public bool AsksConflicts => true;
+
+ /// The working state read again holds a newer Chronos's settings (a pull took them), or no longer does.
+ public event Action? ReadOnlyChanged;
public event Action? JobChanged;
@@ -183,6 +185,10 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// The project is read-only, or its media are gone.
/// The media changed since they were read (a copy job): read them again first.
+ ///
+ /// 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.
+ ///
public Task 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);
}
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ /// A merge path of a frame position (an exclusion, the hero, a camera keyframe, a frame waiting for its photo).
+ 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 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
///
/// 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 when that changed).
///
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();
}
///
diff --git a/src/Chronos.App/Sections/SequencePickerView.xaml b/src/Chronos.App/Sections/SequencePickerView.xaml
index 7191b87c..53b3bc32 100644
--- a/src/Chronos.App/Sections/SequencePickerView.xaml
+++ b/src/Chronos.App/Sections/SequencePickerView.xaml
@@ -80,10 +80,18 @@
Grid.IsSharedSizeScope="True" Visibility="{Binding Picker.HasWorkspaceItems, Converter={StaticResource BoolToVisibility}}">
+
-
+
+
+
+
+
+
+
diff --git a/src/Chronos.App/Sections/SequencePickerViewModel.cs b/src/Chronos.App/Sections/SequencePickerViewModel.cs
index 346702a5..6a1da6e2 100644
--- a/src/Chronos.App/Sections/SequencePickerViewModel.cs
+++ b/src/Chronos.App/Sections/SequencePickerViewModel.cs
@@ -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
/// Opens a project of the Workspace group (double-click, Enter in its list), else the selected one.
public ICommand OpenProjectCommand { get; }
+ /// "Remove local copy…" of a project of the Workspace group (its menu, Delete in its list), also one that cannot open.
+ public ICommand RemoveCopyCommand { get; }
+
/// The Workspace group read last, then its projects' states (tests wait for it).
public async Task WorkspaceLoadedAsync()
{
diff --git a/src/Chronos.App/Sections/SequenceView.xaml b/src/Chronos.App/Sections/SequenceView.xaml
index 1dbc580b..f93fa080 100644
--- a/src/Chronos.App/Sections/SequenceView.xaml
+++ b/src/Chronos.App/Sections/SequenceView.xaml
@@ -121,6 +121,7 @@
+
+ private readonly Queue _waiting = new();
+
/// The project the next open of its sequence takes (the picker's Workspace group, a project file, the project menu).
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;
}
- /// Closes if it is still the open one.
+ ///
+ /// Shows 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.
+ ///
+ internal void OpenDialogWhenFree(ArchiveDialogViewModel dialog)
+ {
+ if (_dialog is null) OpenDialog(dialog);
+ else _waiting.Enqueue(dialog);
+ }
+
+ /// Closes if it is still the open one; the next one waiting shows (one closed meanwhile is skipped).
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;
+ }
+ }
+
+ ///
+ /// "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.
+ ///
+ 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
/// 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.
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);
diff --git a/src/Chronos.App/Server/SyncText.cs b/src/Chronos.App/Server/SyncText.cs
index 6341e8a5..757f5a5e 100644
--- a/src/Chronos.App/Server/SyncText.cs
+++ b/src/Chronos.App/Server/SyncText.cs
@@ -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",
};
+ /// The paths of positions parked by photo: "pendingFrames.<photo>.<flag>".
+ private const string PendingPrefix = "pendingFrames.";
+
/// "originals · proxies", "proxies" (cached server proxies) or "—".
public static string Local(SyncEntry entry)
{
@@ -267,9 +271,23 @@ public static class SyncText
///
/// 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.<photo>.keyframes" or ".excluded".
///
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--)
{
diff --git a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
index 1a7e9353..f6a49add 100644
--- a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
+++ b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
@@ -17,8 +17,18 @@ namespace Chronos.App.Workspace;
/// What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project.
public interface IWorkspaceUi
{
+ /// The dialog open now; null when none is.
+ ArchiveDialogViewModel? Dialog { get; }
+
+ /// Shows now, in place of an open one (the dialog the user acted in leads to it).
void ShowDialog(ArchiveDialogViewModel dialog);
+ ///
+ /// Shows 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.
+ ///
+ void ShowDialogWhenFree(ArchiveDialogViewModel dialog);
+
void CloseDialog(ArchiveDialogViewModel dialog);
/// True when the user chose the action (a destructive confirmation).
@@ -37,15 +47,20 @@ public interface IWorkspaceUi
}
///
-/// 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.
///
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
+ /// How long after the last edit the chip reads the working state again (a little after the editor's save).
+ 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;
+ /// Counts the editor's changes, so only the last one's state read applies.
+ private int _changes;
+
+ /// The conflict dialog asked in the background, until it is closed (one is asked at a time).
+ 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; }
+ /// Open project…: another project of the sequence, one of the library's (a Save both sibling, another PC's) or a new one.
+ 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;
- /// Reads where the project stands (against its home) and whether the home's frames moved; a conflict found meanwhile is asked about.
+ /// Reads where the project stands (against its home) and whether the home's frames moved.
public async Task RefreshAsync()
{
try
@@ -194,7 +220,10 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (result.Status.Conflict is { } conflict) AskConflict(conflict);
}
- /// Sync: the home's new versions taken into the editor, the local ones sent; a conflict is asked about.
+ ///
+ /// 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 : the sync ran in the background).
+ ///
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
}
}
- /// Settles a conflict as chosen, then brings the settled working state into the editor.
- public async Task ResolveAsync(ConflictChoice choice)
+ ///
+ /// Settles the conflict 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.
+ ///
+ 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));
+ }
}
///
@@ -259,18 +311,28 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await RefreshAsync();
}
- /// The settings that differ between the project now and (positions compared photo by photo).
+ ///
+ /// The settings that differ between the project now and , 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).
+ ///
public IReadOnlyList 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
}
}
+ ///
+ /// 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).
+ ///
+ 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
}
}
- /// The working state saved as a version and everything sent, for Send first.
- /// Something could not be sent.
+ ///
+ /// 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.
+ ///
+ /// Something could not be sent: a conflict to settle first, or the work not in the library yet.
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)
+ ///
+ /// Asks how to settle , the choice applying to it as listed. One a sync met in the
+ /// (after an analysis) waits for the open dialog to close, and is asked once: the chip
+ /// says Conflict meanwhile, and Sync asks again.
+ ///
+ 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);
+ }
+
+ /// The editor's project changed (an edit, undo, a merge; the UI thread): the chip reads the working state again a moment later.
+ private void OnProjectChanged()
+ {
+ if (_disposed) return;
+ _ = RefreshLocalAsync(++_changes);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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}");
+ }
+ }
+
+ ///
+ /// The state read without the home () 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.
+ ///
+ 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 };
}
/// A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread.
diff --git a/src/Chronos.App/Workspace/WorkspaceDialogs.cs b/src/Chronos.App/Workspace/WorkspaceDialogs.cs
index bb4a99da..67399eeb 100644
--- a/src/Chronos.App/Workspace/WorkspaceDialogs.cs
+++ b/src/Chronos.App/Workspace/WorkspaceDialogs.cs
@@ -37,9 +37,10 @@ public static class ProjectNames
}
///
-/// "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.
///
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 projects, Action close)
+ /// The names a new project cannot take (default: those of ).
+ public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList projects, Action close,
+ IReadOnlyList? 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
///
/// "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 () can only be discarded that way.
///
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
{
private readonly Func _remove;
private readonly Func _sendFirst;
+ private readonly Func _confirmDiscard;
- public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func remove, Func sendFirst, Action close)
+ /// The typed confirmation Discard changes asks first (); true when the user confirmed.
+ public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func remove, Func sendFirst, Func confirmDiscard, Action 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 Facts { get; }
- public bool HasUnsent => !Plan.IsSafe;
+ /// Something would not be at the library after the removal (or the library no longer has the project): Discard changes shows.
+ 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");
+ ///
+ /// 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.
+ ///
+ 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"),
+ };
+
+ /// Asks through : true when the user typed the name and confirmed.
+ 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 action)
{
ClearError();
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs
index 7290f506..45374e7c 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.cs
@@ -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 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).
///
-public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline)
+///
+/// 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).
+///
+public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline, bool Gone = false)
{
/// Everything the copy holds is at the home: it can go without discarding anything.
public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
@@ -80,8 +85,11 @@ public sealed class WorkspaceHost
_engine = engine;
}
- /// The program and PC versions made here carry, as the archive's own versions do.
- public static string ClientName { get; } = "Chronos on " + Environment.MachineName;
+ ///
+ /// 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).
+ ///
+ public static string ClientName { get; } = Environment.MachineName;
/// How long an operation waits for a project another writer holds (a copy job writing its media index).
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"));
- /// The projects of the workspace (one whose working state cannot be read is left out, and logged).
- public Task> ListAsync(CancellationToken cancellationToken = default) =>
- Task.Run(() => (IReadOnlyList)[.. Store.ListBundles().Select(b => Entry(b.Project, b.Bundle))], cancellationToken);
+ ///
+ /// 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.
+ ///
+ public Task> ListAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
+ {
+ if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
+ return (IReadOnlyList)[.. Store.ListBundles().Select(b => Entry(b.Project, b.Bundle))];
+ }, cancellationToken);
/// The workspace projects of one sequence.
public async Task> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
[.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
/// A workspace project by id; null when the workspace has none (or it cannot be read).
- public Task FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(() =>
+ public Task 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
///
/// The home has no such project, or the name is invalid or taken.
/// The archive is offline or busy.
+ /// The workspace folder lies inside a library: nothing was written, here or at the home.
public async Task 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);
///
- /// Where a project stands. With , 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 , 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 , whose local copy can then only be removed (nothing is removed by itself).
///
public Task 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);
///
- /// Settles the conflict a sync stopped at, then sends what waits. sends this
+ /// Settles the conflict a sync stopped at, as 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
+ /// () to be asked again. sends this
/// workspace's versions to a sibling project named "<name> (<this PC>)" (a number added when that name is taken).
///
public Task ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet? 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);
/// " (PC)", within the 60 characters of a project name.
@@ -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
/// (.chronos/projects/.trash) holds every version; then the local copy goes.
///
+ ///
+ /// 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.
+ ///
/// Something could not be sent (the home out of reach, a conflict): nothing was deleted.
/// Main, or the project is gone.
- public async Task DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
+ public async Task 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;
+ }
+
+ ///
+ /// "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.
+ ///
+ /// A conflict waits (open the project and Sync to settle it), or something is still not at the home.
+ 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"));
}
/// The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.
@@ -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);
///
@@ -588,6 +653,27 @@ public sealed class WorkspaceHost
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
}
+ ///
+ /// The workspace folder lies inside a library this index knows (a portable copy's data folder under a library
+ /// at a drive's root): editing happens outside every library, so nothing is checked out or copied there.
+ ///
+ private async Task 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;
diff --git a/src/Chronos.App/Workspace/WorkspaceText.cs b/src/Chronos.App/Workspace/WorkspaceText.cs
index 42d40ba5..c2c9ccdc 100644
--- a/src/Chronos.App/Workspace/WorkspaceText.cs
+++ b/src/Chronos.App/Workspace/WorkspaceText.cs
@@ -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
/// "Saved", "Merged", "Restored", "Imported", "Outside change".
public static string VersionKind(ProjectVersionKind kind) => Loc.L("Editor.History.Kind." + kind);
- /// Who made a version: its author, else the PC it was made on.
+ ///
+ /// 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).
+ ///
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;
}
+ /// What programs put before the PC's name in a version's client name (not words of the UI: the PC alone is shown).
+ private static readonly string[] ClientPrefixes = ["chronos@", "server@", "workspace@", "Chronos on "];
+
/// "28/10/2026 18:02".
public static string When(DateTimeOffset at) => $"{Formatting.Date(at)} {Formatting.TimeOfDay(at)}";
diff --git a/src/Chronos.Core/Model/Entities.cs b/src/Chronos.Core/Model/Entities.cs
index 8416b7ce..9ca93a2d 100644
--- a/src/Chronos.Core/Model/Entities.cs
+++ b/src/Chronos.Core/Model/Entities.cs
@@ -258,7 +258,7 @@ public sealed record ProjectVersion
public ProjectVersionKind Kind { get; init; }
public string? Author { get; init; }
- /// The program and PC it was made on ("Chronos on STUDIO-PC").
+ /// The PC it was made on ("STUDIO-PC" from a workspace; the archive's own versions carry its lease owner, "chronos@STUDIO-PC").
public string? ClientName { get; init; }
public string? Note { get; init; }
diff --git a/src/Chronos.Data/Workspaces/WorkspaceSync.cs b/src/Chronos.Data/Workspaces/WorkspaceSync.cs
index 076dc932..e7c2f69a 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceSync.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceSync.cs
@@ -31,6 +31,12 @@ public enum WorkspaceState
/// The workspace holds no media for the project (never copied, or removed): copy them again to edit.
MediaRemoved,
+
+ ///
+ /// The home answered that it no longer has the project or its sequence (the sequence left its index): nothing more can be
+ /// sent, and the local copy can only be removed, its work kept aside. Told by the desktop, which asks the home.
+ ///
+ Gone,
}
///
@@ -45,7 +51,15 @@ public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ah
/// What a push, pull or resolve did: the versions it stored at the home and those it took from there, and where it left the project.
/// After : the new project at the home holding this workspace's versions.
public sealed record WorkspaceSyncResult(WorkspaceStatus Status, IReadOnlyList Pushed, IReadOnlyList Pulled,
- SequenceProject? SavedAs = null);
+ SequenceProject? SavedAs = null)
+{
+ ///
+ /// After settled a conflict: the working state as keeping this side's values on
+ /// the settings both changed would have left it (positions on the media's frames), so the editor takes the server's
+ /// values as one step its undo takes back, and only them; null otherwise.
+ ///
+ public ProjectSettings? Kept { get; init; }
+}
/// How a conflict is settled (owner review 2, R8: only on real conflicts).
public enum ConflictChoice
@@ -82,13 +96,14 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
/// When the home moved meanwhile, its new versions are pulled and each local commit is replayed on top of them
/// (, new ids, the old files kept in versions/.replaced), and the working state is
/// merged too (); settings both sides changed to different values stop
-/// there as a conflict () for the user to settle (). Versions
-/// travel in the portable form (), so frames inserted at the home never move a position; before
-/// a merge the media learn how the home names its photos now (hashed or converted there since the copy), so every side
-/// names one photo alike. Settings of a newer Chronos are never merged with this one's: a project with nothing of its own
-/// moves onto them read-only, any other waits on a conflict of format that only Save both settles
-/// (). Every operation holds the project's lease; nothing is ever deleted: a
-/// restore or save-both first saves uncommitted changes as a version.
+/// there as a conflict () for the user to settle (), a choice
+/// applying only to the conflicts the user was shown. Versions travel in the portable form (),
+/// so frames inserted at the home never move a position; before a merge the media learn how the home names its photos now
+/// (hashed or converted there since the copy), so every side names one photo alike. Settings of a newer Chronos are never
+/// merged with this one's: a project with nothing of its own moves onto them read-only, any other waits on a conflict of
+/// format that only Save both settles (). Every operation holds the project's
+/// lease; nothing is ever deleted: a restore, a save-both or taking the server's values first saves uncommitted changes as
+/// a version.
/// Every write sequence survives a cut at any step: the working state's base is the commit point. A push moves the base
/// before its local file reads as sent; a replay journals itself in sync.json (), writes
/// the replayed versions, then the base, and only then sets the old ones aside; a save-both journals its copy and the ids
@@ -261,7 +276,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
///
/// Takes the home's versions newer than the base: the working state (and any local versions, replayed) moves onto the
- /// home's head; a real conflict stops it ().
+ /// home's head; a real conflict stops it (). A conflict recorded before is worked
+ /// out again (the home may have moved on, this side may have been edited since), so what is asked is what differs now;
+ /// one that no longer conflicts is settled by the merge.
///
/// The home cannot be reached.
public async Task PullAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
@@ -272,9 +289,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
{
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
IReadOnlyList pulled = [];
- if (project.ReadSync().Conflict is null)
+ var bundle = project.ReadBundle();
+ if (project.ReadSync().Conflict is not null)
+ {
+ (_, var conflict, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
+ if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
+ }
+ else
{
- var bundle = project.ReadBundle();
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
if (head.Id != bundle.Workspace!.Base?.VersionId) (_, _, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
}
@@ -283,16 +305,20 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
}
///
- /// Settles the conflict a pull or push stopped at. keeps this workspace's values
- /// (but for the members in ), takes the server's
- /// wherever both changed; either way the local versions are replayed on the home's head and wait to be pushed.
+ /// Settles the conflict a pull or push stopped at, as the user was shown it (, else the one
+ /// recorded). keeps this workspace's values (but for the members in
+ /// ), takes the server's on the settings listed;
+ /// either way the local versions are replayed on the home's head and wait to be pushed. A choice applies only to the
+ /// conflicts listed: when what differs now is not that (the home moved on, or this side was edited meanwhile), nothing
+ /// is settled, and the conflict found now is recorded and returned to be asked again. Taking the server's first saves
+ /// uncommitted changes as a version, so the values it replaces are kept (its file in versions/.replaced).
/// saves the working state as a version, sends this workspace's versions to a new
/// project at the home (, else this project's name with a number) made from the base,
/// and moves this project onto the home's head.
///
/// The home cannot be reached; the conflict stays.
public async Task ResolveAsync(Guid projectId, IProjectHome home, ConflictChoice choice, IReadOnlySet? takeServer = null,
- string? saveBothName = null, CancellationToken cancellationToken = default)
+ string? saveBothName = null, WorkspaceConflict? shown = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
var project = Existing(projectId);
@@ -301,20 +327,26 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
var bundle = project.ReadBundle();
var sync = project.ReadSync();
- if (sync.Conflict is null) return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
+ if (sync.Conflict is not { } recorded) return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
if (choice == ConflictChoice.SaveBoth)
return await SaveBothAsync(project, bundle, home, saveBothName, cancellationToken).ConfigureAwait(false);
+ if (choice == ConflictChoice.TakeServer && !bundle.IsReadOnly) CommitLocked(project, bundle, null, null);
IReadOnlySet takeTheirs = choice == ConflictChoice.TakeServer ? AllPaths : takeServer ?? new HashSet();
- var (_, conflict, pulled) = await ReplayAsync(project, bundle, home, takeTheirs, cancellationToken).ConfigureAwait(false);
+ ProjectSettings? kept = null;
+ var (_, conflict, pulled) = await ReplayAsync(project, bundle, home, takeTheirs, cancellationToken, shown ?? recorded, k => kept = k).ConfigureAwait(false);
if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
- return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
+ return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled)
+ {
+ Kept = conflict is null ? kept : null,
+ };
}
}
///
/// Brings version back as the working state (from this workspace, else from
- /// ); the next version saved is a "restore" of it. Uncommitted changes are saved as a version
- /// first, so a restore loses nothing.
+ /// ); the next version saved is a "restore" of it while the working state still holds it.
+ /// Uncommitted changes are saved as a version first, also while a conflict waits (settling it replays that version
+ /// too), so a restore loses nothing.
///
/// Neither this workspace nor the home has the version.
public async Task RestoreAsync(Guid projectId, Guid versionId, IProjectHome? home = null, CancellationToken cancellationToken = default)
@@ -332,11 +364,15 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
if (version is null) throw new ProjectException(ProjectError.NotFound, $"Version {versionId} of project {projectId} is not known here.");
var bundle = project.ReadBundle();
if (bundle.IsReadOnly) throw ReadOnly(projectId);
- if (project.ReadSync().Conflict is null) CommitLocked(project, bundle, null, null);
+ CommitLocked(project, bundle, null, null);
var media = project.ReadMedia();
- var working = ProjectSettings.FromJson(ProjectContent.Place(version.SettingsJson, media?.Photos ?? NoFrames), allowNewer: true);
- project.WriteBundle(project.ReadBundle() with { Project = working, Saved = DateTimeOffset.UtcNow });
- project.WriteSync(project.ReadSync() with { RestoredFrom = versionId });
+ var photos = media?.Photos ?? NoFrames;
+ var working = ProjectSettings.FromJson(ProjectContent.Place(version.SettingsJson, photos), allowNewer: true);
+ bundle = project.ReadBundle();
+ project.WriteBundle(bundle with { Project = working, Saved = DateTimeOffset.UtcNow });
+ // Restoring what the project already is changes nothing: the next version is no restore.
+ if (Tip(project, bundle, Unpushed(project, bundle)) is not { } tip || !ProjectContent.SameChoices(tip.SettingsJson, version.SettingsJson, photos))
+ project.WriteSync(project.ReadSync() with { RestoredFrom = versionId });
return working;
}
}
@@ -360,12 +396,16 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
///
/// Pulls the home's versions after the base and replays the local ones and the working state on its head. With
/// null a conflict is recorded and nothing else moves (the versions pulled are kept as
- /// files; the base only moves onto local commits the home already holds); with a choice the conflicts are settled by it.
- /// Written in steps a cut can stop at any point (): 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.
+ /// files; the base only moves onto local commits the home already holds); with a choice the conflicts are settled by it,
+ /// only when they are those lists (others are recorded and asked about first, as without a
+ /// choice). Taking the server's everywhere tells the working state as keeping this side's values
+ /// would have left it (placed). Written in steps a cut can stop at any point (): 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.
///
private async Task<(ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList Pulled)> ReplayAsync(WorkspaceProject project,
- ProjectBundle bundle, IProjectHome home, IReadOnlySet? takeTheirs, CancellationToken cancellationToken)
+ ProjectBundle bundle, IProjectHome home, IReadOnlySet? takeTheirs, CancellationToken cancellationToken, WorkspaceConflict? shown = null,
+ Action? kept = null)
{
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
// A local commit the home stored although its answer was lost comes back among the home's versions, and the commits
@@ -415,12 +455,15 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var choice = takeTheirs is EveryPath ? null : takeTheirs;
List mine = [.. locals.Select(v => ProjectMerge.Read(ProjectContent.Rebind(v.SettingsJson, photos)))];
var 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));
var newTip = replay.Commits.Count > 0 ? replay.Commits[^1] : headSettings;
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 = replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path).ToList();
- if (differences.Count > 0 && takeTheirs is null)
+ 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);
if (ours.Count > 0)
@@ -472,6 +515,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
Step("replay.base");
await FinishReplayAsync(project, journal, held, home, cancellationToken).ConfigureAwait(false);
project.WriteSync(project.ReadSync() with { Replay = null });
+ if (takeTheirs is EveryPath && kept is not null)
+ kept(ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(keptMine.ToJson()), photos), allowNewer: true));
return (moved, null, theirs);
}
@@ -695,13 +740,17 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
: (workspace.Base?.VersionId, workspace.Base?.Number ?? 0, workspace.Base?.ContentHash);
if (hash == tipHash || SameAsTip(project, bundle, locals, portable, media)) return null;
var sync = project.ReadSync();
+ // A restore taken back since (Undo, Ctrl+Z) no longer shows in the working state: that version is no restore.
+ var restoredFrom = sync.RestoredFrom is { } restored && StillRestores(project, restored, Tip(project, bundle, locals), portable, media?.Photos ?? NoFrames)
+ ? sync.RestoredFrom
+ : null;
var version = new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = project.ProjectId,
ParentId = tipId,
Number = tipNumber + 1,
- Kind = sync.RestoredFrom is null ? ProjectVersionKind.Commit : ProjectVersionKind.Restore,
+ Kind = restoredFrom is null ? ProjectVersionKind.Commit : ProjectVersionKind.Restore,
Author = author,
ClientName = clientName,
Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim(),
@@ -709,7 +758,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
ContentHash = hash,
SettingsFormat = ProjectContent.FormatOf(portable),
FramesVersion = media?.FramesVersion ?? workspace.Media.FramesVersion,
- RestoredFrom = sync.RestoredFrom,
+ RestoredFrom = restoredFrom,
CreatedAt = DateTimeOffset.UtcNow,
};
project.WriteVersion(version);
@@ -769,10 +818,34 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
private static bool SameAsTip(WorkspaceProject project, ProjectBundle bundle, List locals, string portable, WorkspaceMedia? media)
{
if (media is null) return false;
- var tip = locals.Count > 0 ? locals[^1] : bundle.Workspace!.Base is { } basis ? project.Versions().FirstOrDefault(v => v.Id == basis.VersionId) : null;
- return tip is not null && ProjectContent.SameChoices(tip.SettingsJson, portable, media.Photos);
+ return Tip(project, bundle, locals) is { } tip && ProjectContent.SameChoices(tip.SettingsJson, portable, media.Photos);
}
+ /// The last version: the newest local one, else the base (null when this workspace keeps neither).
+ private static ProjectVersion? Tip(WorkspaceProject project, ProjectBundle bundle, List locals) =>
+ locals.Count > 0 ? locals[^1] : bundle.Workspace!.Base is { } basis ? project.Versions().FirstOrDefault(v => v.Id == basis.VersionId) : null;
+
+ ///
+ /// Whether the working state , saved as a version on , still restores
+ /// version : that version differs from the parent, and the working state holds its values
+ /// wherever it does. A restore taken back since (the toast's Undo, Ctrl+Z) is no restore; one whose version this
+ /// workspace no longer keeps counts as recorded.
+ ///
+ private static bool StillRestores(WorkspaceProject project, Guid restoredId, ProjectVersion? parent, string portable, FramePhotos photos)
+ {
+ if (project.Versions().FirstOrDefault(v => v.Id == restoredId) is not { } restored) return true;
+ var then = ProjectContent.Rebind(restored.SettingsJson, photos);
+ var before = parent is null ? ProjectContent.ToPortable(new ProjectSettings(), photos) : ProjectContent.Rebind(parent.SettingsJson, photos);
+ if (then == before) return false;
+ var now = ProjectContent.Rebind(portable, photos);
+ var merge = ProjectMerge.MergeWithConflicts(ProjectMerge.Read(before), ProjectMerge.Read(now), ProjectMerge.Read(then));
+ return merge.Conflicts.Count == 0 && ProjectContent.Canonical(merge.Merged.ToJson()) == ProjectContent.Canonical(now);
+ }
+
+ /// Whether two conflicts list the same settings with the same values on each side (in any order).
+ private static bool SameDifferences(IReadOnlyList shown, IReadOnlyList found) =>
+ shown.Count == found.Count && shown.ToHashSet().SetEquals(found);
+
/// The local versions after the base, oldest first, each the child of the one before (the base's for the first).
private static List Unpushed(WorkspaceProject project, ProjectBundle bundle)
{
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
index 099da7c1..27d9d530 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
@@ -273,6 +273,9 @@ public sealed class WorkspaceEditorTests(TestContext context)
var head = await there.HomeOfSequence(bed.SequenceId).HeadAsync(sibling.Id, bed.Ct);
Assert.Equal(0.8, ProjectSettings.FromJson(head.SettingsJson).Exposure.ExposureOffsetEv, "nothing is lost: the sibling holds this side's values");
Assert.Equal(Loc.L("Editor.Workspace.SavedAs", sibling.Name), uiB.Toasts[^1].Title);
+ // The toast opens the sibling, which no other way lists while this project is the sequence's here.
+ uiB.Toasts[^1].Action!();
+ Assert.Equal((bed.SequenceId, sibling.Id), uiB.Opened[^1]);
}
}
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
index 3bc3d8ba..13a769e8 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
@@ -255,10 +255,25 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.True(plan is { Modified: true, Unsent: 0, Conflict: false, Offline: false, IsSafe: false });
Assert.True(plan.Files >= 4 + 2, "the proxies, the media index and the working state");
Assert.Greater(plan.Bytes, 0);
- var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, _ => { });
+ var discards = new List();
+ var asked = 0;
+ var dialog = new RemoveCopyDialogViewModel(plan, d =>
+ {
+ discards.Add(d);
+ return Task.CompletedTask;
+ }, () => Task.CompletedTask, () => ++asked > 1, _ => { });
Assert.False(dialog.RemoveCommand.CanExecute(null), "not while work is not in the library");
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), dialog.RemoveToolTip);
Assert.True(dialog.SendFirstCommand.CanExecute(null) && dialog.DiscardCommand.CanExecute(null));
+ // Discard changes asks for the typed confirmation first: refused, nothing is removed; confirmed, it is.
+ dialog.DiscardCommand.Execute(null);
+ await WorkspaceTestBed.UntilAsync(() => asked == 1 && dialog.DiscardCommand.CanExecute(null), "the confirmation is asked");
+ Assert.Empty(discards, "refused: nothing discarded");
+ dialog.DiscardCommand.Execute(null);
+ await WorkspaceTestBed.UntilAsync(() => discards.Count == 1, "confirmed: discarded");
+ Assert.True(discards[0]);
+ var request = RemoveCopyDialogViewModel.DiscardRequest("Main");
+ Assert.True(request is { IsDestructive: true, TypedConfirmation: "Main" } && request.TypedPrompt is { Length: > 0 });
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
new file mode 100644
index 00000000..7303f4e3
--- /dev/null
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
@@ -0,0 +1,313 @@
+using System.IO;
+using Chronos.App.Editor;
+using Chronos.App.Infrastructure;
+using Chronos.App.Workspace;
+using Chronos.Core.Localization;
+using Chronos.Core.Model;
+using Chronos.Core.Project;
+using Chronos.Data.Sync;
+using Chronos.Data.Workspaces;
+using Chronos.Testing;
+
+namespace Chronos.App.Tests.Workspace;
+
+///
+/// The editor and the project menu of a workspace project as review 2's phase 5a found them wanting (owner review 2, R8):
+/// saves that merge positions photo by photo and ask where both changed a setting, Take the library's as one undo step,
+/// the chip read again after edits, conflicts that wait for the open dialog, Send first that shows the conflict it met,
+/// Open project, read-only after a pull, a workspace inside a library, and how differences and authors read.
+///
+[Category("workspace")]
+public sealed class WorkspaceMenuTests(TestContext context)
+{
+ private static ProjectSettings Exposure(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } };
+
+ [Test]
+ public async Task SavesMergeExclusionsPhotoByPhotoAndAskWhereBothChangedASetting()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context);
+ var host = bed.Host();
+ var projectId = await bed.CheckoutAsync(host);
+ var (_, session) = await bed.OpenAsync(host, projectId);
+ var conflicts = new List();
+ session.ConflictFound += conflicts.Add;
+ await using (session)
+ {
+ var folder = host.Store.Find(projectId)!;
+ // A sync wrote another PC's exclusion of frame 5 while the editor's exclusion of frame 2 waited for its save.
+ var stored = folder.ReadBundle();
+ folder.WriteBundle(stored with { Project = stored.Project with { ExcludedFrames = [5] } });
+ Assert.True(session.SetExcluded([2], excluded: true));
+ Assert.True(await session.FlushAsync());
+ Assert.SequenceEqual([2, 5], folder.ReadBundle().Project.ExcludedFrames, "both exclusions are kept");
+ Assert.SequenceEqual([2, 5], session.Project.ExcludedFrames, "the editor shows the other one too");
+ Assert.Empty(conflicts);
+
+ // The same setting to another value meanwhile: asked, never decided for the editor.
+ stored = folder.ReadBundle();
+ folder.WriteBundle(stored with { Project = Exposure(stored.Project, 0.5) });
+ Assert.True(session.Edit(p => Exposure(p, 0.9)));
+ Assert.False(await session.FlushAsync(), "nothing is stored until the user chooses");
+ Assert.Count(1, conflicts);
+ var conflict = conflicts[0];
+ Assert.Contains(conflict.Differences, d => d.Path == "exposure.exposureOffsetEv");
+ Assert.Equal(0.5, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
+ var request = EditorViewModel.LibraryConflictRequest(conflict, "Harbour");
+ Assert.Equal(Loc.L("Editor.Workspace.Conflict.TakeHome"), request.SafeText);
+ Assert.Contains("0.9", request.Detail!);
+ Assert.True(session.ResolveConflict(keepMine: true));
+ Assert.True(await session.FlushAsync());
+ Assert.Equal(0.9, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
+ Assert.SequenceEqual([2, 5], folder.ReadBundle().Project.ExcludedFrames);
+ }
+ }
+
+ [Test]
+ public async Task TakingTheLibrarysValuesIsOneUndoStepThatKeepsItsOtherChanges()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context);
+ var here = bed.Host();
+ var there = bed.Host(name: "other-pc");
+ var mainId = await bed.CheckoutAsync(here);
+ await bed.CheckoutAsync(there);
+ var (sourceA, sessionA) = await bed.OpenAsync(there, mainId);
+ var (sourceB, sessionB) = await bed.OpenAsync(here, mainId);
+ var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
+ await using (sessionA)
+ await using (sessionB)
+ using (var a = new ProjectMenuViewModel(there, sourceA, sessionA, uiA))
+ using (var b = new ProjectMenuViewModel(here, sourceB, sessionB, uiB))
+ {
+ // The other PC changes the exposure and the camera; this one the exposure only.
+ sessionA.Edit(p => Exposure(p, 0.1) with { Camera = p.Camera with { OffsetY = 0.2 } });
+ await a.SaveVersionAsync(null);
+ sessionB.Edit(p => Exposure(p, 0.7));
+ await b.SyncAsync();
+ var dialog = Assert.NotNull(uiB.Open as ConflictDialogViewModel);
+ Assert.Count(1, dialog.Differences);
+
+ dialog.TakeHomeCommand.Execute(null);
+ await WorkspaceTestBed.UntilAsync(() => uiB.Open is null, "take the library's settles it");
+ Assert.Equal((0.1, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
+ var toast = uiB.Toasts[^1];
+ Assert.Equal(Loc.L("Editor.Workspace.TookLibrary"), toast.Title);
+
+ // Its Undo brings this PC's exposure back, not the camera the library alone changed; Ctrl+Z takes the take back alike.
+ toast.Action!();
+ Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
+ Assert.True(sessionB.Undo());
+ Assert.Equal(0.1, sessionB.Project.Exposure.ExposureOffsetEv);
+ Assert.True(sessionB.Undo());
+ Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
+ Assert.True(await sessionB.FlushAsync());
+ var working = here.Store.Find(mainId)!.ReadBundle().Project;
+ Assert.Equal((0.7, 0.2), (working.Exposure.ExposureOffsetEv, working.Camera.OffsetY), "the values brought back are stored");
+ }
+ }
+
+ [Test]
+ public async Task TheChipFollowsEditsAndABackgroundConflictWaitsForTheOpenDialog()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context);
+ var here = bed.Host();
+ var there = bed.Host(name: "other-pc");
+ var mainId = await bed.CheckoutAsync(here);
+ await bed.CheckoutAsync(there);
+ var (sourceA, sessionA) = await bed.OpenAsync(there, mainId);
+ var (sourceB, sessionB) = await bed.OpenAsync(here, mainId);
+ var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
+ await using (sessionA)
+ await using (sessionB)
+ using (var a = new ProjectMenuViewModel(there, sourceA, sessionA, uiA))
+ using (var b = new ProjectMenuViewModel(here, sourceB, sessionB, uiB))
+ {
+ await b.RefreshAsync();
+ Assert.Equal(Loc.L("Editor.Workspace.State.InSync"), b.StateText);
+ sessionB.Edit(p => Exposure(p, 0.7));
+ await WorkspaceTestBed.UntilAsync(() => b.StateText == Loc.L("Editor.Workspace.State.Modified"), "the chip says the work is not saved as a version");
+
+ sessionA.Edit(p => Exposure(p, 0.1));
+ await a.SaveVersionAsync(null);
+ // The user types a note in Save version when an automatic sync (after an analysis) meets the conflict.
+ b.SaveVersionCommand.Execute(null);
+ var saving = Assert.NotNull(uiB.Open as SaveVersionDialogViewModel);
+ saving.Note = "Warmer";
+ await b.SyncAsync(quiet: true);
+ Assert.Same(saving, uiB.Open, "the open dialog stays");
+ Assert.Equal("Warmer", saving.Note);
+ Assert.Equal(WorkspaceState.Conflict, b.Status!.State);
+ await b.SyncAsync(quiet: true);
+ Assert.Count(1, uiB.Waiting, "asked once");
+ uiB.CloseDialog(saving);
+ Assert.NotNull(uiB.Open as ConflictDialogViewModel, "asked once the dialog closed");
+ }
+ }
+
+ [Test]
+ public async Task SendFirstShowsTheConflictItMeetsAndRemovesNothing()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context);
+ var here = bed.Host();
+ var there = bed.Host(name: "other-pc");
+ var mainId = await bed.CheckoutAsync(here);
+ await bed.CheckoutAsync(there);
+ var (sourceA, sessionA) = await bed.OpenAsync(there, mainId);
+ var (sourceB, sessionB) = await bed.OpenAsync(here, mainId);
+ var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
+ await using (sessionA)
+ await using (sessionB)
+ using (var a = new ProjectMenuViewModel(there, sourceA, sessionA, uiA))
+ using (var b = new ProjectMenuViewModel(here, sourceB, sessionB, uiB))
+ {
+ sessionA.Edit(p => Exposure(p, 0.1));
+ await a.SaveVersionAsync(null);
+ sessionB.Edit(p => Exposure(p, 0.7));
+ Assert.True(await sessionB.FlushAsync());
+
+ b.RemoveCopyCommand.Execute(null);
+ await WorkspaceTestBed.UntilAsync(() => uiB.Open is RemoveCopyDialogViewModel, "the plan shows");
+ var removing = (RemoveCopyDialogViewModel)uiB.Open!;
+ removing.SendFirstCommand.Execute(null);
+ await WorkspaceTestBed.UntilAsync(() => uiB.Open is ConflictDialogViewModel, "the conflict is asked, not hidden behind Discard");
+ Assert.Equal(0, uiB.Closed, "the editor stays open");
+ Assert.NotNull(here.Store.Find(mainId), "nothing was removed");
+ }
+ }
+
+ [Test]
+ public async Task OpenProjectOffersTheLibrarysOtherProjects()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context);
+ var host = bed.Host();
+ var mainId = await bed.CheckoutAsync(host);
+ var vertical = await host.CreateProjectAsync(bed.SequenceId, "Vertical", null);
+ var (source, session) = await bed.OpenAsync(host, mainId);
+ var ui = new RecordingUi();
+ await using (session)
+ using (var menu = new ProjectMenuViewModel(host, source, session, ui))
+ {
+ menu.OpenProjectCommand.Execute(null);
+ await WorkspaceTestBed.UntilAsync(() => ui.Open is OpenInWorkspaceDialogViewModel, "the projects are listed");
+ var dialog = (OpenInWorkspaceDialogViewModel)ui.Open!;
+ Assert.SequenceEqual(["Vertical"], dialog.Projects.Select(p => p.Project.Name), "the open project is not offered");
+ dialog.IsNew = true;
+ dialog.NewName.Text = "Main";
+ Assert.False(dialog.CanOpen, "the open project's name is taken");
+ dialog.IsExisting = true;
+ dialog.SelectedProject = dialog.Projects[0];
+ dialog.OpenCommand.Execute(null);
+ await WorkspaceTestBed.UntilAsync(() => ui.Opened.Count == 1, "the project opens");
+ Assert.Equal((bed.SequenceId, vertical.Id), ui.Opened[0]);
+ }
+ }
+
+ [Test]
+ public async Task APullOfANewerChronossSettingsTurnsTheEditorReadOnly()
+ {
+ 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);
+ var raised = 0;
+ source.ReadOnlyChanged += () => raised++;
+ await using (session)
+ {
+ Assert.False(session.IsReadOnly);
+ var folder = host.Store.Find(projectId)!;
+ var stored = folder.ReadBundle();
+ folder.WriteBundle(stored with { Project = stored.Project with { Version = ProjectSettings.CurrentVersion + 1 } });
+ await session.ReloadAsync();
+ Assert.True(session.IsReadOnly);
+ Assert.Equal(1, raised, "the editor is told, and shows it");
+ Assert.False(session.HasPendingSave, "no save that could never be stored waits");
+ Assert.False(session.Edit(p => Exposure(p, 0.4)));
+ Assert.True(await session.FlushAsync(), "operations that store the last edit go on");
+ }
+ }
+
+ [Test]
+ public async Task AWorkspaceInsideALibraryIsRefusedBeforeAnythingIsWritten()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context);
+ var row = await bed.RowAsync();
+ var root = (await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath;
+ var inside = Path.Combine(root, "Chronos", "data", "workspace");
+ var host = bed.Host(new AppSettings { WorkspaceFolder = inside });
+ Assert.Empty(await host.ListAsync());
+ Assert.Null(await host.FindAsync(Guid.NewGuid()));
+ var refused = await Assert.ThrowsAsync(() => host.CheckoutAsync(bed.SequenceId, null, null));
+ Assert.Equal(Loc.L("Errors.Workspace.InsideLibraryEdit", inside), refused.Message);
+ Assert.False(Directory.Exists(inside), "nothing was written there");
+ }
+
+ [Test]
+ public void ACopyTheLibraryNoLongerHasCanOnlyBeDiscarded()
+ {
+ var plan = new WorkspaceRemovalPlan(Guid.NewGuid(), "Vertical", 3, 100, 0, false, false, true, Gone: true);
+ var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => false, _ => { });
+ Assert.False(dialog.RemoveCommand.CanExecute(null) || dialog.SendFirstCommand.CanExecute(null));
+ Assert.True(dialog.HasUnsent && dialog.DiscardCommand.CanExecute(null));
+ Assert.Equal(Loc.L("Errors.Workspace.ProjectGone"), dialog.RemoveToolTip);
+
+ // The chip keeps what the library said last when the working state is read again after an edit.
+ var basis = new BundleBase(Guid.NewGuid(), 2, new string('a', 64));
+ var gone = new WorkspaceStatus(WorkspaceState.Gone, false, 0, 0, true, false, false, null, basis, null);
+ var edited = new WorkspaceStatus(WorkspaceState.Modified, true, 0, 0, false, false, false, null, basis, null);
+ Assert.Equal(WorkspaceState.Gone, ProjectMenuViewModel.WithLocal(gone, edited).State);
+ var behind = gone with { State = WorkspaceState.Behind, Behind = 2, Offline = false };
+ Assert.Equal((WorkspaceState.Behind, 2), (ProjectMenuViewModel.WithLocal(behind, edited).State, ProjectMenuViewModel.WithLocal(behind, edited).Behind));
+ Assert.Equal(WorkspaceState.Modified, ProjectMenuViewModel.WithLocal(behind, edited with { Base = basis with { VersionId = Guid.NewGuid() } }).State,
+ "a base that moved since says nothing of how far the library is ahead");
+ }
+
+ [Test]
+ public void DifferencesNameTheirSettingsAndAuthorsReadAsThePc()
+ {
+ var lines = WorkspaceText.ConflictLines(
+ [
+ new SettingsDifference("hero", "{\"hero\":true}", "{\"hero\":true}"),
+ new SettingsDifference("pendingFrames.sha:ab12#0.keyframes", "[]", "[{\"x\":1}]"),
+ new SettingsDifference("pendingFrames.sha:cd34#0.excluded", "true", "false"),
+ ], 10);
+ Assert.Count(3, lines);
+ Assert.Contains(lines, l => l.Contains(Loc.L("Server.Setting.HeroFrame"), StringComparison.Ordinal));
+ Assert.Contains(lines, l => l.Contains(Loc.L("Server.Setting.Keyframes"), StringComparison.Ordinal));
+ Assert.Contains(lines, l => l.Contains(Loc.L("Server.Setting.ExcludedFrames"), StringComparison.Ordinal));
+ Assert.False(lines.Any(l => l.Contains(Loc.L("Server.Setting.Other"), StringComparison.Ordinal)), "every line names its setting");
+
+ ProjectVersion Made(string? client, string? author = null) => new()
+ {
+ Id = Guid.NewGuid(),
+ ProjectId = Guid.NewGuid(),
+ Number = 1,
+ SettingsJson = "{}",
+ ContentHash = new string('0', 64),
+ ClientName = client,
+ Author = author,
+ };
+ Assert.Equal("STUDIO-PC", WorkspaceText.Author(Made("chronos@STUDIO-PC")));
+ Assert.Equal("STUDIO-PC", WorkspaceText.Author(Made("Chronos on STUDIO-PC")));
+ Assert.Equal("STUDIO-PC", WorkspaceText.Author(Made("STUDIO-PC")));
+ Assert.Equal("Alberto", WorkspaceText.Author(Made("STUDIO-PC", "Alberto")));
+ Assert.Equal(Environment.MachineName, WorkspaceHost.ClientName);
+ }
+
+ [Test]
+ public async Task CompareNamesExclusionsAsTheSettingTheyAre()
+ {
+ 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);
+ var ui = new RecordingUi();
+ await using (session)
+ using (var menu = new ProjectMenuViewModel(host, source, session, ui))
+ {
+ var head = (await host.HistoryAsync(projectId)).Versions[0];
+ Assert.True(session.SetExcluded([1, 3], excluded: true));
+ var lines = menu.Compare(head);
+ Assert.Count(1, lines);
+ Assert.Contains(Loc.L("Server.Setting.ExcludedFrames"), lines[0]);
+ }
+ }
+}
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
index 8f70d602..2b46ac08 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
@@ -180,6 +180,11 @@ internal sealed class RecordingUi : IWorkspaceUi
public List SequencesChanged { get; } = [];
+ /// Dialogs waiting for the open one to close ().
+ public Queue Waiting { get; } = new();
+
+ public ArchiveDialogViewModel? Dialog => Open;
+
public void ShowDialog(ArchiveDialogViewModel dialog)
{
Open?.Dispose();
@@ -187,11 +192,23 @@ internal sealed class RecordingUi : IWorkspaceUi
Open = dialog;
}
+ public void ShowDialogWhenFree(ArchiveDialogViewModel dialog)
+ {
+ if (Open is null) ShowDialog(dialog);
+ else Waiting.Enqueue(dialog);
+ }
+
public void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(Open, dialog)) return;
dialog.Dispose();
Open = null;
+ while (Waiting.TryDequeue(out var next))
+ {
+ if (next.IsClosed) continue;
+ ShowDialog(next);
+ break;
+ }
}
public bool Confirm(ConfirmRequest request)
diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs
new file mode 100644
index 00000000..b9da2d64
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs
@@ -0,0 +1,188 @@
+using Chronos.Core.Model;
+using Chronos.Core.Project;
+using Chronos.Data.Projects;
+using Chronos.Data.Tests.Archiving;
+using Chronos.Data.Tests.Infrastructure;
+using Chronos.Data.Workspaces;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Workspaces;
+
+///
+/// Settling a workspace conflict and restoring a version (owner review 2, R8): a choice applies only to the conflicts the
+/// user was shown, what a choice replaces stays in a version, a restore loses nothing while a conflict waits, and only a
+/// restore the working state still shows makes a "restore" version.
+///
+[Category("workspace")]
+public abstract class WorkspaceConflictTests(TestContext context) : DatabaseTest(context)
+{
+ private async Task FixtureAsync(int frames = 5)
+ {
+ var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
+ return Own(await WorkspaceFixture.CreateAsync(Context, archive, frames));
+ }
+
+ /// The working state edited as the editor does: read, changed, stored.
+ private static async Task EditAsync(WorkspaceSync sync, Guid projectId, Func edit, CancellationToken ct)
+ {
+ var session = await sync.OpenAsync(projectId, ct);
+ await sync.SaveAsync(projectId, edit(session.Working), ct);
+ }
+
+ private static ProjectSettings Offset(ProjectSettings s, double ev) => s with { Exposure = s.Exposure with { ExposureOffsetEv = ev } };
+
+ private static ProjectSettings Stack(ProjectSettings s, StackSetting mode) => s with { Stack = new StackSettings { Mode = mode } };
+
+ /// Two workspaces of Main; the first has sent an offset of 0.5 and a Median stack, the second changed the offset to 1 and was asked.
+ private static async Task<(WorkspaceFixture Fx, WorkspaceSync One, WorkspaceSync Two, Guid Id, WorkspaceConflict Shown)> AskedAsync(WorkspaceFixture fx)
+ {
+ 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 => Stack(Offset(s, 0.5), StackSetting.Median), fx.Ct);
+ await one.CommitAsync(id, cancellationToken: fx.Ct);
+ await one.PushAsync(id, fx.Home, fx.Ct);
+ await EditAsync(two, id, s => Offset(s, 1.0), fx.Ct);
+ var pulled = await two.PullAsync(id, fx.Home, fx.Ct);
+ var shown = Assert.NotNull(pulled.Status.Conflict);
+ Assert.Equal("exposure.exposureOffsetEv", shown.Differences.Single().Path, "the stack only one side changed merges");
+ return (fx, one, two, id, shown);
+ }
+
+ [Test]
+ public async Task AChoiceSettlesOnlyTheConflictsTheUserWasShown()
+ {
+ var (fx, _, two, id, shown) = await AskedAsync(await FixtureAsync());
+
+ // Later: editing goes on, and the stack, which the library changed too, is set here. Nobody was shown that one.
+ await EditAsync(two, id, s => Stack(s, StackSetting.StarTrails), fx.Ct);
+ var asked = await two.ResolveAsync(id, fx.Home, ConflictChoice.TakeServer, shown: shown, cancellationToken: fx.Ct);
+ Assert.Equal(WorkspaceState.Conflict, asked.Status.State);
+ var again = Assert.NotNull(asked.Status.Conflict);
+ Assert.SequenceEqual(["exposure.exposureOffsetEv", "stack.mode"], again.Differences.Select(d => d.Path).Order(StringComparer.Ordinal));
+ var working = (await two.OpenAsync(id, fx.Ct)).Working;
+ Assert.Equal((1.0, StackSetting.StarTrails), (working.Exposure.ExposureOffsetEv, working.Stack.Mode), "nothing was settled");
+
+ // Asked again with both, take the library's: its values; this side's are kept in a version all the same.
+ Assert.Null(asked.Kept, "nothing settled, nothing to take back");
+ var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.TakeServer, shown: again, cancellationToken: fx.Ct);
+ Assert.Null(settled.Status.Conflict);
+ working = (await two.OpenAsync(id, fx.Ct)).Working;
+ Assert.Equal((0.5, StackSetting.Median), (working.Exposure.ExposureOffsetEv, working.Stack.Mode));
+ // What keeping this side's values would have left, for the editor's undo of the take.
+ var kept = Assert.NotNull(settled.Kept);
+ Assert.Equal((1.0, StackSetting.StarTrails), (kept.Exposure.ExposureOffsetEv, kept.Stack.Mode));
+ var replaced = Path.Combine(two.Store.Find(id)!.VersionsDirectory, WorkspaceProject.ReplacedFolder);
+ Assert.True(Directory.GetFiles(replaced).Select(ProjectSidecars.ReadVersion).Any(v =>
+ ProjectSettings.FromJson(v.SettingsJson) is { Stack.Mode: StackSetting.StarTrails, Exposure.ExposureOffsetEv: 1.0 }), "the values taken over stay in a version");
+ }
+
+ [Test]
+ public async Task KeepMineIsAskedAgainWhenTheLibraryMovedOnASettingThisSideChanged()
+ {
+ var (fx, one, two, id, shown) = await AskedAsync(await FixtureAsync());
+ await EditAsync(two, id, s => s with { Motion = s.Motion with { TargetShutterAngle = s.Motion.TargetShutterAngle.WithManual(90) } }, fx.Ct);
+
+ // Meanwhile the other workspace sends a change of that same setting.
+ await one.PullAsync(id, fx.Home, fx.Ct);
+ await EditAsync(one, id, s => s with { Motion = s.Motion with { TargetShutterAngle = s.Motion.TargetShutterAngle.WithManual(270) } }, fx.Ct);
+ await one.CommitAsync(id, cancellationToken: fx.Ct);
+ await one.PushAsync(id, fx.Home, fx.Ct);
+
+ var asked = await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: shown, cancellationToken: fx.Ct);
+ var again = Assert.NotNull(asked.Status.Conflict, "the library's newer change is asked about, not overwritten");
+ Assert.Equal(2, again.Differences.Count);
+ Assert.Contains(again.Differences, d => d.Path.StartsWith("motion.targetShutterAngle", StringComparison.Ordinal));
+ Assert.Equal(270.0, ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson).Motion.TargetShutterAngle.Resolve(0));
+
+ var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: again, cancellationToken: fx.Ct);
+ Assert.Equal(WorkspaceState.Modified, settled.Status.State, "this side's values are the working state, on the library's head");
+ Assert.Null(settled.Kept, "keeping mine replaces nothing of this side's");
+ await two.CommitAsync(id, cancellationToken: fx.Ct);
+ await two.PushAsync(id, fx.Home, fx.Ct);
+ var head = ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson);
+ Assert.Equal((1.0, 90.0, StackSetting.Median), (head.Exposure.ExposureOffsetEv, head.Motion.TargetShutterAngle.Resolve(0), head.Stack.Mode));
+ }
+
+ [Test]
+ public async Task SyncAsksAboutWhatDiffersNowWhileAConflictWaits()
+ {
+ var (fx, _, two, id, _) = await AskedAsync(await FixtureAsync());
+
+ // Edited during Later: the next pull lists the stack too.
+ await EditAsync(two, id, s => Stack(s, StackSetting.Mean), fx.Ct);
+ var refreshed = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict);
+ Assert.SequenceEqual(["exposure.exposureOffsetEv", "stack.mode"], refreshed.Differences.Select(d => d.Path).Order(StringComparer.Ordinal));
+
+ // This side takes the library's values by hand: nothing conflicts any more, and the pull settles it.
+ await EditAsync(two, id, s => Stack(Offset(s, 0.5), StackSetting.Median), fx.Ct);
+ var pulled = await two.PullAsync(id, fx.Home, fx.Ct);
+ Assert.Null(pulled.Status.Conflict);
+ Assert.Equal(WorkspaceState.InSync, pulled.Status.State);
+ Assert.Null(await two.CommitAsync(id, cancellationToken: fx.Ct), "nothing new to save, and no conflict refuses a version");
+ }
+
+ [Test]
+ public async Task ARestoreWhileAConflictWaitsKeepsTheUnsavedChangesAsAVersion()
+ {
+ var (fx, _, two, id, _) = await AskedAsync(await FixtureAsync());
+ var first = (await fx.Home.HistoryAsync(id, null, 10, fx.Ct)).Single(v => v.Number == 1);
+
+ // Later, then an edit stored but saved as no version, then History › Restore.
+ await EditAsync(two, id, s => Stack(s, StackSetting.Mean), fx.Ct);
+ var restored = await two.RestoreAsync(id, first.Id, fx.Home, fx.Ct);
+ Assert.Equal((0.0, StackSetting.None), (restored.Exposure.ExposureOffsetEv, restored.Stack.Mode));
+ var kept = Assert.Contains(two.Unpushed(id), v => ProjectSettings.FromJson(v.SettingsJson) is { Stack.Mode: StackSetting.Mean, Exposure.ExposureOffsetEv: 1.0 });
+ Assert.Equal(ProjectVersionKind.Commit, kept.Kind);
+ Assert.NotNull((await two.StatusAsync(id, fx.Home, fx.Ct)).Conflict, "the conflict still waits");
+
+ // Settled for this side, the saved edit reaches the library under the restore.
+ var asked = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict);
+ await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: asked, cancellationToken: fx.Ct);
+ await two.PushAsync(id, fx.Home, fx.Ct);
+ Assert.Contains(await fx.Home.HistoryAsync(id, null, 10, fx.Ct), v => ProjectSettings.FromJson(v.SettingsJson).Stack.Mode == StackSetting.Mean);
+ }
+
+ [Test]
+ public async Task OnlyARestoreTheWorkingStateStillShowsMakesARestoreVersion()
+ {
+ var fx = await FixtureAsync();
+ var (_, sync) = fx.Workspace();
+ var id = (await fx.CheckoutAsync(sync)).ProjectId;
+ var original = await fx.Home.HeadAsync(id, fx.Ct);
+ await EditAsync(sync, id, s => Offset(s, 0.3), fx.Ct);
+ var warm = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct));
+
+ // Restoring the version the project is changes nothing: the next version is a plain one.
+ await sync.RestoreAsync(id, warm.Id, fx.Home, fx.Ct);
+ await EditAsync(sync, id, s => Stack(s, StackSetting.Mean), fx.Ct);
+ var next = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct));
+ Assert.Equal((ProjectVersionKind.Commit, (Guid?)null), (next.Kind, next.RestoredFrom));
+
+ // A restore taken back (the editor's Undo writes the state from before it again), then another edit: no restore either.
+ var before = (await sync.OpenAsync(id, fx.Ct)).Working;
+ await sync.RestoreAsync(id, original.Id, fx.Home, fx.Ct);
+ await sync.SaveAsync(id, before, fx.Ct);
+ await EditAsync(sync, id, s => s with { ExcludedFrames = [1] }, fx.Ct);
+ var after = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct));
+ Assert.Equal((ProjectVersionKind.Commit, (Guid?)null), (after.Kind, after.RestoredFrom));
+
+ // A restore the working state still shows, edited further: a restore of it.
+ await sync.RestoreAsync(id, original.Id, fx.Home, fx.Ct);
+ await EditAsync(sync, id, s => s with { HeroFrame = 2 }, fx.Ct);
+ var restore = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct));
+ Assert.Equal((ProjectVersionKind.Restore, (Guid?)original.Id), (restore.Kind, restore.RestoredFrom));
+ }
+}
+
+public sealed class SqliteWorkspaceConflictTests(TestContext context) : WorkspaceConflictTests(context)
+{
+ protected override Backend Backend => Backend.SqliteFile;
+}
+
+[RequiresEnvironment(PgTestServer.Variable)]
+public sealed class PostgresWorkspaceConflictTests(TestContext context) : WorkspaceConflictTests(context)
+{
+ protected override Backend Backend => Backend.Postgres;
+}