feat(setup): --capture renders every setup stage, uninstall plan and Arabic layout

The installer had no screenshot mode, so CI could not review its stages. Titano.Setup.exe --capture <dir>
builds a small sample installer in a temporary folder and renders install options, programs running,
installing, installed, failed and uninstall with the "Remove my data" plan, in the dark and light themes and
in Arabic (mirrored). Nothing is installed, removed or registered.

Also: uploader smoke tests (names, focusable rows, no premature errors, right-to-left islands), and watch
chips cap the path itself because the button template measures content without a width limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 17:20:42 +00:00
1 parent 1187c36d66
commit 39627b3f4a
6 files changed
+415 -6

No files matched your search

+2
View File
@@ -18,6 +18,8 @@ internal static class Program
using var log = new FileLogSink(SetupPaths.LogDirectory, "setup");
Log.SetSink(log);
Log.Info("setup", $"Titano.Setup {typeof(Program).Assembly.GetName().Version} {string.Join(' ', args)}");
// The screenshot mode of every Titano program (CI); it builds its own sample installer.
if (args is ["--capture", var captureDirectory]) return Views.SetupCapture.Run(captureDirectory);
SetupArguments arguments;
try
+196
View File
@@ -0,0 +1,196 @@
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.Core.Diagnostics;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Engine;
using Titano.Ui.Theming;
namespace Titano.Setup.Views;
/// <summary>
/// <c>Titano.Setup.exe --capture &lt;dir&gt;</c>: renders the setup window in every stage (install options, programs
/// running, installing, installed, failed, uninstall with its data plan) in the dark and light themes, then in
/// Arabic (right to left, dark), from a small sample installer built in a temporary folder. Nothing is installed,
/// removed or registered.
/// </summary>
internal static class SetupCapture
{
private const string Product = "Titano";
private static readonly (string Name, SetupStage Stage)[] InstallStages =
[
("install", SetupStage.Options),
("running", SetupStage.Confirm),
("installing", SetupStage.Working),
("installed", SetupStage.Done),
("failed", SetupStage.Failed),
];
/// <summary>What a user data folder typically holds; eight entries, so the plan also shows its "more" line.</summary>
private static readonly UserDataPlan SamplePlan = new(
[
new UserDataEntry("cache", 2_140_000_000),
new UserDataEntry("backups", 1_210_000_000),
new UserDataEntry("titano.db", 41_000_000),
new UserDataEntry("logs", 12_400_000),
new UserDataEntry("titano.db-wal", 4_200_000),
new UserDataEntry("uploader-queue.json", 1_900_000),
new UserDataEntry("settings.json", 3_100),
new UserDataEntry("uploader.json", 1_200),
]);
/// <summary>Returns the process exit code: 0 when every screen was written.</summary>
public static int Run(string directory)
{
var work = Directory.CreateTempSubdirectory("titano-setup-capture-").FullName;
try
{
var installer = WriteSampleInstaller(work);
var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
ThemeManager.Initialize(app, AppTheme.Dark);
var code = 0;
app.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
{
try
{
Directory.CreateDirectory(directory);
CaptureLanguage(installer, directory, "en", string.Empty, [AppTheme.Dark, AppTheme.Light]);
// Mirrored layout with paths and file names kept left to right (BRIEF §16).
CaptureLanguage(installer, directory, "ar", "-ar", [AppTheme.Dark]);
Log.Info("capture", $"Screenshots written to {Path.GetFullPath(directory)}");
}
catch (Exception ex)
{
Log.Error("capture", "Capture failed", ex);
code = 1;
}
finally
{
app.Shutdown();
}
});
app.Run();
return code;
}
finally
{
try
{
Directory.Delete(work, recursive: true);
}
catch (IOException ex)
{
// The sample installer may still be mapped; the OS temp cleanup takes it.
Log.Warning("capture", $"Sample installer folder '{work}' not removed", ex);
}
}
}
private static void CaptureLanguage(string installer, string directory, string language, string suffix, IReadOnlyList<AppTheme> themes)
{
Program.ApplyLanguage(language);
using var payload = PayloadReader.Open(installer);
using var install = SetupViewModel.ForInstall(new SetupArguments(), payload);
using var uninstall = SetupViewModel.ForUninstall(new SetupArguments(), new InstalledProduct(
SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product), new InstallLog { Product = Product, Version = "1.0.0" }));
foreach (var theme in themes)
{
ThemeManager.Apply(theme);
var name = suffix + "-" + theme.ToString().ToLowerInvariant();
Capture(install, [.. InstallStages.Select(s => ("setup-" + s.Name + name, s.Stage, (UserDataPlan?)null))], directory);
Capture(uninstall, [("setup-uninstall" + name, SetupStage.Options, SamplePlan)], directory);
}
}
/// <summary>One window per model; each screen puts the model in its stage and is saved as <c>&lt;file&gt;.png</c>.</summary>
private static void Capture(SetupViewModel model, IReadOnlyList<(string File, SetupStage Stage, UserDataPlan? Plan)> screens, string directory)
{
var window = new SetupWindow(model)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
foreach (var (file, stage, plan) in screens)
{
model.Preview(stage, plan);
Save(window, Path.Combine(directory, file + ".png"));
}
}
finally
{
window.Close();
}
}
/// <summary>Three components of random (incompressible) bytes, with the shortcuts the real installer carries.</summary>
private static string WriteSampleInstaller(string work)
{
var random = new Random(1);
var components = new (string Id, string DisplayName, bool Selected, string Program, int Bytes)[]
{
("Titano", "Titano", true, "Titano.exe", 2_400_000),
("Uploader", "Titano Uploader", true, "Titano.Uploader.exe", 900_000),
("Server", "Titano Server", false, "Titano.Server.exe", 1_600_000),
};
foreach (var c in components)
{
var folder = Directory.CreateDirectory(Path.Combine(work, c.Id)).FullName;
var bytes = new byte[c.Bytes];
random.NextBytes(bytes);
File.WriteAllBytes(Path.Combine(folder, c.Program), bytes);
}
var installer = Path.Combine(work, "setup.exe");
PayloadWriter.Write(Environment.ProcessPath ?? throw new InvalidOperationException("No process path."), new PayloadSource
{
Product = Product,
Version = "1.0.0",
Components = [.. components.Select(c => new PayloadComponentSource(c.Id, c.DisplayName, c.Selected, Path.Combine(work, c.Id)))],
Shortcuts = [.. components.Select(c => new PayloadShortcut { Component = c.Id, Name = c.DisplayName, Target = c.Program, StartMenu = true, Desktop = c.Id != "Server" })],
}, installer);
return installer;
}
private static void Save(Window window, string path)
{
// Let bindings, templates and deferred layout complete.
window.UpdateLayout();
window.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, () => { });
window.UpdateLayout();
if (VisualTreeHelper.GetChildrenCount(window) == 0) return;
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
var dpi = VisualTreeHelper.GetDpi(window);
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
if (width <= 0 || height <= 0) return;
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
bitmap.Render(window.FlowDirection == FlowDirection.RightToLeft ? Mirrored(root) : root);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path);
encoder.Save(stream);
}
/// <summary>
/// A right-to-left window is mirrored by a transform on the window itself, which rendering its content alone
/// would leave out: draw the content through that mirror.
/// </summary>
private static DrawingVisual Mirrored(FrameworkElement root)
{
var size = new Rect(0, 0, root.ActualWidth, root.ActualHeight);
var visual = new DrawingVisual();
using var dc = visual.RenderOpen();
dc.PushTransform(new MatrixTransform(-1, 0, 0, 1, size.Width, 0));
dc.DrawRectangle(new VisualBrush(root) { Stretch = Stretch.Fill, ViewboxUnits = BrushMappingMode.Absolute, Viewbox = size }, null, size);
return visual;
}
}
+17
View File
@@ -361,6 +361,23 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
if (_arguments.Elevated && IsInstall && CanStart) Start(InstallAsync);
}
/// <summary>
/// For <c>--capture</c> only: shows <paramref name="stage"/> with sample progress and outcome (a program to
/// launch, a full disk) and, when given, a data plan with "Remove my data" checked. Nothing runs.
/// </summary>
internal void Preview(SetupStage stage, UserDataPlan? dataPlan = null)
{
_runningPrograms = "Titano Uploader";
_progress = 0.46;
_indeterminate = false;
_progressFile = @"Titano\Titano.Core.dll";
_launchProgram = IsInstall ? "Titano.exe" : null;
_failure = SetupExitCode.DiskFull;
_dataPlan = dataPlan;
_removeUserData = dataPlan is not null;
Stage = stage;
}
public override void Dispose()
{
foreach (var c in Components) c.Dispose();
+5 -3
View File
@@ -184,7 +184,7 @@
</ItemsControl>
<TextBlock Grid.Row="2" Text="{l:Loc Uploader.Connect.User}" Style="{StaticResource Text.Label}" Margin="0,12,12,0" />
<TextBox Grid.Row="2" Grid.Column="1" Margin="0,12,0,0" Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.User}"
<TextBox x:Name="UserBox" Grid.Row="2" Grid.Column="1" Margin="0,12,0,0" Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.User}"
ToolTip="{l:Loc Tooltips.Uploader.User}" AutomationProperties.Name="{l:Loc Uploader.Connect.User}" />
<TextBlock Grid.Row="3" Text="{l:Loc Uploader.Connect.Password}" Style="{StaticResource Text.Label}" Margin="0,12,12,0" />
@@ -353,7 +353,7 @@
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type s:WatchFolderViewModel}">
<Button Style="{StaticResource Button.Chip}" MaxWidth="260" Margin="0,0,10,4" Click="OnWatchChipClick" ToolTip="{Binding ToolTip}"
<Button Style="{StaticResource Button.Chip}" Margin="0,0,10,4" Click="OnWatchChipClick" ToolTip="{Binding ToolTip}"
AutomationProperties.Name="{Binding Text}">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding MenuOptions}" ItemContainerStyle="{StaticResource WatchMenuItem}" />
@@ -363,7 +363,9 @@
Fill="{DynamicResource Brush.TextFaint}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding IntervalText}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="·" Foreground="{DynamicResource Brush.TextFaint}" Margin="6,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding Path}" FlowDirection="LeftToRight" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
<!-- The button template lays content out without a width limit, so the path carries its own. -->
<TextBlock Text="{Binding Path}" MaxWidth="180" FlowDirection="LeftToRight" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
</DockPanel>
</Button>
<DataTemplate.Triggers>
+5 -3
View File
@@ -147,8 +147,9 @@ public sealed partial class MainWindow : TitanoWindow
switch (e.PropertyName)
{
case nameof(MainViewModel.CurrentItem) when _vm.CurrentItem is { } item && !ItemList.IsKeyboardFocusWithin:
// Follow the upload unless the user is reading the list with the keyboard.
ScrollNearTop(item);
// Follow the upload unless the user is reading the list with the keyboard; a list that has just
// appeared has its scroll viewer once it is laid out.
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => ScrollNearTop(item));
break;
// Raised with every session change; only a real switch between the form and the queue moves the keyboard.
case nameof(MainViewModel.IsConnectVisible) when _vm.IsConnectVisible != _connectShown:
@@ -188,7 +189,8 @@ public sealed partial class MainWindow : TitanoWindow
private void FocusStart()
{
if (!_vm.IsConnectVisible) FocusLater(BrowseButton);
else FocusLater(_vm.Connect.Address.Length == 0 || _vm.Connect.Username.Length == 0 ? AddressBox : Password);
else if (_vm.Connect.Address.Length == 0) FocusLater(AddressBox);
else FocusLater(_vm.Connect.Username.Length == 0 ? UserBox : Password);
}
/// <summary>Focuses <paramref name="target"/> once a visibility change has been laid out; text is selected so typing replaces it.</summary>
@@ -0,0 +1,190 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Uploader.DesignTime;
using Titano.Uploader.Shell;
using Titano.Uploader.Uploads;
namespace Titano.App.Tests.Uploader;
/// <summary>
/// The uploader window on the <c>--capture</c> sample data, shown off screen: icon-only buttons and queue rows are
/// named for screen readers, rows take keyboard focus, no field shows an error before use, disabled controls say
/// why, and in a right-to-left language the window mirrors while paths, file names and the media glyph do not.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(120_000)]
public sealed class UploaderScreenSmokeTests
{
[Test]
public Task EveryScreenIsNamedFocusableAndCalm() => ScreenHost.RunAsync(async () =>
{
UiLanguage.Apply("en");
using var screen = await UploaderScreen.OpenAsync();
var vm = screen.ViewModel;
screen.Sample.ShowConnect();
await screen.SettleAsync();
Assert.Equal(FlowDirection.LeftToRight, screen.Window.FlowDirection);
Assert.False(vm.Connect.HasErrors, "the address is not marked before a sign-in");
Assert.Null(vm.Connect.PasswordError);
Assert.Null(vm.Connect.ErrorText);
foreach (var box in screen.Visible<TextBox>())
Assert.False(Validation.GetHasError(box), $"{AutomationProperties.GetName(box)} shows an error before use");
screen.AssertIconButtonsNamed("connect");
screen.Sample.ShowQueue();
await screen.SettleAsync();
screen.AssertIconButtonsNamed("queue");
Assert.Equal(Loc.L("Uploader.Queue.List"), AutomationProperties.GetName(screen.Named<ListBox>("ItemList")));
var rows = screen.Visible<ListBoxItem>();
Assert.NotEmpty(rows);
foreach (var row in rows)
{
Assert.True(row.Focusable, "queue rows take keyboard focus");
var item = (UploadItem)row.DataContext;
var name = UIElementAutomationPeer.CreatePeerForElement(row)?.GetName();
Assert.Contains(item.FileName, name);
Assert.Contains(UploadStateTextConverter.Text(item.State), name);
}
Assert.Contains(rows, r => r.DataContext == vm.CurrentItem);
Assert.NotNull(vm.FirstFailed());
Assert.NotNull(vm.FailedText);
Assert.True(screen.Named<Button>("FailedLink").IsVisible, "the failure count is a link to the failed file");
// Disabled controls say why; the settings panel keeps Tab inside it.
Assert.Equal(Loc.L("Tooltips.Uploader.SequenceDisabled"), vm.SequenceToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Pause"), vm.PauseToolTip);
Assert.Equal(Loc.L("Tooltips.Uploader.Stop"), vm.StopToolTip);
Assert.Equal(KeyboardNavigationMode.Cycle, KeyboardNavigation.GetTabNavigation(screen.Named<Border>("SettingsPanel")));
vm.IsSettingsOpen = true;
await screen.SettleAsync();
screen.AssertIconButtonsNamed("settings");
vm.IsSettingsOpen = false;
});
[Test]
public Task TheWindowMirrorsForRightToLeftLanguages() => ScreenHost.RunAsync(async () =>
{
UiLanguage.Apply("ar");
try
{
using var screen = await UploaderScreen.OpenAsync();
screen.Sample.ShowQueue();
await screen.SettleAsync();
Assert.Equal(FlowDirection.RightToLeft, screen.Window.FlowDirection);
// File names, paths and addresses read left to right in every language.
var fileNames = screen.Visible<ListBoxItem>().Select(r => ((UploadItem)r.DataContext).FileName).ToHashSet();
var islands = screen.Visible<TextBlock>()
.Where(t => fileNames.Contains(t.Text) || t.Text.Contains('\\') || t.Text.StartsWith("https://", StringComparison.Ordinal))
.ToList();
Assert.NotEmpty(islands);
foreach (var text in islands) Assert.Equal(FlowDirection.LeftToRight, text.FlowDirection, text.Text);
// Media glyphs (pause, play) are not mirrored.
var pause = screen.Visible<Button>().Single(b => AutomationProperties.GetName(b) == screen.ViewModel.PauseLabel);
Assert.Equal(FlowDirection.LeftToRight, pause.FlowDirection);
screen.Sample.ShowConnect();
await screen.SettleAsync();
Assert.Equal(FlowDirection.LeftToRight, screen.Named<TextBox>("AddressBox").FlowDirection);
var mark = screen.Visible<BrandMarkIcon>().Single(m => m.ActualWidth >= 48);
Assert.Equal(FlowDirection.LeftToRight, mark.FlowDirection);
}
finally
{
UiLanguage.Apply("en");
}
});
/// <summary>A <see cref="MainWindow"/> on <see cref="SampleData"/>, shown off screen like <c>--capture</c>.</summary>
private sealed class UploaderScreen : IDisposable
{
private UploaderScreen(SampleData sample, MainViewModel viewModel, MainWindow window)
{
Sample = sample;
ViewModel = viewModel;
Window = window;
}
public SampleData Sample { get; }
public MainViewModel ViewModel { get; }
public MainWindow Window { get; }
public static async Task<UploaderScreen> OpenAsync()
{
ThemeManager.Apply(AppTheme.Dark);
var sample = new SampleData();
var vm = sample.CreateViewModel();
var window = new MainWindow(vm, sample.Settings)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 760,
Height = 700,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
var screen = new UploaderScreen(sample, vm, window);
await screen.SettleAsync();
return screen;
}
public async Task SettleAsync()
{
Window.UpdateLayout();
// Bindings, templates and the work the window defers to the dispatcher (scrolling, focus).
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
Window.UpdateLayout();
}
public List<T> Visible<T>()
where T : FrameworkElement => [.. All<T>(Window).Where(e => e.IsVisible)];
public T Named<T>(string name)
where T : FrameworkElement => All<T>(Window).Single(e => e.Name == name);
/// <summary>DESIGN §4: an icon-only button carries an accessible name (and a tooltip).</summary>
public void AssertIconButtonsNamed(string screen)
{
foreach (var button in Visible<Button>().Where(b => b.Content is null))
{
Assert.False(string.IsNullOrWhiteSpace(AutomationProperties.GetName(button)), $"{screen}: an icon-only button has no name");
Assert.True(button.ToolTip is not null, $"{screen}: {AutomationProperties.GetName(button)} has no tooltip");
}
}
public void Dispose()
{
Window.Close();
ViewModel.Dispose();
}
private static IEnumerable<T> All<T>(DependencyObject node)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) yield return match;
foreach (var nested in All<T>(child)) yield return nested;
}
}
}
}