using System.IO; using System.Windows; using Titano.App.DesignTime; using Titano.App.Editor; using Titano.App.Infrastructure; using Titano.App.Shell; using Titano.App.Tests.Windows; using Titano.Core.Localization; using Titano.Core.Project; using Titano.Testing; using Titano.Ui.Controls; using Titano.Ui.Theming; namespace Titano.App.Tests.Editor; /// /// .titano project files (BRIEF ยง18) in the real main window on the editor sample: the editor saves one, and /// opening one shows its sequence with the file's settings as one undo step, or says in one sentence why not. /// [WindowsOnly] [Serial] [Timeout(300_000)] public sealed class ProjectFilesTests(TestContext context) { [Test] public Task AProjectFileSavesAndOpensItsSequenceWithItsSettings() => ScreenHost.RunAsync(async () => { var folder = context.CreateTempDirectory("project-files"); var environment = AppEnvironment.ForCapture(); UiLanguage.Apply("en"); ThemeManager.Apply(AppTheme.Dark); var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new FolderDialogs(folder)); var sample = SampleData.Configure(services); var shell = new ShellViewModel(services); var toasts = new List(); shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []); var window = new MainWindow(shell) { WindowStartupLocation = WindowStartupLocation.Manual, Left = -20000, Top = -20000, Width = 1200, Height = 788, ShowActivated = false, ShowInTaskbar = false, }; window.Show(); try { await sample.OpenEmptyAsync(); await shell.StartAsync(); var id = await sample.FillEditorAsync(); var files = new ProjectFiles(shell); // Saved under the sequence's title, never over an earlier file. var editor = Assert.NotNull(await shell.Sequence.ShowAsync(id)); await files.SaveAsync(editor.Session); await files.SaveAsync(editor.Session); var path = Path.Combine(folder, "Harbour sunset.titano"); Assert.FileExists(path); Assert.FileExists(Path.Combine(folder, "Harbour sunset (2).titano")); Assert.Equal(Loc.L("Editor.ProjectFile.Saved"), toasts[^1].Title); var bundle = ProjectBundle.Load(path); Assert.Equal(id, bundle.Sequence.Id); Assert.Equal(editor.FrameCount, bundle.Sequence.Frames); Assert.Equal(editor.Session.Project.ToJson(), bundle.Project.ToJson()); // Opening it with other settings shows the sequence with them, as one step Undo takes back. var before = editor.Session.Project; bundle.ExposureOffset(0.7).Save(path); await files.OpenAsync(path); Assert.Same(editor, shell.Sequence.Editor); Assert.Equal(0.7, editor.Session.Project.Exposure.ExposureOffsetEv); var applied = toasts[^1]; Assert.Equal(Loc.L("Editor.ProjectFile.Applied"), applied.Title); Assert.False(applied.IsError); applied.ActionCommand!.Execute(null); Assert.Equal(before.ToJson(), editor.Session.Project.ToJson()); // A sequence this library does not have, and a file that is not a project: one sentence each. var elsewhere = bundle with { Archive = bundle.Archive with { Id = Guid.CreateVersion7() }, Sequence = bundle.Sequence with { Id = Guid.CreateVersion7(), Folder = "2026/elsewhere" }, }; var missing = Path.Combine(folder, "Elsewhere.titano"); elsewhere.Save(missing); await files.OpenAsync(missing); Assert.Equal(Loc.L("Editor.ProjectFile.NotFound"), toasts[^1].Title); Assert.True(toasts[^1].IsError); var text = Path.Combine(folder, "notes.titano"); await File.WriteAllTextAsync(text, "not a project"); await files.OpenAsync(text); Assert.Equal(Loc.L("Editor.ProjectFile.Unreadable"), toasts[^1].Title); Assert.True(toasts[^1].IsError); Assert.Same(editor, shell.Sequence.Editor, "the open sequence stays"); await editor.Session.FlushAsync(); } finally { window.Close(); await shell.Sequence.CloseAsync(); shell.Dispose(); await services.DisposeAsync(); environment.DeleteCaptureData(); } }); [Test] public void AHandOverMessageRoundTrips() { string[] args = [@"C:\Users\me\Desktop\Harbour sunset.titano"]; Assert.SequenceEqual(args, SingleInstance.Decode(SingleInstance.Encode(args))!); Assert.Empty(SingleInstance.Decode(SingleInstance.Encode([]))!); Assert.Null(SingleInstance.Decode("TITANO-UPLOADER/1\nE:\\"u8)); } [Test] public void ASecondLaunchOnTheSameDataFolderHandsItsFileToTheFirst() { var data = context.CreateTempDirectory("instance"); var first = Assert.NotNull(SingleInstance.TryAcquire(data)); try { first.Listen(); Assert.Null(SingleInstance.TryAcquire(data), "one Titano per data folder"); using (var other = SingleInstance.TryAcquire(context.CreateTempDirectory("other-copy"))) Assert.NotNull(other, "a portable copy with its own data folder runs on its own"); // Launches while the first one is still opening its window are kept until the window takes them. The pipe // takes one launch at a time, so once the second hand-over is through, the first one is already waiting. Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Early.titano"])); Assert.True(SingleInstance.HandOver(data, [])); using var received = new System.Collections.Concurrent.BlockingCollection>(); first.Receive(received.Add); Assert.True(received.TryTake(out var early, TimeSpan.FromSeconds(10)), "the hand-over that came first is delivered"); Assert.SequenceEqual([@"D:\Projects\Early.titano"], early!); Assert.True(received.TryTake(out var show, TimeSpan.FromSeconds(10)), "then the plain launch"); Assert.Empty(show!); Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"])); Assert.True(received.TryTake(out var later, TimeSpan.FromSeconds(10)), "the running instance received the hand-over"); Assert.SequenceEqual([@"D:\Projects\Roof.titano"], later!); } finally { first.Dispose(); } } [Test] public void ALaunchWhileTitanoClosesWaitsForItAndStartsInItsPlace() { var data = context.CreateTempDirectory("closing"); var first = Assert.NotNull(SingleInstance.TryAcquire(data)); first.Listen(); first.Receive(_ => { }); // Closing: it no longer answers, but it still holds the data folder until its services have stopped. first.StopListening(); Assert.False(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"]), "a closing Titano takes no file it could not open"); Assert.Null(SingleInstance.TryAcquire(data)); // The next launch waits (the mutex belongs to a thread, so it waits on its own) and gets its turn once the first exits. var next = OnOwnThread(() => { using var instance = SingleInstance.WaitForTurn(data, TimeSpan.FromSeconds(20)); return instance is not null; }); Assert.False(next.Wait(TimeSpan.FromMilliseconds(300)), "it waits while the first one still runs"); first.Dispose(); Assert.True(next.Wait(TimeSpan.FromSeconds(20)) && next.Result, "it starts once the first one has exited"); // Nobody exits in time: the launch gives up. var holder = Assert.NotNull(SingleInstance.TryAcquire(data)); try { Assert.False(OnOwnThread(() => SingleInstance.WaitForTurn(data, TimeSpan.FromMilliseconds(200)) is { } got && Dispose(got)).Result); } finally { holder.Dispose(); } static bool Dispose(SingleInstance instance) { instance.Dispose(); return true; } // A thread of its own, never this one: a mutex this thread owns would let it in at once, and a task waited on // before it started may run inline on the waiting thread. static Task OnOwnThread(Func launch) { var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); new Thread(() => { try { done.SetResult(launch()); } catch (Exception ex) { done.SetException(ex); } }) { IsBackground = true }.Start(); return done.Task; } } /// Dialogs that pick one folder and cancel everything else. private sealed class FolderDialogs(string folder) : IAppDialogs { public string? PickFolder(string title, string? initialFolder = null) => folder; public string? PickJsonFile(string title) => null; public bool Confirm(ConfirmRequest request) => false; public bool SignIn(string server, string? username, Func> signIn) => false; } } internal static class ProjectBundleTestExtensions { /// The same file with another exposure offset. public static ProjectBundle ExposureOffset(this ProjectBundle bundle, double ev) => bundle with { Project = bundle.Project with { Exposure = bundle.Project.Exposure with { ExposureOffsetEv = ev } } }; }