diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index 3cb381b3..77fb1442 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -291,6 +291,7 @@
Restore database…Run maintenanceTrash…
+ {0} (server)the name of the archive of a server's downloaded originals; {0} the server's name{0:N0} issue{0:N0} issuesThe orphan search stoppedlong
diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index 5c16556f..6b0eb1c2 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -9,6 +9,8 @@
The archive could not be opened.longThe current index could not be backed up or replaced; the restore runs again at the next start.longThis backup cannot be restored; choose another one.long
+ {0} presents the ID of {1} with another certificate; check that it is not a copy of that server.{0} the server's name now, {1} the name it had
+ The folders could not be sorted: {0}. Nothing was deleted; Chronos tries again at the next start.{0} the reasonEnter a number from {0} to {1}.Enter a whole number from {0} to {1}.Enter a folder.
@@ -34,6 +36,7 @@
{0} did not arrive intact; download it again.{0} file nameThe sequence is no longer in this PC's archive index.Open or create an archive on this PC to receive the originals.
+ No folder could be made for the originals of {0}; check that the drive of this PC's archive can be written.{0} the server's nameNot connected to this server; connect and retry the job.This sequence is not on the server yet; upload it first.No original reached the server: they are missing here or already in another server sequence.
diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx
index 8619d1c8..38ce56ae 100644
--- a/i18n/en/Settings.resx
+++ b/i18n/en/Settings.resx
@@ -178,12 +178,18 @@
testing…Reset sectionSearch settings
+ Server cacheTrusted certificatesDefault serverForget: {0}
+ Known serversNoneOffer this PC
+ Offline
+ Originals folderRender node
+ Server ID
+ Signed inClearSpilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.longClear the cache?
@@ -206,11 +212,13 @@
Workspace folder changedChoose the workspace folderlong; folder picker titleFolder
+ Home foldersKept versionsFolder not changedProjects found: {0}{0} count of the projects the folder chosen holdsProjects left: {0}{0} count of the projects the folder in use keepsSync
+ This PCUse folder{0} version{0} versions
diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx
index d9200b8f..e8b4e776 100644
--- a/i18n/en/Shell.resx
+++ b/i18n/en/Shell.resx
@@ -5,6 +5,13 @@
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Chronosinvariant
+ Server ID clash
+ {0} project moved{0} count
+ {0} projects moved{0} count
+ Originals folder made
+ Folders pending
+ Projects in use, or a workspace being moved, follow at the next start.long; toast message under Folders pending
+ Folders sortedJob finished{0} job finished{0} jobs finished
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index 3be6f60e..ba8ca96d 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -805,6 +805,14 @@
Frames whose mean brightness is at most this share of white count as night (star fields, night presets) · Enter applies, Esc revertsOpen the data folder in ExplorerShow the workspace folder in Explorer
+ This server's proxies, render-node files and staged imports, inside the cache folder
+ Servers this PC has signed in to, with the folders kept for each
+ Not signed in: its projects open from the workspace and wait to sync
+ Show this server's share of the cache in Explorer
+ Show the archive of this server's downloaded originals in Explorer
+ Where Download originals puts this server's photos, apart from this PC's archive
+ Identifies the server even when its address or name changes: {0}{0} the whole id
+ This PC is signed in to this server nowVersion, build, system, licence, third-party codePortable mode, logs, diagnostics, database backup and restore, resetAnalysis width, night and star thresholds, deep analysis
@@ -892,6 +900,7 @@
Replace the installed version in place · your data is keptCollapse navigation to icons · Ctrl+BShow navigation names · Ctrl+B
+ Show the logs folder in Explorer: the log says which folder could not be sortedPause the job shown; it continues from its checkpoint when resumedStop the current job · it can be resumed laterAdd a folder to watch
@@ -975,6 +984,10 @@
Keep the workspace's trash as it isWhat the workspace folder takes on its drive, its trash includedThe workspace's folder (a fast disk is best); Change uses another one, Move takes the projects along
+ Each home keeps its projects in its own folder inside the workspace
+ Open this home's folder in Explorer
+ Projects of sequences on {0}: {1}{0} the server's name, {1} the folder
+ Projects of sequences in this PC's archive: {0}{0} the folderMove the workspace folder with its projects to another folder, after a plan; each file is checked before its source goesPast this size, the media of the projects used longest ago are removed once they are in step with their home; their versions stayThe workspace grows as needed; only Clean after removes media
diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx
index 3fecf541..cea69074 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -285,6 +285,7 @@
Ripristina database…Esegui manutenzioneCestino…
+ {0} (server){0:N0} problema{0:N0} problemiRicerca degli orfani interrotta
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index 601bb54b..2000a8d5 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -9,6 +9,8 @@
Impossibile aprire l'archivio.Non è stato possibile copiare o sostituire l'indice attuale; il ripristino riparte al prossimo avvio.Questa copia non si può ripristinare; scegline un'altra.
+ {0} presenta l'ID di {1} con un altro certificato; verifica che non sia una copia di quel server.
+ Non è stato possibile riordinare le cartelle: {0}. Non è stato eliminato nulla; Chronos riprova al prossimo avvio.Inserisci un numero da {0} a {1}.Inserisci un numero intero da {0} a {1}.Inserisci una cartella.
@@ -34,6 +36,7 @@
{0} non è arrivato integro; scaricalo di nuovo.La sequenza non è più nell'indice dell'archivio di questo PC.Apri o crea un archivio su questo PC per ricevere gli originali.
+ Non è stato possibile creare una cartella per gli originali di {0}; verifica che il disco dell'archivio di questo PC sia scrivibile.Non connesso a questo server; collegati e riprova l'attività.Questa sequenza non è ancora sul server; caricala prima.Nessun originale è arrivato al server: mancano qui o sono già in un'altra sequenza del server.
diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx
index c0bc4322..0a78d616 100644
--- a/i18n/it/Settings.it.resx
+++ b/i18n/it/Settings.it.resx
@@ -175,12 +175,18 @@
in prova…Ripristina sezioneCerca impostazioni
+ Cache del serverCertificati attendibiliServer predefinitoDimentica: {0}
+ Server notiNessunoOffri questo PC
+ Non in linea
+ Cartella originaliNodo di rendering
+ ID server
+ ConnessoSvuotaI fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti.Svuotare la cache?
@@ -203,11 +209,13 @@
Cartella cambiataScegli la cartella dello spazio di lavoroCartella
+ Cartelle per origineVersioni tenuteCartella non cambiataProgetti trovati: {0}Progetti lasciati: {0}Sincronizzazione
+ Questo PCUsa cartella{0} versione{0} versioni
diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx
index 0b51d68b..13b193e9 100644
--- a/i18n/it/Shell.it.resx
+++ b/i18n/it/Shell.it.resx
@@ -4,6 +4,13 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ ID server in conflitto
+ {0} progetto spostato
+ {0} progetti spostati
+ Cartella originali creata
+ Cartelle in attesa
+ I progetti in uso, o uno spazio di lavoro in spostamento, seguono al prossimo avvio.
+ Cartelle riordinateAttività completata{0} attività completata{0} attività completate
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 4a6a5ca8..3ab4112f 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -876,6 +876,14 @@
I fotogrammi con luminosità media al massimo pari a questa quota del bianco contano come notturni (campi stellari, preset notturni) · Invio applica, Esc annullaApri la cartella dati in Esplora fileMostra la cartella dello spazio di lavoro in Esplora file
+ Proxy, file del nodo di rendering e importazioni in attesa di questo server, dentro la cartella della cache
+ I server a cui questo PC ha effettuato l'accesso, con le cartelle tenute per ciascuno
+ Accesso non effettuato: i suoi progetti si aprono dallo spazio di lavoro e attendono la sincronizzazione
+ Mostra la parte della cache di questo server in Esplora file
+ Mostra l'archivio degli originali scaricati da questo server in Esplora file
+ Dove Scarica originali mette le foto di questo server, separate dall'archivio di questo PC
+ Identifica il server anche quando cambiano indirizzo o nome: {0}
+ Questo PC ha effettuato l'accesso a questo server oraQuando Chronos è ridotto a icona o in secondo piano, schede inserite, attività finite e messaggi del server compaiono anche come notifiche di WindowsVersione, build, sistema, licenza, codice di terze partiModalità portatile, log, diagnostica, backup e ripristino del database, valori predefiniti
@@ -935,6 +943,10 @@
Svuota per sempre il cestino dello spazio di lavoro, dopo un elenco di ciò che contiene e una conferma scrittaIl cestino dello spazio di lavoro è vuotoLa cartella dello spazio di lavoro (meglio un disco veloce); Cambia ne usa un'altra, Sposta porta con sé i progetti
+ Ogni origine tiene i suoi progetti in una cartella propria dentro lo spazio di lavoro
+ Apri la cartella di questa origine in Esplora file
+ Progetti delle sequenze su {0}: {1}
+ Progetti delle sequenze nell'archivio di questo PC: {0}Il progetto che hai aperto per ultimo per la sequenzaIl progetto Principale della sequenza, che ne tiene le impostazioniSposta la cartella dello spazio di lavoro con i suoi progetti in un'altra cartella, dopo un piano; ogni file è verificato prima di rimuovere l'origine
@@ -989,6 +1001,7 @@
Sostituisci la versione installata · i tuoi dati restanoRiduci la navigazione alle icone · Ctrl+BMostra i nomi della navigazione · Ctrl+B
+ Mostra la cartella dei log in Esplora file: il log dice quale cartella non è stata riordinataMette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresaFerma l'attività in corso · potrai riprenderlaAggiungi una cartella da controllare
diff --git a/src/Chronos.App/DesignTime/SampleData.cs b/src/Chronos.App/DesignTime/SampleData.cs
index ace1ca49..27577fb2 100644
--- a/src/Chronos.App/DesignTime/SampleData.cs
+++ b/src/Chronos.App/DesignTime/SampleData.cs
@@ -84,7 +84,7 @@ public sealed class SampleData
services.CheckForUpdateAsync = _ => Task.FromResult(null);
services.Devices.Dispose();
services.Devices = new SampleDeviceMonitor();
- services.Sync.RemoteFactory = (_, _, _) => sample._remote;
+ services.Sync.RemoteFactory = (_, _, _, _) => sample._remote;
services.Sync.EditorFactory = (_, _, _) => sample._remote;
// The schedules keep the sample's moment: nothing becomes due while the screenshots are taken.
services.SchedulerTime = new FixedTime(Now);
@@ -134,6 +134,16 @@ public sealed class SampleData
settings.ProtectedToken = "sample-token";
settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }];
settings.RecentServers = ["https://nas.local:8443"];
+ // Settings › Server › Known servers (owner review 5): the sample's server, known by its id.
+ settings.KnownServers =
+ [
+ new KnownServer
+ {
+ Id = Guid.Parse("5a3c1f0e-7d2b-4c8e-9f10-2b6d4e8a1c37"), Name = "Studio NAS", LastAddress = "https://nas.local:8443", Fingerprint = ServerFingerprint,
+ Aliases = [Chronos.Data.Sync.SyncService.ServerKey(new Uri("https://nas.local:8443"))], LastSeen = Now,
+ },
+ ];
+ _services.Sync.KnownServersChanged();
settings.RenderNodeOptIn = true;
// The jobs sample shows a deep analysis that yielded to the render (owner review 1).
settings.PriorityQueue = true;
diff --git a/src/Chronos.App/Editor/ProjectFiles.cs b/src/Chronos.App/Editor/ProjectFiles.cs
index e1436daa..49eb6313 100644
--- a/src/Chronos.App/Editor/ProjectFiles.cs
+++ b/src/Chronos.App/Editor/ProjectFiles.cs
@@ -74,7 +74,7 @@ public sealed class ProjectFiles(ShellViewModel shell)
if (bundle.Workspace is { } workspace)
{
// A workspace's own working state opens as it is; a copy of one (saved elsewhere, another PC's) gives its project its settings.
- var own = shell.Services.Workspace.Store.Find(workspace.ProjectId) is { } project
+ var own = shell.Services.Workspace.Find(workspace.ProjectId) is { } project
&& string.Equals(Path.GetFullPath(project.BundlePath), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle));
return;
diff --git a/src/Chronos.App/Infrastructure/AppServices.cs b/src/Chronos.App/Infrastructure/AppServices.cs
index d87a7c8d..c88ee52b 100644
--- a/src/Chronos.App/Infrastructure/AppServices.cs
+++ b/src/Chronos.App/Infrastructure/AppServices.cs
@@ -12,6 +12,7 @@ using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
+using Chronos.Core.IO;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
@@ -21,6 +22,7 @@ using Chronos.Core.Windows.MediaFoundation;
using Chronos.Core.Windows.Wic;
using Chronos.Data;
using Chronos.Data.Archiving;
+using Chronos.Data.Homes;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Scheduling;
@@ -78,6 +80,8 @@ public sealed class AppServices : IAsyncDisposable
Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine);
// A server that keeps projects is the home of the workspace projects of its sequences (owner review 2, R8, phase 5b).
Workspace.ServerHomes = Sync.ProjectHome;
+ // A server home's folder is named by its server's id, whichever address reached it (owner review 5, #66).
+ Workspace.Identity = () => Sync.Identity;
Sync.ProjectChanged += Workspace.OnServerProjectChanged;
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
@@ -151,6 +155,12 @@ public sealed class AppServices : IAsyncDisposable
/// How the restore staged in Settings › Advanced went when the index opened; null when none was staged.
public StagedRestoreResult? StagedRestore { get; private set; }
+ /// What the sorting of the folders into homes did when the index opened (owner review 5, #66); null when it had nothing to do.
+ public HomeLayoutResult? HomeLayout { get; private set; }
+
+ /// Why the folders could not be sorted into homes when the index opened; null when they were, or had nothing to sort.
+ public Exception? HomeLayoutError { get; private set; }
+
/// Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.
public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
@@ -201,7 +211,8 @@ public sealed class AppServices : IAsyncDisposable
new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing,
() => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(),
services.Workspace.MovedAsync,
- () => services.Workspace.Root);
+ () => services.Workspace.Root,
+ services.Workspace.SameServer);
///
/// Queues a scan of unless one is already waiting or running; the sequences it indexes get
@@ -284,6 +295,8 @@ public sealed class AppServices : IAsyncDisposable
_schedulerReady.TrySetResult(false);
return;
}
+ // Before any job runs: the folders of the workspace and the cache go to their homes (owner review 5, #66).
+ await SortHomesAsync(Database, ct);
try
{
await StartJobsAsync(Database, startEngine: true, ct);
@@ -474,6 +487,66 @@ public sealed class AppServices : IAsyncDisposable
}
}
+ ///
+ /// Sorts the workspace's projects and the cache's server folders into their homes (owner review 5, #66:
+ /// ; renames only, a clash to the trash, never deleted), or takes up a sorting a previous
+ /// start left half done. Projects in use or a workspace being moved wait for a later start; a failure is logged and kept
+ /// for Settings to tell (), and the start goes on: the folders not sorted read as before.
+ ///
+ private async Task SortHomesAsync(ChronosDatabase database, CancellationToken ct)
+ {
+ try
+ {
+ var migration = new HomeLayoutMigration(new HomeLayoutOptions
+ {
+ DataDirectory = Environment.DataDirectory,
+ WorkspaceRoot = Workspace.IsEnabled ? Workspace.Root : null,
+ CacheRoot = CacheStore.Folder(Environment, Settings),
+ Identity = Sync.Identity,
+ CurrentServer = Sync.LastServer,
+ Database = database,
+ });
+ var result = await Task.Run(() => migration.ApplyAsync(ct), ct);
+ if (result != HomeLayoutResult.Nothing)
+ {
+ HomeLayout = result;
+ Log.Info("app", $"Folders sorted into homes: {result.ProjectsMoved} project(s), {result.EntriesMoved} entr(ies), {result.InUse} in use, "
+ + $"{result.Clashes} clash(es){(result.Deferred is { } deferred ? $", the workspace waits ({deferred})" : string.Empty)}");
+ }
+ }
+ catch (Exception ex) when (ex is HomeLayoutException or IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
+ {
+ HomeLayoutError = ex;
+ Log.Error("app", "The folders could not be sorted into homes; the next start tries again", ex);
+ }
+ finally
+ {
+ Workspace.Reopen();
+ }
+ }
+
+ ///
+ /// The scan schedule scanned this PC's archive (any thread): the archives of the servers' downloaded originals are scanned
+ /// after it (owner review 5, Q1: they are archives of their own, which the schedule, made for one archive, does not name).
+ ///
+ private void OnScheduledScanDone(Job job)
+ {
+ if (job is not { Kind: JobKind.Scan, State: JobState.Done, ScheduleId: not null, TargetIds: [var scanned] }) return;
+ _ = Task.Run(async () =>
+ {
+ try
+ {
+ var archives = await Sync.OriginalsArchivesAsync(_stopping.Token).ConfigureAwait(false);
+ if (archives.Any(a => a.Id == scanned)) return;
+ foreach (var originals in archives) await QueueScanAsync(originals, full: false, _stopping.Token).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or OperationCanceledException)
+ {
+ Log.Warning("app", "The archives of the servers' originals could not be queued to be scanned", ex);
+ }
+ });
+ }
+
private async Task StartJobsAsync(ChronosDatabase database, bool startEngine, CancellationToken ct)
{
_wic = new WicDecoderProvider();
@@ -508,6 +581,7 @@ public sealed class AppServices : IAsyncDisposable
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue });
// The workspace's size limit runs after each copy of media into it (phase 5c).
Engine.JobChanged += Workspace.OnJobChanged;
+ Engine.JobChanged += OnScheduledScanDone;
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
Sync.Update();
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
@@ -554,7 +628,8 @@ public sealed class AppServices : IAsyncDisposable
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{
ClientName = System.Environment.MachineName,
- CacheDirectory = Path.Combine(cache, "render-node"),
+ // Each server keeps its own downloads (owner review 5, #66: the render-node folder of its home in the cache).
+ CacheDirectory = Path.Combine(CacheStore.ServerFolder(cache, Sync.KeyOf(session.Address), Sync.Identity), HomeFolders.RenderNode),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
diff --git a/src/Chronos.App/Infrastructure/AppSettings.cs b/src/Chronos.App/Infrastructure/AppSettings.cs
index f8abdfe0..0e41bd62 100644
--- a/src/Chronos.App/Infrastructure/AppSettings.cs
+++ b/src/Chronos.App/Infrastructure/AppSettings.cs
@@ -10,6 +10,7 @@ using Chronos.Core.Naming;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
+using Chronos.Data.Sync;
using Chronos.Ui.Theming;
namespace Chronos.App.Infrastructure;
@@ -66,6 +67,27 @@ public sealed class TrustedCertificate
public DateTimeOffset TrustedAt { get; set; }
}
+///
+/// A server this PC signed in to that announced its stable id (owner review 5, #66): its name and last address, the TLS
+/// fingerprint it presented, the address keys it was reached under before (or besides) its id
+/// (: projects, links and jobs made then still name them), the archive its
+/// downloaded originals go to, and when it was last seen. Its folders (servers\<id> in the workspace and the
+/// cache) are named by the id, never by the name.
+///
+public sealed class KnownServer
+{
+ public Guid Id { get; set; }
+ public string? Name { get; set; }
+ public string? LastAddress { get; set; }
+ public string? Fingerprint { get; set; }
+ public List Aliases { get; set; } = [];
+
+ /// The archive of this PC that holds the server's downloaded originals (owner review 5, Q1); null until the first download.
+ public Guid? OriginalsArchiveId { get; set; }
+
+ public DateTimeOffset LastSeen { get; set; }
+}
+
///
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
/// settings.json next to the database and written atomically, because language and theme apply before the
@@ -257,6 +279,19 @@ public sealed class AppSettings
public List TrustedCertificates { get; set; } = [];
public List RecentServers { get; set; } = [];
+ ///
+ /// The servers known by their stable id and the address keys each was reached under (owner review 5, #66): a server's
+ /// projects, links and jobs stay its own whatever address it is reached by. This PC's state: Reset and Import keep it,
+ /// Export leaves it out.
+ ///
+ public List KnownServers { get; set; } = [];
+
+ /// The alias table of , as the sync and the workspace compare server keys through it.
+ public ServerIdentity KnownIdentity() => new([.. KnownServers.Where(k => k.Id != Guid.Empty).Select(k => new KnownServerKey(k.Id, [.. k.Aliases]))]);
+
+ /// The known server of ; null when this PC has none.
+ public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id);
+
/// Let the server send render jobs to this PC (BRIEF §14.7).
public bool RenderNodeOptIn { get; set; }
@@ -377,6 +412,7 @@ public sealed class AppSettings
ProtectedToken = ProtectedToken,
TrustedCertificates = TrustedCertificates,
RecentServers = RecentServers,
+ KnownServers = KnownServers,
Window = Window,
RailCollapsed = RailCollapsed,
EditorGroups = EditorGroups,
@@ -400,6 +436,7 @@ public sealed class AppSettings
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
copy.WorkspaceOpened = [];
+ copy.KnownServers = [];
return copy;
}
@@ -423,6 +460,7 @@ public sealed class AppSettings
imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened;
+ imported.KnownServers = KnownServers;
return imported;
}
}
diff --git a/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs b/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs
index 35c54b61..ad08192c 100644
--- a/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs
+++ b/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs
@@ -5,10 +5,12 @@ using System.Text;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
+using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Core.Windows.Codecs;
using Chronos.Data;
using Chronos.Data.Sqlite;
+using Chronos.Data.Sync;
namespace Chronos.App.Infrastructure;
@@ -34,8 +36,11 @@ public static class DiagnosticsBundle
var settings = services.Settings.ToJson();
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
+ var workspace = services.Workspace;
+ var cache = CacheStore.Folder(services.Environment, services.Settings);
return Task.Run(async () =>
{
+ report += HomesLines(workspace, cache);
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
var codecs = Codecs(services.Encoders);
var path = ExportNaming.Unique(folder, $"Chronos diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip");
@@ -76,6 +81,33 @@ public static class DiagnosticsBundle
return sb.ToString();
}
+ /// The homes' folders (owner review 5, #66): the workspace's, each with its projects, and the servers' in the cache.
+ private static string HomesLines(Chronos.App.Workspace.WorkspaceHost workspace, string cache)
+ {
+ var sb = new StringBuilder();
+ try
+ {
+ if (workspace.IsEnabled && Directory.Exists(workspace.Root))
+ {
+ var homes = workspace.Homes;
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Workspace {homes.Root} ({(homes.IsSplit ? "homes" : "1.0 layout")})");
+ foreach (var home in homes.Homes())
+ sb.AppendLine(CultureInfo.InvariantCulture, $" {(home.IsLegacy ? "(parent)" : home.Folder)}: {home.Store.List().Count} project(s){(home.Server?.Name is { } name ? " · " + name : string.Empty)}");
+ }
+ var servers = CacheStore.ServersFolder(cache);
+ if (Directory.Exists(servers))
+ {
+ foreach (var folder in Directory.EnumerateDirectories(servers).Order(StringComparer.Ordinal))
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Cache home {Path.GetFileName(folder)}");
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ sb.AppendLine("The homes could not be listed: " + ex.Message);
+ }
+ return sb.ToString();
+ }
+
private static string DatabaseLine(ChronosDatabase? database)
{
if (database is null) return "Index not open\n";
@@ -135,6 +167,19 @@ public static class CacheStore
public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
+ /// The servers' homes in the cache (<cache>\servers, owner review 5, #66).
+ public static string ServersFolder(string cache) => Path.Combine(cache, HomeFolders.Servers);
+
+ ///
+ /// The home of server in the cache (<cache>\servers\<folder>, named by its
+ /// canonical key through ): its proxies, render-node downloads and staged imports.
+ ///
+ public static string ServerFolder(string cache, string serverKey, ServerIdentity identity)
+ {
+ ArgumentNullException.ThrowIfNull(identity);
+ return Path.Combine(ServersFolder(cache), identity.FolderName(serverKey));
+ }
+
/// Creates the folder (if needed) and marks it as Chronos's.
public static void Prepare(string folder)
{
diff --git a/src/Chronos.App/Jobs/DesktopScheduleHost.cs b/src/Chronos.App/Jobs/DesktopScheduleHost.cs
index cf29b2f5..3a378ce3 100644
--- a/src/Chronos.App/Jobs/DesktopScheduleHost.cs
+++ b/src/Chronos.App/Jobs/DesktopScheduleHost.cs
@@ -84,7 +84,11 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func GetArchiveAsync(CancellationToken cancellationToken)
{
if (database() is not { } db || archives() is not { } service) return null;
- var archive = CurrentArchive.Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), settings.LastArchivePath);
+ var listed = await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false);
+ // Never a server's originals archive in place of this PC's (owner review 5): the app scans those after this one.
+ var originals = settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet();
+ var archive = (settings.LastArchivePath is { Length: > 0 } last ? CurrentArchive.At(listed, last) : null)
+ ?? CurrentArchive.Pick([.. listed.Where(a => !originals.Contains(a.Id))], null) ?? CurrentArchive.Pick(listed, null);
if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null;
try
{
@@ -110,14 +114,15 @@ public sealed class DesktopScheduleHost(AppSettings settings, Funccache-trim (owner review 2, R10): brings the cache folder down to Settings › Storage ›
/// Cache limit, oldest files first, skipping files in use (). The proxies of server sequences
/// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an
-/// import to the server stages are never trimmed; Settings › Storage › Clear still empties everything.
+/// import to the server stages are never trimmed, in the former shared folders and in each server's own (servers,
+/// owner review 5); Settings › Storage › Clear still empties everything.
///
public sealed class CacheTrimStep(Func folder, Func limitBytes) : ICleanupStep
{
public const string StepName = "cache-trim";
/// Folders of the cache the trim leaves whole.
- public static IReadOnlyList Kept { get; } = ["proxies", "render-node", "server-import"];
+ public static IReadOnlyList Kept { get; } = ["proxies", "render-node", "server-import", Chronos.Core.IO.HomeFolders.Servers];
public string Name => StepName;
diff --git a/src/Chronos.App/Library/LibraryActions.cs b/src/Chronos.App/Library/LibraryActions.cs
index 6f99ff4d..a13f8711 100644
--- a/src/Chronos.App/Library/LibraryActions.cs
+++ b/src/Chronos.App/Library/LibraryActions.cs
@@ -117,11 +117,7 @@ public sealed class LibraryActions(ShellViewModel shell)
await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
return true;
case SyncAction.DownloadOriginals when entry is not null:
- if ((entry.Local?.ArchiveId ?? (await Services.Sync.CurrentArchiveAsync())?.Id) is not { } archive)
- {
- shell.Notify(Loc.L("Errors.Sync.NoArchive"));
- return false;
- }
+ if (await Services.Sync.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => shell.Notify(title, message, isError: isError)) is not { } archive) return false;
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
return true;
case SyncAction.GetExports when entry is not null:
diff --git a/src/Chronos.App/Sections/ImportViewModel.cs b/src/Chronos.App/Sections/ImportViewModel.cs
index acd4a894..fc17cc81 100644
--- a/src/Chronos.App/Sections/ImportViewModel.cs
+++ b/src/Chronos.App/Sections/ImportViewModel.cs
@@ -989,7 +989,20 @@ public sealed class ImportViewModel : SectionViewModel
/// What the signed-in user may still store on the server; null without a quota.
private long? ServerSpace() => Services.Server.User is { QuotaBytes: > 0 } user ? System.Math.Max(0, user.QuotaBytes - user.UsedBytes) : null;
- private string ServerStagingRoot => Path.Combine(CacheStore.Folder(Services.Environment, Services.Settings), "server-import");
+ ///
+ /// Where an import to the server is staged before it is uploaded: the signed-in server's own folder of the cache
+ /// (servers\<id>\import, owner review 5); signed out, the cache's former shared folder.
+ ///
+ private string ServerStagingRoot
+ {
+ get
+ {
+ var cache = CacheStore.Folder(Services.Environment, Services.Settings);
+ return Services.Sync.Server is { } server
+ ? Path.Combine(CacheStore.ServerFolder(cache, server, Services.Sync.Identity), Chronos.Core.IO.HomeFolders.Import)
+ : Path.Combine(cache, Chronos.Data.Homes.HomeLayoutMigration.LegacyServerImport);
+ }
+ }
private async Task PlanAsync()
{
diff --git a/src/Chronos.App/Sections/SequencePickerViewModel.cs b/src/Chronos.App/Sections/SequencePickerViewModel.cs
index 8cb7db73..21fef618 100644
--- a/src/Chronos.App/Sections/SequencePickerViewModel.cs
+++ b/src/Chronos.App/Sections/SequencePickerViewModel.cs
@@ -189,7 +189,7 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
{
var generation = _generation;
foreach (var item in WorkspaceItems.Where(i => change.ProjectId is { } id ? i.ProjectId == id
- : i.Entry.IsServerHome && string.Equals(i.Entry.Home.Server, change.Server, StringComparison.OrdinalIgnoreCase)).ToList())
+ : i.Entry.IsServerHome && Shell.Services.Workspace.SameServer(i.Entry.Home.Server, change.Server)).ToList())
{
if (generation != _generation) return;
try
diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs
index c6e7a8fb..e9987ec0 100644
--- a/src/Chronos.App/Sections/SequenceViewModel.cs
+++ b/src/Chronos.App/Sections/SequenceViewModel.cs
@@ -643,7 +643,7 @@ public sealed class SequenceViewModel : SectionViewModel
{
workspace.Remember(row.Id, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId);
- return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
+ return (new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
@@ -748,9 +748,9 @@ public sealed class SequenceViewModel : SectionViewModel
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server:
// made again whenever the sign-in changes, so a project opened signed out renders once signed in.
var server = entry.Home.Server;
- var editorHome = new WorkspaceServerHome(() => string.Equals(sync.Server, server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null,
+ var editorHome = new WorkspaceServerHome(() => sync.Identity.Same(sync.Server, server) ? sync.ConnectEditor() : null,
() => sync.Session);
- return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle));
+ return new ServerOpen((new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle));
}
// An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server.
if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null;
diff --git a/src/Chronos.App/Sections/SettingsView.xaml b/src/Chronos.App/Sections/SettingsView.xaml
index d1deb8e3..299d4d7d 100644
--- a/src/Chronos.App/Sections/SettingsView.xaml
+++ b/src/Chronos.App/Sections/SettingsView.xaml
@@ -563,6 +563,28 @@
Visibility="{Binding WorkspaceRows.HasUsageText, Converter={StaticResource BoolToVisibility}}" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -648,6 +670,62 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Chronos.App/Sections/SettingsViewModel.cs b/src/Chronos.App/Sections/SettingsViewModel.cs
index baf1c69b..12e02f6e 100644
--- a/src/Chronos.App/Sections/SettingsViewModel.cs
+++ b/src/Chronos.App/Sections/SettingsViewModel.cs
@@ -90,8 +90,8 @@ public sealed class SettingsViewModel : SectionViewModel
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia",
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
- "Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash"]),
- new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
+ "Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash", "Settings.Workspace.Homes"]),
+ new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
@@ -272,7 +272,12 @@ public sealed class SettingsViewModel : SectionViewModel
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false);
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
- if (value == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
+ if (value == SettingsPage.Workspace)
+ {
+ _ = WorkspaceRows.MeasureAsync();
+ _ = LoadHomeFoldersAsync();
+ }
+ if (value == SettingsPage.Server) _ = LoadKnownServersAsync();
if (value == SettingsPage.Advanced) LoadBackups();
}
}
@@ -741,7 +746,7 @@ public sealed class SettingsViewModel : SectionViewModel
{
try
{
- ShellActions.Reveal(Shell.Services.Workspace.Store.Root);
+ ShellActions.Reveal(Shell.Services.Workspace.Homes.Root);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
@@ -793,6 +798,16 @@ public sealed class SettingsViewModel : SectionViewModel
public bool HasCertificates => Certificates.Count > 0;
+ /// Settings › Server › Known servers (owner review 5, #66): the servers this PC signed in to, with their folders.
+ public ObservableCollection KnownServers { get; } = [];
+
+ public bool HasKnownServers => KnownServers.Count > 0;
+
+ /// Settings › Workspace › Home folders (owner review 5, #66): where each home keeps its projects.
+ public ObservableCollection HomeFolderRows { get; } = [];
+
+ public bool HasHomeFolderRows => HomeFolderRows.Count > 0;
+
// ---------------- Updates ----------------
public bool CheckForUpdates
@@ -897,6 +912,8 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true);
break;
}
+ NotifyHomeLayout();
+ Shell.Services.Sync.IdentityClash += (name, was) => Shell.Notify(Loc.L("Shell.Homes.Clash"), Loc.L("Errors.Homes.Clash", name, was), isError: true);
// BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead, and
// leaves the data it kept beside it before where it is. Only a user folder that is itself synchronised is unsafe.
var environment = Shell.Services.Environment;
@@ -1559,6 +1576,27 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
+ ///
+ /// How the sorting of the folders into homes went at start (owner review 5, #66): sorted, with Open on the workspace;
+ /// pending, when projects in use or a workspace being moved wait for the next start; or failed, with Open on the logs.
+ ///
+ private void NotifyHomeLayout()
+ {
+ var services = Shell.Services;
+ if (services.HomeLayoutError is { } error)
+ {
+ Shell.Notify(Loc.L("Shell.Homes.Pending"), Loc.L("Errors.Homes.Failed", error.Message), Loc.L("Settings.Advanced.Logs"),
+ Loc.L("Tooltips.Shell.Homes.Logs"), () => ShellActions.Reveal(services.Environment.LogDirectory), isError: true);
+ return;
+ }
+ if (services.HomeLayout is not { } result) return;
+ if (result.Deferred is not null || result.InUse > 0)
+ Shell.Notify(Loc.L("Shell.Homes.Pending"), Loc.L("Shell.Homes.PendingText"));
+ else if (result.ProjectsMoved > 0)
+ Shell.Notify(Loc.L("Shell.Homes.Sorted"), Loc.Plural("Shell.Homes.Moved", result.ProjectsMoved), Loc.L("Common.Open"),
+ Loc.L("Tooltips.Settings.OpenWorkspace"), OpenWorkspaceFolder);
+ }
+
private void CancelRestore()
{
try
@@ -1781,6 +1819,57 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Import.Done"));
}
+ /// The home folders of the workspace as they are now (read off the UI thread; none while the workspace cannot be read).
+ private async Task LoadHomeFoldersAsync()
+ {
+ var workspace = Shell.Services.Workspace;
+ if (!workspace.IsEnabled) return;
+ var known = _s.KnownServers.ToList();
+ IReadOnlyList rows;
+ try
+ {
+ rows = await Task.Run(() => HomeFolderRow.Of(workspace.Homes, known, RevealFolder));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ Log.Info("settings", $"The home folders of the workspace could not be read: {ex.Message}");
+ rows = [];
+ }
+ HomeFolderRows.Clear();
+ foreach (var row in rows) HomeFolderRows.Add(row);
+ OnPropertyChanged(nameof(HasHomeFolderRows));
+ }
+
+ /// The known servers, most recently seen first, with the archive of their originals and their share of the cache.
+ private async Task LoadKnownServersAsync()
+ {
+ var services = Shell.Services;
+ IReadOnlyList archives = services.Database is { } db ? await db.Archives.ListAsync() : [];
+ var cache = CacheStore.Folder(services.Environment, services.Settings);
+ var signedIn = services.Sync.Server;
+ KnownServers.Clear();
+ foreach (var server in _s.KnownServers.Where(k => k.Id != Guid.Empty).OrderByDescending(k => k.LastSeen))
+ {
+ var key = HomeFolders.IdKey(server.Id);
+ var originals = server.OriginalsArchiveId is { } id ? archives.FirstOrDefault(a => a.Id == id)?.RootPath : null;
+ KnownServers.Add(new KnownServerRow(server, services.Sync.Identity.Same(signedIn, key), originals,
+ CacheStore.ServerFolder(cache, key, services.Sync.Identity), RevealFolder));
+ }
+ OnPropertyChanged(nameof(HasKnownServers));
+ }
+
+ private void RevealFolder(string folder)
+ {
+ try
+ {
+ ShellActions.Reveal(folder);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Shell.ReportError(ex);
+ }
+ }
+
private void LoadCertificates()
{
Certificates.Clear();
diff --git a/src/Chronos.App/Sections/VideosViewModel.cs b/src/Chronos.App/Sections/VideosViewModel.cs
index 26529849..1b746f04 100644
--- a/src/Chronos.App/Sections/VideosViewModel.cs
+++ b/src/Chronos.App/Sections/VideosViewModel.cs
@@ -551,7 +551,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
var workspace = services.Workspace;
if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return [];
var projects = await workspace.ListAsync(cancellationToken);
- return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Store, projects), cancellationToken);
+ return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Homes, projects), cancellationToken);
}
/// The signed-in session's server, its capability and the account's rights.
diff --git a/src/Chronos.App/Server/SyncHost.cs b/src/Chronos.App/Server/SyncHost.cs
index a14e3f26..6e3cdadd 100644
--- a/src/Chronos.App/Server/SyncHost.cs
+++ b/src/Chronos.App/Server/SyncHost.cs
@@ -1,10 +1,14 @@
using System.IO;
+using Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
+using Chronos.Core.IO;
+using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
+using Chronos.Data.Homes;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
@@ -13,8 +17,14 @@ using Chronos.Protocol.Client;
namespace Chronos.App.Server;
-/// Makes the sync connection of a signed-in session.
-public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection trustedFingerprints);
+/// Makes the sync connection of a signed-in session; is the key it names the server by ().
+public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection trustedFingerprints, string server);
+
+///
+/// Where Download originals puts a server sequence's photos (): the archive's id,
+/// and its root when it was made just now (the first download from that server); a null id when there is none to use.
+///
+public sealed record OriginalsTarget(Guid? ArchiveId, string? Created = null);
///
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the of the index, the
@@ -24,25 +34,37 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
/// (), the server as the home of workspace projects when it keeps projects (owner review 2, R8,
/// phase 5b: , ) and the Export "Sync" of finished renders
/// (). Options come from ,
-/// and .
+/// and . A server that announces
+/// its stable id (owner review 5, #66) is keyed by it () and recorded in
+/// with the address keys it was reached under, which match it all the same
+/// (); at a sign-in that tells its id, what this PC keeps under those addresses moves to its id
+/// () before the agent starts.
///
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
{
/// How long a job resumed at start waits for the saved session to be restored.
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
+ /// Jobs that write into the workspace or the servers' homes in the cache: a re-key waits for them.
+ private static readonly JobKind[] RekeyHeldBy =
+ [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove, JobKind.Download, JobKind.UploadCommit, JobKind.VideoCopy];
+
private readonly Lock _gate = new();
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private Running? _running;
private JobEngine? _renders;
+ /// The alias table of , made again whenever a sign-in records a server.
+ private ServerIdentity _identity = services.Settings.KnownIdentity();
+
/// The client project homes of the session share, made at first use for the credentials it holds.
private SharedClient? _projects;
/// Connections over ; screenshots substitute a fake server.
- public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
- new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
+ public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted, server) =>
+ new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true,
+ server);
/// Connections of editors of server sequences over ; screenshots substitute a fake server.
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
@@ -61,8 +83,28 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// The agent's connection, for the table's own calls (conflict resolution); null while signed out.
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
- /// Key of the signed-in server (); null while signed out.
- public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
+ ///
+ /// Key of the signed-in server: its id key when it announced its id (), else
+ /// its address key (); null while signed out.
+ ///
+ public string? Server => Volatile.Read(ref _credentials) is { } c ? c.Key : null;
+
+ /// The servers known by id and the address keys each was reached under (any thread).
+ public ServerIdentity Identity => Volatile.Read(ref _identity);
+
+ ///
+ /// A known server id came back with another TLS certificate and another name (owner review 5: a copied server database,
+ /// two servers sharing one id): the server's name now, and the name it had (UI thread).
+ ///
+ public event Action? IdentityClash;
+
+ /// The key a server reached at goes by: the signed-in one's when it is that server, else its address key mapped through the aliases.
+ public string KeyOf(Uri address)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+ if (Volatile.Read(ref _credentials) is { } c && c.Address == address) return c.Key;
+ return Identity.Canonical(SyncService.ServerKey(address));
+ }
/// The options, and whether the account may change server sequences (without it this PC's edits are not sent).
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit));
@@ -97,15 +139,15 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
///
/// The project home of a workspace project whose home is a server ( over the session's
/// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then
- /// shows the project offline and its work waits.
+ /// shows the project offline and its work waits. A home named by an address the signed-in server was reached under before
+ /// it told its id is that server's all the same (owner review 5).
///
public IProjectHome? ProjectHome(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
- if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials
- || !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
+ if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials || !Identity.Same(home.Server, credentials.Key))
return null;
- return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat);
+ return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat, credentials.Key);
}
///
@@ -121,14 +163,23 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// The agent started, stopped or compared, or the table of the signed-in server changed (any thread).
public event Action? Changed;
- /// Creates the engine over the open index; the proxy cache lives in the client's cache folder.
+ ///
+ /// Creates the engine over the open index; the proxy cache lives in the client's cache folder, one home per server
+ /// (<cache>\servers\<folder>\proxies, owner review 5), read where 1.0 put it until it is moved.
+ ///
public SyncService Open(ChronosDatabase database, Chronos.Data.Archiving.ArchiveService archives, Chronos.Data.Archiving.ArchiveServiceOptions options)
{
var cache = CacheStore.Folder(services.Environment, services.Settings);
- Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") });
+ Service = new SyncService(database, archives, new SyncOptions
+ {
+ Archive = options,
+ ProxyCacheDirectory = Path.Combine(cache, HomeLayoutMigration.LegacyProxies),
+ ServersDirectory = CacheStore.ServersFolder(cache),
+ Identity = () => Identity,
+ });
Service.Changed += server =>
{
- if (server == Server) Changed?.Invoke();
+ if (Server is { } signedIn && Identity.Same(server, signedIn)) Changed?.Invoke();
};
return Service;
}
@@ -138,8 +189,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
{
var session = services.Server;
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
- ? new Credentials(address, token, session.Fingerprints)
+ ? new Credentials(address, token, session.Fingerprints, session.Flow.Info?.ServerId is { } id && id != Guid.Empty ? id : null)
: null;
+ if (wanted is { ServerId: { } serverId } && session.Flow.Info is { } info) Remember(serverId, wanted.Address, info);
Volatile.Write(ref _credentials, wanted);
_switch = SwitchAsync(_switch, wanted);
if (services.Engine is not { } engine) return;
@@ -150,6 +202,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
engine.JobChanged += OnJobChanged;
}
+ /// The servers known by id were changed elsewhere (Settings › Server › Forget, an import): the alias table follows (UI thread).
+ public void KnownServersChanged() => Volatile.Write(ref _identity, services.Settings.KnownIdentity());
+
/// The sign-in uses now (another object once signed in anew); null while signed out.
public object? Session => Volatile.Read(ref _credentials);
@@ -167,18 +222,73 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// Compares again soon (an option changed, an edit on this PC).
public void RequestRefresh() => Agent?.RequestRefresh();
- /// The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.
+ /// This PC's archive: the one at Settings › Archive's folder, else the only one that is not a server's originals archive.
public async Task CurrentArchiveAsync(CancellationToken ct = default)
{
if (services.Database is not { } db) return null;
var archives = await db.Archives.ListAsync(ct);
- if (services.Settings.LastArchivePath is { Length: > 0 } root)
+ if (services.Settings.LastArchivePath is { Length: > 0 } root && CurrentArchive.At(archives, root) is { } current) return current;
+ var originals = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet();
+ var own = archives.Where(a => !originals.Contains(a.Id)).ToList();
+ return own.Count == 1 ? own[0] : null;
+ }
+
+ ///
+ /// Where Download originals puts the photos of a server sequence (owner review 5, Q1; UI thread): the archive of its local
+ /// copy when it has one (a copy keeps receiving where it is), else the signed-in server's own originals archive
+ /// (), made at the first download beside this PC's archive
+ /// (: D:\ChronosArchive - Studio NAS, named "Studio NAS (server)").
+ /// A server that announces no id (an older one) has no home of its own: its originals go to this PC's archive, as in 1.0.
+ ///
+ /// The originals archive's folder cannot be made.
+ public async Task OriginalsArchiveAsync(Sequence? local, CancellationToken ct = default)
+ {
+ if (local?.ArchiveId is { } held) return new OriginalsTarget(held);
+ if (services.Database is not { } db || services.Archives is not { } archives) return new OriginalsTarget(null);
+ if (Volatile.Read(ref _credentials) is not { ServerId: { } id } || services.Settings.FindKnownServer(id) is not { } known)
+ return new OriginalsTarget((await CurrentArchiveAsync(ct))?.Id);
+ var listed = await db.Archives.ListAsync(ct);
+ if (known.OriginalsArchiveId is { } chosen && listed.Any(a => a.Id == chosen)) return new OriginalsTarget(chosen);
+ var name = known.Name is { Length: > 0 } n ? n : services.Server.ServerName ?? known.LastAddress ?? id.ToString("N");
+ var mine = await CurrentArchiveAsync(ct);
+ var root = HomeFolders.OriginalsArchiveRoot(mine?.RootPath ?? services.Settings.LastArchivePath, name, ArchiveLocations.SuggestRoot(),
+ path => Directory.Exists(path) || File.Exists(path) || CurrentArchive.At(listed, path) is not null);
+ var made = await archives.CreateAsync(root, Loc.L("Archive.Name.ServerOriginals", name), cancellationToken: ct);
+ known.OriginalsArchiveId = made.Id;
+ services.SavePreferences();
+ Log.Info("sync", $"The originals of {name} ({id}) go to their own archive {made.RootPath}");
+ return new OriginalsTarget(made.Id, made.RootPath);
+ }
+
+ ///
+ /// The archive Download originals puts a sequence's photos in (; UI thread), with what
+ /// the user is told: where a new originals archive went, or why there is none (: title, message, is error).
+ ///
+ public async Task OriginalsForDownloadAsync(Sequence? local, Action notify)
+ {
+ ArgumentNullException.ThrowIfNull(notify);
+ try
{
- var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
- if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
- is { } current) return current;
+ var target = await OriginalsArchiveAsync(local);
+ if (target.ArchiveId is null) notify(Loc.L("Errors.Sync.NoArchive"), null, true);
+ else if (target.Created is { } made) notify(Loc.L("Shell.Homes.Originals"), AppEnvironment.Shown(made), false);
+ return target.ArchiveId;
}
- return archives.Count == 1 ? archives[0] : null;
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or DatabaseException)
+ {
+ Log.Warning("sync", "The originals archive of the signed-in server could not be made", ex);
+ notify(Loc.L("Errors.Sync.NoOriginalsFolder", services.Server.ServerName ?? Server ?? string.Empty), null, true);
+ return null;
+ }
+ }
+
+ /// The archives of the known servers' downloaded originals that the index holds (the scan schedule scans them too).
+ public async Task> OriginalsArchivesAsync(CancellationToken ct = default)
+ {
+ if (services.Database is not { } db) return [];
+ var ids = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet();
+ if (ids.Count == 0) return [];
+ return [.. (await db.Archives.ListAsync(ct).ConfigureAwait(false)).Where(a => ids.Contains(a.Id))];
}
public async ValueTask ConnectAsync(string server, CancellationToken cancellationToken)
@@ -187,9 +297,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var until = DateTime.UtcNow + RestoreWait;
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
await Task.Delay(500, cancellationToken);
- if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
+ // A job queued under an address the server was reached under before it told its id reaches it all the same.
+ if (Volatile.Read(ref _credentials) is not { } c || !Identity.Same(c.Key, server)) return null;
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
- return RemoteFactory(c.Address, c.Token, c.Fingerprints);
+ return RemoteFactory(c.Address, c.Token, c.Fingerprints, c.Key);
}
///
@@ -240,9 +351,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
_ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload);
}
- /// Key of the server of the saved session (Disconnect keeps it); null without one.
+ /// The key of the server this PC is signed in to, else of the saved session's; null without either.
+ public string? LastServer => Server ?? SavedServer();
+
+ /// Key of the server of the saved session (Disconnect keeps it), its id key when it is known by id; null without one.
private string? SavedServer() =>
- services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? SyncService.ServerKey(address) : null;
+ services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? Identity.Canonical(SyncService.ServerKey(address)) : null;
private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload)
{
@@ -265,6 +379,89 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
}
}
+ ///
+ /// Records the signed-in server in (UI thread): its id, name, address, certificate,
+ /// and the address key it was reached by as an alias; the settings are written only when something changed. A known id
+ /// presented with another certificate and another name is told ().
+ ///
+ private void Remember(Guid id, Uri address, ServerInfo info)
+ {
+ var settings = services.Settings;
+ var alias = SyncService.ServerKey(address);
+ var shown = ServerAddress.Display(address);
+ var known = settings.FindKnownServer(id);
+ var changed = false;
+ if (known is null)
+ {
+ known = new KnownServer { Id = id, Name = info.Name, LastAddress = shown, Fingerprint = info.TlsFingerprint };
+ settings.KnownServers.Add(known);
+ changed = true;
+ Log.Info("sync", $"Server {info.Name} is known by its id {id} from now on (reached at {shown})");
+ }
+ else if (known.Fingerprint is { Length: > 0 } before && info.TlsFingerprint is { Length: > 0 } now
+ && !string.Equals(before, now, StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(known.Name, info.Name, StringComparison.Ordinal))
+ {
+ Log.Warning("sync", $"Server id {id} was {known.Name} with another certificate; it is {info.Name} now: two servers may share one copied database");
+ IdentityClash?.Invoke(info.Name, known.Name ?? shown);
+ }
+ if (!known.Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase))
+ {
+ known.Aliases.Add(alias);
+ changed = true;
+ }
+ if (!string.Equals(known.Name, info.Name, StringComparison.Ordinal) || !string.Equals(known.LastAddress, shown, StringComparison.OrdinalIgnoreCase)
+ || (info.TlsFingerprint is { Length: > 0 } fingerprint
+ && !string.Equals(known.Fingerprint, fingerprint, StringComparison.OrdinalIgnoreCase)))
+ {
+ (known.Name, known.LastAddress, known.Fingerprint) = (info.Name, shown, info.TlsFingerprint ?? known.Fingerprint);
+ changed = true;
+ }
+ if (DateTimeOffset.UtcNow - known.LastSeen > TimeSpan.FromHours(1))
+ {
+ known.LastSeen = DateTimeOffset.UtcNow;
+ changed = true;
+ }
+ if (!changed) return;
+ Volatile.Write(ref _identity, settings.KnownIdentity());
+ services.SavePreferences();
+ }
+
+ ///
+ /// Whatever this PC keeps under the address keys the server of was reached by moves to its
+ /// id (owner review 5, #66: ), before the agent starts. Skipped while a job
+ /// writes into the workspace or the cache, or the workspace is being moved: a later sign-in does it, and the aliases match
+ /// meanwhile. A failure is logged: nothing is lost, and the next sign-in goes on.
+ ///
+ private async Task RekeyAsync(Credentials credentials)
+ {
+ if (credentials.ServerId is not { } id || services.Database is not { } db) return;
+ var aliases = Identity.AliasesOf(id);
+ if (aliases.Count == 0) return;
+ try
+ {
+ if (await db.Jobs.HasPendingAsync(RekeyHeldBy).ConfigureAwait(false))
+ {
+ Log.Info("sync", $"Server {id}: what this PC keeps under its addresses moves to its id at a later sign-in (jobs are under way)");
+ return;
+ }
+ var workspace = services.Workspace;
+ var migration = new HomeLayoutMigration(new HomeLayoutOptions
+ {
+ DataDirectory = services.Environment.DataDirectory,
+ WorkspaceRoot = workspace.IsEnabled && !workspace.IsMoving ? workspace.Root : null,
+ CacheRoot = CacheStore.Folder(services.Environment, services.Settings),
+ Identity = Identity,
+ Database = db,
+ });
+ await migration.RekeyAsync(id, aliases).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
+ {
+ Log.Warning("sync", $"What this PC keeps under the addresses of server {id} could not all move to its id; the next sign-in goes on", ex);
+ }
+ }
+
///
/// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping
/// the old agent when the app exits must not need the UI thread its exit blocks.
@@ -272,7 +469,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private async Task SwitchAsync(Task previous, Credentials? wanted)
{
await previous.ConfigureAwait(false);
- if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
+ if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token
+ && running.Credentials.ServerId == same.ServerId)
return;
var stopped = Volatile.Read(ref _running)?.Remote.Server;
await StopAsync().ConfigureAwait(false);
@@ -283,7 +481,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
Changed?.Invoke();
return;
}
- var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
+ await RekeyAsync(start).ConfigureAwait(false);
+ var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints, start.Key);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
@@ -302,7 +501,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
Changed?.Invoke();
}
- private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection Fingerprints);
+ /// The id the server announced (owner review 5); null for an older server.
+ private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection Fingerprints, Guid? ServerId)
+ {
+ /// The key the server goes by ().
+ public string Key => ServerIdentity.Key(ServerId, Address);
+ }
/// The client project homes share, and the session it was made for.
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
diff --git a/src/Chronos.App/Server/SyncTableViewModel.cs b/src/Chronos.App/Server/SyncTableViewModel.cs
index 080b0772..81c635ac 100644
--- a/src/Chronos.App/Server/SyncTableViewModel.cs
+++ b/src/Chronos.App/Server/SyncTableViewModel.cs
@@ -316,11 +316,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
break;
case SyncAction.DownloadOriginals:
- if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
- {
- _shell.Notify(Loc.L("Errors.Sync.NoArchive"), isError: true);
- return;
- }
+ if (await Host.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => _shell.Notify(title, message, isError: isError)) is not { } archive) return;
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
break;
case SyncAction.GetExports:
diff --git a/src/Chronos.App/Settings/HomeRows.cs b/src/Chronos.App/Settings/HomeRows.cs
new file mode 100644
index 00000000..c0785e15
--- /dev/null
+++ b/src/Chronos.App/Settings/HomeRows.cs
@@ -0,0 +1,97 @@
+using System.IO;
+using System.Windows.Input;
+using Chronos.App.Infrastructure;
+using Chronos.Core.Localization;
+using Chronos.Data.Workspaces;
+using Chronos.Ui.Mvvm;
+
+namespace Chronos.App.Settings;
+
+///
+/// One home's folder in Settings › Workspace › Home folders (owner review 5, #66): "This PC" for the projects of this PC's
+/// archive (local), one row per server for its projects (servers\<id>), with Open.
+///
+public sealed class HomeFolderRow(string name, string path, string toolTip, Action open)
+{
+ public string Name { get; } = name;
+
+ /// The folder as shown (a capture's own folders stand for the real ones).
+ public string Path { get; } = AppEnvironment.Shown(path);
+
+ public string ToolTip { get; } = toolTip;
+
+ public ICommand OpenCommand { get; } = new RelayCommand(() => open(path));
+
+ /// The rows of the workspace's homes: this PC first, then each server by name; none while the workspace is not made.
+ public static IReadOnlyList Of(WorkspaceHomes homes, IReadOnlyList known, Action open)
+ {
+ ArgumentNullException.ThrowIfNull(homes);
+ ArgumentNullException.ThrowIfNull(known);
+ ArgumentNullException.ThrowIfNull(open);
+ if (!homes.IsSplit) return [new HomeFolderRow(Loc.L("Settings.Workspace.ThisPc"), homes.Root, Loc.L("Tooltips.Settings.Workspace.ThisPc", AppEnvironment.Shown(homes.Root)), open)];
+ var rows = new List
+ {
+ new(Loc.L("Settings.Workspace.ThisPc"), homes.LocalRoot, Loc.L("Tooltips.Settings.Workspace.ThisPc", AppEnvironment.Shown(homes.LocalRoot)), open),
+ };
+ foreach (var home in homes.Homes().Where(h => h is { IsLocal: false, IsLegacy: false }).OrderBy(h => NameOf(h, known), StringComparer.CurrentCultureIgnoreCase))
+ {
+ var name = NameOf(home, known);
+ rows.Add(new HomeFolderRow(name, home.Store.Root,
+ Loc.L("Tooltips.Settings.Workspace.ServerHome", name, AppEnvironment.Shown(home.Store.Root)), open));
+ }
+ return rows;
+ }
+
+ /// The server's name as this PC knows it, else as its folder records it, else the folder's name.
+ private static string NameOf(WorkspaceHome home, IReadOnlyList known) =>
+ (home.Server?.Id is { } id ? known.FirstOrDefault(k => k.Id == id)?.Name : null)
+ ?? home.Server?.Name ?? home.Server?.Address ?? System.IO.Path.GetFileName(home.Store.Root);
+}
+
+///
+/// A server this PC signed in to, in Settings › Server › Known servers (owner review 5, #66): its name, last address, id
+/// (short, the whole one in the tooltip), whether this PC is signed in to it now, and its folders: the archive of its
+/// downloaded originals and its share of the cache, each with Open.
+///
+public sealed class KnownServerRow
+{
+ private readonly string? _originals;
+ private readonly string _cache;
+
+ public KnownServerRow(KnownServer server, bool signedIn, string? originalsRoot, string cacheFolder, Action open)
+ {
+ ArgumentNullException.ThrowIfNull(server);
+ ArgumentNullException.ThrowIfNull(open);
+ Server = server;
+ IsSignedIn = signedIn;
+ _originals = originalsRoot;
+ _cache = cacheFolder;
+ OpenOriginalsCommand = new RelayCommand(() => open(_originals!), () => _originals is not null && Directory.Exists(_originals));
+ OpenCacheCommand = new RelayCommand(() => open(_cache), () => Directory.Exists(_cache));
+ }
+
+ public KnownServer Server { get; }
+
+ public string Name => Server.Name is { Length: > 0 } name ? name : Server.LastAddress ?? Server.Id.ToString("N");
+
+ public string Address => Server.LastAddress ?? "—";
+
+ /// The first 8 hex digits of the id; the tooltip has it whole.
+ public string ShortId => Server.Id.ToString("N")[..8];
+
+ public string IdToolTip => Loc.L("Tooltips.Settings.Server.ServerId", Server.Id.ToString("D"));
+
+ public bool IsSignedIn { get; }
+
+ public string StateText => Loc.L(IsSignedIn ? "Settings.Server.SignedIn" : "Settings.Server.Offline");
+
+ public string StateToolTip => Loc.L(IsSignedIn ? "Tooltips.Settings.Server.SignedIn" : "Tooltips.Settings.Server.Offline");
+
+ public string OriginalsPath => _originals is null ? "—" : AppEnvironment.Shown(_originals);
+
+ public string CachePath => AppEnvironment.Shown(_cache);
+
+ public ICommand OpenOriginalsCommand { get; }
+
+ public ICommand OpenCacheCommand { get; }
+}
diff --git a/src/Chronos.App/Videos/VideoSources.cs b/src/Chronos.App/Videos/VideoSources.cs
index 537de7d6..ff608783 100644
--- a/src/Chronos.App/Videos/VideoSources.cs
+++ b/src/Chronos.App/Videos/VideoSources.cs
@@ -429,25 +429,37 @@ public static class VideoSources
public static IReadOnlyList ReadWorkspace(WorkspaceStore store, IEnumerable projects)
{
ArgumentNullException.ThrowIfNull(store);
+ return ReadWorkspace(store.Project, projects);
+ }
+
+ /// The workspace renders of every project, each read in its own home's folder (local\, servers\<id>\).
+ public static IReadOnlyList ReadWorkspace(WorkspaceHomes homes, IEnumerable projects)
+ {
+ ArgumentNullException.ThrowIfNull(homes);
+ return ReadWorkspace(id => homes.Find(id) ?? homes.Local.Project(id), projects);
+ }
+
+ private static List ReadWorkspace(Func project, IEnumerable projects)
+ {
ArgumentNullException.ThrowIfNull(projects);
var entries = new List();
- foreach (var project in projects.Where(p => p.IsReadable))
+ foreach (var entry in projects.Where(p => p.IsReadable))
{
try
{
- var folder = store.Project(project.ProjectId);
+ var folder = project(entry.ProjectId);
foreach (var render in folder.ReadRenders().Entries)
{
var path = folder.ExportFile(render.File);
var exists = File.Exists(path) || Directory.Exists(path);
// A sent render whose file left exports/ is safe at its home, whose entry stands for it: never "missing".
if (render.IsSent && !exists) continue;
- entries.Add(FromWorkspace(render, project, path, exists));
+ entries.Add(FromWorkspace(render, entry, path, exists));
}
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
- Log.Warning("videos", $"The render ledger of workspace project {project.ProjectId} cannot be read", ex);
+ Log.Warning("videos", $"The render ledger of workspace project {entry.ProjectId} cannot be read", ex);
}
}
return entries;
diff --git a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
index 5f99dba6..da5e0fcf 100644
--- a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
+++ b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
@@ -986,7 +986,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
///
private void OnHomeChanged(WorkspaceHomeChange change)
{
- if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase)))
+ if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !_host.SameServer(change.Server, Home.Server)))
return;
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
else _ = HomeChangedAsync(change);
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs b/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
index 3bd71f68..cca04bc8 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
@@ -36,6 +36,12 @@ public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyListNothing to erase: Empty… is disabled.
public bool IsEmpty => Items.Count == 0;
+
+ ///
+ /// The trash of each home the plan lists (owner review 5, separate homes: local\ and each servers\<id>\
+ /// keep their own), each with its own fingerprint; emptying erases each one only while all of them still match.
+ ///
+ public IReadOnlyList Listings { get; init; } = [];
}
/// What emptying the workspace's trash erased.
@@ -63,21 +69,28 @@ public sealed partial class WorkspaceHost
var root = Root;
if (!Directory.Exists(root)) return WorkspaceUsage.None;
var media = 0L;
- foreach (var folder in Directory.EnumerateDirectories(root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)))
+ foreach (var store in Homes.All())
{
- cancellationToken.ThrowIfCancellationRequested();
- media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
+ if (!Directory.Exists(store.Root)) continue;
+ foreach (var folder in Directory.EnumerateDirectories(store.Root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
+ }
}
- var trash = WorkspaceTrash.List(root, cancellationToken);
- return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Bytes, trash.Entries.Count);
+ var trash = Homes.Trash(cancellationToken);
+ return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Sum(t => t.Bytes), trash.Sum(t => t.Entries.Count));
}, cancellationToken);
- /// The plan of emptying the workspace's trash (); nothing is erased.
+ /// The plan of emptying the trash of every home of the workspace (); nothing is erased.
public Task PlanTrashAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{
- var listing = WorkspaceTrash.List(Root, cancellationToken);
- return new WorkspaceTrashPlan(listing.Folder, [.. listing.Entries.Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))], listing.Bytes,
- listing.Fingerprint);
+ var listings = Homes.Trash(cancellationToken);
+ var folder = listings.Count == 1 ? listings[0].Folder : WorkspaceTrash.FolderOf(Root);
+ var fingerprint = string.Join('|', listings.Select(l => l.Folder + "=" + l.Fingerprint));
+ return new WorkspaceTrashPlan(folder, [.. listings.SelectMany(l => l.Entries).Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))
+ .OrderBy(i => i.Trashed)], listings.Sum(l => l.Bytes), fingerprint)
+ { Listings = listings };
}, cancellationToken);
///
@@ -92,11 +105,25 @@ public sealed partial class WorkspaceHost
return Task.Run(() =>
{
EnsureNotMoving();
- var listing = new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
- plan.Fingerprint);
+ IReadOnlyList listings = plan.Listings.Count > 0 ? plan.Listings
+ : [new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
+ plan.Fingerprint)];
try
{
- var (items, bytes) = WorkspaceTrash.Empty(Root, listing, cancellationToken);
+ // Every trash is checked before any is emptied: a plan is erased whole or not at all.
+ foreach (var listing in listings)
+ {
+ var now = WorkspaceTrash.List(Path.GetDirectoryName(listing.Folder)!, cancellationToken);
+ if (!string.Equals(now.Fingerprint, listing.Fingerprint, StringComparison.Ordinal))
+ throw new WorkspaceTrashChangedException($"The trash {now.Folder} changed after it was listed.");
+ }
+ var (items, bytes) = (0, 0L);
+ foreach (var listing in listings.Where(l => !l.IsEmpty))
+ {
+ var (erased, freed) = WorkspaceTrash.Empty(Path.GetDirectoryName(listing.Folder)!, listing, cancellationToken);
+ items += erased;
+ bytes += freed;
+ }
return new WorkspaceTrashResult(items, bytes);
}
catch (WorkspaceTrashChangedException ex)
@@ -130,7 +157,7 @@ public sealed partial class WorkspaceHost
await _cleaning.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
- var cleaner = new WorkspaceCleaner(Sync, db, HomeOf) { LockWait = LockWait };
+ var cleaner = new WorkspaceCleaner(AllSyncs(), db, HomeOf) { LockWait = LockWait };
return await Task.Run(() => cleaner.CleanAsync(options, cancellationToken), cancellationToken).ConfigureAwait(false);
}
finally
@@ -147,10 +174,7 @@ public sealed partial class WorkspaceHost
{
ArgumentNullException.ThrowIfNull(job);
if (job is not { Kind: JobKind.WorkspaceCopy, State: JobState.Done } || _settings.WorkspaceSizeLimitGb <= 0) return;
- if (WorkspaceJobs.CopyParameters(job) is not { } copied
- || !string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(copied.WorkspaceRoot)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root)),
- StringComparison.OrdinalIgnoreCase))
- return;
+ if (WorkspaceJobs.CopyParameters(job) is not { } copied || !IsUnderRoot(copied.WorkspaceRoot)) return;
_ = Task.Run(async () =>
{
try
@@ -165,6 +189,16 @@ public sealed partial class WorkspaceHost
});
}
+ /// The folder is the workspace's own or one of its homes (local\, servers\<id>\).
+ private bool IsUnderRoot(string folder)
+ {
+ if (string.IsNullOrWhiteSpace(folder)) return false;
+ var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root));
+ var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
+ return string.Equals(full, root, StringComparison.OrdinalIgnoreCase)
+ || full.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
+ }
+
/// When each project was opened last, as Settings hold it now (written on the UI thread: copied until a copy reads whole).
private IReadOnlyDictionary OpenedSnapshot()
{
@@ -331,7 +365,7 @@ public sealed partial class WorkspaceHost
if (WorkspaceJobs.SendParameters(pending)?.ProjectId == project.ProjectId) return;
}
var title = project.ReadBundle().Sequence.Title ?? string.Empty;
- var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, Store.Root, project.ProjectId, [], workspace.Home.Server),
+ var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, project.Store.Root, project.ProjectId, [], workspace.Home.Server),
cancellationToken: cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"The renders of project {project.ProjectId} not sent yet are queued to be sent (job {job.Id})");
}
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.Move.cs b/src/Chronos.App/Workspace/WorkspaceHost.Move.cs
index a1477008..093690f5 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.Move.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.Move.cs
@@ -268,13 +268,13 @@ public sealed partial class WorkspaceHost
/// A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).
private async Task MoveProjectAsync(WorkspaceMoveFolder folder, CancellationToken cancellationToken)
{
- var project = Store.Project(folder.ProjectId);
+ var project = Find(folder.ProjectId) ?? Homes.Local.Project(folder.ProjectId);
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
// What a copy this Chronos cannot read holds is not known: it moves as it is, counted as work not at its home.
if (!entry.IsReadable) return new WorkspaceMoveProject(folder.ProjectId, entry.KnownName ?? entry.Name, folder.Files, folder.Bytes, true, false);
try
{
- var status = await Sync.StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
+ var status = await SyncOf(folder.ProjectId).StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
var renders = WorkspaceCleaner.UnsentRenders(project);
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null,
status.Modified && !status.ReadOnly);
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs
index 442a1150..97705210 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.cs
@@ -12,6 +12,7 @@ using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
+using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
@@ -203,27 +204,77 @@ public sealed partial class WorkspaceHost
public AppSettings Settings => _settings;
- /// The sync over the workspace folder in use (made, with the folder and its manifest, at first use).
+ ///
+ /// The servers known by id and their aliases (owner review 5, #66; the desktop's SyncHost.Identity): a server home's
+ /// folder is named by its server's canonical key. Unset, every key is its own.
+ ///
+ public Func? Identity { get; set; }
+
+ /// The two server keys name the same server (its id key and the addresses it was reached by, ).
+ public bool SameServer(string? left, string? right) => (Identity?.Invoke() ?? ServerIdentity.None).Same(left, right);
+
+ ///
+ /// The workspace folder in use split into its homes (owner review 5, #66: local for this PC's archive,
+ /// servers\<id> for each server; a folder still in the 1.0 layout is one store until its folders are sorted),
+ /// made, with the folder and its manifest, at first use.
+ ///
/// The folder cannot be made or read.
/// The folder holds another program's or a newer workspace manifest.
- public WorkspaceSync Sync
+ public WorkspaceHomes Homes
{
get
{
var root = Root;
+ var identity = Identity?.Invoke() ?? ServerIdentity.None;
lock (_gate)
{
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
- {
- var store = new WorkspaceStore(root);
- _open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
- }
- return open.Sync;
+ _open = open = new OpenWorkspace(root, new WorkspaceHomes(root, identity));
+ open.Homes.Identity = identity;
+ return open.Homes;
}
}
}
- public WorkspaceStore Store => Sync.Store;
+ /// Opens the folder in use again at next use (after its folders were sorted into homes: its layout changed).
+ public void Reopen()
+ {
+ lock (_gate) _open = null;
+ }
+
+ /// The project's folder in whichever home holds it; null when the workspace has none.
+ public WorkspaceProject? Find(Guid projectId) => Homes.Find(projectId);
+
+ /// The sync over the store of the home that holds .
+ /// The workspace has no such project (Errors.Workspace.NotCheckedOut).
+ public WorkspaceSync SyncOf(Guid projectId) => SyncOf(Existing(projectId).Store);
+
+ /// The sync over the store a project of is checked out into (made, with its manifest, when it is not there).
+ public WorkspaceSync SyncFor(BundleHome home) => SyncOf(Homes.StoreFor(home));
+
+ /// The sync over (one per store of the folder in use).
+ public WorkspaceSync SyncOf(WorkspaceStore store)
+ {
+ ArgumentNullException.ThrowIfNull(store);
+ _ = Homes;
+ lock (_gate)
+ {
+ var open = _open!;
+ if (!open.Syncs.TryGetValue(store.Root, out var sync))
+ {
+ sync = new WorkspaceSync(store, ClientName) { LockWait = LockWait };
+ open.Syncs[store.Root] = sync;
+ }
+ return sync;
+ }
+ }
+
+ /// The syncs of every home's store (the clean-up counts them together).
+ private IReadOnlyList AllSyncs()
+ {
+ var stores = Homes.All();
+ return stores.Count == 0 ? [SyncOf(Homes.Local)] : [.. stores.Select(SyncOf)];
+ }
///
/// The project home of a server home (phase 5b; the desktop's SyncHost.ProjectHome): null while this PC is not
@@ -273,8 +324,8 @@ public sealed partial class WorkspaceHost
BundleHome home;
try
{
- if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
- || !string.Equals(held.Server, server, StringComparison.OrdinalIgnoreCase))
+ if (!IsAvailable || Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
+ || !SameServer(held.Server, server))
return;
home = held;
}
@@ -298,7 +349,7 @@ public sealed partial class WorkspaceHost
{
// Nothing is written into a folder being moved: the next status read takes the name.
if (IsMoving) Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} waits for the workspace's move");
- else if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
+ else if (HomeOf(home) is { } reached) await SyncOf(change.ProjectId).FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -316,7 +367,7 @@ public sealed partial class WorkspaceHost
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
var entries = new List();
- foreach (var project in Store.List())
+ foreach (var project in Homes.List())
{
try
{
@@ -345,7 +396,7 @@ public sealed partial class WorkspaceHost
{
EnsureNotMoving();
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
- return Store.Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
+ return Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
}, cancellationToken);
/// Why a copy this Chronos cannot read neither opens nor is checked out over: a newer Chronos wrote it, or it is damaged.
@@ -381,7 +432,7 @@ public sealed partial class WorkspaceHost
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);
+ await Task.Run(() => new WorkspaceHomes(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();
@@ -470,10 +521,10 @@ public sealed partial class WorkspaceHost
: listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet.");
}
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
- if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
+ if (Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
throw Unreadable(unreadable);
- var folder = await Sync.CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
- Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
+ var folder = await SyncFor(home).CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
+ Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {folder.Store.Root}");
var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
@@ -507,14 +558,14 @@ public sealed partial class WorkspaceHost
var home = askHome ? HomeOf(named) : null;
try
{
- if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
- return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ if (askHome && home is null && !named.IsArchive) return Offline(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
+ return await SyncOf(projectId).StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
{
var gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound };
Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"The home of project {projectId} could not be asked: {ex.Message}");
- var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var local = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
return local with
{
Offline = true,
@@ -545,8 +596,8 @@ public sealed partial class WorkspaceHost
var version = await Task.Run(async () =>
{
EnsureNotMoving();
- EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
- return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
+ EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
+ return await SyncOf(projectId).CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
@@ -568,8 +619,8 @@ public sealed partial class WorkspaceHost
public Task CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
- EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
- return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
+ EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
+ return await SyncOf(projectId).CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
///
@@ -583,10 +634,10 @@ public sealed partial class WorkspaceHost
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
- var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pulled = await SyncOf(projectId).PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
// Deleted at the library: nothing to send, nothing to prune; the copy stays as it is.
if (pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone) return pulled;
- var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pushed = await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
@@ -609,16 +660,16 @@ public sealed partial class WorkspaceHost
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
try
{
- resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false);
+ resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false);
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
{
- resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
+ resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
}
else
{
- resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
+ resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
if (resolved.Status.State == WorkspaceState.Conflict)
{
@@ -628,7 +679,7 @@ public sealed partial class WorkspaceHost
// Deleted in the library: nothing more to send (a Save both's copy holds the versions already).
if (resolved.Status.State == WorkspaceState.Gone) return resolved;
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
- var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pushed = await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs)
{
Kept = resolved.Kept,
@@ -652,11 +703,11 @@ public sealed partial class WorkspaceHost
public Task RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
- var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var status = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
- var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
+ var restored = await SyncOf(projectId).RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
return restored;
}, cancellationToken);
@@ -665,7 +716,7 @@ public sealed partial class WorkspaceHost
public Task HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
- var unsent = Sync.Unpushed(projectId);
+ var unsent = SyncOf(projectId).Unpushed(projectId);
var home = HomeOf(project.ReadBundle().Workspace!.Home);
IReadOnlyList stored;
var offline = false;
@@ -740,9 +791,9 @@ public sealed partial class WorkspaceHost
var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
var home = HomeOfProject(projectId);
- var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var local = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
- if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
+ if (!local.ReadOnly) await SyncOf(projectId).CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
@@ -773,7 +824,7 @@ public sealed partial class WorkspaceHost
/// A conflict waits (open the project and Sync to settle it), or something is still not at the home.
public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default)
{
- var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
+ var local = await Task.Run(() => SyncOf(projectId).StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false);
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
@@ -837,7 +888,7 @@ public sealed partial class WorkspaceHost
var workspace = project.ReadBundle().Workspace!;
if (!discard)
{
- var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
+ var status = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Unsent(workspace.Home));
@@ -894,8 +945,8 @@ public sealed partial class WorkspaceHost
/// The local versions sent (after the home's new ones were taken), as one sync without the pruning.
private async Task SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
- var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
- return pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ var pulled = await SyncOf(projectId).PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
+ return pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone ? pulled : await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
/// The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.
@@ -948,7 +999,7 @@ public sealed partial class WorkspaceHost
{ State: JobState.Queued or JobState.Running or JobState.Paused })
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
// Filled under a staging name Empty… never lists, and named once whole.
- using var trash = WorkspaceTrash.Begin(Store.Root, project.ProjectId, DateTime.UtcNow);
+ using var trash = WorkspaceTrash.Begin(project.Store.Root, project.ProjectId, DateTime.UtcNow);
var aside = trash.Path;
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
@@ -1087,11 +1138,12 @@ public sealed partial class WorkspaceHost
{
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index.");
- request = WorkspaceJobs.Copy(sequence, Store.Root, projectId, media);
+ request = WorkspaceJobs.Copy(sequence, Existing(projectId).Store.Root, projectId, media);
}
else
{
- request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."), Store.Root,
+ request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."),
+ Existing(projectId).Store.Root,
projectId, media);
}
var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -1108,7 +1160,7 @@ public sealed partial class WorkspaceHost
: "This PC is not signed in to the server of the project, or it keeps no projects.");
}
- private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
+ private WorkspaceProject Existing(Guid projectId) => Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
{
@@ -1206,14 +1258,20 @@ public sealed partial class WorkspaceHost
}
}
- /// The projects a workspace folder holds (folders named by a project id with a working state), without making or opening it.
+ ///
+ /// The projects a workspace folder holds (folders named by a project id with a working state), in it and in its homes'
+ /// folders (local, servers\<folder>, owner review 5), 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)));
+ var stores = new List { folder, HomeFolders.LocalPath(folder) };
+ var servers = Path.Combine(folder, HomeFolders.Servers);
+ if (Directory.Exists(servers)) stores.AddRange(Directory.EnumerateDirectories(servers).Where(d => HomeFolders.IsServerFolder(Path.GetFileName(d))));
+ return stores.Where(Directory.Exists).Sum(store => Directory.EnumerateDirectories(store).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)
{
@@ -1236,5 +1294,9 @@ public sealed partial class WorkspaceHost
return (files, bytes);
}
- private sealed record OpenWorkspace(string Root, WorkspaceSync Sync);
+ /// The workspace folder in use, its homes and the sync of each of its stores (by root).
+ private sealed record OpenWorkspace(string Root, WorkspaceHomes Homes)
+ {
+ public Dictionary Syncs { get; } = new(StringComparer.OrdinalIgnoreCase);
+ }
}
diff --git a/src/Chronos.Core.Windows/Shell/AppPaths.cs b/src/Chronos.Core.Windows/Shell/AppPaths.cs
index 19647f6f..9f750891 100644
--- a/src/Chronos.Core.Windows/Shell/AppPaths.cs
+++ b/src/Chronos.Core.Windows/Shell/AppPaths.cs
@@ -7,7 +7,7 @@ namespace Chronos.Core.Windows.Shell;
/// .\data next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable
/// copy in a OneDrive folder keeps its data in %LOCALAPPDATA%\Chronos instead (
/// names that folder to tell the user, the data it kept there before), and a data
-/// root still under OneDrive is reported by and refused by .
+/// root still under OneDrive is reported by .
///
public sealed class AppPaths
{
@@ -35,8 +35,6 @@ public sealed class AppPaths
public string CacheDirectory => Path.Combine(DataRoot, "cache");
- public string ThumbnailsDirectory => Path.Combine(DataRoot, "thumbnails");
-
/// The OneDrive sync root containing , or null when the location is safe.
public string? SyncedFolder { get; }
@@ -69,16 +67,4 @@ public sealed class AppPaths
: null;
return new AppPaths(location, earlier);
}
-
- /// Creates the data, logs, cache and thumbnails folders.
- /// The data root lies inside a OneDrive-synced folder.
- public void CreateDirectories()
- {
- if (SyncedFolder is not null)
- throw new InvalidOperationException($"The data folder '{DataRoot}' is inside the OneDrive folder '{SyncedFolder}'; the database would be corrupted by synchronisation.");
- Directory.CreateDirectory(DataRoot);
- Directory.CreateDirectory(LogsDirectory);
- Directory.CreateDirectory(CacheDirectory);
- Directory.CreateDirectory(ThumbnailsDirectory);
- }
}
diff --git a/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
index a2fd9cc2..3841b2a9 100644
--- a/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+using System.IO;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
@@ -50,7 +51,7 @@ public sealed class ServerHomeTests(TestContext context)
// Checked out from the server: its media are downloaded by a copy job that names the server, never this PC's archive.
var checkout = await host.CheckoutAsync(named, null, null, cancellationToken: bed.Ct);
- var bundle = host.Store.Find(checkout.Project.Id)!.ReadBundle();
+ var bundle = host.Find(checkout.Project.Id)!.ReadBundle();
Assert.Equal((BundleHome.ServerKind, Server, bed.SequenceId), (bundle.Workspace!.Home.Kind, bundle.Workspace.Home.Server, bundle.Workspace.Home.SequenceId));
using (var parameters = JsonDocument.Parse(checkout.Copy.ParametersJson!))
{
@@ -83,8 +84,8 @@ public sealed class ServerHomeTests(TestContext context)
var other = bed.Host(name: "other-pc");
var otherId = await bed.CheckoutAsync(other);
Assert.Equal(projectId, otherId);
- var session = await other.Sync.OpenAsync(projectId, bed.Ct);
- await other.Sync.SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
+ var session = await other.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
+ await other.SyncOf(projectId).SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
await other.SaveVersionAsync(projectId, null, bed.Ct);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Behind, 1), (status.State, status.Behind));
@@ -109,13 +110,46 @@ public sealed class ServerHomeTests(TestContext context)
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Gone.Server"), WorkspaceText.StateToolTip(status, server: true));
Assert.Equal(StatusKind.Warning, WorkspaceText.Kind(status));
- Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
+ Assert.NotNull(host.Find(projectId)?.ReadMedia());
// A server that answers 404 for the project itself (deleted with its sequence) is gone too.
server.Deleted.Clear();
server.Missing = true;
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
}
+ [Test]
+ public async Task EachHomeChecksOutIntoItsOwnFolderAndTheServerIsOneByItsId()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
+ var serverId = Guid.CreateVersion7();
+ var idKey = Chronos.Core.IO.HomeFolders.IdKey(serverId);
+ var host = bed.Host();
+ host.Identity = () => new Chronos.Data.Sync.ServerIdentity([new Chronos.Data.Sync.KnownServerKey(serverId, [Server])]);
+ var server = new FakeServer(bed);
+ host.ServerHomes = home => host.SameServer(home.Server, idKey) && home.SequenceId == server.Inner.SequenceId ? server : null;
+
+ // A server project goes into the server's folder, named by its id even though the project names its address.
+ var checkout = await host.CheckoutAsync(ServerHome(bed), null, null, cancellationToken: bed.Ct);
+ var folder = host.Find(checkout.Project.Id)!;
+ Assert.Equal(Path.Combine(host.Root, "servers", serverId.ToString("N")), folder.Store.Root);
+ Assert.Equal(Server, folder.ReadBundle().Workspace!.Home.Server);
+ Assert.True(host.SameServer(Server, idKey), "the address is an alias of the id");
+ Assert.False(host.SameServer("https://elsewhere:8443", idKey));
+
+ // The server told by its id reaches the project that names its address.
+ var told = new List();
+ host.HomeChanged += told.Add;
+ host.OnServerProjectChanged(idKey, new ProjectChangedEvent(bed.SequenceId, checkout.Project.Id, ProjectChanges.Pushed, 2, Guid.CreateVersion7()));
+ Assert.Equal(checkout.Project.Id, told.Single().ProjectId);
+
+ // A project of this PC's archive goes into local\, and the picker lists both.
+ var other = bed.Host(name: "second");
+ var localId = await bed.CheckoutAsync(other);
+ Assert.Equal(Path.Combine(other.Root, "local"), other.Find(localId)!.Store.Root);
+ Assert.SequenceEqual([checkout.Project.Id], host.Homes.List().Select(p => p.ProjectId).ToArray());
+ Assert.Count(1, (await host.ListAsync(bed.Ct)).Where(e => e.ProjectId == checkout.Project.Id));
+ }
+
[Test]
public void TheServersProjectChangesReachOnlyTheProjectsItIsHomeOf()
{
@@ -146,7 +180,7 @@ public sealed class ServerHomeTests(TestContext context)
// Opened signed out; the sign-in made later is the one the source connects with.
FakeRemoteSequenceApi? signedIn = null;
- var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => signedIn, () => signedIn));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -181,7 +215,7 @@ public sealed class ServerHomeTests(TestContext context)
// In step with the server: the render names the version it holds, whose settings the server renders.
Assert.True(await menu.ReadyToRenderAsync(), "nothing to send");
Assert.Empty(ui.Confirmations);
- var basis = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
+ var basis = host.Find(projectId)!.ReadBundle().Workspace!.Base!;
var (held, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?, string?)>((projectId, basis.VersionId, null), (held.ProjectId, held.ProjectVersionId, held.SettingsJson));
@@ -198,7 +232,7 @@ public sealed class ServerHomeTests(TestContext context)
ui.ConfirmAnswer = true;
Assert.True(await menu.ReadyToRenderAsync(), "saved and sent: the server holds it");
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
- var sent = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
+ var sent = host.Find(projectId)!.ReadBundle().Workspace!.Base!;
Assert.NotEqual(basis.VersionId, sent.VersionId);
var (version, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, string?)>((sent.VersionId, null), (version.ProjectVersionId, version.SettingsJson));
@@ -219,8 +253,8 @@ public sealed class ServerHomeTests(TestContext context)
// Another PC sends a version and the server says so: the chip reads Server newer at once.
var other = bed.Host(name: "other-pc");
await bed.CheckoutAsync(other);
- var theirs = await other.Sync.OpenAsync(projectId, bed.Ct);
- await other.Sync.SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
+ var theirs = await other.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
+ await other.SyncOf(projectId).SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
var stored = (await other.SaveVersionAsync(projectId, null, bed.Ct)).Version!;
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, stored.Number, stored.Id));
Assert.Equal(projectId, told.Single().ProjectId);
@@ -240,7 +274,7 @@ public sealed class ServerHomeTests(TestContext context)
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), menu.StateText);
Assert.False(await menu.ReadyToRenderAsync(), "nothing to render it from");
Assert.True(ui.Toasts[^1].IsError);
- Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
+ Assert.NotNull(host.Find(projectId)?.ReadMedia());
}
}
@@ -260,7 +294,7 @@ public sealed class ServerHomeTests(TestContext context)
var server = new FakeServer(bed) { SettingsFormat = ProjectSettings.BaseVersion };
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
- var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => null, () => null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -282,9 +316,9 @@ public sealed class ServerHomeTests(TestContext context)
Assert.False(menu.SyncCommand.CanExecute(null));
Assert.False(await menu.ReadyToRenderAsync(), "the server cannot read it");
Assert.Equal((Loc.L("Editor.Workspace.RenderHeld"), true), (ui.Toasts[^1].Title, ui.Toasts[^1].IsError));
- var before = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
+ var before = host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
await menu.SyncAsync();
- Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
+ Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// Saved as a version with the turn, then turned back: the working state is of the base format, but the version
// waiting to be sent is not. Sync stays disabled, and the workspace itself never sends it (Send first, Delete,
@@ -300,7 +334,7 @@ public sealed class ServerHomeTests(TestContext context)
var refused = await Assert.ThrowsAsync(() => host.SyncAsync(projectId, bed.Ct));
Assert.True(refused.HomeReadsOlderFormat);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), WorkspaceText.Failure(refused, server: true));
- Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
+ Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// A server of this format takes it.
server.SettingsFormat = ProjectSettings.CurrentVersion;
@@ -323,7 +357,7 @@ public sealed class ServerHomeTests(TestContext context)
private static async Task CheckoutAsync(WorkspaceTestBed bed, WorkspaceHost host)
{
var projectId = await bed.CheckoutAsync(host);
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var bundle = folder.ReadBundle();
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = ServerHome(bed) } });
return projectId;
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
index 2863b2fe..3972c44e 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
@@ -36,7 +36,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
var host = bed.Host(settings);
var mainId = await bed.CheckoutAsync(host);
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
// Open in Edit: kept, with why.
@@ -66,7 +66,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
- Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
+ Assert.True(host.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
}
@@ -76,7 +76,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
Directory.CreateDirectory(project.ExportsDirectory);
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
@@ -90,7 +90,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
- Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
+ Assert.NotNull(host.Find(mainId), "nothing was removed");
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
@@ -102,7 +102,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host();
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
- var folder = WorkspaceTrash.FolderOf(host.Root);
+ var folder = WorkspaceTrash.FolderOf(host.Homes.Local.Root);
foreach (var name in new[] { "a", "b" })
{
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
index 12ff6d73..077927b6 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.cs
@@ -50,7 +50,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
Assert.Equal(0.4, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
Assert.Equal(libraryBefore, (await bed.RowAsync()).SettingsJson, "editing never writes the library");
Assert.Equal(WorkspaceState.Modified, (await host.StatusAsync(projectId)).State);
@@ -72,12 +72,12 @@ public sealed class WorkspaceEditorTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
var host = bed.Host();
var projectId = await bed.CheckoutAsync(host);
- var impatient = new WorkspaceSync(host.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
+ var impatient = new WorkspaceSync(host.Find(projectId)!.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
var source = new WorkspaceSequenceSource(impatient, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine);
await using (source)
{
// A long sync or copy holds the project: the editor says so in words, and nothing was read.
- using (await host.Store.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
+ using (await host.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
{
var busy = await Assert.ThrowsAsync(() => source.LoadAsync(bed.Ct));
Assert.Equal(Loc.L("Errors.Workspace.Busy"), busy.Message);
@@ -328,7 +328,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
Assert.Equal(excluded, session.Content.Frames[3].Id);
Assert.True(session.Edit(p => Exposure(p, 0.2)));
Assert.True(await session.FlushAsync(), "saves go on over the new frames");
- Assert.SequenceEqual([3], host.Store.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
+ Assert.SequenceEqual([3], host.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
}
}
}
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
index 31953661..09fd4aec 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs
@@ -62,7 +62,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
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));
+ Assert.FileExists(Path.Combine(first, "local", 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));
@@ -155,7 +155,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.True(await session.FlushAsync());
}
var unsent = (await host.SaveVersionAsync(mainId, "Not sent")).Version!;
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
await File.WriteAllTextAsync(project.BundlePath, "{ this is not a project", bed.Ct);
// A file this Chronos does not know (a newer one's, the user's own): Discard keeps it too.
await File.WriteAllTextAsync(Path.Combine(project.Folder, "notes.txt"), "kept", bed.Ct);
@@ -195,11 +195,11 @@ public sealed class WorkspaceFallbackTests(TestContext context)
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");
+ Assert.NotNull(host.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)),
+ Assert.Null(host.Find(mainId));
+ var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(mainId.ToString("N"), StringComparison.Ordinal));
Assert.Equal("{ this is not a project", await File.ReadAllTextAsync(Path.Combine(aside, WorkspaceProject.BundleFile), bed.Ct), "kept as it was");
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt"), bed.Ct), "every file of the folder is kept, not only the known ones");
@@ -215,7 +215,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
// A newer Chronos on this PC rewrote the working state in a format this one does not know (a downgrade since).
var json = System.Text.Json.Nodes.JsonNode.Parse(await File.ReadAllTextAsync(project.BundlePath, bed.Ct))!.AsObject();
json["formatVersion"] = ProjectBundle.CurrentFormatVersion + 1;
@@ -330,7 +330,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
await host.SaveVersionAsync(mainId, $"Step {i}");
}
}
- var project = host.Store.Find(mainId)!;
+ var project = host.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.
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
index 218f4e98..908d385b 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
@@ -43,7 +43,7 @@ public sealed class WorkspaceHostTests(TestContext context)
var elsewhere = Path.Combine(context.CreateTempDirectory("fast-disk"), "Chronos workspace");
settings.WorkspaceFolder = elsewhere;
Assert.Equal(elsewhere, host.Root);
- Assert.Equal(elsewhere, host.Store.Root, "the store follows the folder");
+ Assert.Equal(elsewhere, host.Homes.Root, "the homes follow the folder");
Assert.FileExists(Path.Combine(elsewhere, WorkspaceStore.ManifestFile));
// A capture (sample data without an engine) edits its library as before.
@@ -142,6 +142,60 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Count(1, imported.WorkspaceOpened);
}
+ [Test]
+ public void TheKnownServersStayOnThisPc()
+ {
+ var id = Guid.CreateVersion7();
+ var originals = Guid.CreateVersion7();
+ var mine = new AppSettings
+ {
+ KnownServers = [new KnownServer { Id = id, Name = "Studio NAS", LastAddress = "https://nas.local:8443", Aliases = ["https://nas.local:8443"], OriginalsArchiveId = originals }],
+ };
+ var copy = AppSettings.Parse(mine.ToJson())!;
+ Assert.Equal(("Studio NAS", originals, "https://nas.local:8443"), (copy.KnownServers.Single().Name, copy.KnownServers.Single().OriginalsArchiveId, copy.KnownServers.Single().Aliases.Single()));
+ Assert.Equal(id, copy.FindKnownServer(id)?.Id);
+ Assert.True(copy.KnownIdentity().Same("https://nas.local:8443", Chronos.Core.IO.HomeFolders.IdKey(id)), "an alias names the server by its id");
+
+ // Reset and Import keep what this PC knows of its servers; Export leaves it out.
+ Assert.Equal(id, mine.ResetKeepingState().KnownServers.Single().Id);
+ Assert.Empty(AppSettings.Parse(mine.ForExport().ToJson())!.KnownServers);
+ Assert.Equal(id, mine.KeepLocalIn(AppSettings.Parse(new AppSettings().ToJson())!).KnownServers.Single().Id);
+ }
+
+ [Test]
+ public async Task TheTrashOfEveryHomeIsPlannedAndEmptiedTogether()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
+ var host = bed.Host(name: "homes");
+ var homes = host.Homes;
+ Assert.True(homes.IsSplit, "a new workspace is split into homes");
+ var server = homes.StoreFor(new BundleHome(BundleHome.ServerKind, Guid.CreateVersion7(), null, "https://nas.test:8443")).Root;
+ foreach (var (root, name) in new[] { (homes.Local.Root, "a"), (server, "b") })
+ {
+ var entry = Directory.CreateDirectory(Path.Combine(WorkspaceTrash.FolderOf(root), $"{Guid.CreateVersion7():N}-{name}"));
+ File.WriteAllBytes(Path.Combine(entry.FullName, "file.bin"), new byte[100]);
+ }
+
+ // Settings › Workspace › Home folders: this PC first, then the server by what its folder records.
+ var rows = HomeFolderRow.Of(homes, [], _ => { });
+ Assert.SequenceEqual([Loc.L("Settings.Workspace.ThisPc"), "https://nas.test:8443"], rows.Select(r => r.Name).ToArray());
+ Assert.Equal(server, rows[1].Path);
+
+ var usage = await host.UsageAsync(bed.Ct);
+ Assert.Equal((2, 200L), (usage.TrashItems, usage.TrashBytes));
+ var plan = await host.PlanTrashAsync(bed.Ct);
+ Assert.Equal((2, 200L, 2), (plan.Items.Count, plan.Bytes, plan.Listings.Count));
+
+ // One home's trash changed since the plan: nothing is erased, in either.
+ File.WriteAllBytes(Path.Combine(WorkspaceTrash.FolderOf(server), "late.bin"), new byte[5]);
+ await Assert.ThrowsAsync(() => host.EmptyTrashAsync(plan, bed.Ct));
+ Assert.Equal(3, (await host.UsageAsync(bed.Ct)).TrashItems, "nothing was erased");
+
+ var again = await host.PlanTrashAsync(bed.Ct);
+ Assert.Equal(new WorkspaceTrashResult(3, 205), await host.EmptyTrashAsync(again, bed.Ct));
+ Assert.Equal(0, (await host.UsageAsync(bed.Ct)).TrashItems);
+ }
+
[Test]
public void OpeningAProjectRecordsWhenAndSavesIt()
{
@@ -309,7 +363,7 @@ public sealed class WorkspaceHostTests(TestContext context)
var verticalId2 = (await host.HomeProjectsAsync(bed.SequenceId)).Single(p => !p.IsMain).Id;
await bed.CheckoutAsync(host, verticalId2);
Assert.Equal("Vertical", await host.RenameAsync(verticalId2, " Vertical "));
- Assert.Equal("Vertical", host.Store.Find(verticalId2)!.ReadBundle().Workspace!.Name);
+ Assert.Equal("Vertical", host.Find(verticalId2)!.ReadBundle().Workspace!.Name);
Assert.Contains((await host.HomeProjectsAsync(bed.SequenceId)), p => p.Name == "Vertical");
// Delete project…: confirmed, sent first, then gone from the library's list and from the workspace (kept in the library's trash).
@@ -329,7 +383,7 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Equal(1, deleting.Closed);
}
Assert.DoesNotContain(verticalId2, (await host.HomeProjectsAsync(bed.SequenceId)).Select(p => p.Id));
- Assert.Null(host.Store.Find(verticalId2));
+ Assert.Null(host.Find(verticalId2));
var row = await bed.RowAsync();
var trash = Path.Combine(new Chronos.Core.Archiving.ArchivePaths((await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath).Sequence(row.Folder).ProjectsTrashDirectory);
Assert.True(Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(verticalId2.ToString("N"), StringComparison.Ordinal)),
@@ -375,15 +429,15 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.True(request is { IsDestructive: true, TypedConfirmation: "Main" } && request.TypedPrompt is { Length: > 0 });
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), refused.Message);
- Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
+ Assert.NotNull(host.Find(mainId), "nothing was removed");
// Send first: saved and sent, then the library's copy is read back and checked before the local one goes.
await host.SaveVersionAsync(mainId, "Before removal");
await host.SyncAsync(mainId);
Assert.True((await host.PlanRemovalAsync(mainId)).IsSafe);
- var folder = host.Store.Find(mainId)!.Folder;
+ var folder = host.Find(mainId)!.Folder;
await host.RemoveLocalCopyAsync(mainId, discard: false);
- Assert.Null(host.Store.Find(mainId));
+ Assert.Null(host.Find(mainId));
Assert.False(Directory.Exists(Path.Combine(folder, WorkspaceProject.MediaFolder)), "the copied photos are gone");
Assert.Equal(0.3, ProjectSettings.FromJson((await bed.RowAsync()).SettingsJson!).Exposure.ExposureOffsetEv, "the work is in the library");
@@ -397,14 +451,14 @@ public sealed class WorkspaceHostTests(TestContext context)
}
var unsent = (await host.SaveVersionAsync(vertical, "Not sent")).Version!;
await host.RemoveLocalCopyAsync(vertical, discard: true);
- Assert.Null(host.Store.Find(vertical));
- var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
+ Assert.Null(host.Find(vertical));
+ var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal));
Assert.FileExists(Path.Combine(aside, WorkspaceProject.BundleFile));
Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)
|| f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept");
Assert.False(Directory.Exists(Path.Combine(aside, WorkspaceProject.MediaFolder)), "the photos, copies the library can make again, are not");
- Assert.Empty(host.Store.List());
+ Assert.Empty(host.Homes.List());
}
[Test]
@@ -413,7 +467,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
var basis = project.ReadBundle().Workspace!.Base!;
var conflict = $$"""
"conflict": { "theirsVersionId": "{{basis.VersionId}}", "theirsNumber": {{basis.Number}}, "baseVersionId": "{{Guid.CreateVersion7()}}",
@@ -449,9 +503,9 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.True((await host.PlanRemovalAsync(vertical)).Gone);
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(vertical, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.DeletedAtHome"), refused.Message);
- Assert.NotNull(host.Store.Find(vertical), "nothing was removed");
+ Assert.NotNull(host.Find(vertical), "nothing was removed");
await host.RemoveLocalCopyAsync(vertical, discard: true);
- Assert.Null(host.Store.Find(vertical));
+ Assert.Null(host.Find(vertical));
}
[Test]
@@ -460,7 +514,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
- var project = host.Store.Find(vertical)!;
+ var project = host.Find(vertical)!;
var bundle = File.ReadAllBytes(project.BundlePath);
var held = Path.Combine(project.Folder, "notes.txt");
File.WriteAllText(held, "mine");
@@ -471,13 +525,13 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.SequenceEqual(bundle, File.ReadAllBytes(project.BundlePath), "the working state is back");
Assert.Contains(await host.ListAsync(), e => e.ProjectId == vertical && e.IsReadable);
Assert.True(Directory.Exists(project.MediaDirectory) && Directory.Exists(project.VersionsDirectory), "the copy is whole");
- var trash = Path.Combine(host.Root, WorkspaceHost.TrashFolder);
+ var trash = Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder);
Assert.False(Directory.Exists(trash) && Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal)),
"nothing is left aside");
// The file let go: removed.
await host.RemoveLocalCopyAsync(vertical, discard: true);
- Assert.Null(host.Store.Find(vertical));
+ Assert.Null(host.Find(vertical));
}
[Test]
@@ -496,7 +550,7 @@ public sealed class WorkspaceHostTests(TestContext context)
await host.SaveVersionAsync(mainId, $"Step {i}");
}
}
- var project = host.Store.Find(mainId)!;
+ var project = host.Find(mainId)!;
var kept = project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order().ToList();
Assert.SequenceEqual([5, 6], kept, "the base and the one before it");
var history = await host.HistoryAsync(mainId);
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
index 6827ef9d..b78ad19d 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
@@ -44,13 +44,13 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
// Named the server's, as a copy downloaded from the server leaves it.
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var bundle = folder.ReadBundle();
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
// Not signed in to the server: a render from the originals runs here all the same.
- var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome((IRemoteSequenceApi?)null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
@@ -62,7 +62,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
- Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
+ Assert.Equal((projectId, host.Find(projectId)!.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
@@ -108,7 +108,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var (source, session) = await bed.OpenAsync(host, projectId);
var ui = new RecordingUi { ConfirmAnswer = false };
await using (session)
@@ -155,7 +155,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var projectId = await bed.CheckoutAsync(host);
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
Assert.False(await host.SendRendersAsync(projectId, bed.Ct), "nothing waits to be sent");
Assert.False(await host.RenderSendPendingAsync(projectId, bed.SequenceId, bed.Ct));
@@ -171,7 +171,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
var sends = (await bed.Db.Jobs.ListAsync(null, 50, null, bed.Ct)).Items.Where(j => j.Kind == JobKind.WorkspaceSend).ToList();
Assert.Equal(1, sends.Count);
var parameters = Assert.NotNull(WorkspaceJobs.SendParameters(sends[0]));
- Assert.Equal((projectId, host.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
+ Assert.Equal((projectId, host.Find(projectId)!.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
Assert.Empty(parameters.RenderIds);
}
@@ -189,7 +189,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var before = folder.Versions().Count;
// Nothing changed: nothing saved.
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
index 2a017ff3..bfc20ec1 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
@@ -35,7 +35,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
session.ConflictFound += conflicts.Add;
await using (session)
{
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
// A sync wrote another PC's exclusion of frame 5 while the editor's exclusion of frame 2 waited for its save.
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { ExcludedFrames = [5] } });
@@ -102,7 +102,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
Assert.True(sessionB.Undo());
Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
Assert.True(await sessionB.FlushAsync());
- var working = here.Store.Find(mainId)!.ReadBundle().Project;
+ var working = here.Find(mainId)!.ReadBundle().Project;
Assert.Equal((0.7, 0.2), (working.Exposure.ExposureOffsetEv, working.Camera.OffsetY), "the values brought back are stored");
}
}
@@ -172,7 +172,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
removing.SendFirstCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => uiB.Open is ConflictDialogViewModel, "the conflict is asked, not hidden behind Discard");
Assert.Equal(0, uiB.Closed, "the editor stays open");
- Assert.NotNull(here.Store.Find(mainId), "nothing was removed");
+ Assert.NotNull(here.Find(mainId), "nothing was removed");
}
}
@@ -211,7 +211,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
Assert.Equal(b.Name, copy.Message, "the copy Save both made is offered");
Assert.False(b.SaveVersionCommand.CanExecute(null), "nothing can be sent to it");
Assert.Equal(0.7, sessionB.Project.Exposure.ExposureOffsetEv, "the work stays in the editor");
- Assert.Equal(0.7, here.Store.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
+ Assert.Equal(0.7, here.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
}
}
@@ -254,7 +254,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
await using (session)
{
Assert.False(session.IsReadOnly);
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs
index f1d736a2..3bac16f3 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs
@@ -32,7 +32,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.True(session.History.CanUndo);
// A pull with nothing of this PC's waiting moved the working state onto a newer Chronos's settings.
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
@@ -64,7 +64,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
Assert.NotNull(await host.CommitAsync(projectId, bed.Ct));
- var folder = host.Store.Find(projectId)!;
+ var folder = host.Find(projectId)!;
var stored = folder.ReadBundle();
// A sync took a newer Chronos's settings while one more edit waited for its save (made during the sync).
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
@@ -86,7 +86,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
Assert.Equal(0.4, placed.Exposure.ExposureOffsetEv);
Assert.SequenceEqual([2], placed.ExcludedFrames, "the edit as it was, by photo");
Assert.False(folder.Versions().Any(v => v.Id == aside.Id), "outside the chain: never sent");
- Assert.Empty(host.Sync.Unpushed(projectId).Where(v => v.Id == aside.Id));
+ Assert.Empty(host.SyncOf(projectId).Unpushed(projectId).Where(v => v.Id == aside.Id));
// Read again: no throw, nothing more kept aside, the editor as it is.
await session.ReloadAsync();
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs
index 8bb07ec5..20c7301f 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceOpenPolicyTests.cs
@@ -97,7 +97,7 @@ public sealed class WorkspaceOpenPolicyTests(TestContext context)
var mainId = section.OpenProjectId!.Value;
var menu = Assert.NotNull(section.Editor!.Project);
Assert.True(menu.HoldsOriginals);
- var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
+ var media = services.Workspace.Find(mainId)!.ReadMedia()!;
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
Assert.True(await section.ConfirmCloseAsync());
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs
index aeaebcac..e6094bfb 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs
@@ -65,7 +65,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await WorkspaceTestBed.UntilAsync(() => project.Status is not null, "its state is read");
Assert.Equal(WorkspaceState.InSync, project.Status!.State);
Assert.Equal(section.OpenProjectId!.Value, settings.WorkspaceRecent[sequenceId]);
- Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
+ Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), "local", section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
"the project lives in the workspace beside the index");
// Edited in the workspace; the library takes it with the version saved.
@@ -231,7 +231,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
- var folder = Path.Combine(services.Workspace.Root, mainId.ToString("N"));
+ var folder = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"));
var bundle = Path.Combine(folder, WorkspaceProject.BundleFile);
// Saved by a newer Chronos: said at once, nothing offered over it, nothing asked.
@@ -298,7 +298,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await section.CloseAsync();
shell.KeepSequence(null);
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
- var bundle = Path.Combine(services.Workspace.Root, mainId.ToString("N"), WorkspaceProject.BundleFile);
+ var bundle = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"), WorkspaceProject.BundleFile);
// Damaged: the sequence has another project, so it is asked which; Main is listed, disabled, why in its tooltip.
await WriteWhenFreeAsync(bundle, "{ not a project");
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
index 2b46ac08..153e478e 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
@@ -120,7 +120,7 @@ internal sealed class WorkspaceTestBed : IAsyncDisposable
/// The project open in an editor session over the workspace (saves 20 ms after each edit).
public async Task<(WorkspaceSequenceSource Source, EditorSession Session)> OpenAsync(WorkspaceHost host, Guid projectId)
{
- var source = new WorkspaceSequenceSource(host.Sync, projectId, Db, DecoderFactory.CreateClient(null), Engine);
+ var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, Db, DecoderFactory.CreateClient(null), Engine);
var content = await source.LoadAsync(Ct);
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
}
diff --git a/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs b/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs
index e3e61913..1798d1ce 100644
--- a/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs
+++ b/tests/Chronos.Core.Windows.Tests/Shell/AppPathsTests.cs
@@ -18,11 +18,8 @@ public sealed class AppPathsTests(TestContext context)
Assert.Equal(Path.Combine(app, "data", "chronos.db"), paths.DatabasePath);
Assert.False(paths.IsInSyncedFolder);
Assert.Null(paths.PortableSyncRoot);
-
- paths.CreateDirectories();
- Assert.True(Directory.Exists(paths.LogsDirectory));
- Assert.True(Directory.Exists(paths.CacheDirectory));
- Assert.True(Directory.Exists(paths.ThumbnailsDirectory));
+ Assert.Equal(Path.Combine(app, "data", "logs"), paths.LogsDirectory);
+ Assert.Equal(Path.Combine(app, "data", "cache"), paths.CacheDirectory);
}
[Test]
@@ -50,22 +47,19 @@ public sealed class AppPathsTests(TestContext context)
Assert.Equal(Path.Combine(local, "Chronos"), paths.DataRoot);
Assert.Equal(oneDrive, paths.PortableSyncRoot);
Assert.False(paths.IsInSyncedFolder);
- paths.CreateDirectories();
- Assert.True(Directory.Exists(paths.LogsDirectory));
- Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder");
+ Assert.Equal(Path.Combine(local, "Chronos", "logs"), paths.LogsDirectory);
}
[Test]
- public void DataInsideOneDriveIsReportedAndRefused()
+ public void DataInsideOneDriveIsReported()
{
- // Local application data inside a sync root: nowhere is safe, so nothing is created.
+ // Local application data inside a sync root: nowhere is safe, and the app tells the user.
var oneDrive = context.CreateTempDirectory("onedrive");
var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName;
var paths = AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive]);
Assert.True(paths.IsInSyncedFolder);
Assert.Equal(oneDrive, paths.SyncedFolder);
- Assert.Throws(paths.CreateDirectories);
Assert.False(Directory.Exists(paths.DataRoot));
}