using System.IO; using Titano.App.Editor; using Titano.Core.Archiving; using Titano.Core.Codecs.Jpeg; using Titano.Core.Imaging; using Titano.Core.Imaging.Decoders; using Titano.Core.Metadata; using Titano.Core.Model; using Titano.Core.Project; using Titano.Data; using Titano.Data.Archiving; using Titano.Data.Jobs; using Titano.Data.Processing; using Titano.Data.Repositories; using Titano.Testing; namespace Titano.App.Tests.Editor; /// Project merges, and the local source over a real SQLite index and archive folder. public sealed class ProjectStoreTests(TestContext context) { [Test] public void AMemberOnlyTheyChangedIsKept() { var basis = new ProjectSettings(); var ours = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.5 } }; var theirs = basis with { HeroFrame = 12 }; var merged = ProjectMerge.Merge(basis, ours, theirs); Assert.Equal(0.5, merged.Exposure.ExposureOffsetEv); Assert.Equal(12, merged.HeroFrame); } [Test] public void AdviceMergesIntoAManualValueOfTheSameSetting() { var basis = new ProjectSettings(); var ours = basis with { Exposure = basis.Exposure with { Deflicker = basis.Exposure.Deflicker.WithManual(true) } }; var theirs = basis with { Exposure = basis.Exposure with { Deflicker = basis.Exposure.Deflicker.WithAdvice(false, "Advisor.Reason.Deflicker.Off") } }; var merged = ProjectMerge.Merge(basis, ours, theirs).Exposure.Deflicker; Assert.False(merged.IsAuto, "the user's manual choice stays"); Assert.True(merged.Manual); Assert.True(merged.HasAdvice, "the new advice is stored next to it"); Assert.Equal("Advisor.Reason.Deflicker.Off", merged.ReasonKey); } [Test] public void WhenBothChangedAValueTheEditorWins() { var basis = new ProjectSettings(); var merged = ProjectMerge.Merge(basis, basis with { HeroFrame = 3 }, basis with { HeroFrame = 9 }); Assert.Equal(3, merged.HeroFrame); } [Test] public async Task TheLocalSourceReadsDecodesSavesAndQueues() { var (db, sequenceId, root) = await ArchiveAsync(12); await using (db) { var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }; await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options); var content = await source.LoadAsync(context.Cancellation); Assert.Equal(12, content.Count); Assert.Equal(96, content.SourceWidth); Assert.Equal(64, content.SourceHeight); Assert.Null(content.Deep, "not analysed yet"); Assert.NotNull(content.ExportsFolder); Assert.Contains("exports", content.ExportsFolder!); using (var frame = await source.DecodeAsync(3, 32, DecodePurpose.Thumbnail, context.Cancellation)) { Assert.NotNull(frame); Assert.LessOrEqual(Math.Max(frame!.Width, frame.Height), 32); } Assert.Null(await source.DecodeAsync(99, 32, DecodePurpose.Thumbnail, context.Cancellation)); // A save writes project.json and the index row together. var edited = content.Project with { HeroFrame = 4, Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.3 } }; var stored = await source.SaveProjectAsync(edited, content.Project, context.Cancellation); Assert.True(ProjectMerge.SameValues(edited, stored)); var projectPath = Path.Combine(root, "Synthetic", ".titano", "project.json"); Assert.FileExists(projectPath); Assert.Equal(edited.ToJson(), File.ReadAllText(projectPath)); var row = await db.Sequences.GetAsync(sequenceId); Assert.Equal(edited.ToJson(), row!.SettingsJson); // Someone else changes the settings meanwhile (the server API): both edits survive the next save. var theirs = stored with { Camera = stored.Camera with { OffsetY = 0.25 } }; await db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = theirs.ToJson() }, row.SettingsVersion); var mine = stored with { HeroFrame = 7 }; var merged = await source.SaveProjectAsync(mine, stored, context.Cancellation); Assert.Equal(7, merged.HeroFrame); Assert.Equal(0.25, merged.Camera.OffsetY); Assert.Equal(merged.ToJson(), File.ReadAllText(projectPath)); Assert.Equal(merged.ToJson(), (await db.Sequences.GetAsync(sequenceId))!.SettingsJson); var reloaded = await source.LoadAsync(context.Cancellation); Assert.True(ProjectMerge.SameValues(merged, reloaded.Project), "the index copy is read back"); await Assert.ThrowsAsync(() => source.SubmitAsync(ProcessingJobs.DeepAnalysis([sequenceId]), context.Cancellation)); } } [Test] public async Task ASaveThatDoesNotReachTheIndexThrows() { var (db, sequenceId, _) = await ArchiveAsync(4); await using (db) { await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }); var content = await source.LoadAsync(context.Cancellation); Assert.True(await db.Sequences.DeleteAsync(sequenceId)); await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation)); } } [Test] public async Task JobsGoToTheEngine() { var (db, sequenceId, _) = await ArchiveAsync(4); await using (db) { await using var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "test" }); await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), engine); var content = await source.LoadAsync(context.Cancellation); var session = new EditorSession(source, content, []); var id = await session.SubmitAsync(session.AnalysisRequest(), context.Cancellation); var job = await db.Jobs.GetAsync(id); Assert.Equal(JobKind.DeepAnalyse, job!.Kind); Assert.Equal(JobState.Queued, job.State); Assert.SequenceEqual([sequenceId], job.TargetIds); } } [Test] public async Task AnUnreadableProjectIsReportedNotReplaced() { var (db, sequenceId, root) = await ArchiveAsync(4); await using (db) { var path = Path.Combine(root, "Synthetic", ".titano", "project.json"); File.WriteAllText(path, "{ not json"); await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null); await Assert.ThrowsAsync(() => source.LoadAsync(context.Cancellation)); Assert.Equal("{ not json", File.ReadAllText(path)); } } /// A temporary archive with one adopted folder of synthetic JPEGs, indexed. private async Task<(TitanoDatabase Db, Guid SequenceId, string Root)> ArchiveAsync(int frames) { var directory = context.CreateTempDirectory("editor"); var root = Path.Combine(directory, "archive"); var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db"))); var service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }); var archive = await service.CreateAsync(root, "Test"); var sequence = EditorFixture.Sequence(frames); 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 service.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation); var location = (await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single(); return (db, location.Id, root); } }