using System.IO;
using System.Windows;
using Chronos.App.DesignTime;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Testing;
using Chronos.Ui.Controls;
using Chronos.Ui.Theming;
namespace Chronos.App.Tests.Editor;
///
/// .chronos 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.chronos");
Assert.FileExists(path);
Assert.FileExists(Path.Combine(folder, "Harbour sunset (2).chronos"));
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.chronos");
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.chronos");
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.chronos"];
Assert.SequenceEqual(args, SingleInstance.Decode(SingleInstance.Encode(args))!);
Assert.Empty(SingleInstance.Decode(SingleInstance.Encode([]))!);
Assert.Null(SingleInstance.Decode("CHRONOS-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 Chronos 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.chronos"]));
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.chronos"], 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.chronos"]));
Assert.True(received.TryTake(out var later, TimeSpan.FromSeconds(10)), "the running instance received the hand-over");
Assert.SequenceEqual([@"D:\Projects\Roof.chronos"], later!);
}
finally
{
first.Dispose();
}
}
[Test]
public void ALaunchWhileChronosClosesWaitsForItAndStartsInItsPlace()
{
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.chronos"]), "a closing Chronos 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 } } };
}