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;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
///
/// 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.
///
[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();
}
});
[Test]
public Task ARefusedFolderOffersAnotherFromItsToastAndCopiesThisChronosCannotReadAreNeverOpened() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-refused");
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
UiLanguage.Apply("en");
var settings = new AppSettings { Language = "en", FirstRunCompleted = true, CheckForUpdates = false };
var outside = Path.Combine(directory, "outside");
var dialogs = new ScriptedDialogs { Folder = outside };
var services = new AppServices(environment, settings, () => { }, dialogs);
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
var toasts = new List();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []);
try
{
var library = Path.Combine(directory, "archive");
var sequenceId = await SequenceAsync(services, library);
var inside = Path.Combine(library, "workspace");
settings.WorkspaceFolder = inside;
var section = shell.Sequence;
// Open in workspace shows what the copy writes and the room there is, then the folder is refused with a way on.
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], ask.CopyFacts.Select(f => f.Label), "the copy's facts reach the dialog");
ask.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")), "the refusal is said");
var refused = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.OpenFailed"));
Assert.True(refused is { IsError: true, ActionCommand: not null }, "an error with its action");
Assert.Equal((Loc.L("Errors.Workspace.InsideLibraryEdit", Path.GetFullPath(inside)), Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder")),
(refused.Message, refused.ActionText, refused.ActionToolTip));
Assert.False(Directory.Exists(inside), "nothing was written inside the library");
Assert.Null(section.Editor);
// Its action picks another folder, shows the plan and uses it.
refused.ActionCommand!.Execute(null);
await WorkspaceTestBed.UntilAsync(() => string.Equals(services.Workspace.Root, Path.GetFullPath(outside), StringComparison.OrdinalIgnoreCase), "the folder chosen is used");
Assert.Count(1, dialogs.Asked);
Assert.Equal(Loc.L("Settings.Workspace.ChangeTitle"), dialogs.Asked[0].Heading);
// That workspace holds a copy a newer Chronos saved and a damaged one: listed, never opened.
var newerId = Guid.CreateVersion7();
var newer = Directory.CreateDirectory(Path.Combine(outside, newerId.ToString("N"))).FullName;
await File.WriteAllTextAsync(Path.Combine(newer, WorkspaceProject.BundleFile),
$$"""{ "format": "chronos-project", "formatVersion": 9, "sequence": { "title": "Harbour" }, "workspace": { "projectId": "{{newerId}}", "name": "Vertical" } }""");
var damagedId = Guid.CreateVersion7();
var damaged = Directory.CreateDirectory(Path.Combine(outside, damagedId.ToString("N"))).FullName;
await File.WriteAllTextAsync(Path.Combine(damaged, WorkspaceProject.BundleFile), "{ not a project");
await File.WriteAllTextAsync(Path.Combine(damaged, "notes.txt"), "kept");
await section.Picker.ReloadAsync();
await section.Picker.WorkspaceLoadedAsync();
var newerItem = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == newerId);
Assert.True(newerItem is { IsNewer: true, IsDamaged: false, IsReadable: false, Name: "Vertical", SequenceTitle: "Harbour" });
Assert.Null(newerItem.Status, "no state is asked of it");
await section.PickProjectAsync(newerItem);
Assert.Contains(toasts, t => t.Message == Loc.L("Errors.Workspace.NewerCopy") && t.IsError);
Assert.Null(section.Dialog, "nothing is offered over it");
Assert.FileExists(Path.Combine(newer, WorkspaceProject.BundleFile));
// The damaged one offers its removal, named as a damaged copy; Discard asks its files' number and keeps every file aside.
var damagedItem = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == damagedId);
await section.PickProjectAsync(damagedItem);
var remove = Assert.NotNull(section.Dialog as RemoveCopyDialogViewModel);
Assert.Equal(Loc.L("Editor.RemoveCopy.DamagedTitle"), remove.Heading);
dialogs.Answer = true;
remove.DiscardCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => !Directory.Exists(damaged), "the damaged copy goes");
var discard = dialogs.Asked[^1];
Assert.Equal((Loc.L("Editor.RemoveCopy.DamagedDiscard"), Formatting.Count(2), Loc.L("Editor.RemoveCopy.TypeFiles", Formatting.Count(2))),
(discard.Heading, discard.TypedConfirmation, discard.TypedPrompt));
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(outside, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(damagedId.ToString("N"), StringComparison.Ordinal));
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt")));
// Nothing knows its name: the toast names no folder id.
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Removed")), "the removal is said");
Assert.Null(toasts.Single(t => t.Title == Loc.L("Editor.Workspace.Removed")).Message);
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
[Test]
public Task AMainThisChronosCannotReadSaysWhyAtOnceAndADamagedOneOffersItsRemoval() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-unreadable-main");
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 dialogs = new ScriptedDialogs();
var services = new AppServices(environment, settings, () => { }, dialogs);
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
var toasts = new List();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []);
try
{
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
((OpenInWorkspaceDialogViewModel)section.Dialog!).OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "Main opens");
var mainId = section.OpenProjectId!.Value;
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
var folder = Path.Combine(services.Workspace.Root, mainId.ToString("N"));
var bundle = Path.Combine(folder, WorkspaceProject.BundleFile);
// Saved by a newer Chronos: said at once, nothing offered over it, nothing asked.
await WriteWhenFreeAsync(bundle,
$$"""{ "format": "chronos-project", "formatVersion": 9, "sequence": { "title": "Synthetic" }, "workspace": { "projectId": "{{mainId}}", "name": "Main", "isMain": true } }""");
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Message == Loc.L("Errors.Workspace.NewerCopy")), "a newer Main is refused");
var newer = toasts.Single(t => t.Message == Loc.L("Errors.Workspace.NewerCopy"));
Assert.True(newer is { Title: var title, IsError: true, ActionCommand: null } && title == Loc.L("Editor.Workspace.OpenFailed"));
Assert.True(section.Dialog is null && section.Editor is null, "nothing asked, nothing opened");
Assert.FileExists(bundle);
shell.KeepSequence(null);
// Damaged: said at once, with Remove local copy; its Discard keeps the files aside, named as the copy is known.
await WriteWhenFreeAsync(bundle, "{ not a project");
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Message == Loc.L("Errors.Workspace.Damaged")), "a damaged Main is refused");
var damaged = toasts.Single(t => t.Message == Loc.L("Errors.Workspace.Damaged"));
Assert.Equal((Loc.L("Editor.Workspace.OpenFailed"), true, Loc.L("Editor.Project.RemoveCopy"), Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")),
(damaged.Title, damaged.IsError, damaged.ActionText, damaged.ActionToolTip));
Assert.True(section.Dialog is null && section.Editor is null, "nothing asked, nothing opened");
damaged.ActionCommand!.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is RemoveCopyDialogViewModel, "its removal is offered");
var remove = (RemoveCopyDialogViewModel)section.Dialog!;
Assert.True(remove.Plan.Damaged, "removed as a damaged copy");
Assert.Equal(Loc.L("Editor.RemoveCopy.Title", Loc.L("Editor.Project.Main")), remove.Heading);
remove.DiscardCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Removed")), "the copy goes");
Assert.False(Directory.Exists(folder));
var removed = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.Removed"));
Assert.Equal(Loc.L("Editor.Project.Main"), removed.Message, "named as the index knows it, never by its folder");
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
/// Writes once the project's last background read (its state, after the close) lets go of it.
private static async Task WriteWhenFreeAsync(string path, string text)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (true)
{
try
{
await File.WriteAllTextAsync(path, text);
return;
}
catch (IOException) when (DateTime.UtcNow < until)
{
await Task.Delay(50);
}
}
}
/// An archive with one sequence of six synthetic photos, indexed.
private async Task 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;
}
/// Dialogs that pick and answer every confirmation with (yes first), recording what they were asked.
private sealed class ScriptedDialogs : IAppDialogs
{
public string? Folder { get; set; }
public bool Answer { get; set; } = true;
public List Asked { get; } = [];
public string? PickFolder(string title, string? initialFolder = null) => Folder;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request)
{
Asked.Add(request);
return Answer;
}
public bool SignIn(string server, string? username, Func> signIn) => false;
}
/// Dialogs that pick nothing and decline every confirmation.
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> signIn) => false;
}
}