diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs index 105b4f1a..1266176b 100644 --- a/src/Titano.App/DesignTime/SampleData.cs +++ b/src/Titano.App/DesignTime/SampleData.cs @@ -1,14 +1,23 @@ using System.IO; using System.Net; using Titano.App.About; +using Titano.App.Editor; using Titano.App.Infrastructure; using Titano.App.Server; using Titano.App.Settings; +using Titano.Core.Advice; +using Titano.Core.Analysis; +using Titano.Core.Analysis.Deep; +using Titano.Core.Archiving; using Titano.Core.Codecs.Jpeg; +using Titano.Core.Diagnostics.Synthetic; using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Metadata; using Titano.Core.Model; using Titano.Core.Video; using Titano.Data; +using Titano.Data.Archiving; using Titano.Protocol; using Titano.Protocol.Client; @@ -79,6 +88,149 @@ public sealed class SampleData settings.FirstRunCompleted = true; } + /// + /// The sequence editor's sample: a second archive holding a synthetic harbour sunset of real JPEG frames with Exif + /// (flicker, two received exposure steps, white-balance drift, a horizon), indexed by a scan, analysed (light and + /// deep, saved as analysis.json), advised into project.json and given two past renders. + /// + /// The sequence id to open in the editor. + public async Task FillEditorAsync() + { + var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first."); + var archives = _services.Archives ?? throw new InvalidOperationException("The archive engine is not attached."); + var root = Path.Combine(_services.Environment.DataDirectory, "editor-archive"); + var archive = await archives.CreateAsync(root, "Editor sample"); + var sunset = SyntheticSequence.Create(EditorSunset); + var folder = Path.Combine(root, "2026", "2026-09-28 Canon EOS R5"); + Directory.CreateDirectory(folder); + for (var i = 0; i < sunset.Count; i++) + { + using var image = SunsetFrame(sunset, i); + var exif = ExifWriter.BuildJpegApp1(sunset.Metadata[i]); + File.WriteAllBytes(Path.Combine(folder, $"IMG_{4211 + i:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 88, App1Segments = [exif[4..]] })); + } + await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, CancellationToken.None); + var id = (await db.Sequences.ListLocationsAsync(archive.Id)).Single().Id; + await archives.SetSequenceInfoAsync(id, "Harbour sunset", ["sunset", "harbour"], 4, null); + + var source = new LocalSequenceSource(db, id, DecoderFactory.CreateClient(null), null); + var content = await source.LoadAsync(CancellationToken.None); + var deep = await DeepAnalyzer.AnalyzeAsync(new SunsetFrames(sunset)); + var sequence = content.Sequence; + deep.Save(new ArchivePaths(root).Sequence(sequence.Folder).AnalysisPath); + var advice = Advisor.Recommend(content.Light, deep, SequenceContext.FromFrames(content.Frames)); + await source.SaveProjectAsync(Advisor.Apply(content.Project, advice), content.Project, CancellationToken.None); + await db.Sequences.RecordAnalysisAsync(id, SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.HasWarnings, SequenceStatus.None, + advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning), AnalysisSummary.From(deep).ToJson()); + foreach (var (preset, codec, width, height, daysAgo, bytes) in new[] { ("4K archive", "hevc", 3840, 2160, 7, 2_210_000_000L), ("1080p share", "h264", 1920, 1080, 3, 412_000_000L) }) + { + await db.Renders.InsertAsync(new Render + { + Id = Guid.CreateVersion7(), + SequenceId = id, + PresetName = preset, + OutputPath = Path.Combine(folder, "exports", $"2026-09-28 Harbour sunset - {preset}.mp4"), + Codec = codec, + Width = width, + Height = height, + Fps = 24, + DurationSeconds = 5, + Bytes = bytes, + Created = DateTimeOffset.UtcNow.AddDays(-daysAgo), + ProducedBy = "studio-pc", + }); + } + return id; + } + + /// A two-minute sunset at 2 s intervals: darkening scene, flicker, two shutter steps the pixels received, warming light. + private static readonly SyntheticSequenceOptions EditorSunset = new() + { + Width = 600, + Height = 400, + FrameCount = 96, + Seed = 28, + Start = new DateTime(2026, 9, 28, 18, 2, 11), + IntervalSeconds = 2, + StartEv = 0.5, + EndEv = -2.5, + FlickerEv = 0.12, + ExposureSteps = [new SyntheticExposureStep(32, -1), new SyntheticExposureStep(64, -1)], + HorizonFraction = 0.62, + HorizonWave = 0.02, + SkyLevel = 0.32, + LandLevel = 0.06, + StartKelvin = 5600, + EndKelvin = 3200, + WhiteBalanceJitter = 0.03, + NoiseSigma = 0.002, + BaseExposureTime = 1.0 / 125, + BaseFNumber = 8, + BaseIso = 100, + CameraMake = "Canon", + CameraModel = "Canon EOS R5", + Lens = "RF15-35mm F2.8 L IS USM", + }; + + /// + /// The synthetic frame (its exposure truth: scene, steps, flicker, white balance) coloured as a harbour sunset: a + /// blue-to-amber sky gradient normalised to unit luminance, so the measured luminance keeps the truth, and a setting sun. + /// + private static ImageBuffer SunsetFrame(SyntheticSequence sequence, int index) + { + var image = sequence.Render(index); + var (w, h) = (image.Width, image.Height); + var t = index / (double)(sequence.Count - 1); + var horizon = sequence.Options.HorizonFraction * h; + var (sunX, sunY) = (w * 0.64, h * (0.28 + 0.3 * t)); + var gain = Math.Pow(2, sequence.SceneEv[index] + sequence.ExposureOffsetEv[index] + sequence.FlickerEv[index]); + double[][] sky = [Linear("#2A2F6B"), Linear("#8E3F57"), Linear("#E07A48"), Linear("#F5B45E")]; + var land = Linear("#3A3540"); + for (var y = 0; y < h; y++) + { + double[] colour; + if (y < horizon) + { + var f = y / horizon * (sky.Length - 1); + var k = Math.Min((int)f, sky.Length - 2); + colour = [.. Enumerable.Range(0, 3).Select(c => sky[k][c] + (sky[k + 1][c] - sky[k][c]) * (f - k))]; + } + else + { + colour = land; + } + var luminance = 0.2126 * colour[0] + 0.7152 * colour[1] + 0.0722 * colour[2]; + for (var x = 0; x < w; x++) + { + var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY)); + var sun = y < horizon ? gain * 4 * Math.Exp(-d * d / 220) : 0; + for (var c = 0; c < 3; c++) + { + var plane = image.Plane(c); + plane[y * w + x] = (float)(plane[y * w + x] * colour[c] / luminance + sun * (c == 0 ? 1.0 : c == 1 ? 0.75 : 0.45)); + } + } + } + return image; + } + + private static double[] Linear(string hex) + { + var rgb = Convert.FromHexString(hex.TrimStart('#')); + return [.. rgb.Select(v => ColorSpace.SrgbToLinear(v / 255.0))]; + } + + /// The sunset as the deep analysis reads it (the pixels written to the JPEGs, before compression). + private sealed class SunsetFrames(SyntheticSequence sequence) : IFrameSource + { + public int Count => sequence.Count; + + public LightFrame Metadata(int index) => LightFrame.From(sequence.Metadata[index], index); + + public ValueTask LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) => + ValueTask.FromResult(SunsetFrame(sequence, index)); + } + private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId) { var now = new DateTime(2026, 9, 28, 18, 2, 11); diff --git a/src/Titano.App/Editor/EditorImages.cs b/src/Titano.App/Editor/EditorImages.cs index aebf09a6..95ce23bb 100644 --- a/src/Titano.App/Editor/EditorImages.cs +++ b/src/Titano.App/Editor/EditorImages.cs @@ -28,10 +28,27 @@ public static class EditorImages public sealed class EditorThumbnails(ISequenceSource source, int count) : IThumbnailSource { private readonly SemaphoreSlim _decoders = new(int.Clamp(Environment.ProcessorCount / 2, 2, 6)); + private int _pending; public int Count { get; } = count; + /// Thumbnails requested and not yet returned (capture and tests wait for them). + public int Pending => Volatile.Read(ref _pending); + public async ValueTask GetAsync(int index, int pixelWidth, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _pending); + try + { + return await DecodeAsync(index, pixelWidth, cancellationToken); + } + finally + { + Interlocked.Decrement(ref _pending); + } + } + + private async Task DecodeAsync(int index, int pixelWidth, CancellationToken cancellationToken) { await _decoders.WaitAsync(cancellationToken); try diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs index 09ccf623..b0e3c41c 100644 --- a/src/Titano.App/Editor/EditorViewModel.cs +++ b/src/Titano.App/Editor/EditorViewModel.cs @@ -319,6 +319,38 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable Shell.Notify(Loc.L("Editor.Render.Queued"), request.Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); } + /// + /// Completes once the preview, corrections, plan, estimates and filmstrip thumbnails in flight are done (capture and + /// tests); a finished step may start the next (corrections re-render the preview), so it waits until all are quiet. + /// + /// False when the work was still going on after . + public async Task WhenIdleAsync(TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (deadline - DateTime.UtcNow is { Ticks: > 0 } left) + { + var work = Work(); + try + { + await Task.WhenAll(work).WaitAsync(left); + } + catch (TimeoutException) + { + return false; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // A failed run was already logged by its owner; it counts as done. + } + await Task.Delay(50); + // Quiet means nothing new was scheduled meanwhile (the same tasks) and no thumbnail is loading. + if (work.SequenceEqual(Work()) && (Thumbnails as EditorThumbnails)?.Pending is null or 0) return true; + } + return false; + + Task[] Work() => [_preview.Idle, _corrections.Idle, _plans.Idle, .. Tabs.OfType().Select(t => t.EstimatesIdle)]; + } + /// Loads the jobs of this sequence already queued or running (busy state). public async Task AttachJobsAsync() { diff --git a/src/Titano.App/Editor/ExportTab.cs b/src/Titano.App/Editor/ExportTab.cs index 938dad8e..049a167b 100644 --- a/src/Titano.App/Editor/ExportTab.cs +++ b/src/Titano.App/Editor/ExportTab.cs @@ -293,6 +293,9 @@ public sealed class ExportTab : EditorTab public IReadOnlyList Batch => Export.Batch; + /// Completes when the card estimates in flight are done. + public Task EstimatesIdle => _estimates.Idle; + private ExportSettings Export => Editor.Session.Project.Export; private ResolvedExport Resolved => Editor.Plan?.Export ?? ExportResolver.Resolve(Export); diff --git a/src/Titano.App/Editor/ExposureTab.cs b/src/Titano.App/Editor/ExposureTab.cs index 54fce348..1307b452 100644 --- a/src/Titano.App/Editor/ExposureTab.cs +++ b/src/Titano.App/Editor/ExposureTab.cs @@ -89,7 +89,7 @@ public sealed class ExposureTab : EditorTab if (content.Deep is { Regions: not null } withSky && withSky.Frames.SkyLogLuminance.Any(v => v is not null)) { series.Add(new ChartSeries(Loc.L("Editor.Chart.Sky"), withSky.Frames.SkyLogLuminance.Select(v => v ?? double.NaN).ToArray(), "Brush.Region") - { Dash = LineDash.Dashed }); + { Dash = LineDash.Dashed }); legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Sky"), "Brush.Region", LegendSwatch.DashedLine)); } var markers = EditorViewModel.StepMarkers(content); diff --git a/src/Titano.App/Shell/ScreenCapture.cs b/src/Titano.App/Shell/ScreenCapture.cs index 6a406d5a..2646ac07 100644 --- a/src/Titano.App/Shell/ScreenCapture.cs +++ b/src/Titano.App/Shell/ScreenCapture.cs @@ -4,6 +4,7 @@ using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using Titano.App.DesignTime; +using Titano.App.Editor; using Titano.App.Settings; using Titano.Core.Diagnostics; using Titano.Ui.Theming; @@ -97,6 +98,8 @@ public static class ScreenCapture written += await SaveAsync(window, directory, key.ToString().ToLowerInvariant(), theme); } } + + written += await CaptureEditorAsync(window, shell, sample, directory); Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}"); if (written == 0) Environment.ExitCode = 1; } @@ -111,6 +114,34 @@ public static class ScreenCapture } } + /// The sequence editor on the synthetic sunset: every section in both themes (sequence-<tab>-<theme>.png). + private static async Task CaptureEditorAsync(Window window, ShellViewModel shell, SampleData sample, string directory) + { + var written = 0; + var id = await sample.FillEditorAsync(); + shell.OpenSequence(id); + await shell.Sequence.OpenAsync(id); + if (shell.Sequence.Editor is not { } editor) + { + Log.Warning("capture", "The editor sample did not open"); + return 0; + } + foreach (var theme in Themes) + { + ThemeManager.Apply(theme); + foreach (var tab in editor.Tabs) + { + editor.SelectedTab = tab; + editor.CurrentIndex = tab is ExportTab ? 40 : 45; + await Settle(window); + if (!await editor.WhenIdleAsync(TimeSpan.FromSeconds(30))) Log.Warning("capture", $"The {tab.Key} section was still busy"); + written += await SaveAsync(window, directory, "sequence-" + tab.Key.ToLowerInvariant(), theme); + } + } + editor.SelectedTab = editor.Exposure; + return written; + } + private static async Task SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null) { await Settle(window); diff --git a/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs new file mode 100644 index 00000000..77ab4244 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs @@ -0,0 +1,177 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using Titano.App.DesignTime; +using Titano.App.Editor; +using Titano.App.Infrastructure; +using Titano.App.Sections; +using Titano.App.Shell; +using Titano.App.Tests.Windows; +using Titano.Core.Project; +using Titano.Testing; +using Titano.Ui.Theming; +using Titano.Ui.Visuals; + +namespace Titano.App.Tests.Editor; + +/// +/// The sequence editor in the real main window, off screen at the minimum capture size, on the synthetic sunset of +/// --capture (real JPEG frames, deep analysis, advised project): every section shows its measuring tool, its +/// settings and preview pixels in both themes, and an edit goes through undo and redo. +/// +[WindowsOnly] +[Serial] +[Timeout(300_000)] +public sealed class EditorSmokeTests +{ + private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light]; + + [Test] + public Task EverySectionOfTheEditorRendersInBothThemes() => ScreenHost.RunAsync(async () => + { + var environment = AppEnvironment.ForCapture(); + UiLanguage.Apply("en"); + ThemeManager.Apply(AppTheme.Dark); + var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs()); + var sample = SampleData.Configure(services); + var shell = new ShellViewModel(services); + 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(); + shell.OpenSequence(id); + await shell.Sequence.OpenAsync(id); + var editor = Assert.NotNull(shell.Sequence.Editor); + Assert.Equal(96, editor.FrameCount); + Assert.NotNull(editor.Session.Content.Deep, "the sample is analysed"); + Assert.True(editor.Session.Project.Exposure.Deflicker.HasAdvice, "the advice is in the project"); + Assert.Equal("Harbour sunset", editor.Title); + + foreach (var theme in Themes) + { + ThemeManager.Apply(theme); + foreach (var tab in editor.Tabs) + { + editor.SelectedTab = tab; + await SettleAsync(window); + Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), $"{tab.Key}: still busy"); + await SettleAsync(window); + var view = Find(window).Single(v => v.IsVisible); + Assert.NotNull(editor.PreviewImage, $"{tab.Key}: the preview shows pixels"); + ExpectMeasure(view, tab); + Assert.True(Find(view).Any(p => ReferenceEquals(p.Content, tab) && p.ActualHeight > 100), $"{tab.Key}: settings column"); + Assert.Greater(Distinct(Render(window)), 40, $"{tab.Key} drew almost nothing in {theme}"); + } + } + + // An edit through the session is undone and redone (Ctrl+Z / Ctrl+Y run the same commands). + ThemeManager.Apply(AppTheme.Dark); + var before = editor.Session.Project.Exposure.ExposureOffsetEv; + editor.Session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } }); + editor.UndoCommand.Execute(null); + Assert.Equal(before, editor.Session.Project.Exposure.ExposureOffsetEv); + editor.RedoCommand.Execute(null); + Assert.Equal(0.5, editor.Session.Project.Exposure.ExposureOffsetEv); + await editor.Session.FlushAsync(); + Assert.NotNull(editor.Plan, "the export is planned"); + } + finally + { + ThemeManager.Apply(AppTheme.Dark); + window.Close(); + await shell.Sequence.CloseAsync(); + shell.Dispose(); + await services.DisposeAsync(); + environment.DeleteCaptureData(); + } + }); + + /// The measuring tool of each section has content. + private static void ExpectMeasure(SequenceView view, EditorTab tab) + { + switch (tab) + { + case FramesTab frames: + Assert.Equal(96, frames.Frames.Count); + Assert.NotEmpty(Find(view).Where(i => i.DataContext is FrameRow && i.IsVisible)); + break; + case CameraTab or TimeTab: + Assert.NotEmpty(Find(view).Where(c => c.IsVisible && c.ActualHeight > 50)); + break; + case ExportTab export: + Assert.NotEmpty(export.Cards); + Assert.NotEmpty(Find