merge: integration branch into the shared fixes; every window takes its reading direction from TitanoWindow

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-06 07:52:36 +00:00
commit 70dc18787a
286 files changed
+18007 -738

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
using System.IO;
namespace Titano.Setup.Engine;
/// <summary>One top-level file or folder of the user data folder and the bytes it holds.</summary>
internal sealed record UserDataEntry(string Name, long Bytes);
/// <summary>
/// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): every top-level
/// entry of the user data folder with its size, largest first. Links are not followed, as the deletion does not
/// follow them either.
/// </summary>
internal sealed record UserDataPlan(IReadOnlyList<UserDataEntry> Entries)
{
private static readonly EnumerationOptions TopLevel = new() { IgnoreInaccessible = true, AttributesToSkip = 0 };
private static readonly EnumerationOptions Contents = new()
{
RecurseSubdirectories = true,
IgnoreInaccessible = true,
AttributesToSkip = FileAttributes.ReparsePoint,
};
public long TotalBytes => Entries.Sum(e => e.Bytes);
/// <summary>Measures <paramref name="folder"/>; empty when it does not exist. Reads sizes only, changes nothing.</summary>
public static UserDataPlan Measure(string folder)
{
var root = new DirectoryInfo(folder);
if (!root.Exists) return new UserDataPlan([]);
var entries = root.EnumerateFileSystemInfos("*", TopLevel).Select(e => new UserDataEntry(e.Name, SizeOf(e)));
return new UserDataPlan([.. entries.OrderByDescending(e => e.Bytes).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)]);
}
private static long SizeOf(FileSystemInfo entry) => entry switch
{
_ when entry.Attributes.HasFlag(FileAttributes.ReparsePoint) => 0,
DirectoryInfo folder => folder.EnumerateFiles("*", Contents).Sum(f => f.Length),
FileInfo file => file.Length,
_ => 0,
};
}
+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
+4 -4
View File
@@ -30,20 +30,20 @@ internal sealed class ComponentOption(PayloadComponent component, bool selected,
/// <summary>Language offered in the picker.</summary>
internal sealed record LanguageOption(string Code, string Name);
/// <summary>Decimal byte sizes as Explorer shows them for drives ("1.5 MB").</summary>
/// <summary>Decimal byte sizes as Explorer shows them for drives ("1.5 MB"), units in the UI language ("1,5 Mo").</summary>
internal static class ByteSize
{
private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"];
private static readonly string[] Formats = ["Common.Size.B", "Common.Size.KB", "Common.Size.MB", "Common.Size.GB", "Common.Size.TB"];
public static string Format(long bytes)
{
double value = bytes;
var unit = 0;
while (value >= 1000 && unit < Units.Length - 1)
while (value >= 1000 && unit < Formats.Length - 1)
{
value /= 1000;
unit++;
}
return value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture) + " " + Units[unit];
return Loc.L(Formats[unit], value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture));
}
}
+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;
}
}
+93 -3
View File
@@ -11,6 +11,9 @@ using Titano.Ui.Mvvm;
namespace Titano.Setup.Views;
/// <summary>A line of the "Remove my data" dry run: a file or folder name (or "3 more items") and its size.</summary>
internal sealed record DataPlanRow(string Name, string Size, bool IsFileName);
/// <summary>What the setup screen currently shows.</summary>
internal enum SetupStage
{
@@ -28,6 +31,10 @@ internal enum SetupStage
internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
{
private const string FallbackProduct = "Titano";
/// <summary>Largest entries listed in the data plan; the rest are summed in one line.</summary>
private const int PlanRows = 6;
private readonly SetupArguments _arguments;
private readonly PayloadReader? _payload;
private readonly InstallEngine? _engine;
@@ -42,6 +49,8 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private bool _startMenu;
private bool _launchAfter;
private bool _removeUserData;
private UserDataPlan? _dataPlan;
private bool _measuring;
private bool _closeConfirmed;
private double _progress;
private bool _indeterminate;
@@ -197,6 +206,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
if (!Set(ref _directory, value ?? string.Empty)) return;
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory)));
OnPropertyChanged(nameof(DirectoryToolTip));
OnPropertyChanged(nameof(InstallToolTip));
}
}
@@ -206,6 +216,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
? Loc.L("Tooltips.Setup.Locked")
: IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : Loc.L("Tooltips.Setup.FolderInvalid");
/// <summary>Browse is disabled when upgrading; its tooltip then says why (DESIGN §4).</summary>
public string BrowseToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Browse") : Loc.L("Tooltips.Setup.Locked");
public string JustMeToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.JustMe") : Loc.L("Tooltips.Setup.Locked");
public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked");
@@ -232,16 +245,46 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
public bool HasLaunchOption => _engine?.LaunchTarget(SelectedComponents) is not null;
public string InstallText => CanChangeLocation ? Loc.L("Setup.Action.Install") : Loc.L("Setup.Action.Update");
public string InstallToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update");
private bool CanStart => IsOptions && (IsUninstall || (IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected)));
/// <summary>What Install does, or why it is disabled: no program selected, or a folder it cannot use.</summary>
public string InstallToolTip => !Components.Any(c => c.IsSelected) ? Loc.L("Tooltips.Setup.NoComponent")
: !IsDirectoryValid ? Loc.L("Tooltips.Setup.FolderInvalid")
: CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update");
/// <summary>Removing user data waits for its plan, so the user has seen what goes before choosing Uninstall.</summary>
private bool CanStart => IsOptions && (IsUninstall ? !_removeUserData || _dataPlan is not null : IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected));
// ---- Uninstall options ----
/// <summary>Checking it measures the user data folder; the plan is shown before Uninstall can run.</summary>
public bool RemoveUserData
{
get => _removeUserData;
set => Set(ref _removeUserData, value);
set
{
if (!Set(ref _removeUserData, value)) return;
OnPropertyChanged(nameof(IsDataPlanVisible));
CommandManager.InvalidateRequerySuggested();
if (value && _dataPlan is null) _ = MeasureUserDataAsync();
}
}
public bool IsDataPlanVisible => _removeUserData && _dataPlan is not null;
/// <summary>"Deletes 3.4 GB" over the plan's lines.</summary>
public string DataPlanText => _dataPlan is null ? string.Empty : Loc.L("Setup.Uninstall.Plan", ByteSize.Format(_dataPlan.TotalBytes));
/// <summary>The largest entries of the user data folder, then one line for the rest.</summary>
public IReadOnlyList<DataPlanRow> DataPlanRows
{
get
{
if (_dataPlan is null) return [];
var rows = _dataPlan.Entries.Take(PlanRows).Select(e => new DataPlanRow(e.Name, ByteSize.Format(e.Bytes), IsFileName: true)).ToList();
var rest = _dataPlan.Entries.Skip(PlanRows).ToList();
if (rest.Count > 0) rows.Add(new DataPlanRow(Loc.Plural("Setup.Uninstall.More", rest.Count), ByteSize.Format(rest.Sum(e => e.Bytes)), IsFileName: false));
return rows;
}
}
// ---- Confirm, progress, outcome ----
@@ -294,6 +337,12 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
public bool CanRetry => IsFailed && _failure is not (SetupExitCode.PayloadInvalid or SetupExitCode.NotInstalled or SetupExitCode.InvalidArguments);
/// <summary>Done or failed: Close is offered (and Esc closes).</summary>
public bool IsFinished => IsDone || IsFailed;
/// <summary>Close is the default action when there is nothing to launch or retry.</summary>
public bool IsCloseDefault => IsFinished && !CanLaunch && !CanRetry;
public ICommand PrimaryCommand { get; }
public ICommand BrowseCommand { get; }
public ICommand CloseProgramsCommand { get; }
@@ -313,6 +362,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();
@@ -498,9 +564,33 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
Stage = SetupStage.Failed;
}
private async Task MeasureUserDataAsync()
{
if (_measuring) return;
_measuring = true;
try
{
_dataPlan = await Task.Run(() => UserDataPlan.Measure(SetupPaths.UserData));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("setup", $"User data '{SetupPaths.UserData}' not measured", ex);
_dataPlan = new UserDataPlan([]);
}
finally
{
_measuring = false;
}
OnPropertyChanged(nameof(IsDataPlanVisible));
OnPropertyChanged(nameof(DataPlanText));
OnPropertyChanged(nameof(DataPlanRows));
CommandManager.InvalidateRequerySuggested();
}
private void OnComponentsChanged()
{
OnPropertyChanged(nameof(RequiredSpaceText));
OnPropertyChanged(nameof(InstallToolTip));
OnPropertyChanged(nameof(HasDesktopOption));
OnPropertyChanged(nameof(HasStartMenuOption));
OnPropertyChanged(nameof(HasLaunchOption));
+71 -28
View File
@@ -18,7 +18,8 @@
<DockPanel>
<ComboBox DockPanel.Dock="Right" MinWidth="180" VerticalAlignment="Center" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}"
DisplayMemberPath="Name" IsEnabled="{Binding IsOptions}" ToolTip="{l:Loc Tooltips.Setup.Language}" AutomationProperties.Name="{l:Loc Setup.Field.Language}" />
<ui:BrandMarkIcon ShowPlate="True" Width="40" Height="40" Margin="0,0,14,0" VerticalAlignment="Center" />
<!-- The mark is artwork: its off-centre sun must not flip in right-to-left languages. -->
<ui:BrandMarkIcon ShowPlate="True" Width="40" Height="40" Margin="0,0,14,0" VerticalAlignment="Center" FlowDirection="LeftToRight" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.PageTitle}" />
<TextBlock Text="{Binding SubHeading}" Style="{StaticResource Text.Secondary}" />
@@ -43,7 +44,7 @@
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel Margin="0,0,0,6">
<TextBlock DockPanel.Dock="Right" Text="{Binding SizeText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="{Binding SizeText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" ToolTip="{Binding ToolTip}" />
</DockPanel>
</DataTemplate>
@@ -58,13 +59,18 @@
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding AllUsersToolTip}" />
</StackPanel>
<!-- The field comes before Browse in the Tab order, as on screen; a path reads left to right in every language. -->
<TextBlock Grid.Row="2" Text="{l:Loc Setup.Field.Folder}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
<DockPanel Grid.Row="2" Grid.Column="1" VerticalAlignment="Center">
<Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{l:Loc Setup.Folder.Browse}" Command="{Binding BrowseCommand}"
ToolTipService.ShowOnDisabled="True" ToolTip="{l:Loc Tooltips.Setup.Browse}" />
<TextBox Text="{Binding Directory, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding CanChangeLocation}"
<Grid Grid.Row="2" Grid.Column="1" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Directory, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding CanChangeLocation}" FlowDirection="LeftToRight"
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding DirectoryToolTip}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
</DockPanel>
<Button Grid.Column="1" Margin="8,0,0,0" Content="{l:Loc Setup.Folder.Browse}" Command="{Binding BrowseCommand}"
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding BrowseToolTip}" />
</Grid>
<TextBlock Grid.Row="3" Text="{l:Loc Setup.Field.Options}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,16,0" />
<StackPanel Grid.Row="3" Grid.Column="1" Margin="0,12,0,0">
@@ -77,7 +83,7 @@
</StackPanel>
</Grid>
<!-- Uninstall options -->
<!-- Uninstall options; "Remove my data" shows what it deletes before Uninstall can run (dry run). -->
<Grid Grid.Row="1" Margin="0,24,0,0" Visibility="{Binding IsUninstallOptions, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
@@ -86,66 +92,103 @@
<Grid.RowDefinitions>
<RowDefinition Height="44" />
<RowDefinition Height="44" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Setup.Field.Folder}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
<TextBox Grid.Column="1" VerticalAlignment="Center" IsReadOnly="True" Text="{Binding Directory, Mode=OneWay}"
<TextBox Grid.Column="1" VerticalAlignment="Center" IsReadOnly="True" Text="{Binding Directory, Mode=OneWay}" FlowDirection="LeftToRight"
ToolTip="{l:Loc Tooltips.Setup.Installed}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
<CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}"
<CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}" VerticalAlignment="Center"
Foreground="{DynamicResource Brush.Warning}" ToolTip="{l:Loc Tooltips.Setup.RemoveData}" />
<Border Grid.Row="2" Grid.Column="1" Style="{StaticResource Border.Card}" Padding="12,8"
Visibility="{Binding IsDataPlanVisible, Converter={StaticResource BoolToVisibility}}">
<StackPanel>
<TextBlock x:Name="DataPlanHeading" Text="{Binding DataPlanText}" Style="{StaticResource Text.Section}" Foreground="{DynamicResource Brush.Warning}" Margin="0,0,0,6"
AutomationProperties.LiveSetting="Polite" />
<ItemsControl ItemsSource="{Binding DataPlanRows}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" MinWidth="72" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="EntryName" Text="{Binding Name}" Style="{StaticResource Text.Secondary}" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Text="{Binding Size}" Style="{StaticResource Text.Secondary}" HorizontalAlignment="Right" Margin="12,0,0,0"
Typography.NumeralAlignment="Tabular" />
</Grid>
<DataTemplate.Triggers>
<!-- File and folder names read left to right in every language. -->
<DataTrigger Binding="{Binding IsFileName}" Value="True">
<Setter TargetName="EntryName" Property="FlowDirection" Value="LeftToRight" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</Grid>
<!-- Programs still running -->
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}">
<ui:Icon Glyph="{StaticResource Icon.Warning}" Size="20" Foreground="{DynamicResource Brush.Warning}" Margin="0,0,12,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding ConfirmText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
<TextBlock x:Name="ConfirmMessage" Text="{Binding ConfirmText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center"
AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
<!-- Progress -->
<StackPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{Binding WorkingText}" Style="{StaticResource Text.Title}" Margin="0,0,0,14" />
<TextBlock x:Name="WorkingMessage" Text="{Binding WorkingText}" Style="{StaticResource Text.Title}" Margin="0,0,0,14" AutomationProperties.LiveSetting="Polite" />
<DockPanel>
<TextBlock DockPanel.Dock="Right" Text="{Binding ProgressText}" Style="{StaticResource Text.Secondary}" MinWidth="40" TextAlignment="Right" Margin="12,0,0,0" VerticalAlignment="Center" />
<ProgressBar Minimum="0" Maximum="1" Value="{Binding Progress, Mode=OneWay}" IsIndeterminate="{Binding IsIndeterminate}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="{Binding ProgressText}" Style="{StaticResource Text.Secondary}" MinWidth="40" TextAlignment="Right" Margin="12,0,0,0"
VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<ProgressBar Minimum="0" Maximum="1" Value="{Binding Progress, Mode=OneWay}" IsIndeterminate="{Binding IsIndeterminate}" VerticalAlignment="Center"
AutomationProperties.Name="{Binding WorkingText}" />
</DockPanel>
<TextBlock Text="{Binding ProgressFile}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" Margin="0,8,0,0" />
<TextBlock Text="{Binding ProgressFile}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" Margin="0,8,0,0"
FlowDirection="LeftToRight" HorizontalAlignment="Left" />
</StackPanel>
<!-- Success -->
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsDone, Converter={StaticResource BoolToVisibility}}">
<ui:Icon Glyph="{StaticResource Icon.SuccessCircle}" Size="20" Foreground="{DynamicResource Brush.Success}" Margin="0,0,12,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding DoneText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
<TextBlock x:Name="DoneMessage" Text="{Binding DoneText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center"
AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
<!-- Failure -->
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsFailed, Converter={StaticResource BoolToVisibility}}">
<ui:Icon Glyph="{StaticResource Icon.ErrorCircle}" Size="20" Foreground="{DynamicResource Brush.Error}" Margin="0,0,12,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding ErrorText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
<TextBlock x:Name="FailedMessage" Text="{Binding ErrorText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center"
AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
<!-- Footer: space needed and at most two actions per state -->
<!--
Footer: space needed and at most two actions per stage, the safe one first (DESIGN §4). Enter and Esc follow
Windows: Install, Launch and Retry are the default when shown; otherwise the safe action is; Esc is the safe action.
-->
<DockPanel Grid.Row="2" LastChildFill="False" Margin="0,16,0,0">
<TextBlock DockPanel.Dock="Left" Text="{Binding RequiredSpaceText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center"
Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<StackPanel x:Name="Footer" DockPanel.Dock="Right" Orientation="Horizontal">
<Button Content="{l:Loc Setup.Action.Cancel}" MinWidth="88" Margin="0,0,8,0" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Cancel}"
IsCancel="{Binding IsOptions}" IsDefault="{Binding IsUninstallOptions}" Visibility="{Binding IsOptions, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" MinWidth="104" Content="{Binding InstallText}" Command="{Binding PrimaryCommand}" ToolTip="{Binding InstallToolTip}"
ToolTipService.ShowOnDisabled="True" IsDefault="True" Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
ToolTipService.ShowOnDisabled="True" IsDefault="{Binding IsInstallOptions}" Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Destructive}" MinWidth="104" Content="{l:Loc Setup.Action.Uninstall}" Command="{Binding PrimaryCommand}" ToolTip="{l:Loc Tooltips.Setup.Uninstall}"
Visibility="{Binding IsUninstallOptions, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Cancel}" Command="{Binding BackCommand}" ToolTip="{l:Loc Tooltips.Setup.Back}" IsCancel="True" Margin="0,0,8,0"
Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Cancel}" MinWidth="88" Command="{Binding BackCommand}" ToolTip="{l:Loc Tooltips.Setup.Back}" Margin="0,0,8,0"
IsCancel="{Binding IsConfirm}" IsDefault="{Binding IsConfirm}" Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Setup.Action.ClosePrograms}" Command="{Binding CloseProgramsCommand}" ToolTip="{l:Loc Tooltips.Setup.ClosePrograms}"
Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Close}" MinWidth="88" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Close}"
Visibility="{Binding IsDone, Converter={StaticResource BoolToVisibility}}" />
IsCancel="{Binding IsFinished}" IsDefault="{Binding IsCloseDefault}" Visibility="{Binding IsFinished, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" MinWidth="88" Content="{l:Loc Setup.Action.Launch}" Command="{Binding LaunchCommand}" ToolTip="{l:Loc Tooltips.Setup.LaunchNow}" Margin="8,0,0,0"
Visibility="{Binding CanLaunch, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Setup.Action.Close}" MinWidth="88" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Close}"
Visibility="{Binding IsFailed, Converter={StaticResource BoolToVisibility}}" />
IsDefault="{Binding CanLaunch}" Visibility="{Binding CanLaunch, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" MinWidth="88" Content="{l:Loc Setup.Action.Retry}" Command="{Binding RetryCommand}" ToolTip="{l:Loc Tooltips.Setup.Retry}" Margin="8,0,0,0"
Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
IsDefault="{Binding CanRetry}" Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</DockPanel>
</Grid>
+55 -8
View File
@@ -1,28 +1,39 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using Titano.Core.Localization;
using Titano.Setup.Interop;
using Titano.Ui.Controls;
namespace Titano.Setup.Views;
/// <summary>The one setup screen (~720×520, dialog chrome). Closing is blocked while files are being written.</summary>
/// <summary>
/// The one setup screen (~720×520, dialog chrome). Closing is blocked while files are being written, and the
/// title-bar Close is disabled then. Each stage gives the keyboard to its default button and announces its outcome.
/// </summary>
internal sealed partial class SetupWindow : TitanoWindow
{
private readonly SetupViewModel _model;
private SetupStage _shownStage;
public SetupWindow(SetupViewModel model)
{
_model = model;
_shownStage = model.Stage;
DataContext = model;
InitializeComponent();
ApplyFlowDirection();
Loc.CultureChanged += OnCultureChanged;
// Ahead of the chrome's own Close binding, which is always enabled.
CommandBindings.Insert(0, new CommandBinding(SystemCommands.CloseWindowCommand, null, OnCanClose));
model.PickFolder = initial => FolderPicker.Pick(new WindowInteropHelper(this).Handle, Loc.L("Setup.Field.Folder"), initial);
model.Finished += (_, _) => Close();
model.VisibilityRequested += (_, visible) => Visibility = visible ? Visibility.Visible : Visibility.Hidden;
model.PropertyChanged += OnModelChanged;
SourceInitialized += (_, _) => model.WindowHandle = new WindowInteropHelper(this).Handle;
Loaded += (_, _) => FocusDefault();
ContentRendered += (_, _) => model.OnShown();
}
@@ -33,13 +44,49 @@ internal sealed partial class SetupWindow : TitanoWindow
base.OnClosing(e);
}
protected override void OnClosed(EventArgs e)
private void OnCanClose(object sender, CanExecuteRoutedEventArgs e)
{
Loc.CultureChanged -= OnCultureChanged;
base.OnClosed(e);
if (!_model.IsWorking) return;
e.CanExecute = false;
e.Handled = true;
}
private void OnCultureChanged(object? sender, EventArgs e) => ApplyFlowDirection();
/// <summary>
/// A new stage collapses the focused button: the keyboard moves to the new default and the outcome is read out.
/// The "Remove my data" plan is read out when it appears.
/// </summary>
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SetupViewModel.IsDataPlanVisible) && _model.IsDataPlanVisible)
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => Announce(DataPlanHeading));
if (_model.Stage == _shownStage) return;
_shownStage = _model.Stage;
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () =>
{
FocusDefault();
if (StageMessage() is { } message) Announce(message);
});
}
private void ApplyFlowDirection() => FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
/// <summary>Asks screen readers to read <paramref name="element"/> (it carries a live setting).</summary>
private static void Announce(UIElement element)
{
if (element.IsVisible) UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
private TextBlock? StageMessage() => _model.Stage switch
{
SetupStage.Confirm => ConfirmMessage,
SetupStage.Working => WorkingMessage,
SetupStage.Done => DoneMessage,
SetupStage.Failed => FailedMessage,
_ => null,
};
/// <summary>Focuses the visible default button of the footer, else its first visible one.</summary>
private void FocusDefault()
{
var buttons = Footer.Children.OfType<Button>().Where(b => b.IsVisible).ToList();
(buttons.FirstOrDefault(b => b.IsDefault) ?? buttons.FirstOrDefault())?.Focus();
}
}