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;
///
/// 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();
}
});
/// 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 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;
}
}