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; /// /// 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. /// 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; } /// An installed copy's environment (not a capture): its data folder under the test's own local app data. public AppEnvironment Environment { get; } public CancellationToken Ct => _context.Cancellation; public static async Task 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); } /// A workspace of this PC (in its own folder when is given: another PC's, for conflicts). 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)) }; } /// The sequence's row in the index now. public async Task RowAsync() => (await Db.Sequences.GetAsync(SequenceId))!; /// 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. 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); } /// A project of the sequence checked out into 's workspace and its media copied (Main by default). public async Task 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; } /// The project open in an editor session over the workspace (saves 20 ms after each edit). 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))); } /// Waits until the job ends; it must end as . public async Task 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); } } /// Polls until it holds, within the time budget. public static async Task UntilAsync(Func 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(); } } /// The window a project menu lives in, as the tests see it: dialogs opened, toasts said, projects opened and closed. internal sealed class RecordingUi : IWorkspaceUi { public List Dialogs { get; } = []; public ArchiveDialogViewModel? Open { get; private set; } public List<(string Title, string? Message, bool IsError, Action? Action)> Toasts { get; } = []; public List Confirmations { get; } = []; /// What every confirmation answers. public bool ConfirmAnswer { get; set; } = true; public List<(Guid SequenceId, Guid ProjectId)> Opened { get; } = []; public int Closed { get; private set; } public List SequencesChanged { get; } = []; /// Dialogs waiting for the open one to close (). public Queue Waiting { get; } = new(); public ArchiveDialogViewModel? Dialog => Open; public void ShowDialog(ArchiveDialogViewModel dialog) { Open?.Dispose(); Dialogs.Add(dialog); Open = dialog; } public void ShowDialogWhenFree(ArchiveDialogViewModel dialog) { if (Open is null) ShowDialog(dialog); else Waiting.Enqueue(dialog); } public void CloseDialog(ArchiveDialogViewModel dialog) { if (!ReferenceEquals(Open, dialog)) return; dialog.Dispose(); Open = null; while (Waiting.TryDequeue(out var next)) { if (next.IsClosed) continue; ShowDialog(next); break; } } 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 CloseProjectAsync() { Closed++; return Task.FromResult(true); } public Task SequenceChangedAsync(Guid sequenceId) { SequencesChanged.Add(sequenceId); return Task.CompletedTask; } }