feat(app): Edit opens workspace projects, with versions, sync and the project menu
Owner review 2, phase 5a (R8), desktop package: editing moves out of the library. A sequence of this PC's archive now opens in Edit as a project of the workspace (%LOCALAPPDATA%\Chronos\workspace, .\data\workspace when portable), with this PC's archive as its home; the editor writes the workspace's working state, never the library. - WorkspaceHost composes WorkspaceStore and WorkspaceSync over Settings > Workspace's folder: checkout and the WorkspaceCopy job, status, Save version with the sync after it (Sync automatically, on by default), sync (pull, then push), conflicts, restore, history, new / rename / delete project, and Remove local copy, which refuses while work is unsent unless the user sends it first or discards it, reads back the home's head and base and checks their hashes, and keeps discarded work in <workspace>/.trash; versions past Kept versions are pruned only once the home returns them with the same content. - WorkspaceSequenceSource: frames and pixels of the media (proxies), the working state saved atomically under the project's lease and merged against the basis, the home's deep report while its frames are the media's, renders at the home with the portable settings recording the project and the version. - Edit: the project opened last for the sequence, else "Open in workspace" (Main made from the sequence's settings, another project or a new one; proxies) checks out, copies and opens once the copy is done. The picker lists the workspace's projects with their state above the library. The title's project menu: Save version (Ctrl+S, note), Sync, History (compare, restore as one undo step), New project, Rename, Delete project, Remove local copy; a conflict dialog only on real conflicts (keep mine, take the library's, save both, later); Update media when the library's frames moved. .chronos files: format 2 opens its project, format 1 gives its settings to Main. - Settings > Workspace: folder (shown, Open), Sync automatically, Kept versions. Strings in English and Italian. - A capture (sample data without an engine) keeps editing the library. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit da47a580ba9db3ce2a1db2f11c30cf7344c8b394)
This commit is contained in:
1 parent
03d32f18d3
commit
b9d1c396a1
37 files changed
+4547
-104
No files matched your search
@@ -0,0 +1,303 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// The editor over a workspace project (owner review 2, R8): its source (the media's frames, the working state saved
|
||||
/// there and merged, never the library), renders at the home, and the project menu: Save version, Sync, Restore and the
|
||||
/// conflicts a sync meets.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceEditorTests(TestContext context)
|
||||
{
|
||||
private static ProjectSettings Exposure(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } };
|
||||
|
||||
private static double ExposureOf(string? json) => ProjectSettings.FromJson(json!).Exposure.ExposureOffsetEv;
|
||||
|
||||
[Test]
|
||||
public async Task TheEditorEditsTheWorkspaceAndNeverTheLibrary()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context);
|
||||
var host = bed.Host();
|
||||
var libraryBefore = (await bed.RowAsync()).SettingsJson;
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var (source, session) = await bed.OpenAsync(host, projectId);
|
||||
await using (session)
|
||||
{
|
||||
var frames = await bed.Db.Frames.ListBySequenceAsync(bed.SequenceId, -1, 100);
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), session.Content.Frames.Select(f => f.Id), "the media's frames are the home's");
|
||||
Assert.Equal(bed.SequenceId, session.Content.Sequence.Id);
|
||||
Assert.False(session.IsRemote || session.IsReadOnly);
|
||||
Assert.Contains("exports", session.Content.ExportsFolder!);
|
||||
Assert.True(source.Workspace is { IsMain: true, Home.IsArchive: true });
|
||||
using (var thumbnail = await source.DecodeAsync(2, 32, DecodePurpose.Thumbnail, bed.Ct))
|
||||
Assert.True(thumbnail is { Width: > 0 } && Math.Max(thumbnail.Width, thumbnail.Height) <= 32);
|
||||
Assert.Null(await source.DecodeAsync(99, 32, DecodePurpose.Thumbnail, bed.Ct));
|
||||
Assert.True(await source.FramesCurrentAsync(bed.Ct));
|
||||
Assert.False(await source.HomeFramesChangedAsync(bed.Ct));
|
||||
|
||||
Assert.True(session.Edit(p => Exposure(p, 0.4)));
|
||||
Assert.True(await session.FlushAsync());
|
||||
var folder = host.Store.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);
|
||||
|
||||
// The working state written meanwhile by someone else (a pull, a copy): both changes survive the next save.
|
||||
var stored = folder.ReadBundle();
|
||||
folder.WriteBundle(stored with { Project = stored.Project with { Camera = stored.Project.Camera with { OffsetY = 0.25 } } });
|
||||
Assert.True(session.SetHero(3));
|
||||
Assert.True(await session.FlushAsync());
|
||||
var merged = folder.ReadBundle().Project;
|
||||
Assert.Equal((3, 0.25, 0.4), (merged.HeroFrame ?? -1, merged.Camera.OffsetY, merged.Exposure.ExposureOffsetEv));
|
||||
Assert.Equal(0.25, session.Project.Camera.OffsetY, "the editor shows what was merged in");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SaveVersionSendsItAndTheLibraryTakesMain()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context);
|
||||
var host = bed.Host();
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var (source, session) = await bed.OpenAsync(host, projectId);
|
||||
var ui = new RecordingUi();
|
||||
await using (session)
|
||||
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
|
||||
{
|
||||
await menu.RefreshAsync();
|
||||
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
|
||||
Assert.Equal(Loc.L("Editor.Project.Main"), menu.Name);
|
||||
Assert.Equal(Loc.L("Editor.Workspace.State.InSync"), menu.StateText);
|
||||
Assert.False(menu.DeleteCommand.CanExecute(null), "Main holds the sequence's settings");
|
||||
Assert.Equal(Loc.L("Errors.Workspace.MainKept"), menu.DeleteToolTip);
|
||||
|
||||
session.Edit(p => Exposure(p, 0.4));
|
||||
// Save version… asks for a note; saving sends the version at once (Sync automatically is on by default).
|
||||
menu.SaveVersionCommand.Execute(null);
|
||||
var dialog = Assert.NotNull(ui.Open as SaveVersionDialogViewModel);
|
||||
dialog.Note = " Warmer ";
|
||||
dialog.SaveCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => ui.Open is null, "the dialog closes once the version is saved");
|
||||
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
|
||||
Assert.Equal(0.4, ExposureOf((await bed.RowAsync()).SettingsJson), "Main's version is the sequence's settings");
|
||||
Assert.Equal(Loc.L("Editor.Workspace.SavedSent", "2"), ui.Toasts[^1].Title);
|
||||
Assert.Contains(bed.SequenceId, ui.SequencesChanged);
|
||||
var history = await host.HistoryAsync(projectId);
|
||||
Assert.Equal(("Warmer", ProjectVersionKind.Commit, 2), (history.Versions[0].Note, history.Versions[0].Kind, history.Versions[0].Number));
|
||||
Assert.Equal(ProjectVersionKind.Imported, history.Versions[^1].Kind);
|
||||
Assert.Empty(history.Unsent);
|
||||
|
||||
// Nothing new: no version.
|
||||
await menu.SaveVersionAsync(null);
|
||||
Assert.Equal(Loc.L("Editor.Workspace.NothingNew"), ui.Toasts[^1].Title);
|
||||
|
||||
// Without Sync automatically the version waits here until Sync sends it.
|
||||
host.Settings.WorkspaceAutoSync = false;
|
||||
session.Edit(p => Exposure(p, 0.6));
|
||||
await menu.SaveVersionAsync("Brighter");
|
||||
Assert.Equal((WorkspaceState.Ahead, 1), (menu.Status!.State, menu.Status.Ahead));
|
||||
Assert.Equal(Loc.L("Editor.Workspace.Saved", "3"), ui.Toasts[^1].Title);
|
||||
Assert.Equal(0.4, ExposureOf((await bed.RowAsync()).SettingsJson), "not sent yet");
|
||||
var unsent = await host.HistoryAsync(projectId);
|
||||
Assert.True(unsent.Unsent.Contains(unsent.Versions[0].Id) && unsent.Versions[0].Note == "Brighter", "the version not sent is listed first");
|
||||
await menu.SyncAsync();
|
||||
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
|
||||
Assert.Equal(0.6, ExposureOf((await bed.RowAsync()).SettingsJson));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersRunAtTheHomeWithThePortableSettingsAndTheVersion()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var (_, session) = await bed.OpenAsync(host, projectId);
|
||||
await using (session)
|
||||
{
|
||||
Assert.True(session.SetHero(2));
|
||||
Assert.True(await session.FlushAsync());
|
||||
var unsaved = session.RenderRequests(session.Project.Export);
|
||||
var request = Assert.Contains(unsaved, r => r.Kind == JobKind.Render);
|
||||
Assert.SequenceEqual([bed.SequenceId], request.Targets);
|
||||
var (parameters, _) = ProcessingJobs.ReadRender(request.ParametersJson);
|
||||
Assert.Equal<Guid?>(projectId, parameters.ProjectId);
|
||||
Assert.Null(parameters.ProjectVersionId, "an unsaved working state names no version");
|
||||
Assert.False(parameters.UseProxies, "the home renders its originals");
|
||||
var portable = ProjectSettings.FromJson(parameters.SettingsJson!);
|
||||
Assert.Null(portable.HeroFrame, "positions travel by photo");
|
||||
Assert.Contains(portable.PendingFrames!, f => f.Hero);
|
||||
|
||||
var saved = (await host.SaveVersionAsync(projectId, null)).Version!;
|
||||
var (versioned, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
|
||||
Assert.Equal<Guid?>(saved.Id, versioned.ProjectVersionId);
|
||||
Assert.Equal(parameters.SettingsJson, versioned.SettingsJson);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RestoreIsOneUndoStepAndLosesNothing()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context);
|
||||
var host = bed.Host();
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var (source, session) = await bed.OpenAsync(host, projectId);
|
||||
var ui = new RecordingUi();
|
||||
await using (session)
|
||||
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
|
||||
{
|
||||
session.Edit(p => Exposure(p, 0.3));
|
||||
await menu.SaveVersionAsync("Warm");
|
||||
var warm = (await host.HistoryAsync(projectId)).Versions[0];
|
||||
session.Edit(p => Exposure(p, 0.6));
|
||||
Assert.True(await session.FlushAsync());
|
||||
|
||||
// Compare: what differs between now and that version.
|
||||
var lines = menu.Compare(warm);
|
||||
Assert.Count(1, lines);
|
||||
Assert.Contains("0.6", lines[0]);
|
||||
Assert.Contains("0.3", lines[0]);
|
||||
|
||||
// History › Restore: the version is the project again, as one step; the unsaved 0.6 was saved as a version first.
|
||||
menu.HistoryCommand.Execute(null);
|
||||
var history = Assert.NotNull(ui.Open as HistoryDialogViewModel);
|
||||
await WorkspaceTestBed.UntilAsync(() => history.Rows.Count > 0, "the history lists the versions");
|
||||
Assert.SequenceEqual(["2", "1"], history.Rows.Select(r => r.Number));
|
||||
Assert.False(history.Rows.Any(r => r.IsCurrent), "the working state (0.6) is no version yet");
|
||||
Assert.Equal(Loc.L("Editor.History.Kind.Imported"), history.Rows[1].KindText);
|
||||
await history.CompareAsync(warm);
|
||||
Assert.Equal(Loc.L("Editor.History.Compared", "2"), history.ComparedTitle);
|
||||
await history.RestoreAsync(warm);
|
||||
Assert.Null(ui.Open);
|
||||
Assert.Equal(0.3, session.Project.Exposure.ExposureOffsetEv);
|
||||
Assert.Equal(Loc.L("Editor.Workspace.Restored", "2"), ui.Toasts[^1].Title);
|
||||
var all = await host.HistoryAsync(projectId);
|
||||
Assert.Contains(all.Versions, v => v.Number == 3 && v.Kind == ProjectVersionKind.Commit && Math.Abs(ExposureOfVersion(v) - 0.6) < 1e-9);
|
||||
|
||||
// The toast's Undo brings 0.6 back as a new step; Ctrl+Z after that takes the restore back too.
|
||||
ui.Toasts[^1].Action!();
|
||||
Assert.Equal(0.6, session.Project.Exposure.ExposureOffsetEv);
|
||||
Assert.True(session.Undo());
|
||||
Assert.Equal(0.3, session.Project.Exposure.ExposureOffsetEv);
|
||||
|
||||
// The next version records the restore.
|
||||
await menu.SaveVersionAsync(null);
|
||||
var restored = (await host.HistoryAsync(projectId)).Versions[0];
|
||||
Assert.Equal((ProjectVersionKind.Restore, warm.Id), (restored.Kind, restored.RestoredFrom!.Value));
|
||||
}
|
||||
|
||||
static double ExposureOfVersion(ProjectVersion version) => ProjectSettings.FromJson(version.SettingsJson).Exposure.ExposureOffsetEv;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConflictsAreAskedOnlyWhenBothChangedTheSameSetting()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context);
|
||||
var here = bed.Host();
|
||||
var there = bed.Host(name: "other-pc");
|
||||
var mainId = await bed.CheckoutAsync(here);
|
||||
Assert.Equal(mainId, await bed.CheckoutAsync(there));
|
||||
var (sourceA, sessionA) = await bed.OpenAsync(here, mainId);
|
||||
var (sourceB, sessionB) = await bed.OpenAsync(there, mainId);
|
||||
var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
|
||||
await using (sessionA)
|
||||
await using (sessionB)
|
||||
using (var a = new ProjectMenuViewModel(here, sourceA, sessionA, uiA))
|
||||
using (var b = new ProjectMenuViewModel(there, sourceB, sessionB, uiB))
|
||||
{
|
||||
// Different settings: merged without a question, both in the library and in both editors.
|
||||
sessionA.Edit(p => Exposure(p, 0.3));
|
||||
await a.SaveVersionAsync(null);
|
||||
sessionB.Edit(p => p with { Camera = p.Camera with { OffsetY = 0.2 } });
|
||||
await b.SaveVersionAsync(null);
|
||||
Assert.Empty(uiB.Dialogs.OfType<ConflictDialogViewModel>());
|
||||
Assert.Equal((0.3, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
|
||||
await a.SyncAsync();
|
||||
Assert.Equal((0.3, 0.2), (sessionA.Project.Exposure.ExposureOffsetEv, sessionA.Project.Camera.OffsetY));
|
||||
|
||||
// The same setting to different values: asked, keep mine.
|
||||
sessionA.Edit(p => Exposure(p, 0.5));
|
||||
await a.SaveVersionAsync(null);
|
||||
sessionB.Edit(p => Exposure(p, 0.9));
|
||||
await b.SaveVersionAsync(null);
|
||||
var conflict = Assert.NotNull(uiB.Open as ConflictDialogViewModel);
|
||||
Assert.Equal(WorkspaceState.Conflict, b.Status!.State);
|
||||
Assert.False(b.CanSaveVersion, "no version until the conflict is settled");
|
||||
Assert.Contains(conflict.Differences, l => l.Contains("0.9") && l.Contains("0.5"));
|
||||
conflict.KeepMineCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => uiB.Open is null, "keep mine settles it");
|
||||
Assert.Equal(WorkspaceState.InSync, b.Status!.State);
|
||||
Assert.Equal(0.9, ExposureOf((await bed.RowAsync()).SettingsJson));
|
||||
Assert.Equal(0.9, sessionB.Project.Exposure.ExposureOffsetEv);
|
||||
|
||||
// Again, take the library's (the other PC took this one's values first: its sync is in step).
|
||||
await a.SyncAsync();
|
||||
Assert.Equal(0.9, sessionA.Project.Exposure.ExposureOffsetEv);
|
||||
sessionA.Edit(p => Exposure(p, 0.1));
|
||||
await a.SaveVersionAsync(null);
|
||||
sessionB.Edit(p => Exposure(p, 0.7));
|
||||
await b.SaveVersionAsync(null);
|
||||
await b.ResolveAsync(ConflictChoice.TakeServer);
|
||||
Assert.Equal(0.1, sessionB.Project.Exposure.ExposureOffsetEv);
|
||||
Assert.Equal(0.1, ExposureOf((await bed.RowAsync()).SettingsJson));
|
||||
|
||||
// And save both: this workspace's versions go to a sibling project, this one takes the library's.
|
||||
await a.SyncAsync();
|
||||
sessionA.Edit(p => Exposure(p, -0.2));
|
||||
await a.SaveVersionAsync(null);
|
||||
sessionB.Edit(p => Exposure(p, 0.8));
|
||||
await b.SaveVersionAsync(null);
|
||||
var both = Assert.NotNull(uiB.Open as ConflictDialogViewModel);
|
||||
Assert.Equal(WorkspaceHost.SiblingName("Main"), both.SiblingName);
|
||||
await b.ResolveAsync(ConflictChoice.SaveBoth);
|
||||
Assert.Equal(-0.2, sessionB.Project.Exposure.ExposureOffsetEv);
|
||||
var projects = await there.HomeProjectsAsync(bed.SequenceId);
|
||||
var sibling = Assert.Contains(projects, p => p.Name == WorkspaceHost.SiblingName("Main"));
|
||||
var head = await there.HomeOfSequence(bed.SequenceId).HeadAsync(sibling.Id, bed.Ct);
|
||||
Assert.Equal(0.8, ProjectSettings.FromJson(head.SettingsJson).Exposure.ExposureOffsetEv, "nothing is lost: the sibling holds this side's values");
|
||||
Assert.Equal(Loc.L("Editor.Workspace.SavedAs", sibling.Name), uiB.Toasts[^1].Title);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UpdateMediaFollowsTheLibrarysNewFramesByPhoto()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 6);
|
||||
var host = bed.Host();
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var (source, session) = await bed.OpenAsync(host, projectId);
|
||||
var ui = new RecordingUi();
|
||||
await using (session)
|
||||
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
|
||||
{
|
||||
var excluded = session.Content.Frames[2].Id;
|
||||
Assert.True(session.SetExcluded([2], excluded: true));
|
||||
Assert.True(await session.FlushAsync());
|
||||
|
||||
await bed.InsertEarlierFrameAsync();
|
||||
await menu.RefreshAsync();
|
||||
Assert.True(menu.HasMediaUpdate, "the library's frames moved past the workspace's");
|
||||
Assert.Equal(Loc.L("Editor.Workspace.MediaChanged"), menu.MediaUpdateText);
|
||||
Assert.Equal(6, session.Content.Count, "the editor keeps the frames it holds meanwhile");
|
||||
|
||||
menu.UpdateMediaCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => session.Content.Count == 7 && !menu.IsUpdatingMedia && !menu.HasMediaUpdate, "the new media are read");
|
||||
Assert.SequenceEqual([3], session.Project.ExcludedFrames, "the exclusion follows its photo");
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Windows.Shell;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's workspace (owner review 2, R8): where it lives, what it remembers, its projects' states as the picker
|
||||
/// shows them, new, renamed and deleted projects, the removal of a local copy that never loses unsent work, the pruning
|
||||
/// of old versions, and Settings › Workspace.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceHostTests(TestContext context)
|
||||
{
|
||||
static WorkspaceHostTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
[Test]
|
||||
public void TheWorkspaceLivesBesideTheIndexUnlessSettingsSayOtherwise()
|
||||
{
|
||||
var local = context.CreateTempDirectory("local");
|
||||
var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
|
||||
Assert.Equal(Path.Combine(local, "Chronos", "workspace"), WorkspaceHost.DefaultRoot(installed));
|
||||
|
||||
var stick = context.CreateTempDirectory("stick");
|
||||
File.WriteAllText(Path.Combine(stick, PortableMode.MarkerFileName), "");
|
||||
var portable = AppEnvironment.From(AppPaths.Resolve(stick, local, []));
|
||||
Assert.Equal(Path.Combine(stick, "data", "workspace"), WorkspaceHost.DefaultRoot(portable));
|
||||
|
||||
var settings = new AppSettings();
|
||||
var host = new WorkspaceHost(installed, settings, () => { }, () => null, () => null, () => null);
|
||||
Assert.Equal(WorkspaceHost.DefaultRoot(installed), host.Root);
|
||||
Assert.True(host.IsEnabled);
|
||||
Assert.False(host.IsAvailable, "no index yet");
|
||||
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.FileExists(Path.Combine(elsewhere, WorkspaceStore.ManifestFile));
|
||||
|
||||
// A capture (sample data without an engine) edits its library as before.
|
||||
var capture = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
Assert.False(new WorkspaceHost(capture, new AppSettings(), () => { }, () => null, () => null, () => null).IsEnabled);
|
||||
}
|
||||
finally
|
||||
{
|
||||
capture.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheWorkspaceSettingsSurviveTheSettingsFile()
|
||||
{
|
||||
var sequence = Guid.CreateVersion7();
|
||||
var project = Guid.CreateVersion7();
|
||||
var settings = new AppSettings { WorkspaceFolder = @"D:\Fast\Workspace", WorkspaceAutoSync = false, WorkspaceKeptVersions = 50 };
|
||||
settings.WorkspaceRecent[sequence] = project;
|
||||
var copy = AppSettings.Parse(settings.ToJson())!;
|
||||
Assert.Equal((@"D:\Fast\Workspace", false, 50), (copy.WorkspaceFolder, copy.WorkspaceAutoSync, copy.WorkspaceKeptVersions));
|
||||
Assert.Equal(project, copy.WorkspaceRecent[sequence]);
|
||||
|
||||
// A settings file written before the workspace existed gets its defaults: sync on, 20 versions.
|
||||
var older = AppSettings.Parse("""{ "Theme": "Light" }""")!;
|
||||
Assert.Equal((null, true, 20), (older.WorkspaceFolder, older.WorkspaceAutoSync, older.WorkspaceKeptVersions));
|
||||
Assert.Empty(older.WorkspaceRecent);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SettingsWorkspaceRowsStoreEachChoiceAtOnce()
|
||||
{
|
||||
var settings = new AppSettings();
|
||||
var saves = 0;
|
||||
var opened = 0;
|
||||
var rows = new WorkspaceSettingsRows(settings, () => saves++, () => @"C:\Users\me\AppData\Local\Chronos\workspace", () => opened++);
|
||||
Assert.Equal(@"C:\Users\me\AppData\Local\Chronos\workspace", rows.Folder);
|
||||
rows.OpenCommand.Execute(null);
|
||||
Assert.Equal(1, opened);
|
||||
|
||||
Assert.True(rows.AutoSync);
|
||||
rows.AutoSync = false;
|
||||
Assert.Equal((false, 1), (settings.WorkspaceAutoSync, saves));
|
||||
rows.AutoSync = false;
|
||||
Assert.Equal(1, saves, "nothing to store");
|
||||
|
||||
Assert.SequenceEqual(WorkspaceSettingsRows.KeptPresets, rows.KeptChoices.Select(c => c.Value));
|
||||
Assert.Equal(20, rows.SelectedKept.Value);
|
||||
Assert.Equal(Loc.Plural("Settings.Workspace.Versions", 50), rows.KeptChoices.Single(c => c.Value == 50).Label);
|
||||
rows.SelectedKept = rows.KeptChoices.Single(c => c.Value == 50);
|
||||
Assert.Equal((50, 2), (settings.WorkspaceKeptVersions, saves));
|
||||
|
||||
// A value set by hand is listed with the presets; one below 1 is shown as the 1 the workspace applies.
|
||||
settings.WorkspaceKeptVersions = 0;
|
||||
Assert.Equal(1, rows.SelectedKept.Value);
|
||||
Assert.Contains(1, rows.KeptChoices.Select(c => c.Value));
|
||||
|
||||
rows.Reset();
|
||||
Assert.Equal((true, 20), (settings.WorkspaceAutoSync, settings.WorkspaceKeptVersions));
|
||||
|
||||
// The page comes right after Storage.
|
||||
var pages = Enum.GetValues<SettingsPage>().ToList();
|
||||
Assert.Equal(pages.IndexOf(SettingsPage.Storage) + 1, pages.IndexOf(SettingsPage.Workspace));
|
||||
Assert.Equal(Loc.L("Settings.Page.Workspace"), new SettingsPageItem(SettingsPage.Workspace, ["Settings.Workspace.Kept"]).Label);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProjectNamesAndTheirStatesReadAsThePickerShowsThem()
|
||||
{
|
||||
Assert.Equal(Loc.L("Editor.Project.Main"), WorkspaceText.ProjectName("Main", isMain: true));
|
||||
Assert.Equal("Main", WorkspaceText.ProjectName("Main", isMain: false), "only the sequence's Main is translated");
|
||||
Assert.Null(ProjectNames.Validate("Vertical social", ["Main"]));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.NameTaken"), ProjectNames.Validate(" main ", ["Main"]));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.InvalidName"), ProjectNames.Validate(" ", []));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.InvalidName"), ProjectNames.Validate(new string('x', 61), []));
|
||||
var sibling = WorkspaceHost.SiblingName(new string('y', 60));
|
||||
Assert.True(sibling.Length <= 60 && sibling.EndsWith(")", StringComparison.Ordinal), sibling);
|
||||
|
||||
var status = new WorkspaceStatus(WorkspaceState.Ahead, false, 2, 0, false, false, false, null, null, null);
|
||||
Assert.Equal((Loc.L("Editor.Workspace.State.Ahead"), StatusKind.Queued), (WorkspaceText.State(status), WorkspaceText.Kind(status)));
|
||||
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Ahead", "2"), WorkspaceText.StateToolTip(status));
|
||||
Assert.Equal((Loc.L("Editor.Workspace.State.Syncing"), StatusKind.Running), (WorkspaceText.State(status, syncing: true), WorkspaceText.Kind(status, syncing: true)));
|
||||
var offline = status with { State = WorkspaceState.Offline, Offline = true };
|
||||
Assert.Equal((StatusKind.Offline, Loc.L("Tooltips.Editor.Workspace.State.OfflineAhead", "2")), (WorkspaceText.Kind(offline), WorkspaceText.StateToolTip(offline)));
|
||||
foreach (var state in Enum.GetValues<WorkspaceState>())
|
||||
{
|
||||
var each = status with { State = state };
|
||||
Assert.NotEqual("Editor.Workspace.State." + state, WorkspaceText.State(each), "every state has its text");
|
||||
}
|
||||
|
||||
var entry = new WorkspaceEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "Main", true, new BundleHome(BundleHome.ArchiveKind, Guid.CreateVersion7()),
|
||||
"Harbour sunset", HasMedia: true, DateTimeOffset.UtcNow);
|
||||
var item = new WorkspaceProjectItem(entry, null);
|
||||
Assert.Equal(Loc.L("Editor.Workspace.State.Reading"), item.StateText);
|
||||
item.Status = status with { State = WorkspaceState.InSync };
|
||||
Assert.Equal((Loc.L("Editor.Workspace.State.InSync"), StatusKind.Synced), (item.StateText, item.StateKind));
|
||||
Assert.Equal(string.Join(Loc.Separator, Loc.L("Editor.Project.Main"), "Harbour sunset", Loc.L("Editor.Workspace.State.InSync")), item.Description);
|
||||
Assert.Equal(Loc.L("Editor.Workspace.State.MediaRemoved"), new WorkspaceProjectItem(entry with { HasMedia = false }, null).StateText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheWorkspaceRemembersTheProjectOpenedLast()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var saved = 0;
|
||||
var settings = new AppSettings();
|
||||
var host = new WorkspaceHost(bed.Environment, settings, () => saved++, () => bed.Db, () => bed.Archives, () => bed.Engine);
|
||||
Assert.Null(await host.LastUsedAsync(bed.SequenceId));
|
||||
var main = await bed.CheckoutAsync(host);
|
||||
Assert.Equal(main, settings.WorkspaceRecent[bed.SequenceId]);
|
||||
var vertical = await bed.CheckoutAsync(host, newName: "Vertical social");
|
||||
Assert.Equal(vertical, (await host.LastUsedAsync(bed.SequenceId))!.ProjectId, "the project checked out last");
|
||||
host.Remember(bed.SequenceId, main);
|
||||
Assert.Equal(main, (await host.LastUsedAsync(bed.SequenceId))!.ProjectId);
|
||||
Assert.True(saved >= 3);
|
||||
|
||||
var listed = await host.ProjectsOfAsync(bed.SequenceId);
|
||||
Assert.Equal(2, listed.Count);
|
||||
Assert.True(listed.All(p => p.HasMedia));
|
||||
Assert.SequenceEqual(["Main", "Vertical social"], listed.OrderBy(p => p.Name, StringComparer.Ordinal).Select(p => p.Name), "names as the library has them");
|
||||
// The home's projects are those of the library: Main, made from the sequence's settings, and the new one.
|
||||
var home = await host.HomeProjectsAsync(bed.SequenceId);
|
||||
Assert.Equal((2, "Main"), (home.Count, home[0].Name));
|
||||
|
||||
// A project gone from the workspace is forgotten.
|
||||
settings.WorkspaceRecent[bed.SequenceId] = Guid.CreateVersion7();
|
||||
Assert.Contains((await host.LastUsedAsync(bed.SequenceId))!.ProjectId, new[] { main, vertical });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task NewRenamedAndDeletedProjectsReachTheLibrary()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host();
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
var (source, session) = await bed.OpenAsync(host, mainId);
|
||||
var ui = new RecordingUi();
|
||||
await using (session)
|
||||
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
|
||||
{
|
||||
await menu.RefreshAsync();
|
||||
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.3 } });
|
||||
await menu.SaveVersionAsync(null);
|
||||
|
||||
// New project…: the name is checked as it is typed; the project starts from this one's last version in the library.
|
||||
menu.NewProjectCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => ui.Open is ProjectNameDialogViewModel, "the name dialog");
|
||||
var naming = (ProjectNameDialogViewModel)ui.Open!;
|
||||
naming.Name.Text = "main";
|
||||
Assert.False(naming.SaveCommand.CanExecute(null), "Main is taken");
|
||||
Assert.Equal(Loc.L("Errors.Workspace.NameTaken"), naming.SaveToolTip);
|
||||
naming.Name.Text = "Vertical social";
|
||||
naming.SaveCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => ui.Opened.Count == 1, "the new project opens");
|
||||
var (sequenceId, verticalId) = ui.Opened[0];
|
||||
Assert.Equal(bed.SequenceId, sequenceId);
|
||||
var head = await host.HomeOfSequence(bed.SequenceId).HeadAsync(verticalId, bed.Ct);
|
||||
Assert.Equal(0.3, ProjectSettings.FromJson(head.SettingsJson).Exposure.ExposureOffsetEv);
|
||||
}
|
||||
|
||||
// Rename: in the library and in the workspace's working state.
|
||||
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.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).
|
||||
var (verticalSource, verticalSession) = await bed.OpenAsync(host, verticalId2);
|
||||
var deleting = new RecordingUi { ConfirmAnswer = false };
|
||||
await using (verticalSession)
|
||||
using (var menu = new ProjectMenuViewModel(host, verticalSource, verticalSession, deleting))
|
||||
{
|
||||
verticalSession.Edit(p => p with { HeroFrame = 1 });
|
||||
Assert.True(menu.DeleteCommand.CanExecute(null));
|
||||
menu.DeleteCommand.Execute(null);
|
||||
Assert.Count(1, deleting.Confirmations);
|
||||
Assert.Equal(0, deleting.Closed, "kept: nothing happens");
|
||||
deleting.ConfirmAnswer = true;
|
||||
menu.DeleteCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => deleting.Toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Deleted", "Vertical")), "the project is deleted");
|
||||
Assert.Equal(1, deleting.Closed);
|
||||
}
|
||||
Assert.DoesNotContain(verticalId2, (await host.HomeProjectsAsync(bed.SequenceId)).Select(p => p.Id));
|
||||
Assert.Null(host.Store.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)),
|
||||
"the deleted project's versions wait in the library's project trash");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALocalCopyGoesOnlyOnceTheLibraryHoldsItsWorkOrTheUserDiscardsIt()
|
||||
{
|
||||
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 (source, session) = await bed.OpenAsync(host, mainId);
|
||||
await using (session)
|
||||
{
|
||||
Assert.True(source.Workspace!.IsMain);
|
||||
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.3 } });
|
||||
Assert.True(await session.FlushAsync());
|
||||
}
|
||||
|
||||
var plan = await host.PlanRemovalAsync(mainId);
|
||||
Assert.True(plan is { Modified: true, Unsent: 0, Conflict: false, Offline: false, IsSafe: false });
|
||||
Assert.True(plan.Files >= 4 + 2, "the proxies, the media index and the working state");
|
||||
Assert.Greater(plan.Bytes, 0);
|
||||
var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, _ => { });
|
||||
Assert.False(dialog.RemoveCommand.CanExecute(null), "not while work is not in the library");
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), dialog.RemoveToolTip);
|
||||
Assert.True(dialog.SendFirstCommand.CanExecute(null) && dialog.DiscardCommand.CanExecute(null));
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), refused.Message);
|
||||
Assert.NotNull(host.Store.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;
|
||||
await host.RemoveLocalCopyAsync(mainId, discard: false);
|
||||
Assert.Null(host.Store.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");
|
||||
|
||||
// Discard changes: the unsent versions and the working state are kept aside in the workspace's trash, never erased.
|
||||
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
|
||||
var (_, verticalSession) = await bed.OpenAsync(host, vertical);
|
||||
await using (verticalSession)
|
||||
{
|
||||
verticalSession.Edit(p => p with { HeroFrame = 2 });
|
||||
Assert.True(await verticalSession.FlushAsync());
|
||||
}
|
||||
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)),
|
||||
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());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OlderVersionsArePrunedPastKeptVersionsOnlyOnceTheLibraryHoldsThem()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceKeptVersions = 2 });
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
var (_, session) = await bed.OpenAsync(host, mainId);
|
||||
await using (session)
|
||||
{
|
||||
for (var i = 1; i <= 5; i++)
|
||||
{
|
||||
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = i / 10.0 } });
|
||||
Assert.True(await session.FlushAsync());
|
||||
await host.SaveVersionAsync(mainId, $"Step {i}");
|
||||
}
|
||||
}
|
||||
var project = host.Store.Find(mainId)!;
|
||||
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);
|
||||
Assert.Equal(6, history.Versions.Count, "the library keeps every version");
|
||||
// An old version restores from the library.
|
||||
var first = history.Versions.Single(v => v.Number == 2);
|
||||
var restored = await host.RestoreAsync(mainId, first.Id);
|
||||
Assert.Approximately(0.1, restored.Exposure.ExposureOffsetEv, 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Tests.Editor;
|
||||
using Chronos.App.Tests.Windows;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Windows.Shell;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Edit opens this PC's sequences as workspace projects (owner review 2, R8), on the real services without a window:
|
||||
/// "Open in workspace" asks the first time, the media are copied by a job and the project opens; the library is written
|
||||
/// only by a version saved; the picker lists the project in its Workspace group with its state; the next open takes the
|
||||
/// project opened last without asking; a project file of format 1 gives its settings to Main.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceSectionTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public Task OpenInWorkspaceAsksCopiesAndOpensAndThePickerListsTheProject() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
var directory = context.CreateTempDirectory("workspace-section");
|
||||
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
|
||||
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
|
||||
UiLanguage.Apply("en");
|
||||
var settings = new AppSettings { Language = "en", FirstRunCompleted = true, CheckForUpdates = false };
|
||||
var services = new AppServices(environment, settings, () => { }, new DeclineDialogs());
|
||||
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
|
||||
var shell = new ShellViewModel(services);
|
||||
try
|
||||
{
|
||||
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
|
||||
var db = services.Database!;
|
||||
var libraryBefore = (await db.Sequences.GetAsync(sequenceId))!.SettingsJson;
|
||||
var section = shell.Sequence;
|
||||
|
||||
shell.OpenSequence(sequenceId);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
|
||||
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
|
||||
Assert.Equal(Loc.L("Editor.Project.Main"), ask.SelectedProject!.Label, "Main, made from the sequence's settings, is offered first");
|
||||
Assert.True(ask.IsProxies && !ask.CanCopyOriginals, "proxies; the originals come later");
|
||||
Assert.True(section.ShowsPicker && !section.IsLoading, "the picker shows behind the dialog, not the progress bar");
|
||||
ask.OpenCommand.Execute(null);
|
||||
Assert.Null(section.Dialog);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens once its media are copied");
|
||||
var editor = section.Editor!;
|
||||
Assert.True(editor.Session.Source is WorkspaceSequenceSource);
|
||||
var project = Assert.NotNull(editor.Project);
|
||||
Assert.Equal(Loc.L("Editor.Project.Main"), project.Name);
|
||||
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)),
|
||||
"the project lives in the workspace beside the index");
|
||||
|
||||
// Edited in the workspace; the library takes it with the version saved.
|
||||
editor.Session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.4 } });
|
||||
Assert.True(await editor.Session.FlushAsync());
|
||||
Assert.Equal(libraryBefore, (await db.Sequences.GetAsync(sequenceId))!.SettingsJson, "editing never writes the library");
|
||||
await project.SaveVersionAsync("Warmer");
|
||||
Assert.Equal(0.4, ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!).Exposure.ExposureOffsetEv);
|
||||
|
||||
// The picker: the Workspace group lists the project with its state, above the library's sequences.
|
||||
section.ChangeSequenceCommand.Execute(null);
|
||||
await section.Picker.Loading;
|
||||
await section.Picker.WorkspaceLoadedAsync();
|
||||
var item = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == section.OpenProjectId);
|
||||
Assert.True(section.Picker.HasWorkspaceItems);
|
||||
Assert.Same(item, section.Picker.SelectedProject);
|
||||
Assert.Equal(Loc.L("Editor.Workspace.State.InSync"), item.StateText);
|
||||
Assert.Contains(section.Picker.Items, i => i.Id == sequenceId);
|
||||
await section.PickProjectAsync(item);
|
||||
Assert.False(section.IsPicking, "the open project shows again");
|
||||
Assert.Same(editor, section.Editor);
|
||||
|
||||
// Closed, then asked for again: the project opened last opens without a question.
|
||||
Assert.True(await section.ConfirmCloseAsync());
|
||||
await section.CloseAsync();
|
||||
shell.KeepSequence(null);
|
||||
shell.OpenSequence(sequenceId);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "it opens again");
|
||||
Assert.Null(section.Dialog);
|
||||
Assert.Equal(0.4, section.Editor!.Session.Project.Exposure.ExposureOffsetEv);
|
||||
|
||||
// A project file of format 1 gives its settings to Main, as one undo step.
|
||||
var file = Path.Combine(directory, "Harbour.chronos");
|
||||
var bundle = new ProjectBundle(new BundleArchive(Guid.CreateVersion7(), "Elsewhere", null), new BundleSequence(sequenceId, "Synthetic", "Harbour", 6),
|
||||
section.Editor.Session.Project with { Camera = section.Editor.Session.Project.Camera with { OffsetY = 0.3 } }, DateTimeOffset.UtcNow);
|
||||
bundle.Save(file);
|
||||
await new ProjectFiles(shell).OpenAsync(file);
|
||||
Assert.Equal(0.3, section.Editor.Session.Project.Camera.OffsetY);
|
||||
Assert.True(section.Editor.Session.Undo());
|
||||
Assert.Equal(0.0, section.Editor.Session.Project.Camera.OffsetY);
|
||||
Assert.True(await section.Editor.Session.FlushAsync());
|
||||
}
|
||||
finally
|
||||
{
|
||||
await shell.Sequence.CloseAsync();
|
||||
shell.Dispose();
|
||||
await services.DisposeAsync();
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>An archive with one sequence of six synthetic photos, indexed.</summary>
|
||||
private async Task<Guid> SequenceAsync(AppServices services, string root)
|
||||
{
|
||||
var archives = services.Archives!;
|
||||
var archive = await archives.CreateAsync(root, "Test");
|
||||
var sequence = EditorFixture.Sequence(6);
|
||||
var folder = Path.Combine(root, "Synthetic");
|
||||
Directory.CreateDirectory(folder);
|
||||
for (var i = 0; i < sequence.Count; i++)
|
||||
{
|
||||
using var image = sequence.Render(i);
|
||||
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
|
||||
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
|
||||
}
|
||||
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
|
||||
return (await services.Database!.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
|
||||
}
|
||||
|
||||
/// <summary>Dialogs that pick nothing and decline every confirmation.</summary>
|
||||
private sealed class DeclineDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Tests.Editor;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Windows.Shell;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// This PC's archive with one sequence of synthetic photos as the projects' home, its job engine (the workspace copy
|
||||
/// registered), and workspaces of the desktop that edit it (owner review 2, R8). No window: the view models run on the
|
||||
/// test's thread.
|
||||
/// </summary>
|
||||
internal sealed class WorkspaceTestBed : IAsyncDisposable
|
||||
{
|
||||
private readonly TestContext _context;
|
||||
|
||||
private WorkspaceTestBed(TestContext context, string directory, ChronosDatabase db, ArchiveService archives, JobEngine engine, Guid sequenceId,
|
||||
AppEnvironment environment)
|
||||
{
|
||||
_context = context;
|
||||
Directory = directory;
|
||||
Db = db;
|
||||
Archives = archives;
|
||||
Engine = engine;
|
||||
SequenceId = sequenceId;
|
||||
Environment = environment;
|
||||
}
|
||||
|
||||
static WorkspaceTestBed() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
public string Directory { get; }
|
||||
public ChronosDatabase Db { get; }
|
||||
public ArchiveService Archives { get; }
|
||||
public JobEngine Engine { get; }
|
||||
public Guid SequenceId { get; }
|
||||
|
||||
/// <summary>An installed copy's environment (not a capture): its data folder under the test's own local app data.</summary>
|
||||
public AppEnvironment Environment { get; }
|
||||
|
||||
public CancellationToken Ct => _context.Cancellation;
|
||||
|
||||
public static async Task<WorkspaceTestBed> CreateAsync(TestContext context, int frames = 8)
|
||||
{
|
||||
var directory = context.CreateTempDirectory("workspace-app");
|
||||
var root = Path.Combine(directory, "archive");
|
||||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
|
||||
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
|
||||
var archive = await archives.CreateAsync(root, "Test");
|
||||
var sequence = EditorFixture.Sequence(frames);
|
||||
var folder = Path.Combine(root, "Synthetic");
|
||||
System.IO.Directory.CreateDirectory(folder);
|
||||
for (var i = 0; i < sequence.Count; i++)
|
||||
{
|
||||
using var image = sequence.Render(i);
|
||||
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
|
||||
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
|
||||
}
|
||||
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
|
||||
var sequenceId = (await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
|
||||
var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. WorkspaceJobs.CreateHandlers(db, archives)],
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
var app = System.IO.Directory.CreateDirectory(Path.Combine(directory, "app")).FullName;
|
||||
var local = System.IO.Directory.CreateDirectory(Path.Combine(directory, "local")).FullName;
|
||||
var environment = AppEnvironment.From(AppPaths.Resolve(app, local, []));
|
||||
return new WorkspaceTestBed(context, directory, db, archives, engine, sequenceId, environment);
|
||||
}
|
||||
|
||||
/// <summary>A workspace of this PC (in its own folder when <paramref name="name"/> is given: another PC's, for conflicts).</summary>
|
||||
public WorkspaceHost Host(AppSettings? settings = null, string? name = null)
|
||||
{
|
||||
settings ??= new AppSettings();
|
||||
if (name is not null) settings.WorkspaceFolder = Path.Combine(Directory, name);
|
||||
return new WorkspaceHost(Environment, settings, () => { }, () => Db, () => Archives, () => Engine) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
||||
}
|
||||
|
||||
/// <summary>The sequence's row in the index now.</summary>
|
||||
public async Task<Sequence> RowAsync() => (await Db.Sequences.GetAsync(SequenceId))!;
|
||||
|
||||
/// <summary>A photo taken before the others added to the sequence at its home (as an import of earlier photos does): every frame moves one place.</summary>
|
||||
public async Task InsertEarlierFrameAsync()
|
||||
{
|
||||
var row = await RowAsync();
|
||||
var archive = (await Db.Archives.GetAsync(row.ArchiveId))!;
|
||||
var synthetic = EditorFixture.Sequence(1);
|
||||
using var image = synthetic.Render(0);
|
||||
var metadata = synthetic.Metadata[0] with { CapturedAt = row.FirstCapture!.Value.AddSeconds(-30) };
|
||||
var bytes = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80, App1Segments = [ExifWriter.BuildJpegApp1(metadata)[4..]] });
|
||||
var staging = Path.Combine(new ArchivePaths(archive.RootPath).StagingDirectory, "uploads");
|
||||
System.IO.Directory.CreateDirectory(staging);
|
||||
var path = Path.Combine(staging, Guid.NewGuid().ToString("N") + ".part");
|
||||
await File.WriteAllBytesAsync(path, bytes, Ct);
|
||||
await Archives.Ingest.CommitAsync(new IngestRequest(archive.Id, SequenceId, null, null, path, "IMG_0000.JPG", bytes.Length,
|
||||
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)), null, null), Ct);
|
||||
}
|
||||
|
||||
/// <summary>A project of the sequence checked out into <paramref name="host"/>'s workspace and its media copied (Main by default).</summary>
|
||||
public async Task<Guid> CheckoutAsync(WorkspaceHost host, Guid? projectId = null, string? newName = null)
|
||||
{
|
||||
var checkout = await host.CheckoutAsync(SequenceId, projectId, newName, cancellationToken: Ct);
|
||||
await WaitForJobAsync(checkout.Copy.Id);
|
||||
return checkout.Project.Id;
|
||||
}
|
||||
|
||||
/// <summary>The project open in an editor session over the workspace (saves 20 ms after each edit).</summary>
|
||||
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 content = await source.LoadAsync(Ct);
|
||||
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
|
||||
}
|
||||
|
||||
/// <summary>Waits until the job ends; it must end as <paramref name="expected"/>.</summary>
|
||||
public async Task<Job> WaitForJobAsync(Guid jobId, JobState expected = JobState.Done)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
|
||||
while (true)
|
||||
{
|
||||
var job = await Db.Jobs.GetAsync(jobId, Ct);
|
||||
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled })
|
||||
{
|
||||
Assert.Equal(expected, job.State, job.Error ?? job.LogTail);
|
||||
return job;
|
||||
}
|
||||
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {jobId} still {job?.State} after its time budget");
|
||||
await Task.Delay(50, Ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Polls <paramref name="condition"/> until it holds, within the time budget.</summary>
|
||||
public static async Task UntilAsync(Func<bool> condition, string what, double seconds = 60)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(seconds));
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline) Assert.Fail($"Not reached in time: {what}");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Engine.DisposeAsync();
|
||||
await Db.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The window a project menu lives in, as the tests see it: dialogs opened, toasts said, projects opened and closed.</summary>
|
||||
internal sealed class RecordingUi : IWorkspaceUi
|
||||
{
|
||||
public List<ArchiveDialogViewModel> Dialogs { get; } = [];
|
||||
|
||||
public ArchiveDialogViewModel? Open { get; private set; }
|
||||
|
||||
public List<(string Title, string? Message, bool IsError, Action? Action)> Toasts { get; } = [];
|
||||
|
||||
public List<ConfirmRequest> Confirmations { get; } = [];
|
||||
|
||||
/// <summary>What every confirmation answers.</summary>
|
||||
public bool ConfirmAnswer { get; set; } = true;
|
||||
|
||||
public List<(Guid SequenceId, Guid ProjectId)> Opened { get; } = [];
|
||||
|
||||
public int Closed { get; private set; }
|
||||
|
||||
public List<Guid> SequencesChanged { get; } = [];
|
||||
|
||||
public void ShowDialog(ArchiveDialogViewModel dialog)
|
||||
{
|
||||
Open?.Dispose();
|
||||
Dialogs.Add(dialog);
|
||||
Open = dialog;
|
||||
}
|
||||
|
||||
public void CloseDialog(ArchiveDialogViewModel dialog)
|
||||
{
|
||||
if (!ReferenceEquals(Open, dialog)) return;
|
||||
dialog.Dispose();
|
||||
Open = null;
|
||||
}
|
||||
|
||||
public bool Confirm(ConfirmRequest request)
|
||||
{
|
||||
Confirmations.Add(request);
|
||||
return ConfirmAnswer;
|
||||
}
|
||||
|
||||
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false) =>
|
||||
Toasts.Add((title, message, isError, action));
|
||||
|
||||
public Task OpenProjectAsync(Guid sequenceId, Guid projectId)
|
||||
{
|
||||
Opened.Add((sequenceId, projectId));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> CloseProjectAsync()
|
||||
{
|
||||
Closed++;
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task SequenceChangedAsync(Guid sequenceId)
|
||||
{
|
||||
SequencesChanged.Add(sequenceId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user