diff --git a/src/Titano.Setup/Program.cs b/src/Titano.Setup/Program.cs index 0b8fb35c..abb738c3 100644 --- a/src/Titano.Setup/Program.cs +++ b/src/Titano.Setup/Program.cs @@ -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 diff --git a/src/Titano.Setup/Views/SetupCapture.cs b/src/Titano.Setup/Views/SetupCapture.cs new file mode 100644 index 00000000..1212b8e9 --- /dev/null +++ b/src/Titano.Setup/Views/SetupCapture.cs @@ -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; + +/// +/// Titano.Setup.exe --capture <dir>: 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. +/// +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), + ]; + + /// What a user data folder typically holds; eight entries, so the plan also shows its "more" line. + 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), + ]); + + /// Returns the process exit code: 0 when every screen was written. + 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 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); + } + } + + /// One window per model; each screen puts the model in its stage and is saved as <file>.png. + 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(); + } + } + + /// Three components of random (incompressible) bytes, with the shortcuts the real installer carries. + 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); + } + + /// + /// 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. + /// + 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; + } +} diff --git a/src/Titano.Setup/Views/SetupViewModel.cs b/src/Titano.Setup/Views/SetupViewModel.cs index d97f6046..d8b0d190 100644 --- a/src/Titano.Setup/Views/SetupViewModel.cs +++ b/src/Titano.Setup/Views/SetupViewModel.cs @@ -361,6 +361,23 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo if (_arguments.Elevated && IsInstall && CanStart) Start(InstallAsync); } + /// + /// For --capture only: shows 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. + /// + 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(); diff --git a/src/Titano.Uploader/Shell/MainWindow.xaml b/src/Titano.Uploader/Shell/MainWindow.xaml index d2f8ad97..5ac396ae 100644 --- a/src/Titano.Uploader/Shell/MainWindow.xaml +++ b/src/Titano.Uploader/Shell/MainWindow.xaml @@ -184,7 +184,7 @@ - @@ -353,7 +353,7 @@ - diff --git a/src/Titano.Uploader/Shell/MainWindow.xaml.cs b/src/Titano.Uploader/Shell/MainWindow.xaml.cs index bf662766..1fb9c262 100644 --- a/src/Titano.Uploader/Shell/MainWindow.xaml.cs +++ b/src/Titano.Uploader/Shell/MainWindow.xaml.cs @@ -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); } /// Focuses once a visibility change has been laid out; text is selected so typing replaces it. diff --git a/tests/Titano.App.Tests/Uploader/UploaderScreenSmokeTests.cs b/tests/Titano.App.Tests/Uploader/UploaderScreenSmokeTests.cs new file mode 100644 index 00000000..c38aa04f --- /dev/null +++ b/tests/Titano.App.Tests/Uploader/UploaderScreenSmokeTests.cs @@ -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; + +/// +/// The uploader window on the --capture 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. +/// +[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()) + 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("ItemList"))); + var rows = screen.Visible(); + 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