diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx
index b371aa79..79860a7a 100644
--- a/i18n/en/Editor.resx
+++ b/i18n/en/Editor.resx
@@ -191,12 +191,15 @@
Path smoothingStabiliseExisting
+ Free spaceMediathe photos the workspace copies: proxies or originalsNew
+ Not enough spaceOpenOriginalsProjectProxies
+ Copy sizeOpen in workspace{0}: {1} → {2}invariant{0}: {1} ← {2}invariant; right-to-left languages: the arrow points from the old value to the new one
@@ -373,8 +376,11 @@
{0} pxinvariant{0}invariant{0}×invariant
+ Choose folderLater{0} was changed in the library while you edited it here. These settings differ: keep yours, take the library's, or keep both as two projects.long; {0} project name
+ Saved by a newer Chronoslong; the one line a conflict of format lists
+ {0} was saved in the library by a newer Chronos, whose settings this one does not merge with yours. Keep both as two projects, or update Chronos.long; {0} project nameTake library'stake the library's values where both sides changed a settingChanged in the library tooWorkspace copy failed
@@ -402,6 +408,7 @@
Not sentversions saved here wait to be sent to the libraryLibrary newerthe library has versions the workspace has not takenConflict
+ DamagedNot in libraryIn syncNo media
diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index c1581591..a6f90311 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -55,14 +55,17 @@
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 missingThe last edit could not be stored yet; it is tried again, try once more in a moment.
+ {0} cannot be used as the workspace folder; the log says why.long; {0} folderThe 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
+ The workspace folder {0} is inside a library, where Edit copies nothing: choose another workspace folder.long
+ {0} is inside a library, where Edit copies nothing: choose a folder outside your libraries.long; {0} folderA 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.The workspace holds no photos of this project; open it again to copy them.Another project of this sequence has that name.
+ The drive of the workspace folder lacks room for this copy and the 0.5 GB the copy keeps free.The project is no longer in the workspace.The library cannot be reached now; your work stays in the workspace and can be sent once it is back.The workspace copies proxies for now; copying the originals comes in a later version.
@@ -70,6 +73,7 @@
The workspace copy job has no valid parameters.This project is no longer in the library.This project was saved by a newer Chronos: it opens read-only.
+ The library is read-only now; your work stays in the workspace and can be sent once it is writable.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.longSome work is not in the library yet: send it first, or discard it.
diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index 48843efc..2928180e 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -14,6 +14,7 @@
TLS {0} trusted {1}Cancel{0} differs{0} setting name
+ {0} ({1})invariant; {0} setting name, {1} number of photos it differs on{0} {1} here, {2} on the serverlong; {0} setting name, {1} value on this PC, {2} value on the serverThe server copy of {0} will be replaced by this PC's settings.long; {0} sequence titleKeep this PC's settings?
diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx
index bc2192bd..dbc94927 100644
--- a/i18n/en/Settings.resx
+++ b/i18n/en/Settings.resx
@@ -198,9 +198,18 @@
{0} usedLatest versionAfter each version
+ Change…
+ Edit lists the projects in {0} from now on. Those in {1} stay where they are, and come back if you choose that folder again.long; {0} the folder chosen, {1} the folder in use
+ Use another workspace folder?long; confirmation heading
+ Workspace folder changed
+ Choose the workspace folderlong; folder picker titleFolderKept versions
+ Folder not changed
+ Projects found: {0}{0} count of the projects the folder chosen holds
+ Projects left: {0}{0} count of the projects the folder in use keepsSync
+ Use folder{0} version{0} versions
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index b48b5abb..da4b8aea 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -223,12 +223,14 @@
Not applicable: stabilisation is offNot applicable: stacking is offOpen a project the library has for this sequence; Main holds its settings as they are
+ Free space on the drive of the workspace folder; the copy keeps 0.5 GB free besidesThe new project's name: 1 to 60 characters, each name once per sequenceA new project of this sequence, starting from MainCopy the project's photos into the workspace, then open it thereCopying the originals, to render on this PC, comes in a later updateThe sequence's projects in the libraryCopy the proxies: light and fast to edit; renders use the library's originals
+ What the copy of the proxies writes into the workspace, as reckoned before it startsLet the advisor set every section from the analysis and list what changedThe advisor never stacks on its own: a median erases moving starsApply the advisor’s heavier choices for this section and list what changed · Ctrl+Z undoes
@@ -324,15 +326,19 @@
Photos shown per second of video; more plays the sequence fasterClose without the change; the stored settings stay as they wereStay in the editor; saving is retried in the background
+ Choose a workspace folder outside your libraries; nothing is movedThe settings that differ: your value, then the library'sKeep your values of these settings; they are sent to the libraryDecide later and keep editing; Sync asks againPhotos were added to or removed from this sequence in the library after the workspace copied it
+ The library's project was saved by a newer Chronos: its settings are not merged with yours, so Keep mine and Take library's are not offeredOpen project {0}, which holds your versionslongKeep the library's values in this project, and send yours to a new project “{0}”{0} the new project's name
+ Send your versions to a new project “{0}”; this project takes the library's, read-only until Chronos is updated{0} the new project's nameVersions saved here that wait to be sent to the library: {0}. Sync sends them{0} number of versionsVersions in the library this workspace has not taken yet: {0}. Sync takes them{0} number of versionsYou and the library changed the same settings: Sync to choose which to keep
+ This copy's project file cannot be read, so it cannot open; Remove local copy keeps its files in the workspace's trashThe library no longer has this project or its sequence: nothing more can be sent; remove the local copy (its work is kept aside)longEvery version of this project is in the library, and nothing changed since the last oneThe workspace holds no photos of this project: opening it copies them again
@@ -708,6 +714,7 @@
Where frames spill and thumbnails are kept; a fast SSD helps · Enter applies, Esc revertsLargest size of the disk cache in GB · Enter applies, Esc revertsSpace the cache uses and free space on its drive
+ Use another workspace folder, after a plan; nothing is moved: the projects of this one stay hereLook for a new release when Chronos starts · no data is sentDelete the cache contents nowDelete spilled frames and cached thumbnails; asks first
@@ -731,6 +738,7 @@
Keep the index as it isLog files last written longer ago are deletedKeep every setting as it is
+ Keep the workspace folder in useHow many of the library's versions each project keeps on this PC besides those not sent; older ones stay in the libraryLanguage of the interface · applies immediatelyA log file that reaches this size continues in a new numbered file
@@ -794,7 +802,8 @@
Every pixel is decodedNo decoder on this PC reads its pixels; such frames are left out of rendersSend a daily anonymous count of versions and languages in use; nothing else, off by default
- The workspace's folder (a fast disk is best); moving it comes in a later update
+ Edit uses this folder from now on; nothing is moved or deleted
+ The workspace's folder (a fast disk is best); Change uses another one, moving it comes in a later updateSend each version you save to the library at once, and take the library's new versionsInstall in Program Files for every account · asks for administrator approval{0} · it runs as a Windows service, so it installs for all users in Program Files
diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx
index dcc5a09f..38bc3bcb 100644
--- a/i18n/it/Editor.it.resx
+++ b/i18n/it/Editor.it.resx
@@ -183,12 +183,15 @@
Smussatura percorsoStabilizzaEsistente
+ Spazio liberoMediaNuovo
+ Spazio insufficienteApriOriginaliProgettoProxy
+ Dimensione copiaApri nello spazio di lavoro{0} impostazione cambiata{0} impostazioni cambiate
@@ -348,8 +351,11 @@
NessunoDisattivoAttivo
+ Scegli cartellaPiù tardi{0} è stato modificato nella libreria mentre lo modificavi qui. Queste impostazioni sono diverse: tieni le tue, prendi quelle della libreria o tienile entrambe come due progetti.
+ Salvato da un Chronos più recente
+ {0} è stato salvato nella libreria da un Chronos più recente, le cui impostazioni questo non unisce alle tue. Tienile entrambe come due progetti, oppure aggiorna Chronos.Prendi la libreriaModificato anche nella libreriaCopia di lavoro non riuscita
@@ -377,6 +383,7 @@
Da inviareLibreria più nuovaConflitto
+ DanneggiatoNon in libreriaSincronizzatoSenza media
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index 84954535..7e758a75 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -55,14 +55,17 @@
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.
+ {0} non si può usare come cartella dello spazio di lavoro; il registro dice perché.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.
+ La cartella dello spazio di lavoro {0} è dentro una libreria, dove Modifica non copia nulla: scegli un'altra cartella dello spazio di lavoro.
+ {0} è dentro una libreria, dove Modifica non copia nulla: scegli una cartella 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.Lo spazio di lavoro non ha foto di questo progetto; riaprilo per copiarle.Un altro progetto di questa sequenza ha già quel nome.
+ All'unità della cartella dello spazio di lavoro manca lo spazio per questa copia e per gli 0,5 GB che la copia lascia liberi.Il progetto non è più nello spazio di lavoro.La libreria ora non è raggiungibile; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando torna.Per ora lo spazio di lavoro copia i proxy; la copia degli originali arriverà in una versione successiva.
@@ -70,6 +73,7 @@
Il job di copia di lavoro non ha parametri validi.Questo progetto non è più nella libreria.Questo progetto è stato salvato da un Chronos più recente: si apre in sola lettura.
+ La libreria ora è di sola lettura; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando sarà scrivibile.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/Server.it.resx b/i18n/it/Server.it.resx
index 61193ad6..df711ae3 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -13,6 +13,7 @@
TLS {0} attendibile dal {1}Annulla{0}: valori diversi
+ {0} ({1}){0} {1} qui, {2} sul serverLa copia sul server di {0} sarà sostituita dalle impostazioni di questo PC.Tenere le impostazioni di questo PC?
diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx
index 4af7d46b..3a98ada2 100644
--- a/i18n/it/Settings.it.resx
+++ b/i18n/it/Settings.it.resx
@@ -195,9 +195,18 @@
{0} usatiUltima versioneDopo ogni versione
+ Cambia…
+ Da ora Modifica elenca i progetti in {0}. Quelli in {1} restano dove sono e tornano se scegli di nuovo quella cartella.
+ Usare un'altra cartella dello spazio di lavoro?
+ Cartella cambiata
+ Scegli la cartella dello spazio di lavoroCartellaVersioni tenute
+ Cartella non cambiata
+ Progetti trovati: {0}
+ Progetti lasciati: {0}Sincronizzazione
+ Usa cartella{0} versione{0} versioni
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index d3b216a5..7e71b8c0 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -223,12 +223,14 @@
Non applicabile: la stabilizzazione è spentaNon applicabile: lo stacking è spentoApri un progetto che la libreria ha per questa sequenza; Principale ne contiene le impostazioni attuali
+ Spazio libero sull'unità della cartella dello spazio di lavoro; la copia lascia liberi anche 0,5 GBIl nome del nuovo progetto: da 1 a 60 caratteri, ogni nome una sola volta per sequenzaUn nuovo progetto di questa sequenza, a partire da PrincipaleCopia le foto del progetto nello spazio di lavoro, poi aprilo lìLa copia degli originali, per renderizzare su questo PC, arriverà in un aggiornamento successivoI progetti della sequenza nella libreriaCopia i proxy: leggeri e veloci da modificare; i render usano gli originali della libreria
+ Quanto scrive nello spazio di lavoro la copia dei proxy, come stimato prima che iniziLascia che il consulente imposti ogni sezione dall’analisi ed elenchi cosa è cambiatoIl consulente non fa mai stacking da solo: una mediana cancella le stelle in movimentoApplica le scelte più incisive del consulente per questa sezione ed elenca cosa è cambiato · Ctrl+Z annulla
@@ -323,15 +325,19 @@
Foto mostrate per secondo di video; di più accelera la sequenzaChiude senza la modifica; le impostazioni salvate restano com’eranoResta nell’editor; il salvataggio viene ritentato in background
+ Scegli una cartella dello spazio di lavoro fuori dalle tue librerie; non viene spostato nullaLe impostazioni diverse: il tuo valore, poi quello della libreriaTieni i tuoi valori di queste impostazioni; vengono inviati alla libreriaDecidi più tardi e continua a modificare; Sincronizza lo chiede di nuovoSono state aggiunte o tolte foto a questa sequenza nella libreria dopo che lo spazio di lavoro l'ha copiata
+ Il progetto della libreria è stato salvato da un Chronos più recente: le sue impostazioni non si uniscono alle tue, quindi Tieni le mie e Prendi la libreria non sono propostiApri il progetto {0}, che contiene le tue versioniTieni i valori della libreria in questo progetto e invia i tuoi a un nuovo progetto «{0}»
+ Invia le tue versioni a un nuovo progetto «{0}»; questo progetto prende quello della libreria, in sola lettura finché Chronos non viene aggiornatoVersioni salvate qui in attesa di essere inviate alla libreria: {0}. Sincronizza le inviaVersioni nella libreria non ancora prese da questo spazio di lavoro: {0}. Sincronizza le prendeTu e la libreria avete modificato le stesse impostazioni: sincronizza per scegliere quali tenere
+ Il file di progetto di questa copia non si può leggere, quindi non si apre; Rimuovi copia locale ne tiene i file nel cestino dello spazio di lavoroLa 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'ultimaLo spazio di lavoro non ha foto di questo progetto: aprirlo le copia di nuovo
@@ -706,6 +712,7 @@
Dove vanno i fotogrammi temporanei e le miniature; un SSD veloce aiuta · Invio applica, Esc annullaDimensione massima della cache su disco in GB · Invio applica, Esc annullaSpazio usato dalla cache e spazio libero sulla sua unità
+ Usa un'altra cartella dello spazio di lavoro, dopo un piano; non viene spostato nulla: i progetti di questa restano quiCerca una nuova versione all'avvio di Chronos · nessun dato viene inviatoElimina adesso il contenuto della cacheElimina fotogrammi temporanei e miniature in cache; prima chiede conferma
@@ -729,6 +736,7 @@
Lascia l'indice com'èI file di log scritti l'ultima volta prima di questo periodo vengono eliminatiLascia ogni impostazione com'è
+ Tieni la cartella dello spazio di lavoro in usoQuante versioni della libreria ogni progetto tiene su questo PC oltre a quelle non inviate; le più vecchie restano nella libreriaLingua dell'interfaccia · si applica subitoUn file di log che raggiunge questa dimensione prosegue in un nuovo file numerato
@@ -792,7 +800,8 @@
Ogni pixel viene decodificatoNessun decodificatore su questo PC ne legge i pixel; questi fotogrammi restano fuori dai renderingInvia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinita
- La cartella dello spazio di lavoro (meglio un disco veloce); spostarla arriverà in un aggiornamento successivo
+ Modifica usa questa cartella da ora; nulla viene spostato o eliminato
+ La cartella dello spazio di lavoro (meglio un disco veloce); Cambia ne usa un'altra, spostarla arriverà in un aggiornamento successivoInvia subito alla libreria ogni versione che salvi e prendi le nuove versioni della libreriaInstalla in Programmi per tutti gli account · chiede l'autorizzazione di amministratore{0} · è un servizio di Windows, quindi si installa per tutti gli utenti in Programmi
diff --git a/src/Chronos.App/Sections/SequencePickerViewModel.cs b/src/Chronos.App/Sections/SequencePickerViewModel.cs
index 6a1da6e2..b9a53cfa 100644
--- a/src/Chronos.App/Sections/SequencePickerViewModel.cs
+++ b/src/Chronos.App/Sections/SequencePickerViewModel.cs
@@ -285,6 +285,8 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
foreach (var item in items)
{
if (generation != _generation) return;
+ // Its working state cannot be read: there is no state to ask for.
+ if (item.IsDamaged) continue;
try
{
item.Status = await Shell.Services.Workspace.StatusAsync(item.ProjectId);
diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs
index e5995158..0fe5e8a7 100644
--- a/src/Chronos.App/Sections/SequenceViewModel.cs
+++ b/src/Chronos.App/Sections/SequenceViewModel.cs
@@ -232,6 +232,12 @@ public sealed class SequenceViewModel : SectionViewModel
KeepOpenSequence();
return;
}
+ // A copy whose working state cannot be read cannot open: its removal plan is what it offers.
+ if (item.IsDamaged)
+ {
+ await RemoveProjectCopyAsync(item);
+ return;
+ }
await OpenProjectAsync(item.SequenceId, item.ProjectId);
}
@@ -589,6 +595,8 @@ public sealed class SequenceViewModel : SectionViewModel
{ Main: true } => (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain),
_ => await workspace.LastUsedAsync(row.Id),
};
+ // Its working state cannot be read: nothing is checked out over it (the picker offers Remove local copy).
+ if (entry is { Damaged: true }) throw new WorkspaceException(Loc.L("Errors.Workspace.Damaged"));
if (entry is { HasMedia: true })
{
workspace.Remember(row.Id, entry.ProjectId);
@@ -613,16 +621,43 @@ public sealed class SequenceViewModel : SectionViewModel
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
}
- var checkout = await workspace.CheckoutAsync(row.Id, projectId, newName);
+ WorkspaceCheckout checkout;
+ try
+ {
+ checkout = await workspace.CheckoutAsync(row.Id, projectId, newName);
+ }
+ catch (WorkspaceException ex) when (ex.FolderRefused)
+ {
+ // Nothing was written: the way on is another workspace folder, offered from the refusal.
+ Log.Info("workspace", $"Sequence {row.Id} not checked out: {ex.Message}");
+ Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), ex.Message, Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder"),
+ () => _ = WorkspaceFolderChange.ChooseAsync(Shell), isError: true);
+ _afterOpen = null;
+ Shell.KeepSequence(OpenSequenceId);
+ return null;
+ }
await FollowCopyAsync(row.Id, row.DisplayTitle, checkout.Project.Id, checkout.Copy);
return null;
}
- /// "Open in workspace": the projects of the sequence's home and the media; null when closed without a choice.
+ ///
+ /// "Open in workspace": the projects of the sequence's home, the media, what their copy writes and the room the
+ /// workspace's drive has; null when closed without a choice.
+ ///
private async Task AskProjectAsync(WorkspaceHost workspace, Sequence row)
{
var projects = await workspace.HomeProjectsAsync(row.Id);
- var dialog = new OpenInWorkspaceDialogViewModel(row.DisplayTitle, projects, d => CloseDialog(d));
+ WorkspaceCopyFacts? copy = null;
+ try
+ {
+ copy = await workspace.CopyFactsAsync(row.Id);
+ }
+ catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
+ {
+ // Only shown: the copy measures again before it writes.
+ Log.Info("workspace", $"The copy of sequence {row.Id} could not be measured: {ex.Message}");
+ }
+ var dialog = new OpenInWorkspaceDialogViewModel(row.DisplayTitle, projects, d => CloseDialog(d), copy: copy);
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
IsLoading = false;
OpenDialog(dialog);
@@ -679,6 +714,23 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.Notify(Loc.L(fetch.ProjectId is null ? "Editor.Proxies.Failed" : "Editor.Workspace.CopyFailed"), job.Error ?? fetch.Title, Loc.L("Shell.Nav.Jobs"),
Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs), isError: true);
break;
+ // The user cancelled the first copy of a project's media: the photos it wrote go (a failed one keeps them for its retry).
+ case JobState.Cancelled when fetch.ProjectId is { } cancelled:
+ _ = RemovePartialMediaAsync(cancelled);
+ break;
+ }
+ }
+
+ private async Task RemovePartialMediaAsync(Guid projectId)
+ {
+ try
+ {
+ await Shell.Services.Workspace.RemovePartialMediaAsync(projectId);
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ // Copies the library can make again: they wait for the next copy, which checks each.
+ Log.Warning("workspace", $"The media of a cancelled copy of project {projectId} could not be removed", ex);
}
}
diff --git a/src/Chronos.App/Sections/SettingsView.xaml b/src/Chronos.App/Sections/SettingsView.xaml
index e87dd1cc..cef31194 100644
--- a/src/Chronos.App/Sections/SettingsView.xaml
+++ b/src/Chronos.App/Sections/SettingsView.xaml
@@ -522,17 +522,21 @@
-
+
+
+
diff --git a/src/Chronos.App/Sections/SettingsViewModel.cs b/src/Chronos.App/Sections/SettingsViewModel.cs
index 2495541c..fb3c9cad 100644
--- a/src/Chronos.App/Sections/SettingsViewModel.cs
+++ b/src/Chronos.App/Sections/SettingsViewModel.cs
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
+using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
@@ -168,7 +169,7 @@ public sealed class SettingsViewModel : SectionViewModel
Logs = new LogSettingsRows(_s, Save);
// ---- Workspace ----
- WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => Shell.Services.Workspace.Root, OpenWorkspaceFolder);
+ WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => Shell.Services.Workspace.Root, OpenWorkspaceFolder, ChangeWorkspaceFolderAsync);
// ---- Storage ----
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
@@ -740,6 +741,13 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
+ /// Another workspace folder, after its plan (nothing is moved): Edit lists its projects from then on.
+ private async Task ChangeWorkspaceFolderAsync()
+ {
+ await WorkspaceFolderChange.ChooseAsync(Shell);
+ WorkspaceRows.Refresh();
+ }
+
// ---------------- Server ----------------
public EditableField DefaultServer { get; }
diff --git a/src/Chronos.App/Server/SyncText.cs b/src/Chronos.App/Server/SyncText.cs
index 757f5a5e..96df243c 100644
--- a/src/Chronos.App/Server/SyncText.cs
+++ b/src/Chronos.App/Server/SyncText.cs
@@ -174,29 +174,49 @@ public static class SyncText
///
/// As , each line with both values worded by
/// (setting, this side's value, the other side's) instead of "here, on the server": a
- /// workspace project against its library, a version against now.
+ /// workspace project against its library, a version against now. One setting differing on several photos (positions
+ /// parked by photo) is one line with their count: "Excluded frames (3)".
///
public static IReadOnlyList Differences(IEnumerable differences, int max, Func? worded)
{
ArgumentNullException.ThrowIfNull(differences);
worded ??= (label, mine, server) => Loc.L("Server.Conflict.Difference", label, mine, server);
- var lines = new List();
- var shown = new HashSet(StringComparer.Ordinal);
+ // One line per setting, in the order met; the photos each differs on counted.
+ var settings = new List<(string Key, string? Field, SettingsDifference First, HashSet Photos)>();
+ var index = new Dictionary(StringComparer.Ordinal);
foreach (var difference in differences)
{
var (key, field) = Setting(difference.Path);
- if (!shown.Add(key)) continue;
+ if (!index.TryGetValue(key, out var at))
+ {
+ index[key] = at = settings.Count;
+ settings.Add((key, field, difference, new HashSet(StringComparer.Ordinal)));
+ }
+ if (PhotoOf(difference.Path) is { } photo) settings[at].Photos.Add(photo);
+ }
+ var lines = new List();
+ foreach (var (key, field, difference, photos) in settings)
+ {
var label = Loc.L(key);
var metadata = difference.Path.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal);
- lines.Add((metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine
- && (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server
- ? worded(label, mine, server)
- : Loc.L("Server.Conflict.Changed", label));
+ lines.Add(photos.Count > 1 ? Loc.L("Server.Conflict.Count", label, Formatting.Count(photos.Count))
+ : (metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine
+ && (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server
+ ? worded(label, mine, server)
+ : Loc.L("Server.Conflict.Changed", label));
if (lines.Count == max) break;
}
return lines;
}
+ /// The photo a path of positions parked by photo names ("pendingFrames.<photo>.excluded"); null for any other path.
+ private static string? PhotoOf(string path)
+ {
+ if (!path.StartsWith(PendingPrefix, StringComparison.Ordinal)) return null;
+ var flag = path.LastIndexOf('.');
+ return flag > PendingPrefix.Length ? path[PendingPrefix.Length..flag] : null;
+ }
+
/// The row's buttons, in the order the mockup shows them.
public static IReadOnlyList Actions(SyncEntry entry, SyncRights rights)
{
diff --git a/src/Chronos.App/Settings/WorkspaceSettingsRows.cs b/src/Chronos.App/Settings/WorkspaceSettingsRows.cs
index 1d24a955..ae154743 100644
--- a/src/Chronos.App/Settings/WorkspaceSettingsRows.cs
+++ b/src/Chronos.App/Settings/WorkspaceSettingsRows.cs
@@ -5,14 +5,14 @@ using Chronos.Ui.Mvvm;
namespace Chronos.App.Settings;
///
-/// Settings › Workspace (owner review 2, R8): the workspace folder (shown with Open; moving it, with its plan and
-/// confirmation, comes with phase 5c), Sync automatically (a version saved is sent to its home at once, and the home's
+/// Settings › Workspace (owner review 2, R8): the workspace folder (shown with Open, and Change, which uses another
+/// folder after a plan without moving anything; moving it with its projects comes with phase 5c), Sync automatically (a version saved is sent to its home at once, and the home's
/// new versions taken; on by default) and Kept versions (the versions taken from the home a project keeps in the
/// workspace besides its base and those not sent; 20 by default). Each choice is stored and saved at once. A value set
/// elsewhere (an imported or hand-edited settings file) is listed with the presets; one below 1 is shown as 1, as the
/// workspace applies it.
///
-public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Func folder, Action open) : ObservableObject
+public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Func folder, Action open, Func? change = null) : ObservableObject
{
public static readonly int[] KeptPresets = [5, 10, 20, 50, 100, 200];
@@ -22,6 +22,11 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
/// Shows the folder in Explorer.
public RelayCommand OpenCommand { get; } = new(open);
+ /// Uses another folder, after its plan (WorkspaceFolderChange); none where the folder cannot change.
+ public AsyncRelayCommand ChangeCommand { get; } = new(change ?? (() => Task.CompletedTask), () => change is not null);
+
+ public bool CanChange => change is not null;
+
public bool AutoSync
{
get => settings.WorkspaceAutoSync;
@@ -50,7 +55,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
}
}
- /// The defaults of every row (Reset section); the caller saves. The folder stays (moving it is phase 5c).
+ /// The defaults of every row (Reset section); the caller saves. The folder stays (Change chooses it, after its plan).
public void Reset()
{
var defaults = new AppSettings();
diff --git a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
index f6a49add..660e586e 100644
--- a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
+++ b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
@@ -558,7 +558,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (background && _asking is { IsClosed: false }) return;
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
- _ui.CloseDialog);
+ _ui.CloseDialog, conflict.NewerFormat);
if (!background)
{
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
diff --git a/src/Chronos.App/Workspace/WorkspaceDialogs.cs b/src/Chronos.App/Workspace/WorkspaceDialogs.cs
index 67399eeb..ae1d1e70 100644
--- a/src/Chronos.App/Workspace/WorkspaceDialogs.cs
+++ b/src/Chronos.App/Workspace/WorkspaceDialogs.cs
@@ -49,11 +49,20 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private bool _isNew;
/// The names a new project cannot take (default: those of ).
+ /// What the copy of the media writes and the free space of the workspace's drive; null when not measured (shown as nothing).
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList projects, Action close,
- IReadOnlyList? taken = null)
+ IReadOnlyList? taken = null, WorkspaceCopyFacts? copy = null)
: base(close)
{
SequenceTitle = sequenceTitle;
+ Copy = copy;
+ CopyFacts = copy is null ? []
+ :
+ [
+ new DialogFact(Loc.L("Editor.OpenWorkspace.Size"), Formatting.Bytes(copy.Bytes), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.Size")),
+ new DialogFact(Loc.L("Editor.OpenWorkspace.Free"), copy.Free is { } free ? Formatting.Bytes(free) : Loc.L("Server.Sync.None"),
+ Reason: Loc.L(copy.TooLittleSpace ? "Errors.Workspace.NoRoom" : "Tooltips.Editor.OpenWorkspace.Free")),
+ ];
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p))];
_selected = Projects.FirstOrDefault();
_isNew = Projects.Count == 0;
@@ -68,6 +77,15 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public string SequenceTitle { get; }
+ /// The copy's bytes and the drive's free space, when measured.
+ public WorkspaceCopyFacts? Copy { get; }
+
+ /// "Copy size" and "Free space", under the media.
+ public IReadOnlyList CopyFacts { get; }
+
+ /// The drive lacks room for the copy: the free space says so (the copy would stop saying how much is missing).
+ public bool IsShortOfSpace => Copy?.TooLittleSpace == true;
+
public string Heading => Loc.L("Editor.OpenWorkspace.Title");
public IReadOnlyList Projects { get; }
@@ -381,25 +399,35 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
///
/// A sync that met settings both sides changed (owner review 2, R8: asked only on real conflicts): what differs, then
/// Keep mine, Take the library's, or Save both (this workspace's versions go to a sibling project). Later leaves the
-/// conflict for the next Sync; editing goes on meanwhile.
+/// conflict for the next Sync; editing goes on meanwhile. A conflict of format (the library's project saved by a newer
+/// Chronos, ) cannot be merged either way: only Save both and Later are offered.
///
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
{
private readonly Func _resolve;
+ /// The library holds a newer Chronos's settings: nothing is merged, Save both is the only choice.
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList differences, Func resolve,
- Action close)
+ Action close, bool newerFormat = false)
: base(close)
{
ProjectName = projectName;
SiblingName = siblingName;
- Differences = differences;
+ IsNewerFormat = newerFormat;
+ // The format's number says nothing to the user: the line names the cause.
+ Differences = newerFormat ? [Loc.L("Editor.Workspace.Conflict.NewerFormat")] : differences;
_resolve = resolve;
- KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy);
- TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy);
+ KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy && CanMerge);
+ TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy && CanMerge);
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
}
+ /// The library's project was saved by a newer Chronos.
+ public bool IsNewerFormat { get; }
+
+ /// Keep mine and Take the library's are offered (not for a conflict of format, which neither can settle).
+ public bool CanMerge => !IsNewerFormat;
+
public string ProjectName { get; }
/// The project Save both makes for this workspace's versions.
@@ -407,17 +435,19 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
public string Heading => Loc.L("Editor.Workspace.Conflict.Title");
- public string Message => Loc.L("Editor.Workspace.Conflict.Message", ProjectName);
+ public string Message => Loc.L(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", ProjectName);
public IReadOnlyList Differences { get; }
+ public string DifferencesToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences");
+
public ICommand KeepMineCommand { get; }
public ICommand TakeHomeCommand { get; }
public ICommand SaveBothCommand { get; }
- public string SaveBothToolTip => Loc.L("Tooltips.Editor.Workspace.SaveBoth", SiblingName);
+ public string SaveBothToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", SiblingName);
private async Task ResolveAsync(ConflictChoice choice)
{
@@ -442,7 +472,8 @@ 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 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.
+/// longer has (), or a copy whose working state cannot be read
+/// (), can only be discarded that way.
///
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
{
@@ -466,7 +497,7 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
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 && !plan.Gone);
- SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone);
+ SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone && !plan.Damaged);
DiscardCommand = new AsyncRelayCommand(DiscardAsync, () => !IsBusy && HasUnsent);
}
@@ -485,12 +516,14 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
public ICommand DiscardCommand { get; }
- public string RemoveToolTip => Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
+ public string RemoveToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
+ : 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.Gone ? Loc.L("Errors.Workspace.ProjectGone")
+ public string SendFirstToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
+ : 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");
diff --git a/src/Chronos.App/Workspace/WorkspaceDialogs.xaml b/src/Chronos.App/Workspace/WorkspaceDialogs.xaml
index 4622f29c..cefab681 100644
--- a/src/Chronos.App/Workspace/WorkspaceDialogs.xaml
+++ b/src/Chronos.App/Workspace/WorkspaceDialogs.xaml
@@ -51,6 +51,23 @@
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -188,13 +205,13 @@
-
+
-
+
@@ -206,11 +223,17 @@
-
+
+ MinWidth="96" Margin="0,0,8,8" Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
+ ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
+ Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
+
+
diff --git a/src/Chronos.App/Workspace/WorkspaceFolderChange.cs b/src/Chronos.App/Workspace/WorkspaceFolderChange.cs
new file mode 100644
index 00000000..36d94f64
--- /dev/null
+++ b/src/Chronos.App/Workspace/WorkspaceFolderChange.cs
@@ -0,0 +1,86 @@
+using System.IO;
+using Chronos.App.Editor;
+using Chronos.App.Infrastructure;
+using Chronos.App.Shell;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Localization;
+
+namespace Chronos.App.Workspace;
+
+///
+/// Choosing another workspace folder (owner review 2, R8): Settings › Workspace › Change, and the refusal of a folder
+/// inside a library, where Edit cannot be used until one is chosen. The folder is picked, its plan shown and confirmed
+/// (the projects the folder in use keeps, those the new one holds), a workspace project open in the editor closes (its
+/// last edit stored first), and only then does the setting change. Nothing is moved or deleted: the projects of the
+/// folder left stay there, listed again once it is chosen back. Moving a workspace with its projects comes in phase 5c.
+///
+public static class WorkspaceFolderChange
+{
+ /// The shell's flow: its folder picker and confirmation, its editor, its toasts.
+ public static async Task ChooseAsync(ShellViewModel shell)
+ {
+ ArgumentNullException.ThrowIfNull(shell);
+ var changed = await ChooseAsync(shell.Services.Workspace, shell.Services.Dialogs, async () =>
+ {
+ if (shell.Sequence.Editor?.Session.Source is not WorkspaceSequenceSource) return true;
+ if (!await shell.Sequence.ConfirmCloseAsync()) return false;
+ await shell.Sequence.CloseAsync();
+ shell.KeepSequence(null);
+ return true;
+ }, message => shell.Notify(Loc.L("Settings.Workspace.NotChanged"), message, isError: true));
+ if (changed) shell.Notify(Loc.L("Settings.Workspace.Changed"), shell.Services.Workspace.Root);
+ return changed;
+ }
+
+ ///
+ /// Picks a folder through , confirms its plan, lets close a
+ /// workspace project open in the editor (false keeps everything as it is), then makes it the workspace's folder.
+ /// hears why a folder was refused. True when the folder changed.
+ ///
+ public static async Task ChooseAsync(WorkspaceHost host, IAppDialogs dialogs, Func> closeProject, Action failed)
+ {
+ ArgumentNullException.ThrowIfNull(host);
+ ArgumentNullException.ThrowIfNull(dialogs);
+ ArgumentNullException.ThrowIfNull(closeProject);
+ ArgumentNullException.ThrowIfNull(failed);
+ if (dialogs.PickFolder(Loc.L("Settings.Workspace.ChooseTitle"), Directory.Exists(host.Root) ? host.Root : null) is not { } folder) return false;
+ try
+ {
+ var plan = await host.PlanFolderAsync(folder);
+ if (plan.IsSame) return false;
+ if (plan.InsideLibrary)
+ {
+ failed(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder));
+ return false;
+ }
+ if (!dialogs.Confirm(Request(plan))) return false;
+ if (!await closeProject()) return false;
+ await host.UseFolderAsync(plan.Folder);
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException or WorkspaceException)
+ {
+ Log.Warning("workspace", $"The workspace folder was not changed to {folder}", ex);
+ failed(ex is WorkspaceException ? ex.Message : Loc.L("Errors.Workspace.FolderUnusable", folder));
+ return false;
+ }
+ }
+
+ /// The plan as a confirmation: where Edit's projects come from now, and what stays where it is.
+ public static ConfirmRequest Request(WorkspaceFolderPlan plan)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ return new ConfirmRequest
+ {
+ Heading = Loc.L("Settings.Workspace.ChangeTitle"),
+ Message = Loc.L("Settings.Workspace.ChangeMessage", plan.Folder, plan.Current),
+ Detail = string.Join(Environment.NewLine, Loc.L("Settings.Workspace.ProjectsLeft", Formatting.Count(plan.ProjectsLeft)),
+ Loc.L("Settings.Workspace.ProjectsFound", Formatting.Count(plan.ProjectsFound))),
+ IsDetailMonospaced = false,
+ SafeText = Loc.L("Archive.Dialog.Cancel"),
+ SafeToolTip = Loc.L("Tooltips.Settings.KeepWorkspace"),
+ ActionText = Loc.L("Settings.Workspace.Use"),
+ ActionToolTip = Loc.L("Tooltips.Settings.UseWorkspace"),
+ };
+ }
+}
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs
index 45374e7c..4bd441e3 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.cs
@@ -15,13 +15,39 @@ using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// A workspace operation was refused for a reason the user can act on; the message is one localized sentence.
-public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner);
+public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner)
+{
+ /// The workspace folder itself was refused (it lies inside a library): another folder is the way on (Settings › Workspace › Change).
+ public bool FolderRefused { get; init; }
+}
/// A project of this PC's workspace, as Edit's picker and the editor list it.
/// The workspace holds the project's media (a copy that ended); without them it cannot open.
/// When its working state was last written.
+///
+/// Its working state (project.chronos) cannot be read: listed by its folder, it cannot open, and Remove local copy
+/// can only keep its files aside in the workspace's trash (Discard).
+///
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
- DateTimeOffset Saved);
+ DateTimeOffset Saved, bool Damaged = false);
+
+/// What changing the workspace folder to does: Edit lists its projects from then on; nothing is moved.
+/// The folder in use, whose projects stay where they are (listed again once it is chosen back).
+/// The projects the folder in use holds.
+/// The projects holds already (a workspace used before).
+/// The folder lies inside a library: refused, as the copy would put its files among the library's.
+public sealed record WorkspaceFolderPlan(string Current, string Folder, int ProjectsLeft, int ProjectsFound, bool InsideLibrary)
+{
+ /// The folder chosen is the one in use: nothing to change.
+ public bool IsSame => string.Equals(Path.TrimEndingDirectorySeparator(Current), Path.TrimEndingDirectorySeparator(Folder), StringComparison.OrdinalIgnoreCase);
+}
+
+/// What "Open in workspace" shows of the copy it queues: its bytes (as the copy reckons them) and the free bytes of the workspace's drive.
+public sealed record WorkspaceCopyFacts(long Bytes, long? Free)
+{
+ /// The drive lacks the copy and the reserve the copy keeps: it would stop saying so.
+ public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
+}
/// A project brought into the workspace and the copy of its media that was queued.
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
@@ -43,10 +69,12 @@ public sealed record WorkspaceHistory(IReadOnlyList Versions, IR
/// 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)
+/// The working state cannot be read: what it holds is not known, so the copy can only go with its files 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,
+ bool Damaged = false)
{
/// Everything the copy holds is at the home: it can go without discarding anything.
- public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
+ public bool IsSafe => Unsent == 0 && !Modified && !Conflict && !Damaged;
}
///
@@ -147,33 +175,87 @@ public sealed class WorkspaceHost
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). A workspace folder
- /// not made yet that lies inside a library is not made by listing it: it lists nothing.
+ /// The projects of the workspace; one whose working state cannot be read is listed as damaged (),
+ /// never hidden, and logged. A workspace folder not made yet that lies inside a library is not made by listing it: it lists nothing.
///
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))];
+ return (IReadOnlyList)[.. Store.List().Select(EntryOrDamaged)];
}, 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).
+ /// A workspace project by id (damaged when its working state cannot be read); null when the workspace has none.
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
+ return Store.Find(projectId) is { } project ? EntryOrDamaged(project) : null;
+ }, cancellationToken);
+
+ ///
+ /// What changing the workspace folder to would do (Settings › Workspace › Change, and the
+ /// refusal of a folder inside a library): the projects the folder in use keeps where they are, those the new one holds
+ /// already, and whether it lies inside a library. Nothing is written.
+ ///
+ public Task PlanFolderAsync(string folder, CancellationToken cancellationToken = default) => Task.Run(async () =>
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(folder);
+ var target = Path.GetFullPath(folder);
+ return new WorkspaceFolderPlan(Root, target, CountProjects(Root), CountProjects(target), await InsideALibraryAsync(target, cancellationToken).ConfigureAwait(false));
+ }, cancellationToken);
+
+ ///
+ /// Edit's workspace becomes (made, with its manifest, when it is new): Settings › Workspace ›
+ /// Folder names it from now on (none when it is the default). The projects of the folder left stay there, untouched.
+ ///
+ /// The folder lies inside a library ().
+ /// The folder cannot be made or read.
+ /// The folder holds another program's or a newer workspace manifest.
+ public async Task UseFolderAsync(string folder, CancellationToken cancellationToken = default)
+ {
+ var plan = await PlanFolderAsync(folder, cancellationToken).ConfigureAwait(false);
+ if (plan.IsSame) return;
+ if (plan.InsideLibrary) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder)) { FolderRefused = true };
+ // Opened before it is named: a folder that is no workspace is refused while the one in use still is.
+ await Task.Run(() => new WorkspaceStore(plan.Folder), cancellationToken).ConfigureAwait(false);
+ // Back on the caller's thread (the UI's): the settings are written there.
+ _settings.WorkspaceFolder = string.Equals(plan.Folder, Path.GetFullPath(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : plan.Folder;
+ _savePreferences();
+ Log.Info("workspace", $"The workspace folder is now {plan.Folder} ({plan.ProjectsLeft} project(s) stay in {plan.Current})");
+ }
+
+ /// The bytes the first copy of a sequence's media writes into the workspace, and the free bytes of the workspace's drive.
+ /// The index or the archive engine is not open.
+ public Task CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
+ {
+ var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
+ var archives = _archives() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
+ var root = Root;
+ return Task.Run(async () =>
{
- return Entry(project, project.ReadBundle());
- }
- catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
+ return new WorkspaceCopyFacts(bytes, free);
+ }, cancellationToken);
+ }
+
+ ///
+ /// A first copy of a project's media cancelled before it ended: the photos it wrote (copies the home can make again)
+ /// are removed, so the workspace holds no half media. A project whose copy ended once keeps its media (Update media
+ /// cancelled leaves the earlier ones in use). False when there was nothing to remove.
+ ///
+ public Task RemovePartialMediaAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
+ {
+ if (Store.Find(projectId) is not { } project) return false;
+ using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
- Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
- return null;
+ if (File.Exists(project.MediaIndexPath) || !Directory.Exists(project.MediaDirectory)) return false;
+ Directory.Delete(project.MediaDirectory, recursive: true);
}
+ Log.Info("workspace", $"The media a cancelled first copy of project {projectId} wrote were removed");
+ return true;
}, cancellationToken);
/// The project of opened last here, else the one saved last; null when the workspace has none.
@@ -214,7 +296,8 @@ public sealed class WorkspaceHost
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));
+ if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false))
+ throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root)) { FolderRefused = true };
SequenceProject project;
if (newName is not null)
{
@@ -505,6 +588,12 @@ public sealed class WorkspaceHost
public Task PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
+ if (EntryOrDamaged(project) is { Damaged: true } damaged)
+ {
+ // What it holds is not known: every version file not marked sent counts as unsent work, kept aside by Discard.
+ var (count, size) = Measure(project.Folder);
+ return new WorkspaceRemovalPlan(projectId, damaged.Name, count, size, project.Versions().Count(v => v.StoredAt is null), true, false, false, Damaged: true);
+ }
var name = project.ReadBundle().Workspace!.Name;
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
var (files, bytes) = Measure(project.Folder);
@@ -524,6 +613,14 @@ public sealed class WorkspaceHost
var sequenceId = await Task.Run(async () =>
{
var project = Existing(projectId);
+ if (EntryOrDamaged(project) is { Damaged: true })
+ {
+ // Its working state cannot be read: only Discard, which keeps every file of it aside, takes it out.
+ if (!discard) throw new WorkspaceException(Loc.L("Errors.Workspace.Damaged"));
+ await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
+ Log.Info("workspace", $"Damaged local copy of project {projectId} removed, its files kept in {TrashFolder}");
+ return (Guid?)null;
+ }
var workspace = project.ReadBundle().Workspace!;
if (!discard)
{
@@ -533,9 +630,9 @@ public sealed class WorkspaceHost
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Local copy of project {projectId} ('{workspace.Name}') removed{(discard ? ", its unsent work kept in " + TrashFolder : string.Empty)}");
- return workspace.Home.SequenceId;
+ return (Guid?)workspace.Home.SequenceId;
}, cancellationToken);
- Forget(sequenceId, projectId);
+ if (sequenceId is { } sequence) Forget(sequence, projectId);
}
///
@@ -657,10 +754,12 @@ public sealed class WorkspaceHost
/// 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)
+ private Task InsideALibraryAsync(CancellationToken cancellationToken) => InsideALibraryAsync(Root, cancellationToken);
+
+ private async Task InsideALibraryAsync(string folder, CancellationToken cancellationToken)
{
if (_db() is not { } db) return false;
- var root = Plain(Path.GetFullPath(Root));
+ var root = Plain(Path.GetFullPath(folder));
foreach (var archive in await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (DataLocation.IsUnder(root, Plain(Path.GetFullPath(archive.RootPath)))) return true;
@@ -710,6 +809,38 @@ public sealed class WorkspaceHost
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
}
+ /// The project's entry; a damaged one, named by its folder, when its working state cannot be read (logged).
+ private static WorkspaceEntry EntryOrDamaged(WorkspaceProject project)
+ {
+ try
+ {
+ return Entry(project, project.ReadBundle());
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
+ var saved = File.Exists(project.BundlePath) ? new DateTimeOffset(File.GetLastWriteTimeUtc(project.BundlePath), TimeSpan.Zero) : DateTimeOffset.MinValue;
+ return new WorkspaceEntry(project.ProjectId, Guid.Empty, Path.GetFileName(project.Folder), false, new BundleHome(BundleHome.ArchiveKind, Guid.Empty),
+ project.Folder, false, saved, Damaged: true);
+ }
+ }
+
+ /// The projects a workspace folder holds (folders named by a project id with a working state), without making or opening it.
+ private static int CountProjects(string folder)
+ {
+ if (!Directory.Exists(folder)) return 0;
+ try
+ {
+ return Directory.EnumerateDirectories(folder).Count(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
+ && File.Exists(Path.Combine(d, WorkspaceProject.BundleFile)));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Info("workspace", $"The projects of {folder} could not be counted: {ex.Message}");
+ return 0;
+ }
+ }
+
/// Files and bytes under , the lease left out.
private static (int Files, long Bytes) Measure(string folder)
{
diff --git a/src/Chronos.App/Workspace/WorkspaceProjectItem.cs b/src/Chronos.App/Workspace/WorkspaceProjectItem.cs
index f09e163c..b36d14cf 100644
--- a/src/Chronos.App/Workspace/WorkspaceProjectItem.cs
+++ b/src/Chronos.App/Workspace/WorkspaceProjectItem.cs
@@ -8,7 +8,8 @@ namespace Chronos.App.Workspace;
///
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
-/// where it stands, a chip read from its home after the list shows.
+/// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed
+/// as damaged, by its folder.
///
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
{
@@ -41,11 +42,16 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
}
}
- public string StateText => Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
+ /// Its working state cannot be read: it cannot open, and Remove local copy keeps its files aside.
+ public bool IsDamaged => Entry.Damaged;
- public StatusKind StateKind => Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
+ public string StateText => Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
+ : Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
- public string StateToolTip => Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
+ public StatusKind StateKind => Entry.Damaged ? StatusKind.Error : Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies;
+
+ public string StateToolTip => Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.Damaged")
+ : Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
/// "Vertical social · Harbour sunset · In sync": what screen readers hear for the row.
public string Description => string.Join(Loc.Separator, Name, SequenceTitle, StateText);
diff --git a/src/Chronos.App/Workspace/WorkspaceText.cs b/src/Chronos.App/Workspace/WorkspaceText.cs
index c2c9ccdc..caa653bd 100644
--- a/src/Chronos.App/Workspace/WorkspaceText.cs
+++ b/src/Chronos.App/Workspace/WorkspaceText.cs
@@ -71,9 +71,17 @@ public static class WorkspaceText
/// "28/10/2026 18:02".
public static string When(DateTimeOffset at) => $"{Formatting.Date(at)} {Formatting.TimeOfDay(at)}";
- /// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most .
- public static IReadOnlyList ConflictLines(IEnumerable differences, int max) =>
- SyncText.Differences(differences, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
+ ///
+ /// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most .
+ /// A conflict of format () reads as its cause, never as the format's numbers.
+ ///
+ public static IReadOnlyList ConflictLines(IEnumerable differences, int max)
+ {
+ ArgumentNullException.ThrowIfNull(differences);
+ var list = differences.ToList();
+ if (list.Any(d => d.Path == ProjectMerge.FormatPath)) return [Loc.L("Editor.Workspace.Conflict.NewerFormat")];
+ return SyncText.Differences(list, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
+ }
/// One line per setting that differs between now and a version ("Deflicker window 41 now, 33 in that version").
public static IReadOnlyList CompareLines(IEnumerable differences, int max) =>
@@ -83,6 +91,9 @@ public static class WorkspaceText
public static string Failure(Exception ex) => ex switch
{
WorkspaceException or LeaseUnavailableException => ex.Message,
+ // A library that can be read but not written (a read-only share, a write-protected disk): the work waits here as offline.
+ HomeUnavailableException { InnerException: ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } }
+ or ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } => Loc.L("Errors.Workspace.ReadOnlyHome"),
HomeUnavailableException or ArchiveOfflineException => Loc.L("Errors.Workspace.Offline"),
ProjectException { Reason: ProjectError.NameTaken } => Loc.L("Errors.Workspace.NameTaken"),
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
diff --git a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs
index 945be6b3..28866431 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs
@@ -35,6 +35,20 @@ public static class WorkspaceJobs
/// parameters name).
///
public static IReadOnlyList CreateHandlers(ChronosDatabase db, ArchiveService archives) => [new WorkspaceCopyJobHandler(db, archives)];
+
+ ///
+ /// What a first copy of a sequence's proxies writes into a workspace, as the copy reckons it before it starts (the
+ /// archive's proxies' sizes, an estimate for those it makes), and the free bytes on 's
+ /// drive (null when it cannot be measured): "Open in workspace" shows both. The copy keeps
+ /// free besides.
+ ///
+ /// The index has no such sequence or archive.
+ public static Task<(long Bytes, long? Free)> CopyFactsAsync(ChronosDatabase db, ArchiveService archives, Guid sequenceId, string workspaceRoot,
+ CancellationToken cancellationToken = default) =>
+ new WorkspaceCopyJobHandler(db, archives).FactsAsync(sequenceId, workspaceRoot, cancellationToken);
+
+ /// Bytes the copy leaves free on the workspace's drive besides what it copies.
+ public static long CopySpaceReserve => WorkspaceCopyJobHandler.SpaceReserve;
}
///
@@ -62,7 +76,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
/// Bytes left free on the workspace's drive besides the copy, as a download keeps ().
- private const long SpaceReserve = 512L << 20;
+ internal const long SpaceReserve = 512L << 20;
/// A proxy at px, when the archive has none to measure: some 1.5 MB.
private const long ProxyEstimate = 3L << 19;
@@ -348,11 +362,13 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// nothing for a frame the workspace holds a file of already (kept, or replaced by one of about its size), the archive's
/// proxy's size where it has one, else an estimate at the proxy size the copy makes ().
///
- private static long[] Remaining(WorkspaceProject project, SequencePaths folder, List frames, ProxyPolicy policy)
- {
- var held = Directory.Exists(project.ProxiesDirectory)
+ private static long[] Remaining(WorkspaceProject project, SequencePaths folder, List frames, ProxyPolicy policy) =>
+ Remaining(Directory.Exists(project.ProxiesDirectory)
? Directory.EnumerateFiles(project.ProxiesDirectory).Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase)
- : [];
+ : [], folder, frames, policy);
+
+ private static long[] Remaining(HashSet held, SequencePaths folder, List frames, ProxyPolicy policy)
+ {
var proxies = Directory.Exists(folder.Proxies)
? new DirectoryInfo(folder.Proxies).EnumerateFiles().ToDictionary(f => f.Name, f => f.Length, StringComparer.OrdinalIgnoreCase)
: [];
@@ -369,6 +385,17 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
return remaining;
}
+ /// What a first copy of the sequence writes (nothing held yet), and the free bytes of the workspace's drive.
+ internal async Task<(long Bytes, long? Free)> FactsAsync(Guid sequenceId, string workspaceRoot, CancellationToken cancellationToken)
+ {
+ var (row, frames) = await FramesAsync(sequenceId, cancellationToken).ConfigureAwait(false);
+ var archive = await db.Archives.GetAsync(row.ArchiveId, cancellationToken).ConfigureAwait(false)
+ ?? throw new InvalidOperationException(Loc.L("Archive.Log.SequenceMissing", sequenceId));
+ var paths = new ArchivePaths(archive.RootPath);
+ var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
+ return (Remaining([], paths.Sequence(row.Folder), frames, policy)[0], FreeBytes(workspaceRoot));
+ }
+
/// A proxy's size when the archive has none to measure: some 1.5 MB at 1920 px, scaled by the area at the copy's long edge.
private static long Estimate(Frame frame, ProxyPolicy policy)
{
diff --git a/src/Chronos.Data/Workspaces/WorkspaceStore.cs b/src/Chronos.Data/Workspaces/WorkspaceStore.cs
index 40843c6c..d75083b5 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceStore.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceStore.cs
@@ -392,6 +392,16 @@ public sealed class WorkspaceProject
}
}
+ ///
+ /// Writes a version straight into versions/.replaced: kept, never part of the chain of versions to send (the
+ /// working state a take of the server's values replaced).
+ ///
+ internal void WriteAside(ProjectVersion version)
+ {
+ ArgumentNullException.ThrowIfNull(version);
+ ProjectSidecars.WriteVersion(Path.Combine(VersionsDirectory, ReplacedFolder, Path.GetFileName(VersionPath(version))), version);
+ }
+
/// Moves tried, some 1 s in all, before a version file held open fails to move aside.
private const int SetAsideAttempts = 15;
diff --git a/src/Chronos.Data/Workspaces/WorkspaceSync.cs b/src/Chronos.Data/Workspaces/WorkspaceSync.cs
index 8a76265d..d3c3970c 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceSync.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceSync.cs
@@ -102,8 +102,9 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
/// (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.
+/// lease; nothing is ever deleted: a restore or a save-both first saves uncommitted changes as a version, and taking the
+/// server's values keeps the working state they replace aside (versions/.replaced). A conflict lists this side's
+/// values as the working state holds them, so it is asked and settled against what the user sees.
/// 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
@@ -310,8 +311,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// ), 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).
+ /// is settled, and the conflict found now is recorded and returned to be asked again. Taking the server's keeps the
+ /// working state it replaces as a version file in versions/.replaced, outside the chain: nothing is committed,
+ /// replayed or sent for it, so a take that leaves only the server's values sends nothing.
/// 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.
@@ -330,8 +332,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
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);
- // A conflict of format refuses the choice (nothing is merged with a newer Chronos's settings): nothing is saved first.
- if (choice == ConflictChoice.TakeServer && !bundle.IsReadOnly && !recorded.NewerFormat) CommitLocked(project, bundle, null, null);
+ // Nothing is committed first: a version of the working state would be replayed into one that only repeats the
+ // head, and sent. What the take replaces of the working state is kept aside by the replay instead.
IReadOnlySet takeTheirs = choice == ConflictChoice.TakeServer ? AllPaths : takeServer ?? new HashSet();
ProjectSettings? kept = null;
var (_, conflict, pulled) = await ReplayAsync(project, bundle, home, takeTheirs, cancellationToken, shown ?? recorded, k => kept = k).ConfigureAwait(false);
@@ -463,7 +465,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, choice);
var keptMine = takeTheirs is EveryPath ? ProjectMerge.MergeWithConflicts(tip, working, keptTip).Merged : merge.Merged;
if (takeTheirs is EveryPath) merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, Paths(merge.Conflicts));
- var differences = replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path).ToList();
+ var differences = AsInTheWorkingState(replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path),
+ ProjectMerge.Conflicts(basisSettings, working, headSettings));
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);
@@ -503,6 +506,10 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
}
var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(merge.Merged.ToJson()), photos), allowNewer: true);
var moved = WithBase(bundle, head) with { Project = placed, Saved = DateTimeOffset.UtcNow };
+ // Taking the server's values over changes no version holds yet: the working state is kept aside first, never in the chain.
+ if (takeTheirs is EveryPath && differences.Count > 0 && Portable(bundle.Project, media) is { } unsaved
+ && (tipVersion is null || !ProjectContent.SameChoices(tipVersion.SettingsJson, unsaved, photos)))
+ project.WriteAside(VersionOf(project, unsaved, tipVersion, ProjectVersionKind.Commit, null, null, null, media?.FramesVersion ?? bundle.Workspace!.Media.FramesVersion));
var journal = new WorkspaceReplay(head.Id, [.. locals.Select(v => v.Id)], [.. rebased.Select(v => v.Id)], [.. held.Select(v => v.Id)]);
project.WriteSync(project.ReadSync() with { Replay = journal });
Step("replay.journal");
@@ -710,7 +717,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, [head], copy);
}
- /// A new project at the home named , else " (2)", "(3)"… whichever is free.
+ /// A new project at the home named , else " (2)", "(3)"… whichever is free.
private static async Task CreateNamedAsync(IProjectHome home, string? name, string source, Guid? from, CancellationToken cancellationToken)
{
if (!string.IsNullOrWhiteSpace(name)) return await home.CreateAsync(name, from, null, cancellationToken).ConfigureAwait(false);
@@ -745,28 +752,37 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
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 = restoredFrom is null ? ProjectVersionKind.Commit : ProjectVersionKind.Restore,
- Author = author,
- ClientName = clientName,
- Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim(),
- SettingsJson = portable,
- ContentHash = hash,
- SettingsFormat = ProjectContent.FormatOf(portable),
- FramesVersion = media?.FramesVersion ?? workspace.Media.FramesVersion,
- RestoredFrom = restoredFrom,
- CreatedAt = DateTimeOffset.UtcNow,
- };
+ var version = VersionOf(project, portable, (tipId, tipNumber), restoredFrom is null ? ProjectVersionKind.Commit : ProjectVersionKind.Restore, note, author,
+ restoredFrom, media?.FramesVersion ?? workspace.Media.FramesVersion);
project.WriteVersion(version);
if (sync.RestoredFrom is not null) project.WriteSync(sync with { RestoredFrom = null });
return version;
}
+ /// A version of this workspace holding , the child of (null: the first).
+ private ProjectVersion VersionOf(WorkspaceProject project, string portable, ProjectVersion? parent, ProjectVersionKind kind, string? note, string? author,
+ Guid? restoredFrom, int framesVersion) =>
+ VersionOf(project, portable, (parent?.Id, parent?.Number ?? 0), kind, note, author, restoredFrom, framesVersion);
+
+ private ProjectVersion VersionOf(WorkspaceProject project, string portable, (Guid? Id, int Number) parent, ProjectVersionKind kind, string? note, string? author,
+ Guid? restoredFrom, int framesVersion) => new()
+ {
+ Id = Guid.CreateVersion7(),
+ ProjectId = project.ProjectId,
+ ParentId = parent.Id,
+ Number = parent.Number + 1,
+ Kind = kind,
+ Author = author,
+ ClientName = clientName,
+ Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim(),
+ SettingsJson = portable,
+ ContentHash = ProjectContent.Hash(portable),
+ SettingsFormat = ProjectContent.FormatOf(portable),
+ FramesVersion = framesVersion,
+ RestoredFrom = restoredFrom,
+ CreatedAt = DateTimeOffset.UtcNow,
+ };
+
private async Task StatusLockedAsync(WorkspaceProject project, IProjectHome? home, CancellationToken cancellationToken)
{
var bundle = project.ReadBundle();
@@ -843,6 +859,17 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
return merge.Conflicts.Count == 0 && ProjectContent.Canonical(merge.Merged.ToJson()) == ProjectContent.Canonical(now);
}
+ ///
+ /// The conflicts found as the user sees them: where the working state holds a value of its own against the home's
+ /// (: edited since the last local version), that value is this side's, not the version's.
+ /// Keeping mine keeps it, and taking the server's replaces it, so one answer settles what was listed.
+ ///
+ private static List AsInTheWorkingState(IEnumerable found, IReadOnlyList working)
+ {
+ var now = working.DistinctBy(d => d.Path).ToDictionary(d => d.Path, StringComparer.Ordinal);
+ return [.. found.Select(d => now.TryGetValue(d.Path, out var held) ? held : d)];
+ }
+
/// 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);
diff --git a/tests/Chronos.App.Tests/Server/SyncTextTests.cs b/tests/Chronos.App.Tests/Server/SyncTextTests.cs
index f98a5c2d..352bbd28 100644
--- a/tests/Chronos.App.Tests/Server/SyncTextTests.cs
+++ b/tests/Chronos.App.Tests/Server/SyncTextTests.cs
@@ -153,6 +153,27 @@ public sealed class SyncTextTests
Assert.Equal(0, rows.Count(r => SyncText.Matches(r, SyncFilter.Conflicts, "comet")));
}
+ [Test]
+ public void ASettingDifferingOnSeveralPhotosIsOneLineWithTheirCount()
+ {
+ var keyframes = new SettingsDifference("pendingFrames.sha:ab12#0.keyframes", "[]", "[{\"x\":1}]");
+ var lines = SyncText.Differences(
+ [
+ new SettingsDifference("pendingFrames.sha:ab12#0.excluded", "true", "false"),
+ keyframes,
+ new SettingsDifference("pendingFrames.sha:cd34#0.excluded", "true", "false"),
+ new SettingsDifference("pendingFrames.sha:ef56#1.excluded", "false", "true"),
+ new SettingsDifference("pendingFrames.sha:ab12#0.excluded", "true", "false"),
+ ], 10);
+ // Counted by photo, in the order the settings were met; a setting on one photo keeps its values.
+ Assert.SequenceEqual(
+ [Loc.L("Server.Conflict.Count", Loc.L("Server.Setting.ExcludedFrames"), Chronos.App.Infrastructure.Formatting.Count(3)), SyncText.Differences([keyframes], 1)[0]],
+ lines);
+ Assert.Contains(Loc.L("Server.Setting.Keyframes"), lines[1]);
+ Assert.Count(1, SyncText.Differences([new SettingsDifference("pendingFrames.sha:ab12#0.excluded", "true", "false")], 10));
+ Assert.Contains(Loc.L("Server.Setting.ExcludedFrames"), SyncText.Differences([new SettingsDifference("pendingFrames.sha:ab12#0.excluded", "true", "false")], 10)[0]);
+ }
+
[Test]
public void ATransferCountsWhereItsOriginalsAre()
{
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
new file mode 100644
index 00000000..5f6be60f
--- /dev/null
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
@@ -0,0 +1,319 @@
+using System.Globalization;
+using System.IO;
+using Chronos.App.Archiving;
+using Chronos.App.Infrastructure;
+using Chronos.App.Settings;
+using Chronos.App.Workspace;
+using Chronos.Core.Archiving;
+using Chronos.Core.Localization;
+using Chronos.Data.Projects;
+using Chronos.Data.Sync;
+using Chronos.Data.Workspaces;
+using Chronos.Testing;
+using Chronos.Ui.Controls;
+
+namespace Chronos.App.Tests.Workspace;
+
+///
+/// The ways on that review 2's phase 5a fix round 2 gave the workspace (owner review 2, R8): another workspace folder when
+/// the one in use is refused, a copy whose working state cannot be read listed as damaged and removed only after a plan,
+/// the half media of a cancelled first copy, the copy's size and the drive's free space before it starts, a conflict of
+/// format that offers only Save both, a read-only library named as such, and pruning that keeps a version the library
+/// cannot give back.
+///
+[Category("workspace")]
+public sealed class WorkspaceFallbackTests(TestContext context)
+{
+ static WorkspaceFallbackTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
+
+ [Test]
+ public async Task AnotherWorkspaceFolderIsUsedAfterItsPlanAndNothingIsMoved()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var settings = new AppSettings();
+ var saves = 0;
+ var host = new WorkspaceHost(bed.Environment, settings, () => saves++, () => bed.Db, () => bed.Archives, () => bed.Engine)
+ {
+ LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)),
+ };
+ var mainId = await bed.CheckoutAsync(host);
+ var first = host.Root;
+ var before = saves;
+ var row = await bed.RowAsync();
+ var library = (await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath;
+
+ // A folder inside a library is refused, and nothing changes.
+ var inside = Path.Combine(library, "workspace");
+ Assert.True((await host.PlanFolderAsync(inside)).InsideLibrary);
+ var refused = await Assert.ThrowsAsync(() => host.UseFolderAsync(inside));
+ Assert.True(refused.FolderRefused);
+ Assert.Equal(Loc.L("Errors.Workspace.InsideLibraryFolder", Path.GetFullPath(inside)), refused.Message);
+ Assert.Equal(((string?)null, before, first), (settings.WorkspaceFolder, saves, host.Root));
+ Assert.False(Directory.Exists(inside), "nothing was written there");
+
+ // The plan counts what stays and what is found; using the folder names it in the settings and lists its projects.
+ var other = Path.Combine(bed.Directory, "other workspace");
+ var plan = await host.PlanFolderAsync(other);
+ Assert.Equal(new WorkspaceFolderPlan(first, Path.GetFullPath(other), 1, 0, false), plan);
+ Assert.False(plan.IsSame);
+ Assert.True((await host.PlanFolderAsync(first + Path.DirectorySeparatorChar)).IsSame);
+ await host.UseFolderAsync(other);
+ Assert.Equal((Path.GetFullPath(other), before + 1), (settings.WorkspaceFolder, saves));
+ Assert.Equal(Path.GetFullPath(other), host.Root);
+ Assert.Empty(await host.ListAsync());
+ Assert.FileExists(Path.Combine(first, mainId.ToString("N"), WorkspaceProject.BundleFile));
+
+ // Chosen back, the default is named by no setting and its project is listed again.
+ Assert.Equal(new WorkspaceFolderPlan(Path.GetFullPath(other), first, 0, 1, false), await host.PlanFolderAsync(first));
+ await host.UseFolderAsync(first);
+ Assert.Equal(((string?)null, before + 2), (settings.WorkspaceFolder, saves));
+ Assert.Equal(mainId, (await host.ListAsync()).Single().ProjectId);
+ }
+
+ [Test]
+ public async Task ChoosingAFolderAsksItsPlanAndClosesTheProjectFirst()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var settings = new AppSettings();
+ var host = bed.Host(settings);
+ await bed.CheckoutAsync(host);
+ var first = host.Root;
+ var library = (await bed.Db.Archives.GetAsync((await bed.RowAsync()).ArchiveId))!.RootPath;
+ var failures = new List();
+ var closes = 0;
+ var close = true;
+ Task CloseProject()
+ {
+ closes++;
+ return Task.FromResult(close);
+ }
+
+ // Nothing picked, or the folder in use: nothing asked.
+ var dialogs = new ScriptedDialogs { Folder = null };
+ Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
+ dialogs.Folder = first;
+ Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
+ Assert.Empty(dialogs.Asked);
+
+ // Inside a library: refused with why, without asking.
+ dialogs.Folder = Path.Combine(library, "inside");
+ Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
+ Assert.SequenceEqual([Loc.L("Errors.Workspace.InsideLibraryFolder", Path.GetFullPath(dialogs.Folder!))], failures);
+ Assert.Empty(dialogs.Asked);
+
+ // Declined, or the open project kept open: the folder stays.
+ var other = Path.Combine(bed.Directory, "elsewhere");
+ dialogs.Folder = other;
+ dialogs.Answer = false;
+ Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
+ Assert.Count(1, dialogs.Asked);
+ var asked = dialogs.Asked[0];
+ Assert.Equal(Loc.L("Settings.Workspace.ChangeMessage", Path.GetFullPath(other), first), asked.Message);
+ Assert.Contains(Loc.L("Settings.Workspace.ProjectsLeft", Formatting.Count(1)), asked.Detail);
+ Assert.Contains(Loc.L("Settings.Workspace.ProjectsFound", Formatting.Count(0)), asked.Detail);
+ Assert.True(asked is { IsDestructive: false, ActionText.Length: > 0, ActionToolTip.Length: > 0, SafeToolTip.Length: > 0 });
+ Assert.Equal(0, closes, "nothing closed before the plan is confirmed");
+ dialogs.Answer = true;
+ close = false;
+ Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
+ Assert.Equal((1, first), (closes, host.Root));
+
+ close = true;
+ Assert.True(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
+ Assert.Equal((Path.GetFullPath(other), 2), (host.Root, closes));
+ Assert.Count(1, failures);
+ }
+
+ [Test]
+ public void SettingsWorkspaceChangesTheFolderOnlyWhereItCan()
+ {
+ var settings = new AppSettings();
+ var changes = 0;
+ var rows = new WorkspaceSettingsRows(settings, () => { }, () => @"D:\Workspace", () => { }, () =>
+ {
+ changes++;
+ return Task.CompletedTask;
+ });
+ Assert.True(rows.CanChange && rows.ChangeCommand.CanExecute(null));
+ rows.ChangeCommand.Execute(null);
+ Assert.Equal(1, changes);
+ var capture = new WorkspaceSettingsRows(settings, () => { }, () => @"D:\Workspace", () => { });
+ Assert.False(capture.CanChange || capture.ChangeCommand.CanExecute(null));
+ }
+
+ [Test]
+ public async Task ACopyWhoseWorkingStateCannotBeReadIsListedAsDamagedAndGoesOnlyByDiscard()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
+ var mainId = await bed.CheckoutAsync(host);
+ var (_, session) = await bed.OpenAsync(host, mainId);
+ await using (session)
+ {
+ session.Edit(p => p with { HeroFrame = 2 });
+ Assert.True(await session.FlushAsync());
+ }
+ var unsent = (await host.SaveVersionAsync(mainId, "Not sent")).Version!;
+ var project = host.Store.Find(mainId)!;
+ await File.WriteAllTextAsync(project.BundlePath, "{ this is not a project", bed.Ct);
+
+ var all = await host.ListAsync();
+ Assert.Count(1, all);
+ var listed = all[0];
+ Assert.True(listed is { Damaged: true, HasMedia: false });
+ Assert.Equal(mainId, listed.ProjectId);
+ Assert.True((await host.FindAsync(mainId))!.Damaged);
+ Assert.Empty(await host.ProjectsOfAsync(bed.SequenceId), "a copy that cannot say its sequence is not one of it");
+ var item = new WorkspaceProjectItem(listed, null);
+ Assert.Equal((Loc.L("Editor.Workspace.State.Damaged"), StatusKind.Error, Loc.L("Tooltips.Editor.Workspace.State.Damaged")),
+ (item.StateText, item.StateKind, item.StateToolTip));
+
+ var plan = await host.PlanRemovalAsync(mainId);
+ Assert.True(plan is { Damaged: true, IsSafe: false, Unsent: 1 });
+ Assert.Greater(plan.Files, 0);
+ var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => false, _ => { });
+ Assert.False(dialog.RemoveCommand.CanExecute(null) || dialog.SendFirstCommand.CanExecute(null));
+ Assert.True(dialog.DiscardCommand.CanExecute(null));
+ Assert.Equal((Loc.L("Errors.Workspace.Damaged"), Loc.L("Errors.Workspace.Damaged")), (dialog.RemoveToolTip, dialog.SendFirstToolTip));
+
+ var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
+ Assert.Equal(Loc.L("Errors.Workspace.Damaged"), refused.Message);
+ Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
+
+ await host.RemoveLocalCopyAsync(mainId, discard: true);
+ Assert.Null(host.Store.Find(mainId));
+ var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
+ d => Path.GetFileName(d).StartsWith(mainId.ToString("N"), StringComparison.Ordinal));
+ Assert.Equal("{ this is not a project", await File.ReadAllTextAsync(Path.Combine(aside, WorkspaceProject.BundleFile), bed.Ct), "kept as it was");
+ Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase)
+ || f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept");
+ }
+
+ [Test]
+ public async Task ACancelledFirstCopyLeavesNoHalfMedia()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var host = bed.Host();
+ var mainId = await bed.CheckoutAsync(host);
+ var project = host.Store.Find(mainId)!;
+ Assert.False(await host.RemovePartialMediaAsync(mainId), "a copy that ended keeps its media");
+ Assert.FileExists(project.MediaIndexPath);
+
+ // A first copy stopped before its index was written: what it wrote goes, the working state stays.
+ File.Delete(project.MediaIndexPath);
+ Assert.NotEmpty(Directory.EnumerateFiles(project.MediaDirectory, "*", SearchOption.AllDirectories));
+ Assert.True(await host.RemovePartialMediaAsync(mainId));
+ Assert.False(Directory.Exists(project.MediaDirectory));
+ Assert.FileExists(project.BundlePath);
+ Assert.False(await host.RemovePartialMediaAsync(mainId), "nothing left to remove");
+ Assert.False(await host.RemovePartialMediaAsync(Guid.NewGuid()));
+ }
+
+ [Test]
+ public async Task OpenInWorkspaceShowsTheCopysSizeAndTheFreeSpace()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var host = bed.Host();
+ var facts = await host.CopyFactsAsync(bed.SequenceId);
+ Assert.Greater(facts.Bytes, 0);
+ Assert.NotNull(facts.Free);
+ Assert.False(facts.TooLittleSpace, "the test drive has room for four small proxies");
+
+ var dialog = new OpenInWorkspaceDialogViewModel("Synthetic", await host.HomeProjectsAsync(bed.SequenceId), _ => { }, copy: facts);
+ Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], dialog.CopyFacts.Select(f => f.Label));
+ Assert.Equal(Formatting.Bytes(facts.Bytes), dialog.CopyFacts[0].Value);
+ Assert.False(dialog.IsShortOfSpace);
+
+ var short_ = new OpenInWorkspaceDialogViewModel("Synthetic", [], _ => { }, copy: new WorkspaceCopyFacts(1_000_000, 1_000_000));
+ Assert.True(short_.IsShortOfSpace);
+ Assert.Equal(Loc.L("Errors.Workspace.NoRoom"), short_.CopyFacts[1].Reason);
+ var unknown = new OpenInWorkspaceDialogViewModel("Synthetic", [], _ => { }, copy: new WorkspaceCopyFacts(1_000_000, null));
+ Assert.Equal((false, Loc.L("Server.Sync.None")), (unknown.IsShortOfSpace, unknown.CopyFacts[1].Value));
+ Assert.Empty(new OpenInWorkspaceDialogViewModel("Synthetic", [], _ => { }).CopyFacts);
+ Assert.False(new WorkspaceCopyFacts(1_000, 1_000 + WorkspaceJobs.CopySpaceReserve).TooLittleSpace);
+ Assert.True(new WorkspaceCopyFacts(1_000, 999 + WorkspaceJobs.CopySpaceReserve).TooLittleSpace);
+ }
+
+ [Test]
+ public void AConflictOfFormatOffersOnlySaveBothAndSaysWhy()
+ {
+ var newer = new ConflictDialogViewModel("Main", "Main (STUDIO-PC)", ["Version 1 here, 2 in the library"], _ => Task.CompletedTask, _ => { },
+ newerFormat: true);
+ Assert.False(newer.CanMerge || newer.KeepMineCommand.CanExecute(null) || newer.TakeHomeCommand.CanExecute(null));
+ Assert.True(newer.SaveBothCommand.CanExecute(null));
+ Assert.SequenceEqual([Loc.L("Editor.Workspace.Conflict.NewerFormat")], newer.Differences);
+ Assert.Equal(Loc.L("Editor.Workspace.Conflict.NewerMessage", "Main"), newer.Message);
+ Assert.Equal(Loc.L("Tooltips.Editor.Workspace.NewerFormat"), newer.DifferencesToolTip);
+ Assert.Equal(Loc.L("Tooltips.Editor.Workspace.SaveBothNewer", "Main (STUDIO-PC)"), newer.SaveBothToolTip);
+
+ var merge = new ConflictDialogViewModel("Main", "Main (STUDIO-PC)", ["Hero frame 2 here, 3 in the library"], _ => Task.CompletedTask, _ => { });
+ Assert.True(merge.CanMerge && merge.KeepMineCommand.CanExecute(null) && merge.TakeHomeCommand.CanExecute(null));
+ Assert.Equal(Loc.L("Tooltips.Editor.Workspace.SaveBoth", "Main (STUDIO-PC)"), merge.SaveBothToolTip);
+
+ // The format's numbers never reach the lines: one line names the cause.
+ var lines = WorkspaceText.ConflictLines([new SettingsDifference(ProjectMerge.FormatPath, "1", "2"), new SettingsDifference("hero", "2", "3")], 10);
+ Assert.SequenceEqual([Loc.L("Editor.Workspace.Conflict.NewerFormat")], lines);
+ }
+
+ [Test]
+ public void AReadOnlyLibraryIsNamedAsSuchNotAsOffline()
+ {
+ var readOnly = new ArchiveOfflineException(@"E:\Library", ArchiveAvailability.ReadOnly);
+ Assert.Equal(Loc.L("Errors.Workspace.ReadOnlyHome"), WorkspaceText.Failure(new HomeUnavailableException(readOnly.Message, readOnly)));
+ Assert.Equal(Loc.L("Errors.Workspace.ReadOnlyHome"), WorkspaceText.Failure(readOnly));
+ var offline = new ArchiveOfflineException(@"E:\Library", ArchiveAvailability.Offline);
+ Assert.Equal(Loc.L("Errors.Workspace.Offline"), WorkspaceText.Failure(new HomeUnavailableException(offline.Message, offline)));
+ Assert.Equal(Loc.L("Errors.Workspace.Offline"), WorkspaceText.Failure(new HomeUnavailableException("The project's home cannot be reached from this PC.")));
+ }
+
+ [Test]
+ public async Task PruningKeepsAVersionTheLibraryCannotGiveBack()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var settings = new AppSettings { WorkspaceKeptVersions = 100 };
+ var host = bed.Host(settings);
+ var mainId = await bed.CheckoutAsync(host);
+ var (_, session) = await bed.OpenAsync(host, mainId);
+ await using (session)
+ {
+ for (var i = 1; i <= 5; i++)
+ {
+ session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = i / 10.0 } });
+ Assert.True(await session.FlushAsync());
+ await host.SaveVersionAsync(mainId, $"Step {i}");
+ }
+ }
+ var project = host.Store.Find(mainId)!;
+ Assert.SequenceEqual([1, 2, 3, 4, 5, 6], project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order());
+
+ // The library's file of version 2 is damaged: the workspace's copy is the only good one left, so it stays.
+ var second = project.Versions().Single(v => v.Number == 2);
+ var row = await bed.RowAsync();
+ var library = (await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath;
+ var damaged = new ArchivePaths(library).Sequence(row.Folder).VersionPath(mainId, 2, second.Id);
+ Assert.FileExists(damaged);
+ await File.WriteAllTextAsync(damaged, "{ damaged", bed.Ct);
+
+ settings.WorkspaceKeptVersions = 2;
+ Assert.Equal(3, await host.PruneAsync(mainId, host.HomeOfSequence(bed.SequenceId)));
+ Assert.SequenceEqual([2, 5, 6], project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order());
+ }
+
+ /// Dialogs that pick and answer every confirmation with , recording what they were asked.
+ private sealed class ScriptedDialogs : IAppDialogs
+ {
+ public string? Folder { get; set; }
+ public bool Answer { get; set; }
+ public List Asked { get; } = [];
+ public string? PickFolder(string title, string? initialFolder = null) => Folder;
+ public string? PickJsonFile(string title) => null;
+
+ public bool Confirm(ConfirmRequest request)
+ {
+ Asked.Add(request);
+ return Answer;
+ }
+
+ public bool SignIn(string server, string? username, Func> signIn) => false;
+ }
+}
diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs
index b9da2d64..51b18b07 100644
--- a/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs
+++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs
@@ -78,6 +78,80 @@ public abstract class WorkspaceConflictTests(TestContext context) : DatabaseTest
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 TakingTheLibrarysValuesOverUnsavedChangesSendsNoVersion()
+ {
+ var (fx, _, two, id, shown) = await AskedAsync(await FixtureAsync());
+ // Unsaved too: a setting only this side changed.
+ await EditAsync(two, id, s => s with { Motion = s.Motion with { TargetShutterAngle = s.Motion.TargetShutterAngle.WithManual(90) } }, fx.Ct);
+ var history = await fx.Home.HistoryAsync(id, null, 10, fx.Ct);
+
+ var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.TakeServer, shown: shown, cancellationToken: fx.Ct);
+ Assert.Null(settled.Status.Conflict);
+ Assert.Empty(two.Unpushed(id), "no version of the working state is made, so none repeating the head is sent");
+ Assert.Equal(WorkspaceState.Modified, settled.Status.State, "the change only this side made waits, unsaved as it was");
+ var working = (await two.OpenAsync(id, fx.Ct)).Working;
+ Assert.Equal((0.5, StackSetting.Median, 90.0), (working.Exposure.ExposureOffsetEv, working.Stack.Mode, working.Motion.TargetShutterAngle.Resolve(0)));
+ Assert.Equal(1.0, Assert.NotNull(settled.Kept).Exposure.ExposureOffsetEv);
+ Assert.Empty((await two.PushAsync(id, fx.Home, fx.Ct)).Pushed);
+ Assert.Equal(history.Count, (await fx.Home.HistoryAsync(id, null, 10, fx.Ct)).Count, "the library's history holds no empty version");
+
+ // The value taken over stays in a version file set aside, outside the versions to send.
+ var replaced = Path.Combine(two.Store.Find(id)!.VersionsDirectory, WorkspaceProject.ReplacedFolder);
+ Assert.Contains(Directory.GetFiles(replaced).Select(ProjectSidecars.ReadVersion), v => ProjectSettings.FromJson(v.SettingsJson).Exposure.ExposureOffsetEv == 1.0);
+ }
+
+ [Test]
+ public async Task AConflictListsTheWorkingStatesValueAndOneAnswerSettlesIt()
+ {
+ var fx = await FixtureAsync();
+ var (_, one) = fx.Workspace("one");
+ var (_, two) = fx.Workspace("two");
+ var id = (await fx.CheckoutAsync(one)).ProjectId;
+ await fx.CheckoutAsync(two, id);
+ await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
+ await one.CommitAsync(id, cancellationToken: fx.Ct);
+ await one.PushAsync(id, fx.Home, fx.Ct);
+ // This side saved 0.8 as a version, then went on to 1 without saving.
+ await EditAsync(two, id, s => Offset(s, 0.8), fx.Ct);
+ await two.CommitAsync(id, "warmer", cancellationToken: fx.Ct);
+ await EditAsync(two, id, s => Offset(s, 1.0), fx.Ct);
+
+ var shown = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict);
+ var difference = shown.Differences.Single();
+ Assert.Equal(("exposure.exposureOffsetEv", 1.0, 0.5), (difference.Path, Number(difference.Mine), Number(difference.Theirs)),
+ "this side's value is the one the editor shows");
+
+ var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.TakeServer, shown: shown, cancellationToken: fx.Ct);
+ Assert.Null(settled.Status.Conflict, "one answer settles what was shown");
+ Assert.Equal(0.5, (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv);
+ Assert.Equal(1.0, Assert.NotNull(settled.Kept).Exposure.ExposureOffsetEv);
+ Assert.Equal("warmer", two.Unpushed(id).Single().Note, "the saved version is replayed, nothing more");
+ }
+
+ [Test]
+ public async Task KeepMineKeepsTheWorkingStatesValueItListed()
+ {
+ var fx = await FixtureAsync();
+ var (_, one) = fx.Workspace("one");
+ var (_, two) = fx.Workspace("two");
+ var id = (await fx.CheckoutAsync(one)).ProjectId;
+ await fx.CheckoutAsync(two, id);
+ await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
+ await one.CommitAsync(id, cancellationToken: fx.Ct);
+ await one.PushAsync(id, fx.Home, fx.Ct);
+ await EditAsync(two, id, s => Offset(s, 0.8), fx.Ct);
+ await two.CommitAsync(id, cancellationToken: fx.Ct);
+ await EditAsync(two, id, s => Offset(s, 1.0), fx.Ct);
+
+ var shown = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict);
+ var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: shown, cancellationToken: fx.Ct);
+ Assert.Null(settled.Status.Conflict);
+ Assert.Equal(1.0, (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv, "the value listed as this side's is kept");
+ }
+
+ private static double? Number(string? json) => json is null ? null : double.Parse(json, System.Globalization.CultureInfo.InvariantCulture);
+
[Test]
public async Task KeepMineIsAskedAgainWhenTheLibraryMovedOnASettingThisSideChanged()
{
diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceRecoveryTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceRecoveryTests.cs
index 9a96501b..59418dfa 100644
--- a/tests/Chronos.Data.Tests/Workspaces/WorkspaceRecoveryTests.cs
+++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceRecoveryTests.cs
@@ -159,8 +159,8 @@ public abstract class WorkspaceRecoveryTests(TestContext context) : DatabaseTest
Assert.Equal(WorkspaceState.InSync, (await one.PushAsync(id, fx.Home, fx.Ct)).Status.State);
var head = Settings(await fx.Home.HeadAsync(id, fx.Ct));
Assert.Equal((1.0, StackSetting.Mean), (head.Exposure.ExposureOffsetEv, head.Stack.Mode));
- // Taking the server's first saves the unsaved offset as a version (kept for its undo); the versions before it reach the home in order.
- Assert.SequenceEqual(["first", "other", "second"], (await NotesAsync(fx, id)).Skip(1).Take(3));
+ // The unsaved offset taken over is kept aside, never sent: the home holds exactly these versions, in order.
+ Assert.SequenceEqual(["first", "other", "second"], (await NotesAsync(fx, id)).Skip(1));
}
[Test]