refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,64 @@
using Chronos.Core.Localization;
using Chronos.Core.Packaging;
using Chronos.Ui.Mvvm;
namespace Chronos.Setup.Views;
/// <summary>
/// A component checkbox: localized name and tooltip (falling back to the manifest), size and selection. A component
/// that installs for all users only says so in its tooltip, and is unavailable when an installation that is not an
/// all-users one inside Program Files is upgraded.
/// </summary>
/// <param name="unavailableToolTip">The tooltip key saying why it cannot be added here; null when it can.</param>
internal sealed class ComponentOption(PayloadComponent component, bool selected, string? unavailableToolTip, Action changed) : LocalizedViewModel
{
private bool _selected = selected;
public string Id => component.Id;
public string Name => Loc.Get("Setup.Component." + component.Id, Loc.Culture) ?? component.DisplayName;
/// <summary>Installs for all users only (the Server runs as a LocalSystem service from Program Files).</summary>
public bool AllUsersOnly => component.AllUsersOnly;
/// <summary>False when it cannot be installed here: it needs all users in Program Files and this installation is not.</summary>
public bool IsAvailable => unavailableToolTip is null;
public string ToolTip => unavailableToolTip is { } reason ? Loc.L(reason)
: AllUsersOnly ? Loc.L("Tooltips.Setup.AllUsersOnly", Description)
: Description;
private string Description => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component");
public string SizeText => ByteSize.Format(component.EstimatedSize);
public bool IsSelected
{
get => _selected;
set
{
if (Set(ref _selected, value)) changed();
}
}
}
/// <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"), units in the UI language ("1,5 Mo").</summary>
internal static class ByteSize
{
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 < Formats.Length - 1)
{
value /= 1000;
unit++;
}
return Loc.L(Formats[unit], value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture));
}
}
+185
View File
@@ -0,0 +1,185 @@
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Chronos.Core.Diagnostics;
using Chronos.Core.Packaging;
using Chronos.Setup.Cli;
using Chronos.Setup.Engine;
using Chronos.Ui.Theming;
namespace Chronos.Setup.Views;
/// <summary>
/// <c>Chronos.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 = "Chronos";
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(SetupPaths.UserData,
[
new UserDataEntry("cache", 2_140_000_000),
new UserDataEntry("backups", 1_210_000_000),
new UserDataEntry("chronos.db", 41_000_000),
new UserDataEntry("logs", 12_400_000),
new UserDataEntry("chronos.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("chronos-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);
// Both programs' data, whatever this machine has installed, so every capture shows the same screen.
using var uninstall = SetupViewModel.ForUninstall(new SetupArguments(), new InstalledProduct(
SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product), new InstallLog { Product = Product, Version = "1.0.0", Components = ["Chronos", "Uploader"] }),
UserDataOwners.All);
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)[]
{
("Chronos", "Chronos", true, "Chronos.exe", 2_400_000),
("Uploader", "Chronos Uploader", true, "Chronos.Uploader.exe", 900_000),
("Server", "Chronos Server", false, "Chronos.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), AllUsersOnly: c.Id == "Server"))],
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);
// A right-to-left window's content already renders mirrored, as on screen.
bitmap.Render(root);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path);
encoder.Save(stream);
}
}
+718
View File
@@ -0,0 +1,718 @@
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Windows.Input;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Packaging;
using Chronos.Setup.Cli;
using Chronos.Setup.Engine;
using Chronos.Ui.Mvvm;
namespace Chronos.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
{
Options,
Confirm,
Working,
Done,
Failed,
}
/// <summary>
/// The single setup screen for install and uninstall: options, a prompt when installed programs must close,
/// progress, success and failure. Work runs on the thread pool and reports through <see cref="Progress{T}"/>.
/// </summary>
internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
{
private const string FallbackProduct = "Chronos";
/// <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;
private readonly InstallPlan? _plan;
private readonly InstalledProduct? _installed;
private readonly string _product;
private readonly string? _version;
private readonly IReadOnlySet<string> _dataOwners;
private SetupStage _stage;
private string _directory = string.Empty;
private bool _allUsers;
private bool _desktop;
private bool _startMenu;
private bool _launchAfter;
private bool _removeUserData;
private UserDataPlan? _dataPlan;
private bool _measuring;
private bool _closeConfirmed;
private double _progress;
private bool _indeterminate;
private string _progressFile = string.Empty;
private string _runningPrograms = string.Empty;
private SetupExitCode _failure;
private bool _accessDenied;
private string? _launchProgram;
private Func<Task>? _operation;
/// <summary>The services setup stopped for the current step, started again after the upgrade or when the step fails.</summary>
private IReadOnlyList<InstalledService> _stopped = [];
private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed,
IReadOnlySet<string>? dataOwners = null)
{
_arguments = arguments;
_product = product;
_version = version;
_payload = payload;
_installed = installed;
// "Remove my data" covers the programs this product installed that no other installed Chronos product still has.
_dataOwners = installed is null ? new HashSet<string>()
: dataOwners ?? UserDataOwners.RemovableBeside(installed.Log.Components, SetupRegistry.OtherInstalls(installed.Directory, InstallEngine.Publisher));
if (payload is not null)
{
_engine = new InstallEngine(payload);
_plan = InstallPlan.Resolve(_engine.Manifest, arguments);
_directory = _plan.Directory;
_allUsers = _plan.Scope == InstallScope.AllUsers;
}
_desktop = !arguments.NoDesktopShortcut;
_startMenu = !arguments.NoStartMenu;
_launchAfter = arguments.Launch;
Components = _engine is null
? []
: [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), UnavailableReason(c),
OnComponentsChanged))];
Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))];
PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart);
BrowseCommand = new RelayCommand(Browse, () => IsOptions && CanChangeLocation);
CloseProgramsCommand = new RelayCommand(() =>
{
_closeConfirmed = true;
Start(_operation!);
}, () => IsConfirm && _operation is not null);
BackCommand = new RelayCommand(() => Stage = SetupStage.Options, () => IsConfirm);
LaunchCommand = new RelayCommand(Launch, () => CanLaunch);
CloseCommand = new RelayCommand(() => Finish(ExitCode), () => !IsWorking);
RetryCommand = new RelayCommand(() => Start(_operation!), () => CanRetry && _operation is not null);
}
public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) =>
new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null);
/// <param name="dataOwners">Whose user data "Remove my data" covers; null works it out from the installed products.</param>
public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed, IReadOnlySet<string>? dataOwners = null) =>
new(arguments, installed.Log.Product, installed.Log.Version, null, installed, dataOwners) { Directory = installed.Directory };
/// <summary>A screen that can only report why setup cannot run (no payload, nothing installed…).</summary>
public static SetupViewModel ForFailure(SetupArguments arguments, SetupExitCode code)
{
var model = new SetupViewModel(arguments, SilentSetup.PayloadProduct() ?? FallbackProduct, null, null, null);
model.Fail(new SetupException(code, code.ToString()));
return model;
}
/// <summary>Raised when setup is finished and the window should close; <see cref="ExitCode"/> holds the outcome.</summary>
public event EventHandler? Finished;
/// <summary>Raised with false to hide the window while an elevated copy works, true to show it again.</summary>
public event EventHandler<bool>? VisibilityRequested;
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
/// <summary>Shows the folder picker; provided by the view, which owns the window handle.</summary>
public Func<string, string?>? PickFolder { get; set; }
/// <summary>Window handle that owns the administrator prompt.</summary>
public IntPtr WindowHandle { get; set; }
public SetupExitCode ExitCode { get; private set; } = SetupExitCode.Cancelled;
public bool IsInstall => _engine is not null;
public bool IsUninstall => _installed is not null;
public string WindowTitle => IsUninstall ? Loc.L("Setup.Window.Uninstall", _product) : Loc.L("Setup.Window.Title", _product);
public string Heading => _product;
public string SubHeading => _version is null
? string.Empty
: _plan?.Existing is { Version.Length: > 0 } existing
? Loc.L("Setup.Header.Upgrade", _version, existing.Version)
: Loc.L("Setup.Header.Version", _version);
public IReadOnlyList<LanguageOption> Languages { get; }
public LanguageOption SelectedLanguage
{
get => Languages.FirstOrDefault(l => l.Code.Equals(Loc.Culture.Name, StringComparison.OrdinalIgnoreCase)) ?? Languages[0];
set
{
if (value is not null) Program.ApplyLanguage(value.Code);
}
}
public SetupStage Stage
{
get => _stage;
private set
{
_stage = value;
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
}
public bool IsOptions => _stage == SetupStage.Options;
public bool IsInstallOptions => IsOptions && IsInstall;
public bool IsUninstallOptions => IsOptions && IsUninstall;
public bool IsConfirm => _stage == SetupStage.Confirm;
public bool IsWorking => _stage == SetupStage.Working;
public bool IsDone => _stage == SetupStage.Done;
public bool IsFailed => _stage == SetupStage.Failed;
// ---- Install options ----
public IReadOnlyList<ComponentOption> Components { get; }
private List<string> SelectedComponents => [.. Components.Where(c => c.IsSelected).Select(c => c.Id)];
public string RequiredSpaceText => _engine is null ? string.Empty : Loc.L("Setup.Space.Required", ByteSize.Format(_engine.RequiredBytes(SelectedComponents)));
/// <summary>False when upgrading: the existing folder and scope are kept.</summary>
public bool CanChangeLocation => _plan?.Existing is null;
public bool IsAllUsers
{
get => _allUsers;
set
{
var before = DefaultDirectory();
if (!Set(ref _allUsers, value)) return;
OnPropertyChanged(nameof(IsJustMe));
// Follow the scope while the folder is still the suggested one.
if (string.Equals(Path.TrimEndingDirectorySeparator(_directory), before, StringComparison.OrdinalIgnoreCase)) Directory = DefaultDirectory();
else OnDirectoryRuleChanged();
}
}
public bool IsJustMe
{
get => !_allUsers;
set => IsAllUsers = !value;
}
public string Directory
{
get => _directory;
set
{
if (Set(ref _directory, value ?? string.Empty)) OnDirectoryRuleChanged();
}
}
/// <summary>
/// A folder setup can use; inside Program Files when a selected component runs as a LocalSystem service (a folder
/// such as C:\Chronos would let standard users replace the program the service starts).
/// </summary>
private bool IsDirectoryValid => _engine is not null
&& InstallPlan.IsValidDirectory(_engine.Manifest, _allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, _directory, SelectedComponents);
/// <summary>Why the folder cannot be used: not a usable folder, or outside Program Files for a service.</summary>
private string FolderErrorText => SetupPaths.IsUsableInstallDirectory(_directory) && AllUsersComponent is { } component
? Loc.L("Tooltips.Setup.FolderProgramFiles", component.Name)
: Loc.L("Tooltips.Setup.FolderInvalid");
public string DirectoryToolTip => !CanChangeLocation
? Loc.L("Tooltips.Setup.Locked")
: IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : FolderErrorText;
/// <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");
/// <summary>A selected component installs for all users only (the Server runs as a LocalSystem service from Program Files).</summary>
private ComponentOption? AllUsersComponent => Components.FirstOrDefault(c => c.IsSelected && c.AllUsersOnly);
/// <summary>"Just me" is offered unless the location is fixed (upgrade) or a selected component needs all users.</summary>
public bool CanChooseJustMe => CanChangeLocation && AllUsersComponent is null;
public string JustMeToolTip => !CanChangeLocation ? Loc.L("Tooltips.Setup.Locked")
: AllUsersComponent is { } component ? Loc.L("Tooltips.Setup.JustMeLocked", component.Name)
: Loc.L("Tooltips.Setup.JustMe");
public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked");
public bool DesktopShortcut
{
get => _desktop;
set => Set(ref _desktop, value);
}
public bool StartMenuShortcuts
{
get => _startMenu;
set => Set(ref _startMenu, value);
}
public bool LaunchAfter
{
get => _launchAfter;
set => Set(ref _launchAfter, value);
}
public bool HasDesktopOption => SelectedShortcuts().Any(s => s.Desktop);
public bool HasStartMenuOption => SelectedShortcuts().Any(s => s.StartMenu);
public bool HasLaunchOption => _engine?.LaunchTarget(SelectedComponents) is not null;
public string InstallText => CanChangeLocation ? Loc.L("Setup.Action.Install") : Loc.L("Setup.Action.Update");
/// <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 ? FolderErrorText
: 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
{
if (!Set(ref _removeUserData, value)) return;
OnPropertyChanged(nameof(IsDataPlanVisible));
CommandManager.InvalidateRequerySuggested();
if (value && _dataPlan is null) _ = MeasureUserDataAsync();
}
}
/// <summary>
/// "Remove my data" is offered when this product's programs keep data no other installed Chronos product still uses
/// (the desktop app and the Uploader share the folder).
/// </summary>
public bool HasRemoveDataOption => _dataOwners.Count > 0;
/// <summary>What "Remove my data" deletes: both programs' data, or only the desktop app's or the Uploader's.</summary>
public string RemoveDataToolTip => Loc.L(UserDataOwners.All.All(_dataOwners.Contains) ? "Tooltips.Setup.RemoveData"
: _dataOwners.Contains(UserDataOwners.Uploader) ? "Tooltips.Setup.RemoveDataUploader"
: "Tooltips.Setup.RemoveDataChronos");
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 ----
public string ConfirmText => Loc.L("Setup.Running.Prompt", _runningPrograms);
public string WorkingText => IsUninstall ? Loc.L("Setup.Progress.Removing", _product) : Loc.L("Setup.Progress.Installing", _product);
public double Progress
{
get => _progress;
private set
{
if (Set(ref _progress, value)) OnPropertyChanged(nameof(ProgressText));
}
}
public string ProgressText => _indeterminate ? string.Empty : _progress.ToString("P0", Loc.Culture);
public bool IsIndeterminate
{
get => _indeterminate;
private set
{
if (Set(ref _indeterminate, value)) OnPropertyChanged(nameof(ProgressText));
}
}
public string ProgressFile
{
get => _progressFile;
private set => Set(ref _progressFile, value);
}
public string DoneText => IsUninstall ? Loc.L("Setup.Done.Removed", _product) : Loc.L("Setup.Done.Installed", _product);
public bool CanLaunch => IsDone && _launchProgram is not null;
public string ErrorText => _failure switch
{
SetupExitCode.PayloadInvalid => Loc.L("Setup.Error.Payload"),
SetupExitCode.ElevationDeclined => Loc.L("Setup.Error.Elevation"),
SetupExitCode.ProgramRunning => Loc.L("Setup.Error.Running", _runningPrograms),
SetupExitCode.DiskFull => Loc.L("Setup.Error.DiskFull"),
SetupExitCode.NotInstalled => Loc.L("Setup.Error.NotInstalled", _product),
SetupExitCode.InvalidArguments => Loc.L("Setup.Error.Arguments"),
_ when _accessDenied => Loc.L("Setup.Error.Access"),
_ => IsUninstall ? Loc.L("Setup.Error.Uninstall") : Loc.L("Setup.Error.Install"),
};
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; }
public ICommand BackCommand { get; }
public ICommand LaunchCommand { get; }
public ICommand CloseCommand { get; }
public ICommand RetryCommand { get; }
public bool HasErrors => IsInstall && !IsDirectoryValid;
public IEnumerable GetErrors(string? propertyName) =>
propertyName == nameof(Directory) && HasErrors ? new[] { FolderErrorText } : Array.Empty<string>();
/// <summary>Called once the window is visible: an elevated copy continues the install the user already started.</summary>
public void OnShown()
{
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 = "Chronos Uploader";
_progress = 0.46;
_indeterminate = false;
_progressFile = @"Chronos\Chronos.Core.dll";
_launchProgram = IsInstall ? "Chronos.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();
_payload?.Dispose();
base.Dispose();
}
private void Start(Func<Task> operation)
{
_operation = operation;
_ = operation();
}
private async Task InstallAsync()
{
var engine = _engine!;
string? directory = null;
try
{
var request = new InstallRequest(
Path.TrimEndingDirectorySeparator(Path.GetFullPath(_directory)),
_allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser,
SelectedComponents,
HasDesktopOption && _desktop,
HasStartMenuOption && _startMenu);
var target = engine.LaunchTarget(request.Components);
var program = target is null ? null : PayloadPath.Resolve(request.Directory, target);
var launch = _launchAfter ? program : null;
if (request.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
{
await InstallElevatedAsync(request, program);
return;
}
directory = request.Directory;
// Read before the upgrade rewrites the log, so a program it drops still names its service.
var programs = InstallPlan.Programs(engine.Manifest, request.Directory).ToList();
var owned = CommandProgram.FullPaths(request.Directory, programs);
if (await CloseProgramsAsync(request.Directory, programs, owned) is not { } running) return;
BeginWork(indeterminate: false);
if (running.Count > 0)
{
_stopped = running;
await ApplyToServicesAsync(request.Directory, running, ServiceActions.Stop);
}
var progress = new Progress<SetupProgress>(ReportProgress);
await Task.Run(() => engine.Install(request, progress, CancellationToken.None));
// Services whose program the upgrade removed go; the ones stopped for it run again.
var after = InstalledServices.Find(owned).Where(s => !File.Exists(s.Program)).UnionBy(_stopped, s => s.Name, StringComparer.OrdinalIgnoreCase).ToList();
_stopped = [];
await ApplyToServicesAsync(request.Directory, after, ServiceActions.Prune | ServiceActions.Start);
_launchProgram = program;
Complete();
if (launch is not null) Launch();
}
catch (Exception ex)
{
await StartStoppedAsync(directory);
Fail(ex);
}
}
/// <summary>
/// All users without administrator rights: an elevated copy installs with the chosen options. This process
/// stays behind, hidden, to start <paramref name="program"/> unelevated if the copy asks for it.
/// </summary>
private async Task InstallElevatedAsync(InstallRequest request, string? program)
{
if (_arguments.Elevated) throw new SetupException(SetupExitCode.ElevationDeclined, "Still not elevated after relaunch.");
var switches = new SetupArguments
{
Directory = request.Directory,
Components = request.Components,
AllUsers = true,
NoDesktopShortcut = !request.DesktopShortcuts,
NoStartMenu = !request.StartMenuShortcuts,
Launch = _launchAfter,
Language = Loc.Culture.Name,
};
var child = Elevation.Start(switches, WindowHandle) ?? throw new SetupException(SetupExitCode.ElevationDeclined, "Administrator approval declined.");
VisibilityRequested?.Invoke(this, false);
Finish(await Elevation.WaitAsync(child, program));
}
private async Task UninstallAsync()
{
var installed = _installed!;
try
{
var owned = CommandProgram.FullPaths(installed.Directory, installed.Log.Files);
if (await CloseProgramsAsync(installed.Directory, installed.Log.Files, owned) is not { } running) return;
BeginWork(indeterminate: false);
// Only now that the programs are closed. A service that was not running is still registered: none may
// outlive its program. If one cannot be deleted, the ones stopped here run again.
_stopped = running;
await ApplyToServicesAsync(installed.Directory, InstalledServices.Find(owned), ServiceActions.Remove);
_stopped = [];
var progress = new Progress<SetupProgress>(ReportProgress);
var userData = _removeUserData ? _dataPlan : null;
await Task.Run(() => UninstallEngine.Uninstall(installed, userData, progress));
Complete();
}
catch (Exception ex)
{
await StartStoppedAsync(installed.Directory);
Fail(ex);
}
}
/// <summary>
/// Null when the user must first confirm (Confirm stage) that the programs and services running from
/// <paramref name="directory"/> may close. Otherwise the running programs have closed, and the result lists the
/// running services of <paramref name="owned"/>, which the caller stops or deletes: a program that does not close
/// stops setup before any service is touched.
/// </summary>
private async Task<IReadOnlyList<InstalledService>?> CloseProgramsAsync(string directory, IEnumerable<string> programs, IReadOnlySet<string> owned)
{
// A confirmation answers one prompt only; a later attempt asks again.
var confirmed = _closeConfirmed;
_closeConfirmed = false;
var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList();
var running = RunningPrograms.Find(directory, programs, services);
try
{
if (running.Count == 0 && services.Count == 0) return services;
_runningPrograms = RunningPrograms.Describe(running, services);
if (!confirmed)
{
Stage = SetupStage.Confirm;
return null;
}
BeginWork(indeterminate: true);
var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout);
if (still.Count == 0) return services;
_runningPrograms = RunningPrograms.Describe(still);
throw new SetupException(SetupExitCode.ProgramRunning, $"Still running: {_runningPrograms}");
}
finally
{
foreach (var p in running) p.Dispose();
}
}
/// <summary>Applies <paramref name="actions"/> to <paramref name="services"/> (an elevated step when needed); throws when that fails.</summary>
private async Task ApplyToServicesAsync(string directory, IReadOnlyList<InstalledService> services, ServiceActions actions)
{
var code = await InstalledServices.ApplyAsync(directory, services, actions, WindowHandle);
if (code == SetupExitCode.Success) return;
_runningPrograms = RunningPrograms.Describe([], services);
throw new SetupException(code, $"Services not updated ({actions}): {_runningPrograms}");
}
/// <summary>After a failure, starts again the services setup stopped for the step, so a failed upgrade does not leave the server down.</summary>
private async Task StartStoppedAsync(string? directory)
{
var stopped = _stopped;
_stopped = [];
if (directory is null || stopped.Count == 0) return;
try
{
var code = await InstalledServices.ApplyAsync(directory, stopped, ServiceActions.Start, WindowHandle);
if (code != SetupExitCode.Success) Log.Warning("setup", $"Stopped services not started again: {code}");
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or IOException)
{
Log.Warning("setup", "Stopped services not started again", ex);
}
}
private void Browse()
{
if (PickFolder?.Invoke(_directory) is not { } folder) return;
// Choosing a parent such as D:\Apps installs into D:\Apps\<product>, never loose files in D:\Apps.
Directory = Path.GetFileName(Path.TrimEndingDirectorySeparator(folder)).Equals(_product, StringComparison.OrdinalIgnoreCase)
? folder
: Path.Combine(folder, _product);
}
private void Launch()
{
if (_launchProgram is null) return;
if (_arguments.Elevated)
{
// The unelevated parent starts the program, so it does not run as administrator.
Finish(SetupExitCode.LaunchRequested);
return;
}
try
{
Launcher.Start(_launchProgram);
}
catch (Win32Exception ex)
{
Log.Warning("setup", $"Could not start '{_launchProgram}'", ex);
}
Finish(SetupExitCode.Success);
}
private void Finish(SetupExitCode code)
{
ExitCode = code;
Finished?.Invoke(this, EventArgs.Empty);
}
private void BeginWork(bool indeterminate)
{
Progress = 0;
ProgressFile = string.Empty;
IsIndeterminate = indeterminate;
Stage = SetupStage.Working;
}
private void ReportProgress(SetupProgress value)
{
IsIndeterminate = false;
Progress = value.Fraction;
if (value.CurrentFile.Length > 0) ProgressFile = value.CurrentFile;
}
private void Complete()
{
ExitCode = SetupExitCode.Success;
Stage = SetupStage.Done;
}
private void Fail(Exception ex)
{
Log.Error("setup", IsUninstall ? "Uninstall failed" : "Install failed", ex);
_failure = SilentSetup.CodeFor(ex);
_accessDenied = ex is UnauthorizedAccessException;
ExitCode = _failure;
VisibilityRequested?.Invoke(this, true);
Stage = SetupStage.Failed;
}
private async Task MeasureUserDataAsync()
{
if (_measuring) return;
_measuring = true;
try
{
_dataPlan = await Task.Run(() => UserDataPlan.Measure(SetupPaths.UserData, _dataOwners));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("setup", $"User data '{SetupPaths.UserData}' not measured", ex);
_dataPlan = new UserDataPlan(SetupPaths.UserData, []);
}
finally
{
_measuring = false;
}
OnPropertyChanged(nameof(IsDataPlanVisible));
OnPropertyChanged(nameof(DataPlanText));
OnPropertyChanged(nameof(DataPlanRows));
CommandManager.InvalidateRequerySuggested();
}
private void OnComponentsChanged()
{
// The Server runs as a LocalSystem service, which must not start a program its user can replace: selecting it
// moves a new installation to all users (Program Files).
if (AllUsersComponent is not null && !_allUsers && CanChangeLocation) IsAllUsers = true;
OnPropertyChanged(nameof(CanChooseJustMe));
OnPropertyChanged(nameof(JustMeToolTip));
OnPropertyChanged(nameof(RequiredSpaceText));
OnPropertyChanged(nameof(HasDesktopOption));
OnPropertyChanged(nameof(HasStartMenuOption));
OnPropertyChanged(nameof(HasLaunchOption));
OnDirectoryRuleChanged();
}
/// <summary>The folder, the scope or the components changed: whether the folder is valid, and why not, may have too.</summary>
private void OnDirectoryRuleChanged()
{
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory)));
OnPropertyChanged(nameof(DirectoryToolTip));
OnPropertyChanged(nameof(InstallToolTip));
CommandManager.InvalidateRequerySuggested();
}
/// <summary>The tooltip key saying why <paramref name="component"/> cannot be added to the installation upgraded here; null when it can.</summary>
private string? UnavailableReason(PayloadComponent component) =>
_plan!.CanInstall(component) ? null
: _plan.Existing is { Scope: InstallScope.CurrentUser } ? "Tooltips.Setup.NeedsAllUsers"
: "Tooltips.Setup.NeedsProgramFiles";
private IEnumerable<PayloadShortcut> SelectedShortcuts()
{
if (_engine is null) return [];
var selected = SelectedComponents;
return _engine.Manifest.Shortcuts.Where(s => selected.Contains(s.Component, StringComparer.OrdinalIgnoreCase));
}
private string DefaultDirectory() =>
SetupPaths.DefaultDirectory(_allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, _product);
}
+197
View File
@@ -0,0 +1,197 @@
<ui:ChronosWindow x:Class="Chronos.Setup.Views.SetupWindow" x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
Style="{StaticResource {x:Type ui:ChronosWindow}}"
Title="{Binding WindowTitle}"
Width="720" Height="520" ResizeMode="NoResize" IsDialog="True"
WindowStartupLocation="CenterScreen">
<Grid Margin="24,20,24,20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Header: mark, product, version, language -->
<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" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.PageTitle}" />
<TextBlock Text="{Binding SubHeading}" Style="{StaticResource Text.Secondary}" />
</StackPanel>
</DockPanel>
<!-- Install options -->
<Grid Grid.Row="1" Margin="0,24,0,0" Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="44" />
<RowDefinition Height="44" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Setup.Field.Components}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,3,16,0" />
<ItemsControl Grid.Column="1" ItemsSource="{Binding Components}" Focusable="False" Margin="0,0,0,8">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel Margin="0,0,0,6">
<TextBlock DockPanel.Dock="Right" Text="{Binding SizeText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" IsEnabled="{Binding IsAvailable}" ToolTip="{Binding ToolTip}"
ToolTipService.ShowOnDisabled="True" />
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Grid.Row="1" Text="{l:Loc Setup.Field.Scope}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<RadioButton Content="{l:Loc Setup.Scope.JustMe}" IsChecked="{Binding IsJustMe}" IsEnabled="{Binding CanChooseJustMe}"
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding JustMeToolTip}" Margin="0,0,20,0" />
<RadioButton Content="{l:Loc Setup.Scope.AllUsers}" IsChecked="{Binding IsAllUsers}" IsEnabled="{Binding CanChangeLocation}"
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" />
<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}" />
<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">
<CheckBox Content="{l:Loc Setup.Options.Desktop}" IsChecked="{Binding DesktopShortcut}" ToolTip="{l:Loc Tooltips.Setup.Desktop}" Margin="0,0,0,6"
Visibility="{Binding HasDesktopOption, Converter={StaticResource BoolToVisibility}}" />
<CheckBox Content="{l:Loc Setup.Options.StartMenu}" IsChecked="{Binding StartMenuShortcuts}" ToolTip="{l:Loc Tooltips.Setup.StartMenu}" Margin="0,0,0,6"
Visibility="{Binding HasStartMenuOption, Converter={StaticResource BoolToVisibility}}" />
<CheckBox Content="{l:Loc Setup.Options.Launch}" IsChecked="{Binding LaunchAfter}" ToolTip="{l:Loc Tooltips.Setup.Launch}"
Visibility="{Binding HasLaunchOption, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</Grid>
<!-- 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" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<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}" FlowDirection="LeftToRight"
ToolTip="{l:Loc Tooltips.Setup.Installed}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
<!-- Only this product's data, and only what no other installed Chronos product still uses. -->
<CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}" VerticalAlignment="Center"
Foreground="{DynamicResource Brush.Warning}" ToolTip="{Binding RemoveDataToolTip}"
Visibility="{Binding HasRemoveDataOption, Converter={StaticResource BoolToVisibility}}" />
<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 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 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" 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"
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 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 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 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 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="{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}" 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}"
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"
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"
IsDefault="{Binding CanRetry}" Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</DockPanel>
</Grid>
</ui:ChronosWindow>
@@ -0,0 +1,92 @@
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 Chronos.Core.Localization;
using Chronos.Setup.Interop;
using Chronos.Ui.Controls;
namespace Chronos.Setup.Views;
/// <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 : ChronosWindow
{
private readonly SetupViewModel _model;
private SetupStage _shownStage;
public SetupWindow(SetupViewModel model)
{
_model = model;
_shownStage = model.Stage;
DataContext = model;
InitializeComponent();
// 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();
}
protected override void OnClosing(CancelEventArgs e)
{
// Interrupting a copy half-way would leave staging folders behind; the operation is short.
if (_model.IsWorking) e.Cancel = true;
base.OnClosing(e);
}
private void OnCanClose(object sender, CanExecuteRoutedEventArgs e)
{
if (!_model.IsWorking) return;
e.CanExecute = false;
e.Handled = true;
}
/// <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);
});
}
/// <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();
}
}