Files
Chronos/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs
T
Claude f7a7506fe7 fix(app): say why an action failed in localized words, not exception text
Error toasts showed the exception's own message, often technical English from
.NET or the OS, under a translated title. The editor's failed save, a job posted
to the server from the Library, and the card check or delete after an import now
say why in one catalog sentence: what the server answered or that it does not
answer, that the card left, is locked or a file could not be read, and the
archive causes of ArchiveFailures for a local save. The details stay in the log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 10:13:34 +00:00

371 lines
18 KiB
C#

using System.Collections.Specialized;
using System.Globalization;
using System.Net.Http;
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.Advice;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Editor;
/// <summary>
/// The sequence editor in the real main window, off screen at the minimum capture size, on the synthetic sunset of
/// <c>--capture</c> (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.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class EditorSmokeTests
{
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
/// <summary>Here rather than with the other texts: it switches the UI language, which only a serial class may do.</summary>
[Test]
public void AnOptimiseLinePointsFromTheOldValueToTheNewOneInEitherReadingDirection()
{
var change = new SettingChange(AdvisorParameters.DeflickerWindow, 21, 41, "reason", []);
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Equal("Deflicker window: 21 frames → 41 frames", EditorText.Change(change));
Loc.SetCulture(CultureInfo.GetCultureInfo("ar"));
Assert.Equal(Loc.L("Editor.Optimise.ChangeRtl", Loc.L("Editor.Exposure.Window"), Loc.Plural("Editor.Value.Frames", 21), Loc.Plural("Editor.Value.Frames", 41)),
EditorText.Change(change), "Arabic reads the old value first, from the right");
Assert.Contains("←", EditorText.Change(change));
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[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);
Assert.Equal("Titano — Harbour sunset", shell.WindowTitle, "the window title follows the open sequence");
Assert.False(shell.IsJobBarVisible, "the idle job bar gives its height to the editor");
// The Render split button can be clicked once the plan exists (its command re-reads its state).
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await SettleAsync(window);
Assert.True(editor.CanRender, editor.RenderBlockedReason ?? "renderable");
var render = Find<SplitButton>(window).Single(b => b.IsVisible);
Assert.True(Find<Button>(render).First().IsEnabled, "Render is enabled");
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<SequenceView>(window).Single(v => v.IsVisible);
Assert.NotNull(editor.PreviewImage, $"{tab.Key}: the preview shows pixels");
ExpectMeasure(view, tab);
Assert.True(Find<ContentPresenter>(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}");
}
}
// The Export tab: Add to queue and Batch follow the plan and the ticked presets.
ThemeManager.Apply(AppTheme.Dark);
var export = editor.Tabs.OfType<ExportTab>().Single();
editor.ShowVectors = true;
editor.SelectedTab = export;
await SettleAsync(window);
Assert.False(Find<PreviewViewport>(window).Single(p => p.IsVisible).ShowVectors, "a tool without a button on the Export tab draws nothing");
Assert.True(export.AddToQueueCommand.CanExecute(null));
Assert.False(export.BatchCommand.CanExecute(null), "nothing ticked");
var batchButton = Find<Button>(window).Single(b => ReferenceEquals(b.Command, export.BatchCommand));
Assert.False(batchButton.IsEnabled);
export.Cards.First(c => c.CanBatch).IsInBatch = true;
await SettleAsync(window);
Assert.True(batchButton.IsEnabled, "ticking a card enables Batch…");
editor.ShowVectors = false;
// The waveform of the Exposure tab is measured from the preview.
editor.SelectedTab = editor.Exposure;
editor.Exposure.ChartMode = ExposureChart.Waveform;
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.NotNull(editor.WaveformImage, "the waveform shows the frame on screen");
editor.Exposure.ChartMode = ExposureChart.Luminance;
// 1:1 renders the source's own pixels; Fit returns to the view's size.
editor.ZoomMode = PreviewZoomMode.Actual;
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.Equal(editor.Session.Content.SourceWidth, ((BitmapSource)editor.PreviewImage!).PixelWidth, "1:1 shows source pixels");
editor.ZoomMode = PreviewZoomMode.Fit;
// A language switch makes again what the tabs keep in objects: the chart legend and the Auto chips follow at once.
var chip = editor.Exposure.Rows.OfType<AutoSwitchRow>().First();
var english = chip.AutoText;
UiLanguage.Apply("it");
try
{
Assert.True(editor.Exposure.Legend.Any(i => i.Text == "luminanza misurata"), "the legend follows the language");
Assert.Equal(Loc.L("Common.Auto") + Loc.Separator + Loc.L(chip.IsOn ? "Editor.Value.On" : "Editor.Value.Off"), chip.AutoText);
Assert.NotEqual(english, chip.AutoText);
}
finally
{
UiLanguage.Apply("en");
}
// 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.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
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();
}
});
/// <summary>
/// A server sequence opened with this PC's proxies (the sample server's Sunrise over Superga): the header names the
/// server, the preview shows a proxy, Save to and Sync wait for the server, and Render posts a server job.
/// </summary>
[Test]
public Task AServerSequenceOpensWithItsProxies() => 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();
await sample.FillAsync();
await services.Server.RestoreAsync();
await services.Sync.RefreshAsync();
await sample.CacheProxiesAsync();
var id = sample.ProxiedSequenceId;
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(shell.Sequence.Editor);
Assert.True(editor.IsRemote);
Assert.Equal("Studio NAS", editor.RemoteText);
Assert.Equal(3, editor.FrameCount);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await SettleAsync(window);
Assert.NotNull(editor.PreviewImage, "the preview shows a proxy");
var view = Find<SequenceView>(window).Single(v => v.IsVisible);
Assert.True(Find<StatusGlyph>(view).Any(g => g is { Kind: StatusKind.Remote, IsVisible: true, Text: "Studio NAS" }), "the header names the server");
Assert.Greater(Distinct(Render(window)), 40, "the remote editor drew almost nothing");
var export = editor.Tabs.OfType<ExportTab>().Single();
editor.SelectedTab = export;
await SettleAsync(window);
Assert.Equal(ExportSyncGate.Remote, editor.SyncGate);
Assert.False(Find<CheckBox>(view).Single(c => ReferenceEquals(c.DataContext, export) && c.IsVisible).IsEnabled, "Sync: the server's renders stay there");
Assert.False(Find<ComboBox>(view).Single(c => ReferenceEquals(c.ItemsSource, export.SaveChoices)).IsEnabled, "Save to: the server's exports folder");
Assert.True(editor.CanRender, editor.RenderBlockedReason ?? "renderable");
await editor.RenderAsync(JobPriority.User, batch: false);
var queued = Assert.Contains(await editor.Session.Source.ListJobsAsync(CancellationToken.None), _ => true);
Assert.Equal(JobKind.Render, queued.Kind);
// Without the Edit right a server sequence is only shown: every change is disabled and says why.
var content = EditorFixture.Content(EditorFixture.Sunset);
var looking = new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content) { IsRemote = true, IsReadOnly = true }, content, []);
var viewer = new EditorViewModel(shell, looking, [], EncoderHost.Client);
await using (viewer)
{
Assert.False(viewer.IsEditable);
Assert.Equal(Loc.L("Tooltips.Editor.ReadOnly"), viewer.LockedToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.ReadOnly"), viewer.Frames.HeroToolTip);
Assert.False(viewer.Frames.SetHeroCommand.CanExecute(null));
Assert.False(viewer.OptimiseAllCommand.CanExecute(null));
Assert.False(viewer.AnalyseCommand.CanExecute(null));
}
// A failed save says why in one localized sentence (BRIEF §0.2 rule 6); the exception's own text stays in the log.
var toasts = new List<Toast>();
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
shell.PendingToasts.CollectionChanged += collect;
try
{
foreach (var (remote, failure, cause) in new (bool, Exception, string)[]
{
(true, new HttpRequestException("No such host is known."), "Server.Error.Unreachable"),
(false, new UnauthorizedAccessException(@"Access to the path 'D:\Archive\.titano\sequence.json' is denied."), "Archive.Failed.Access"),
})
{
toasts.Clear();
var saving = new FakeSequenceSource(EditorFixture.Sunset, content) { IsRemote = remote, FailNextSave = failure };
var failing = new EditorViewModel(shell, new EditorSession(saving, content, []), [], EncoderHost.Client);
await using (failing)
{
failing.Session.Edit(p => p with { HeroFrame = 1 });
Assert.False(await failing.Session.FlushAsync(), "the save failed");
var toast = Assert.Contains(toasts, t => t.Title == Loc.L("Editor.Save.Failed"));
Assert.Equal(Loc.L(cause), toast.Message);
}
}
}
finally
{
shell.PendingToasts.CollectionChanged -= collect;
}
}
finally
{
window.Close();
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
environment.DeleteCaptureData();
}
});
/// <summary>The measuring tool of each section has content.</summary>
private static void ExpectMeasure(SequenceView view, EditorTab tab)
{
switch (tab)
{
case FramesTab frames:
Assert.Equal(96, frames.Frames.Count);
Assert.NotEmpty(Find<ListBoxItem>(view).Where(i => i.DataContext is FrameRow && i.IsVisible));
break;
case CameraTab or TimeTab:
Assert.NotEmpty(Find<CurveEditor>(view).Where(c => c.IsVisible && c.ActualHeight > 50));
break;
case ExportTab export:
Assert.NotEmpty(export.Cards);
Assert.NotEmpty(Find<Button>(view).Where(b => b.DataContext is PresetCard && b.IsVisible));
Assert.True(export.Cards.Any(c => c.Estimate is not null), "estimates on the cards");
break;
default:
var chart = Find<SeriesChart>(view).Single(c => c.IsVisible);
Assert.True(chart.ActualHeight > 50, $"{tab.Key}: chart height");
Assert.NotEmpty(chart.Series!);
break;
}
}
private static async Task SettleAsync(Window window)
{
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
private static RenderTargetBitmap Render(Window window)
{
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
var dpi = VisualTreeHelper.GetDpi(window);
var bitmap = new RenderTargetBitmap((int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX), (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY),
dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
bitmap.Render(root);
return bitmap;
}
private static int Distinct(BitmapSource bitmap)
{
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
var colours = new HashSet<int>();
for (var i = 0; i < pixels.Length && colours.Count < 2000; i += 4 * 5) colours.Add(BitConverter.ToInt32(pixels, i));
return colours.Count;
}
private static List<T> Find<T>(DependencyObject root)
where T : DependencyObject
{
var found = new List<T>();
var stack = new Stack<DependencyObject>([root]);
while (stack.TryPop(out var node))
{
if (node is T match) found.Add(match);
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) stack.Push(VisualTreeHelper.GetChild(node, i));
}
return found;
}
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}