diff --git a/src/Titano.Setup/App.cs b/src/Titano.Setup/App.cs
new file mode 100644
index 00000000..b6868594
--- /dev/null
+++ b/src/Titano.Setup/App.cs
@@ -0,0 +1,76 @@
+using System.Windows;
+using Titano.Core.Diagnostics;
+using Titano.Core.Packaging;
+using Titano.Setup.Cli;
+using Titano.Setup.Engine;
+using Titano.Setup.Views;
+using Titano.Ui.Theming;
+
+namespace Titano.Setup;
+
+///
+/// Interactive setup: opens the payload (or, for /uninstall, the installation), elevates an all-users
+/// uninstall up front, and shows the setup window. The exit code is the view model's outcome.
+///
+internal sealed class App(SetupArguments arguments) : Application
+{
+ protected override void OnStartup(StartupEventArgs e)
+ {
+ base.OnStartup(e);
+ ShutdownMode = ShutdownMode.OnExplicitShutdown;
+ ThemeManager.Initialize(this, AppTheme.Dark);
+ _ = StartAsync();
+ }
+
+ private async Task StartAsync()
+ {
+ try
+ {
+ var model = arguments.Uninstall ? await ForUninstallAsync() : ForInstall();
+ if (model is null) return;
+ var window = new SetupWindow(model);
+ MainWindow = window;
+ window.Closed += (_, _) =>
+ {
+ model.Dispose();
+ Shutdown((int)model.ExitCode);
+ };
+ window.Show();
+ }
+ catch (Exception ex)
+ {
+ Log.Error("setup", "Setup could not start", ex);
+ Shutdown((int)SetupExitCode.Failed);
+ }
+ }
+
+ private SetupViewModel ForInstall()
+ {
+ PayloadReader? payload = null;
+ try
+ {
+ payload = PayloadReader.OpenCurrentProcess();
+ return SetupViewModel.ForInstall(arguments, payload);
+ }
+ catch (Exception ex) when (ex is PayloadException or SetupException)
+ {
+ payload?.Dispose();
+ Log.Error("setup", "Cannot install", ex);
+ return SetupViewModel.ForFailure(arguments, SilentSetup.CodeFor(ex));
+ }
+ }
+
+ /// The uninstall window, or null when this process handed over to an elevated copy and is shutting down.
+ private async Task ForUninstallAsync()
+ {
+ var product = UninstallEngine.Locate(arguments.Directory, SilentSetup.PayloadProduct());
+ if (product is null) return SetupViewModel.ForFailure(arguments, SetupExitCode.NotInstalled);
+ if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
+ {
+ var code = arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null);
+ Shutdown((int)code);
+ return null;
+ }
+ return SetupViewModel.ForUninstall(arguments, product);
+ }
+}
diff --git a/src/Titano.Setup/App.xaml b/src/Titano.Setup/App.xaml
deleted file mode 100644
index f0e5e815..00000000
--- a/src/Titano.Setup/App.xaml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
diff --git a/src/Titano.Setup/App.xaml.cs b/src/Titano.Setup/App.xaml.cs
deleted file mode 100644
index 24976df3..00000000
--- a/src/Titano.Setup/App.xaml.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-using System.Windows;
-
-namespace Titano.Setup;
-
-public partial class App : Application
-{
-}
diff --git a/src/Titano.Setup/Cli/SetupArguments.cs b/src/Titano.Setup/Cli/SetupArguments.cs
new file mode 100644
index 00000000..e5f54e19
--- /dev/null
+++ b/src/Titano.Setup/Cli/SetupArguments.cs
@@ -0,0 +1,105 @@
+using System.Text;
+
+namespace Titano.Setup.Cli;
+
+///
+/// Command-line switches, case-insensitive, with / or -:
+/// /S silent · /DIR=path · /COMPONENTS=Titano,Uploader · /ALLUSERS · /NODESKTOP ·
+/// /NOSTARTMENU · /LAUNCH · /LANG=it · /uninstall.
+/// Internal: /ELEVATED (relaunched for administrator rights), /CLEANUP=path /WAITPID=n (removes the
+/// uninstaller after the uninstall process exits).
+///
+internal sealed record SetupArguments
+{
+ public bool Silent { get; init; }
+ public bool Uninstall { get; init; }
+ public string? Directory { get; init; }
+ public IReadOnlyList? Components { get; init; }
+ public bool AllUsers { get; init; }
+ public bool NoDesktopShortcut { get; init; }
+ public bool NoStartMenu { get; init; }
+ public bool Launch { get; init; }
+ public string? Language { get; init; }
+ public bool Elevated { get; init; }
+ public string? CleanupTarget { get; init; }
+ public int WaitProcessId { get; init; }
+
+ /// Parses ; throws for unknown or malformed switches.
+ public static SetupArguments Parse(IEnumerable args)
+ {
+ var result = new SetupArguments();
+ foreach (var arg in args)
+ {
+ if (arg.Length < 2 || arg[0] is not ('/' or '-')) throw new ArgumentException($"Unexpected argument '{arg}'.");
+ var eq = arg.IndexOf('=', StringComparison.Ordinal);
+ var name = (eq < 0 ? arg[1..] : arg[1..eq]).ToUpperInvariant();
+ var value = eq < 0 ? null : arg[(eq + 1)..];
+ result = (name, value) switch
+ {
+ ("S", null) => result with { Silent = true },
+ ("UNINSTALL", null) => result with { Uninstall = true },
+ ("ALLUSERS", null) => result with { AllUsers = true },
+ ("NODESKTOP", null) => result with { NoDesktopShortcut = true },
+ ("NOSTARTMENU", null) => result with { NoStartMenu = true },
+ ("LAUNCH", null) => result with { Launch = true },
+ ("ELEVATED", null) => result with { Elevated = true },
+ ("DIR", { Length: > 0 }) => result with { Directory = value.Trim('"') },
+ ("LANG", { Length: > 0 }) => result with { Language = value },
+ ("COMPONENTS", { Length: > 0 }) => result with { Components = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) },
+ ("CLEANUP", { Length: > 0 }) => result with { CleanupTarget = value.Trim('"') },
+ ("WAITPID", { Length: > 0 }) when int.TryParse(value, out var pid) && pid > 0 => result with { WaitProcessId = pid },
+ _ => throw new ArgumentException($"Unknown or malformed switch '{arg}'."),
+ };
+ }
+ if (result.CleanupTarget is not null && result.WaitProcessId == 0) throw new ArgumentException("/CLEANUP needs /WAITPID.");
+ return result;
+ }
+
+ /// The switches that reproduce these arguments, for relaunching with administrator rights.
+ public IEnumerable ToSwitches()
+ {
+ if (Uninstall) yield return "/uninstall";
+ if (Silent) yield return "/S";
+ if (Directory is not null) yield return "/DIR=" + Directory;
+ if (Components is not null) yield return "/COMPONENTS=" + string.Join(',', Components);
+ if (AllUsers) yield return "/ALLUSERS";
+ if (NoDesktopShortcut) yield return "/NODESKTOP";
+ if (NoStartMenu) yield return "/NOSTARTMENU";
+ if (Launch) yield return "/LAUNCH";
+ if (Language is not null) yield return "/LANG=" + Language;
+ if (Elevated) yield return "/ELEVATED";
+ }
+
+ ///
+ /// Joins arguments into one command line that CommandLineToArgvW splits back into the same strings
+ /// (quotes around spaces, backslashes doubled before a quote).
+ ///
+ public static string JoinCommandLine(IEnumerable arguments)
+ {
+ var sb = new StringBuilder();
+ foreach (var argument in arguments)
+ {
+ if (sb.Length > 0) sb.Append(' ');
+ if (argument.Length > 0 && argument.IndexOfAny([' ', '\t', '"']) < 0)
+ {
+ sb.Append(argument);
+ continue;
+ }
+ sb.Append('"');
+ var backslashes = 0;
+ foreach (var c in argument)
+ {
+ if (c == '\\')
+ {
+ backslashes++;
+ continue;
+ }
+ sb.Append('\\', c == '"' ? backslashes * 2 + 1 : backslashes);
+ backslashes = 0;
+ sb.Append(c);
+ }
+ sb.Append('\\', backslashes * 2).Append('"');
+ }
+ return sb.ToString();
+ }
+}
diff --git a/src/Titano.Setup/Cli/SetupExitCode.cs b/src/Titano.Setup/Cli/SetupExitCode.cs
new file mode 100644
index 00000000..d044bd45
--- /dev/null
+++ b/src/Titano.Setup/Cli/SetupExitCode.cs
@@ -0,0 +1,41 @@
+namespace Titano.Setup.Cli;
+
+/// Process exit codes of Titano.Setup (stable contract for silent deployments).
+internal enum SetupExitCode
+{
+ Success = 0,
+
+ /// Installation or removal did not complete; the setup log in %TEMP%\Titano Setup has details.
+ Failed = 1,
+
+ InvalidArguments = 2,
+
+ /// The installer carries no payload or the payload is damaged.
+ PayloadInvalid = 3,
+
+ /// All-users operation and the administrator prompt was declined.
+ ElevationDeclined = 4,
+
+ /// An installed program did not close when asked to.
+ ProgramRunning = 5,
+
+ /// /uninstall found no installation.
+ NotInstalled = 6,
+
+ DiskFull = 7,
+
+ /// The window was closed before anything changed.
+ Cancelled = 8,
+
+ ///
+ /// Internal: an instance relaunched with administrator rights finished and asks its unelevated parent to start
+ /// the program, so the program does not run elevated. The parent turns it into .
+ ///
+ LaunchRequested = 100,
+}
+
+/// A setup failure that maps to a specific exit code and message.
+internal sealed class SetupException(SetupExitCode code, string message) : Exception(message)
+{
+ public SetupExitCode Code { get; } = code;
+}
diff --git a/src/Titano.Setup/Engine/Elevation.cs b/src/Titano.Setup/Engine/Elevation.cs
new file mode 100644
index 00000000..91f7936a
--- /dev/null
+++ b/src/Titano.Setup/Engine/Elevation.cs
@@ -0,0 +1,79 @@
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Security.Principal;
+using Titano.Setup.Cli;
+using Titano.Setup.Interop;
+
+namespace Titano.Setup.Engine;
+
+///
+/// Administrator rights for all-users operations. Setup runs asInvoker and, only when needed, starts itself
+/// again through ShellExecuteEx with the runas verb (the UAC prompt) and the same switches plus /ELEVATED.
+///
+internal static class Elevation
+{
+ public static bool IsElevated
+ {
+ get
+ {
+ using var identity = WindowsIdentity.GetCurrent();
+ return new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator);
+ }
+ }
+
+ ///
+ /// Runs this program elevated with and waits for it; see .
+ /// Returns when the prompt was refused.
+ ///
+ public static async Task RunElevatedAsync(SetupArguments arguments, string? launchProgram) =>
+ Start(arguments, IntPtr.Zero) is { } child ? await WaitAsync(child, launchProgram).ConfigureAwait(false) : SetupExitCode.ElevationDeclined;
+
+ /// Starts this program elevated (UAC prompt owned by ); null when the user declines.
+ public static Process? Start(SetupArguments arguments, IntPtr owner)
+ {
+ var start = new ProcessStartInfo(Environment.ProcessPath ?? throw new InvalidOperationException("Unknown setup path."))
+ {
+ UseShellExecute = true,
+ Verb = "runas",
+ Arguments = SetupArguments.JoinCommandLine((arguments with { Elevated = true }).ToSwitches()),
+ ErrorDialogParentHandle = owner,
+ };
+ try
+ {
+ return Process.Start(start) ?? throw new InvalidOperationException("The elevated setup did not start.");
+ }
+ catch (Win32Exception ex) when (ex.NativeErrorCode == NativeMethods.ERROR_CANCELLED)
+ {
+ return null;
+ }
+ }
+
+ ///
+ /// Waits for the elevated copy and returns its exit code; when it asks for it, starts
+ /// from this unelevated process so the program does not run as administrator.
+ ///
+ public static async Task WaitAsync(Process child, string? launchProgram)
+ {
+ using (child)
+ {
+ await child.WaitForExitAsync().ConfigureAwait(false);
+ var code = (SetupExitCode)child.ExitCode;
+ if (code != SetupExitCode.LaunchRequested) return code;
+ if (launchProgram is not null) Launcher.Start(launchProgram);
+ return SetupExitCode.Success;
+ }
+ }
+}
+
+/// Starts an installed program the way Explorer does.
+internal static class Launcher
+{
+ public static void Start(string program)
+ {
+ using var process = Process.Start(new ProcessStartInfo(program)
+ {
+ UseShellExecute = true,
+ WorkingDirectory = System.IO.Path.GetDirectoryName(program)!,
+ });
+ }
+}
diff --git a/src/Titano.Setup/Engine/InstallEngine.cs b/src/Titano.Setup/Engine/InstallEngine.cs
new file mode 100644
index 00000000..dc216279
--- /dev/null
+++ b/src/Titano.Setup/Engine/InstallEngine.cs
@@ -0,0 +1,149 @@
+using System.IO;
+using System.Reflection;
+using Titano.Core.Diagnostics;
+using Titano.Core.Packaging;
+using Titano.Setup.Cli;
+using Titano.Setup.Interop;
+
+namespace Titano.Setup.Engine;
+
+/// What to install, where and with which shortcuts.
+internal sealed record InstallRequest(string Directory, InstallScope Scope, IReadOnlyList Components, bool DesktopShortcuts, bool StartMenuShortcuts);
+
+/// Overall progress (0–1) and the file being written.
+internal readonly record struct SetupProgress(double Fraction, string CurrentFile);
+
+///
+/// Installs or upgrades in place from the payload: verified extraction into staging, an all-or-nothing move into
+/// the folder, removal of files the previous version shipped and this one does not, then shortcuts, file types and
+/// the Add/Remove Programs entry. The user data folder is never touched.
+///
+internal sealed class InstallEngine(PayloadReader payload)
+{
+ private const double ExtractShare = 0.9;
+
+ public PayloadManifest Manifest => payload.Manifest;
+
+ /// Bytes the selected components occupy once installed, uninstaller included.
+ public long RequiredBytes(IEnumerable components) => Manifest.FilesFor(components).Sum(f => f.Size) + payload.PayloadOffset;
+
+ /// Payload path of the program to start after installing: the first shortcut target among the components.
+ public string? LaunchTarget(IEnumerable components)
+ {
+ var selected = new HashSet(components, StringComparer.OrdinalIgnoreCase);
+ return Manifest.Shortcuts.FirstOrDefault(s => selected.Contains(s.Component))?.Target;
+ }
+
+ public InstallLog Install(InstallRequest request, IProgress? progress, CancellationToken cancellationToken)
+ {
+ var directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(request.Directory));
+ var product = Manifest.Product;
+ var uninstaller = SetupPaths.UninstallerName(product);
+ var files = Manifest.FilesFor(request.Components);
+ if (files.Any(f => PayloadPath.Comparer.Equals(f.Path, uninstaller) || PayloadPath.Comparer.Equals(f.Path, InstallLog.FileName)))
+ throw new PayloadException(PayloadError.Corrupt, "The payload overwrites setup's own files.");
+ EnsureFreeSpace(directory, RequiredBytes(request.Components));
+ var previous = InstallLog.TryLoad(directory);
+ Log.Info("setup", $"Installing {product} {Manifest.Version} ({string.Join(",", request.Components)}) to '{directory}' for {request.Scope}");
+
+ using (var transaction = new InstallTransaction(directory))
+ {
+ var extractProgress = progress is null ? null : new MappedProgress(progress, 0, ExtractShare);
+ payload.Extract(files, transaction.StagingDirectory, extractProgress, cancellationToken);
+ payload.WriteStub(Path.Combine(transaction.StagingDirectory, uninstaller));
+ cancellationToken.ThrowIfCancellationRequested();
+ transaction.Commit([.. files.Select(f => f.Path), uninstaller]);
+ }
+ progress?.Report(new SetupProgress(ExtractShare, string.Empty));
+
+ var shortcuts = PlanShortcuts(request, directory);
+ var fileTypes = PlanFileTypes(request);
+ var log = new InstallLog
+ {
+ Product = product,
+ Version = Manifest.Version,
+ Scope = request.Scope,
+ Components = [.. request.Components],
+ Files = [.. files.Select(f => f.Path)],
+ Shortcuts = [.. shortcuts.Select(s => s.Link)],
+ Associations = [.. fileTypes.Select(a => new InstalledAssociation(a.Extension, a.ProgId))],
+ };
+ if (previous is not null) RemoveLeftovers(directory, previous, log);
+ // Saved before registration so that an uninstall can always undo whatever follows.
+ log.Save(directory);
+
+ foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name);
+ foreach (var a in fileTypes)
+ SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, a.Description, PayloadPath.Resolve(directory, a.Target));
+ if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged();
+
+ var uninstallerPath = Path.Combine(directory, uninstaller);
+ var icon = LaunchTarget(request.Components) is { } main ? PayloadPath.Resolve(directory, main) : uninstallerPath;
+ SetupRegistry.WriteUninstallEntry(request.Scope, SetupPaths.ProductKey(product), new UninstallEntry(
+ product, Manifest.Version, Publisher, directory, uninstallerPath, icon, RequiredBytes(request.Components), AboutUrl));
+ progress?.Report(new SetupProgress(1, string.Empty));
+ Log.Info("setup", $"Installed {files.Count} files");
+ return log;
+ }
+
+ private static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute()?.Company ?? "Titano";
+
+ private static string? AboutUrl =>
+ typeof(InstallEngine).Assembly.GetCustomAttributes().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo
+ ? "https://github.com/" + repo
+ : null;
+
+ private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory)
+ {
+ var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase);
+ var result = new List<(string, string, string)>();
+ foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component)))
+ {
+ var target = PayloadPath.Resolve(directory, s.Target);
+ if (s.StartMenu && request.StartMenuShortcuts) result.Add((Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name));
+ if (s.Desktop && request.DesktopShortcuts) result.Add((Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name));
+ }
+ return result;
+ }
+
+ private List PlanFileTypes(InstallRequest request)
+ {
+ var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase);
+ return Manifest.Associations.Where(a => selected.Contains(a.Component)).ToList();
+ }
+
+ /// Removes what the previous version installed and this one no longer does (files, shortcuts, file types).
+ private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current)
+ {
+ var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList();
+ if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete);
+ foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase))
+ UninstallEngine.DeleteShortcut(link, previous.Scope);
+ foreach (var a in previous.Associations.Except(current.Associations))
+ {
+ if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId);
+ }
+ }
+
+ private static void EnsureFreeSpace(string directory, long required)
+ {
+ long available;
+ try
+ {
+ available = new DriveInfo(Path.GetPathRoot(directory)!).AvailableFreeSpace;
+ }
+ catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
+ {
+ // Network shares have no DriveInfo; the copy itself reports a full disk.
+ return;
+ }
+ if (available < required) throw new SetupException(SetupExitCode.DiskFull, $"{required:N0} bytes needed, {available:N0} available.");
+ }
+
+ /// Maps extraction progress onto a slice of the overall bar.
+ private sealed class MappedProgress(IProgress target, double from, double to) : IProgress
+ {
+ public void Report(PayloadProgress value) =>
+ target.Report(new SetupProgress(from + (to - from) * (value.Total == 0 ? 1 : (double)value.Done / value.Total), value.CurrentPath));
+ }
+}
diff --git a/src/Titano.Setup/Engine/InstallLog.cs b/src/Titano.Setup/Engine/InstallLog.cs
new file mode 100644
index 00000000..4cdc6f5c
--- /dev/null
+++ b/src/Titano.Setup/Engine/InstallLog.cs
@@ -0,0 +1,60 @@
+using System.IO;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Titano.Core.IO;
+
+namespace Titano.Setup.Engine;
+
+///
+/// Record of one installation, kept as install-log.json in the install folder. The uninstaller carries no
+/// payload, so everything it removes comes from here: payload files, shortcuts and file types. User data is never
+/// listed.
+///
+internal sealed class InstallLog
+{
+ public const string FileName = "install-log.json";
+
+ public int FormatVersion { get; set; } = 1;
+ public required string Product { get; set; }
+ public required string Version { get; set; }
+ public InstallScope Scope { get; set; }
+ public List Components { get; set; } = [];
+
+ /// Installed payload paths, relative to the install folder (the uninstaller and this log excluded).
+ public List Files { get; set; } = [];
+
+ /// Full paths of the shortcuts setup created.
+ public List Shortcuts { get; set; } = [];
+ public List Associations { get; set; } = [];
+
+ [JsonIgnore]
+ public string ProductKey => SetupPaths.ProductKey(Product);
+
+ [JsonIgnore]
+ public string UninstallerName => SetupPaths.UninstallerName(Product);
+
+ /// The log in , or null when there is none or it is unreadable.
+ public static InstallLog? TryLoad(string directory)
+ {
+ var path = Path.Combine(directory, FileName);
+ try
+ {
+ return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllBytes(path), InstallLogJson.Default.InstallLog) : null;
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ Titano.Core.Diagnostics.Log.Warning("setup", $"Install log '{path}' is unreadable", ex);
+ return null;
+ }
+ }
+
+ public void Save(string directory) =>
+ AtomicFile.WriteAllBytes(Path.Combine(directory, FileName), JsonSerializer.SerializeToUtf8Bytes(this, InstallLogJson.Default.InstallLog));
+}
+
+/// A file type registered by setup.
+internal sealed record InstalledAssociation(string Extension, string ProgId);
+
+[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)]
+[JsonSerializable(typeof(InstallLog))]
+internal sealed partial class InstallLogJson : JsonSerializerContext;
diff --git a/src/Titano.Setup/Engine/InstallPlan.cs b/src/Titano.Setup/Engine/InstallPlan.cs
new file mode 100644
index 00000000..6b9f3cdc
--- /dev/null
+++ b/src/Titano.Setup/Engine/InstallPlan.cs
@@ -0,0 +1,37 @@
+using Titano.Core.Packaging;
+using Titano.Setup.Cli;
+
+namespace Titano.Setup.Engine;
+
+///
+/// Where and what to install before the user changes anything: an existing installation fixes folder and scope
+/// (upgrade in place) and suggests its components; otherwise the switches, then the manifest defaults, apply.
+///
+internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList Components, ExistingInstall? Existing)
+{
+ public static InstallPlan Resolve(PayloadManifest manifest, SetupArguments arguments)
+ {
+ var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product));
+ var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser);
+ var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product);
+
+ IReadOnlyList components;
+ if (arguments.Components is { } requested)
+ {
+ var unknown = requested.FirstOrDefault(id => manifest.FindComponent(id) is null);
+ if (unknown is not null) throw new SetupException(SetupExitCode.InvalidArguments, $"Unknown component '{unknown}'.");
+ components = [.. requested.Select(id => manifest.FindComponent(id)!.Id).Distinct()];
+ }
+ else
+ {
+ var previous = existing is null ? null : InstallLog.TryLoad(existing.Directory)?.Components;
+ var kept = previous?.Select(manifest.FindComponent).OfType().Select(c => c.Id).ToList();
+ components = kept is { Count: > 0 } ? kept : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)];
+ }
+ return new InstallPlan(scope, directory, components, existing);
+ }
+
+ /// Executables to look for among running processes: the new payload's and the previous install's.
+ public static IEnumerable Programs(PayloadManifest manifest, string directory) =>
+ manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []);
+}
diff --git a/src/Titano.Setup/Engine/RunningPrograms.cs b/src/Titano.Setup/Engine/RunningPrograms.cs
new file mode 100644
index 00000000..b060a50b
--- /dev/null
+++ b/src/Titano.Setup/Engine/RunningPrograms.cs
@@ -0,0 +1,54 @@
+using System.Diagnostics;
+using System.IO;
+using Titano.Setup.Interop;
+
+namespace Titano.Setup.Engine;
+
+///
+/// Installed programs that are running. Setup only ever asks them to close (WM_CLOSE to the main window, as when
+/// the user clicks ✕); it never terminates a process.
+///
+internal static class RunningPrograms
+{
+ /// Processes of (payload paths) started from inside .
+ public static IReadOnlyList Find(string directory, IEnumerable executables)
+ {
+ var names = executables
+ .Where(p => p.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !p.Contains('/', StringComparison.Ordinal))
+ .Select(Path.GetFileNameWithoutExtension)
+ .Distinct(StringComparer.OrdinalIgnoreCase);
+ var found = new List();
+ foreach (var name in names)
+ {
+ foreach (var process in Process.GetProcessesByName(name))
+ {
+ var image = process.Id == Environment.ProcessId ? null : NativeMethods.ProcessImagePath(process.Id);
+ if (image is not null && SetupPaths.IsSameOrInside(image, directory)) found.Add(process);
+ else process.Dispose();
+ }
+ }
+ return found;
+ }
+
+ /// Display names ("Titano", "Titano.Uploader") of the given processes, for the prompt.
+ public static string Describe(IReadOnlyList processes) =>
+ string.Join(", ", processes.Select(p => p.ProcessName).Distinct(StringComparer.OrdinalIgnoreCase));
+
+ /// Asks each process to close and waits up to ; returns those still running.
+ public static async Task> CloseAsync(IReadOnlyList processes, TimeSpan timeout)
+ {
+ foreach (var process in processes)
+ {
+ if (!process.HasExited) process.CloseMainWindow();
+ }
+ using var cts = new CancellationTokenSource(timeout);
+ try
+ {
+ await Task.WhenAll(processes.Select(p => p.WaitForExitAsync(cts.Token))).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ }
+ return processes.Where(p => !p.HasExited).ToList();
+ }
+}
diff --git a/src/Titano.Setup/Engine/SelfCleanup.cs b/src/Titano.Setup/Engine/SelfCleanup.cs
new file mode 100644
index 00000000..3f296f16
--- /dev/null
+++ b/src/Titano.Setup/Engine/SelfCleanup.cs
@@ -0,0 +1,83 @@
+using System.Diagnostics;
+using System.IO;
+using System.Threading;
+using Titano.Core.Diagnostics;
+using Titano.Setup.Cli;
+using Titano.Setup.Interop;
+
+namespace Titano.Setup.Engine;
+
+///
+/// Removes the uninstaller, which cannot delete its own running executable. It copies itself to a fresh folder in
+/// %TEMP% and starts the copy with /CLEANUP=<uninstaller> /WAITPID=<its id>; the copy waits for the
+/// uninstaller to exit, deletes it and the then-empty install folder, and exits. The copy itself is scheduled for
+/// deletion at the next restart when setup has administrator rights; otherwise Windows' temporary-file cleanup
+/// removes it. This works for per-user installs, where MoveFileEx(MOVEFILE_DELAY_UNTIL_REBOOT) is not allowed.
+///
+internal static class SelfCleanup
+{
+ private const string Prefix = "Uninstall ";
+
+ /// Starts the helper that deletes once this process has exited.
+ public static void Schedule(string uninstallerPath)
+ {
+ var folder = Path.Combine(Path.GetTempPath(), "Titano Setup", "cleanup-" + Guid.NewGuid().ToString("N")[..8]);
+ Directory.CreateDirectory(folder);
+ var copy = Path.Combine(folder, "Titano-Cleanup.exe");
+ File.Copy(Environment.ProcessPath!, copy);
+ var start = new ProcessStartInfo(copy) { UseShellExecute = false, CreateNoWindow = true };
+ start.ArgumentList.Add("/CLEANUP=" + uninstallerPath);
+ start.ArgumentList.Add("/WAITPID=" + Environment.ProcessId.ToString(System.Globalization.CultureInfo.InvariantCulture));
+ using var helper = Process.Start(start);
+ Log.Info("setup", $"Cleanup helper started for '{uninstallerPath}'");
+ }
+
+ /// The helper side: waits for , then removes the uninstaller and its empty folder.
+ public static SetupExitCode Run(string uninstallerPath, int processId)
+ {
+ var name = Path.GetFileName(uninstallerPath);
+ if (!Path.IsPathFullyQualified(uninstallerPath) || !name.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase)
+ || !name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
+ return SetupExitCode.InvalidArguments;
+
+ try
+ {
+ using var parent = Process.GetProcessById(processId);
+ parent.WaitForExit(TimeSpan.FromMinutes(2));
+ }
+ catch (ArgumentException)
+ {
+ // Already exited.
+ }
+
+ var removed = false;
+ for (var attempt = 0; attempt < 20 && !removed; attempt++)
+ {
+ try
+ {
+ if (File.Exists(uninstallerPath)) File.Delete(uninstallerPath);
+ removed = true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Thread.Sleep(500);
+ }
+ }
+ var folder = Path.GetDirectoryName(uninstallerPath)!;
+ try
+ {
+ if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("setup", $"Install folder '{folder}' not removed", ex);
+ }
+
+ if (Elevation.IsElevated && Environment.ProcessPath is { } self)
+ {
+ NativeMethods.DeleteAtReboot(self);
+ NativeMethods.DeleteAtReboot(Path.GetDirectoryName(self)!);
+ }
+ return removed ? SetupExitCode.Success : SetupExitCode.Failed;
+ }
+}
diff --git a/src/Titano.Setup/Engine/SetupPaths.cs b/src/Titano.Setup/Engine/SetupPaths.cs
new file mode 100644
index 00000000..4a1ac77d
--- /dev/null
+++ b/src/Titano.Setup/Engine/SetupPaths.cs
@@ -0,0 +1,78 @@
+using System.IO;
+using Titano.Core.Packaging;
+
+namespace Titano.Setup.Engine;
+
+/// Per-user (no administrator rights) or machine-wide installation.
+internal enum InstallScope
+{
+ CurrentUser,
+ AllUsers,
+}
+
+/// Folders and names that depend on the product and the install scope.
+internal static class SetupPaths
+{
+ private static string LocalAppData => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
+
+ /// %LOCALAPPDATA%\Programs\<product> for the current user, Program Files\<product> for all users.
+ public static string DefaultDirectory(InstallScope scope, string product) => Path.Combine(
+ scope == InstallScope.AllUsers ? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) : Path.Combine(LocalAppData, "Programs"),
+ product);
+
+ public static string StartMenu(InstallScope scope) =>
+ Environment.GetFolderPath(scope == InstallScope.AllUsers ? Environment.SpecialFolder.CommonPrograms : Environment.SpecialFolder.Programs);
+
+ public static string Desktop(InstallScope scope) =>
+ Environment.GetFolderPath(scope == InstallScope.AllUsers ? Environment.SpecialFolder.CommonDesktopDirectory : Environment.SpecialFolder.DesktopDirectory);
+
+ ///
+ /// %LOCALAPPDATA%\Titano: database, settings, logs and caches of the desktop programs. Installing and
+ /// upgrading never touch it; uninstall removes it only when the user asks.
+ ///
+ public static string UserData => Path.Combine(LocalAppData, "Titano");
+
+ /// Setup's own log files (%TEMP%\Titano Setup), outside the user data folder.
+ public static string LogDirectory => Path.Combine(Path.GetTempPath(), "Titano Setup");
+
+ /// Registry key name under …\CurrentVersion\Uninstall: the product name without spaces or symbols.
+ public static string ProductKey(string product) => string.Concat(product.Where(char.IsAsciiLetterOrDigit));
+
+ public static string UninstallerName(string product) => $"Uninstall {product}.exe";
+
+ ///
+ /// True for an absolute local or UNC folder whose names Windows stores verbatim, that is not a drive root, not
+ /// inside the Windows folder and not the user data folder.
+ ///
+ public static bool IsUsableInstallDirectory(string? path)
+ {
+ if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path) || path.IndexOfAny(Path.GetInvalidPathChars()) >= 0) return false;
+ string full;
+ try
+ {
+ full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ return false;
+ }
+ var root = Path.TrimEndingDirectorySeparator(Path.GetPathRoot(full) ?? string.Empty);
+ if (full.Length <= root.Length) return false;
+ foreach (var segment in full[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
+ {
+ if (!PayloadPath.IsValidSegment(segment)) return false;
+ }
+ return !IsSameOrInside(full, Environment.GetFolderPath(Environment.SpecialFolder.Windows))
+ && !IsSameOrInside(full, UserData)
+ && !IsSameOrInside(UserData, full);
+ }
+
+ /// True when is or lies inside it (case-insensitive).
+ public static bool IsSameOrInside(string path, string folder)
+ {
+ if (folder.Length == 0) return false;
+ var a = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
+ var b = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
+ return a.Equals(b, StringComparison.OrdinalIgnoreCase) || a.StartsWith(b + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs
new file mode 100644
index 00000000..006c7703
--- /dev/null
+++ b/src/Titano.Setup/Engine/SetupRegistry.cs
@@ -0,0 +1,110 @@
+using System.Globalization;
+using System.IO;
+using System.Text.RegularExpressions;
+using Microsoft.Win32;
+
+namespace Titano.Setup.Engine;
+
+/// An installation found in Add/Remove Programs.
+internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version);
+
+/// Values written to the Add/Remove Programs entry.
+internal sealed record UninstallEntry(string DisplayName, string Version, string Publisher, string Directory, string UninstallerPath, string DisplayIcon, long EstimatedBytes, string? AboutUrl);
+
+///
+/// Registry state owned by setup: the Add/Remove Programs entry under
+/// Software\Microsoft\Windows\CurrentVersion\Uninstall\<key> and file types under Software\Classes,
+/// in HKCU for per-user installs and HKLM for all-users installs.
+///
+internal static partial class SetupRegistry
+{
+ private const string UninstallRoot = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\";
+ private const string ClassesRoot = @"Software\Classes\";
+
+ private static RegistryKey Hive(InstallScope scope) => scope == InstallScope.AllUsers ? Registry.LocalMachine : Registry.CurrentUser;
+
+ /// The installation registered under whose folder still exists, current user first.
+ public static ExistingInstall? FindInstall(string productKey)
+ {
+ foreach (var scope in (ReadOnlySpan)[InstallScope.CurrentUser, InstallScope.AllUsers])
+ {
+ using var key = Hive(scope).OpenSubKey(UninstallRoot + productKey);
+ if (key?.GetValue("InstallLocation") is string directory && Directory.Exists(directory))
+ return new ExistingInstall(scope, directory, key.GetValue("DisplayVersion") as string ?? string.Empty);
+ }
+ return null;
+ }
+
+ public static void WriteUninstallEntry(InstallScope scope, string productKey, UninstallEntry entry)
+ {
+ using var key = Hive(scope).CreateSubKey(UninstallRoot + productKey, writable: true);
+ var quoted = "\"" + entry.UninstallerPath + "\"";
+ key.SetValue("DisplayName", entry.DisplayName);
+ key.SetValue("DisplayVersion", entry.Version);
+ key.SetValue("Publisher", entry.Publisher);
+ key.SetValue("DisplayIcon", entry.DisplayIcon + ",0");
+ key.SetValue("InstallLocation", entry.Directory);
+ key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture));
+ key.SetValue("UninstallString", quoted + " /uninstall");
+ key.SetValue("QuietUninstallString", quoted + " /uninstall /S");
+ key.SetValue("EstimatedSize", (int)Math.Min(int.MaxValue, (entry.EstimatedBytes + 1023) / 1024), RegistryValueKind.DWord);
+ key.SetValue("NoModify", 1, RegistryValueKind.DWord);
+ key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
+ if (entry.AboutUrl is not null) key.SetValue("URLInfoAbout", entry.AboutUrl);
+ }
+
+ public static void DeleteUninstallEntry(InstallScope scope, string productKey) =>
+ Hive(scope).DeleteSubKeyTree(UninstallRoot + productKey, throwOnMissingSubKey: false);
+
+ /// Registers to open with "program" "%1" under .
+ public static void RegisterFileType(InstallScope scope, string extension, string progId, string description, string program)
+ {
+ EnsureValid(extension, progId);
+ var hive = Hive(scope);
+ using (var type = hive.CreateSubKey(ClassesRoot + progId, writable: true))
+ {
+ type.SetValue(string.Empty, description);
+ using (var icon = type.CreateSubKey("DefaultIcon", writable: true)) icon.SetValue(string.Empty, "\"" + program + "\",0");
+ using var command = type.CreateSubKey(@"shell\open\command", writable: true);
+ command.SetValue(string.Empty, "\"" + program + "\" \"%1\"");
+ }
+ using var ext = hive.CreateSubKey(ClassesRoot + extension, writable: true);
+ ext.SetValue(string.Empty, progId);
+ using var openWith = ext.CreateSubKey("OpenWithProgids", writable: true);
+ openWith.SetValue(progId, string.Empty);
+ }
+
+ /// Removes the ProgID and detaches the extension, leaving other programs' registrations intact.
+ public static void UnregisterFileType(InstallScope scope, string extension, string progId)
+ {
+ EnsureValid(extension, progId);
+ var hive = Hive(scope);
+ hive.DeleteSubKeyTree(ClassesRoot + progId, throwOnMissingSubKey: false);
+ using (var ext = hive.OpenSubKey(ClassesRoot + extension, writable: true))
+ {
+ if (ext is null) return;
+ if (ext.GetValue(string.Empty) is string current && current.Equals(progId, StringComparison.OrdinalIgnoreCase)) ext.DeleteValue(string.Empty, false);
+ using (var openWith = ext.OpenSubKey("OpenWithProgids", writable: true))
+ {
+ openWith?.DeleteValue(progId, false);
+ if (openWith is { ValueCount: 0, SubKeyCount: 0 }) ext.DeleteSubKey("OpenWithProgids", false);
+ }
+ if (ext.ValueCount > 0 || ext.SubKeyCount > 0) return;
+ }
+ hive.DeleteSubKey(ClassesRoot + extension, throwOnMissingSubKey: false);
+ }
+
+ /// Guards registry paths built from a log file: an extension and a dotted ProgID, nothing else.
+ public static bool IsValidFileType(string extension, string progId) => ExtensionRegex().IsMatch(extension) && ProgIdRegex().IsMatch(progId);
+
+ private static void EnsureValid(string extension, string progId)
+ {
+ if (!IsValidFileType(extension, progId)) throw new ArgumentException($"Invalid file type '{extension}' / '{progId}'.");
+ }
+
+ [GeneratedRegex(@"^\.[A-Za-z0-9]{1,16}$")]
+ private static partial Regex ExtensionRegex();
+
+ [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z0-9]+)+$")]
+ private static partial Regex ProgIdRegex();
+}
diff --git a/src/Titano.Setup/Engine/SilentSetup.cs b/src/Titano.Setup/Engine/SilentSetup.cs
new file mode 100644
index 00000000..a0c7a398
--- /dev/null
+++ b/src/Titano.Setup/Engine/SilentSetup.cs
@@ -0,0 +1,99 @@
+using System.IO;
+using Titano.Core.Diagnostics;
+using Titano.Core.Packaging;
+using Titano.Setup.Cli;
+
+namespace Titano.Setup.Engine;
+
+///
+/// /S: install or uninstall without a window, reporting only through the exit code and the setup log.
+/// Running programs are asked to close; if they do not, setup stops with .
+/// Silent uninstall never removes user data.
+///
+internal static class SilentSetup
+{
+ public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(20);
+
+ public static async Task RunAsync(SetupArguments arguments)
+ {
+ try
+ {
+ return arguments.Uninstall ? await UninstallAsync(arguments).ConfigureAwait(false) : await InstallAsync(arguments).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ Log.Error("setup", "Silent setup failed", ex);
+ return CodeFor(ex);
+ }
+ }
+
+ /// Exit code for a failure.
+ public static SetupExitCode CodeFor(Exception ex) => ex switch
+ {
+ SetupException s => s.Code,
+ PayloadException => SetupExitCode.PayloadInvalid,
+ // ERROR_DISK_FULL / ERROR_HANDLE_DISK_FULL
+ IOException { HResult: unchecked((int)0x80070070) or unchecked((int)0x80070027) } => SetupExitCode.DiskFull,
+ _ => SetupExitCode.Failed,
+ };
+
+ private static async Task InstallAsync(SetupArguments arguments)
+ {
+ using var payload = PayloadReader.OpenCurrentProcess();
+ var engine = new InstallEngine(payload);
+ var plan = InstallPlan.Resolve(engine.Manifest, arguments);
+ if (plan.Existing is not null && arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory))
+ Log.Warning("setup", $"/DIR ignored: {engine.Manifest.Product} is already installed in '{plan.Directory}'");
+ if (!SetupPaths.IsUsableInstallDirectory(plan.Directory)) return SetupExitCode.InvalidArguments;
+ if (plan.Components.Count == 0) return SetupExitCode.InvalidArguments;
+
+ var launch = arguments.Launch && engine.LaunchTarget(plan.Components) is { } target ? PayloadPath.Resolve(plan.Directory, target) : null;
+ if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
+ return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false);
+
+ if (!await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory)).ConfigureAwait(false))
+ return SetupExitCode.ProgramRunning;
+ var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu);
+ engine.Install(request, null, CancellationToken.None);
+
+ if (launch is null) return SetupExitCode.Success;
+ if (arguments.Elevated) return SetupExitCode.LaunchRequested;
+ Launcher.Start(launch);
+ return SetupExitCode.Success;
+ }
+
+ private static async Task UninstallAsync(SetupArguments arguments)
+ {
+ var product = UninstallEngine.Locate(arguments.Directory, PayloadProduct());
+ if (product is null) return SetupExitCode.NotInstalled;
+ if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
+ return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null).ConfigureAwait(false);
+ if (!await CloseProgramsAsync(product.Directory, product.Log.Files).ConfigureAwait(false)) return SetupExitCode.ProgramRunning;
+ UninstallEngine.Uninstall(product, removeUserData: false, null);
+ return SetupExitCode.Success;
+ }
+
+ /// The product named by this program's payload, when it has one (a full installer run with /uninstall).
+ public static string? PayloadProduct()
+ {
+ try
+ {
+ using var payload = PayloadReader.OpenCurrentProcess();
+ return payload.Manifest.Product;
+ }
+ catch (PayloadException)
+ {
+ return null;
+ }
+ }
+
+ private static async Task CloseProgramsAsync(string directory, IEnumerable programs)
+ {
+ var running = RunningPrograms.Find(directory, programs);
+ if (running.Count == 0) return true;
+ Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close");
+ var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false);
+ foreach (var p in running) p.Dispose();
+ return still.Count == 0;
+ }
+}
diff --git a/src/Titano.Setup/Engine/UninstallEngine.cs b/src/Titano.Setup/Engine/UninstallEngine.cs
new file mode 100644
index 00000000..d793b225
--- /dev/null
+++ b/src/Titano.Setup/Engine/UninstallEngine.cs
@@ -0,0 +1,106 @@
+using System.IO;
+using Titano.Core.Diagnostics;
+using Titano.Core.Packaging;
+using Titano.Setup.Cli;
+using Titano.Setup.Interop;
+
+namespace Titano.Setup.Engine;
+
+/// An installation found on disk: its folder and log.
+internal sealed record InstalledProduct(string Directory, InstallLog Log);
+
+///
+/// Removes an installation using only its log: shortcuts, file types, logged files, the log and the Add/Remove
+/// Programs entry, then the uninstaller itself. Files the log does not list are left alone; the user data folder
+/// is deleted only when removeUserData is set by an explicit choice in the window.
+///
+internal static class UninstallEngine
+{
+ /// The installation to remove: /DIR, the uninstaller's own folder, or the registered location.
+ public static InstalledProduct? Locate(string? directory, string? productFromPayload)
+ {
+ var candidates = new List { directory, Path.GetDirectoryName(Environment.ProcessPath) };
+ if (productFromPayload is not null) candidates.Add(SetupRegistry.FindInstall(SetupPaths.ProductKey(productFromPayload))?.Directory);
+ foreach (var candidate in candidates)
+ {
+ if (string.IsNullOrEmpty(candidate)) continue;
+ if (InstallLog.TryLoad(candidate) is { } log) return new InstalledProduct(Path.GetFullPath(candidate), log);
+ }
+ return null;
+ }
+
+ public static void Uninstall(InstalledProduct product, bool removeUserData, IProgress? progress)
+ {
+ var (directory, log) = product;
+ Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {removeUserData})");
+ // First, so that a failure here leaves the program installed and the uninstaller able to retry.
+ if (removeUserData && Directory.Exists(SetupPaths.UserData))
+ {
+ Log.Info("setup", $"Removing user data '{SetupPaths.UserData}' at the user's request");
+ Directory.Delete(SetupPaths.UserData, recursive: true);
+ }
+ foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope);
+ progress?.Report(new SetupProgress(0.1, string.Empty));
+
+ var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList();
+ foreach (var a in fileTypes) SetupRegistry.UnregisterFileType(log.Scope, a.Extension, a.ProgId);
+ if (fileTypes.Count > 0) NativeMethods.NotifyAssociationsChanged();
+ progress?.Report(new SetupProgress(0.2, string.Empty));
+
+ var failed = InstalledFiles.Remove(directory, log.Files.Where(PayloadPath.IsValid));
+ progress?.Report(new SetupProgress(0.8, string.Empty));
+ if (failed.Count > 0)
+ {
+ // Keep the entry and a log of what is left, so the user can run the uninstaller again.
+ log.Files = [.. failed];
+ log.Shortcuts = [];
+ log.Associations = [];
+ log.Save(directory);
+ throw new SetupException(SetupExitCode.Failed, $"{failed.Count} file(s) could not be removed.");
+ }
+
+ SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey);
+ File.Delete(Path.Combine(directory, InstallLog.FileName));
+ var uninstaller = Path.Combine(directory, log.UninstallerName);
+ try
+ {
+ if (Environment.ProcessPath is { } self && Path.GetFullPath(self).Equals(Path.GetFullPath(uninstaller), StringComparison.OrdinalIgnoreCase))
+ {
+ SelfCleanup.Schedule(uninstaller);
+ }
+ else
+ {
+ if (File.Exists(uninstaller)) File.Delete(uninstaller);
+ InstalledFiles.Remove(directory, [], removeEmptyRoot: true);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception)
+ {
+ // Everything else is gone; a leftover uninstaller is not worth failing the removal.
+ Log.Warning("setup", $"Uninstaller '{uninstaller}' not removed", ex);
+ }
+ progress?.Report(new SetupProgress(1, string.Empty));
+ }
+
+ /// Deletes a shortcut recorded in a log, but only a .lnk directly in the Start menu or desktop folder.
+ public static void DeleteShortcut(string link, InstallScope scope)
+ {
+ var folder = Path.GetDirectoryName(link);
+ var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase)
+ && (folder.Equals(SetupPaths.StartMenu(scope), StringComparison.OrdinalIgnoreCase)
+ || folder.Equals(SetupPaths.Desktop(scope), StringComparison.OrdinalIgnoreCase));
+ if (!allowed)
+ {
+ Log.Warning("setup", $"Ignoring shortcut outside the shortcut folders: '{link}'");
+ return;
+ }
+ try
+ {
+ File.Delete(link);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("setup", $"Shortcut '{link}' not removed", ex);
+ }
+ }
+}
diff --git a/src/Titano.Setup/Interop/FolderPicker.cs b/src/Titano.Setup/Interop/FolderPicker.cs
new file mode 100644
index 00000000..cc77e7e5
--- /dev/null
+++ b/src/Titano.Setup/Interop/FolderPicker.cs
@@ -0,0 +1,129 @@
+using System.IO;
+using System.Runtime.InteropServices;
+
+namespace Titano.Setup.Interop;
+
+/// The Windows folder picker: IFileOpenDialog with FOS_PICKFOLDERS (no WinForms).
+internal static class FolderPicker
+{
+ private const uint FOS_PICKFOLDERS = 0x20;
+ private const uint FOS_FORCEFILESYSTEM = 0x40;
+ private const uint FOS_PATHMUSTEXIST = 0x800;
+ private const uint SIGDN_FILESYSPATH = 0x80058000;
+
+ /// Shows the picker owned by ; returns the chosen folder or null when cancelled.
+ public static string? Pick(IntPtr owner, string title, string? initialFolder)
+ {
+ var dialog = (IFileOpenDialog)new FileOpenDialogObject();
+ try
+ {
+ dialog.GetOptions(out var options);
+ dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
+ dialog.SetTitle(title);
+ if (NearestExisting(initialFolder) is { } start && TryCreateItem(start) is { } item)
+ {
+ dialog.SetFolder(item);
+ Marshal.ReleaseComObject(item);
+ }
+ var hr = dialog.Show(owner);
+ if (hr == NativeMethods.HRESULT_ERROR_CANCELLED) return null;
+ Marshal.ThrowExceptionForHR(hr);
+ dialog.GetResult(out var result);
+ try
+ {
+ result.GetDisplayName(SIGDN_FILESYSPATH, out var path);
+ return path;
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(result);
+ }
+ }
+ finally
+ {
+ Marshal.FinalReleaseComObject(dialog);
+ }
+ }
+
+ private static string? NearestExisting(string? folder)
+ {
+ try
+ {
+ for (var dir = folder; !string.IsNullOrEmpty(dir); dir = Path.GetDirectoryName(dir))
+ {
+ if (Directory.Exists(dir)) return dir;
+ }
+ }
+ catch (ArgumentException)
+ {
+ }
+ return null;
+ }
+
+ private static IShellItem? TryCreateItem(string path)
+ {
+ try
+ {
+ return SHCreateItemFromParsingName(path, IntPtr.Zero, typeof(IShellItem).GUID);
+ }
+ catch (COMException)
+ {
+ return null;
+ }
+ }
+
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
+ [return: MarshalAs(UnmanagedType.Interface)]
+ private static extern IShellItem SHCreateItemFromParsingName(string path, IntPtr bindContext, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
+
+ [ComImport]
+ [Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
+ private class FileOpenDialogObject;
+
+ /// IModalWindow → IFileDialog → IFileOpenDialog, flattened in vtable order.
+ [ComImport]
+ [Guid("D57C7288-D4AD-4768-BE02-9D969532D960")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IFileOpenDialog
+ {
+ [PreserveSig]
+ int Show(IntPtr parent);
+ void SetFileTypes(uint count, IntPtr filterSpec);
+ void SetFileTypeIndex(uint index);
+ void GetFileTypeIndex(out uint index);
+ void Advise(IntPtr events, out uint cookie);
+ void Unadvise(uint cookie);
+ void SetOptions(uint options);
+ void GetOptions(out uint options);
+ void SetDefaultFolder(IShellItem item);
+ void SetFolder(IShellItem item);
+ void GetFolder(out IShellItem item);
+ void GetCurrentSelection(out IShellItem item);
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text);
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
+ void GetResult(out IShellItem item);
+ void AddPlace(IShellItem item, int place);
+ void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension);
+ void Close(int hr);
+ void SetClientGuid(in Guid guid);
+ void ClearClientData();
+ void SetFilter(IntPtr filter);
+ void GetResults(out IntPtr items);
+ void GetSelectedItems(out IntPtr items);
+ }
+
+ [ComImport]
+ [Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellItem
+ {
+ void BindToHandler(IntPtr bindContext, in Guid handler, in Guid riid, out IntPtr result);
+ void GetParent(out IShellItem parent);
+ void GetDisplayName(uint sigdn, [MarshalAs(UnmanagedType.LPWStr)] out string name);
+ void GetAttributes(uint mask, out uint attributes);
+ void Compare(IShellItem other, uint hint, out int order);
+ }
+}
diff --git a/src/Titano.Setup/Interop/NativeMethods.cs b/src/Titano.Setup/Interop/NativeMethods.cs
new file mode 100644
index 00000000..e710bcfb
--- /dev/null
+++ b/src/Titano.Setup/Interop/NativeMethods.cs
@@ -0,0 +1,57 @@
+using System.Runtime.InteropServices;
+
+namespace Titano.Setup.Interop;
+
+/// Win32 entry points used by setup (shell notification, delayed delete, process image path).
+internal static partial class NativeMethods
+{
+ public const int ERROR_CANCELLED = 1223;
+ public const int HRESULT_ERROR_CANCELLED = unchecked((int)0x800704C7);
+
+ private const int SHCNE_ASSOCCHANGED = 0x08000000;
+ private const int SHCNF_IDLIST = 0x0000;
+ private const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
+ private const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
+
+ /// Tells Explorer that file associations changed so icons and "open with" refresh.
+ public static void NotifyAssociationsChanged() => SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
+
+ /// Asks Windows to delete a file or empty folder at the next restart (needs administrator rights).
+ public static bool DeleteAtReboot(string path) => MoveFileExW(path, null, MOVEFILE_DELAY_UNTIL_REBOOT);
+
+ /// Full path of the executable of process , or null when it cannot be queried.
+ public static unsafe string? ProcessImagePath(int processId)
+ {
+ var handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId);
+ if (handle == IntPtr.Zero) return null;
+ try
+ {
+ const int capacity = 1024;
+ var buffer = stackalloc char[capacity];
+ var length = capacity;
+ return QueryFullProcessImageNameW(handle, 0, buffer, ref length) ? new string(buffer, 0, length) : null;
+ }
+ finally
+ {
+ CloseHandle(handle);
+ }
+ }
+
+ [LibraryImport("shell32.dll")]
+ private static partial void SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
+
+ [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool MoveFileExW(string existingFileName, string? newFileName, int flags);
+
+ [LibraryImport("kernel32.dll", SetLastError = true)]
+ private static partial IntPtr OpenProcess(int desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, int processId);
+
+ [LibraryImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static unsafe partial bool QueryFullProcessImageNameW(IntPtr process, int flags, char* exeName, ref int size);
+
+ [LibraryImport("kernel32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static partial bool CloseHandle(IntPtr handle);
+}
diff --git a/src/Titano.Setup/Interop/ShellLink.cs b/src/Titano.Setup/Interop/ShellLink.cs
new file mode 100644
index 00000000..6f033480
--- /dev/null
+++ b/src/Titano.Setup/Interop/ShellLink.cs
@@ -0,0 +1,61 @@
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.ComTypes;
+
+namespace Titano.Setup.Interop;
+
+/// Creates .lnk shortcuts through the shell's IShellLinkW and IPersistFile COM interfaces.
+internal static class ShellLink
+{
+ /// Writes a shortcut at that starts in its own folder.
+ public static void Create(string linkPath, string target, string description)
+ {
+ StaThread.Run(() =>
+ {
+ var link = (IShellLinkW)new ShellLinkObject();
+ try
+ {
+ link.SetPath(target);
+ link.SetWorkingDirectory(Path.GetDirectoryName(target)!);
+ link.SetIconLocation(target, 0);
+ link.SetDescription(description);
+ Directory.CreateDirectory(Path.GetDirectoryName(linkPath)!);
+ ((IPersistFile)link).Save(linkPath, true);
+ }
+ finally
+ {
+ Marshal.FinalReleaseComObject(link);
+ }
+ });
+ }
+
+ [ComImport]
+ [Guid("00021401-0000-0000-C000-000000000046")]
+ private class ShellLinkObject;
+
+ /// Vtable-ordered declaration; only the setters are called, so getters take raw pointers.
+ [ComImport]
+ [Guid("000214F9-0000-0000-C000-000000000046")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellLinkW
+ {
+ void GetPath(IntPtr file, int maxPath, IntPtr findData, uint flags);
+ void GetIDList(out IntPtr idList);
+ void SetIDList(IntPtr idList);
+ void GetDescription(IntPtr name, int maxName);
+ void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string name);
+ void GetWorkingDirectory(IntPtr dir, int maxPath);
+ void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string dir);
+ void GetArguments(IntPtr args, int maxPath);
+ void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string args);
+ void GetHotkey(out short hotkey);
+ void SetHotkey(short hotkey);
+ void GetShowCmd(out int showCmd);
+ void SetShowCmd(int showCmd);
+ void GetIconLocation(IntPtr iconPath, int maxIconPath, out int icon);
+ void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string iconPath, int icon);
+ void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string relativePath, int reserved);
+ void Resolve(IntPtr hwnd, int flags);
+ void SetPath([MarshalAs(UnmanagedType.LPWStr)] string file);
+ }
+}
diff --git a/src/Titano.Setup/Interop/StaThread.cs b/src/Titano.Setup/Interop/StaThread.cs
new file mode 100644
index 00000000..a32a78f7
--- /dev/null
+++ b/src/Titano.Setup/Interop/StaThread.cs
@@ -0,0 +1,33 @@
+using System.Runtime.ExceptionServices;
+using System.Threading;
+
+namespace Titano.Setup.Interop;
+
+/// Runs work on a short-lived single-threaded apartment, as the apartment-threaded shell COM objects expect.
+internal static class StaThread
+{
+ public static void Run(Action action)
+ {
+ if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
+ {
+ action();
+ return;
+ }
+ ExceptionDispatchInfo? failure = null;
+ var thread = new Thread(() =>
+ {
+ try
+ {
+ action();
+ }
+ catch (Exception ex)
+ {
+ failure = ExceptionDispatchInfo.Capture(ex);
+ }
+ });
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ thread.Join();
+ failure?.Throw();
+ }
+}
diff --git a/src/Titano.Setup/Program.cs b/src/Titano.Setup/Program.cs
new file mode 100644
index 00000000..0b8fb35c
--- /dev/null
+++ b/src/Titano.Setup/Program.cs
@@ -0,0 +1,60 @@
+using System.Globalization;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Setup.Cli;
+using Titano.Setup.Engine;
+
+namespace Titano.Setup;
+
+///
+/// Entry point. Silent mode and the uninstaller cleanup helper run without WPF; the interactive window is the
+/// . The return value is the process exit code ().
+///
+internal static class Program
+{
+ [STAThread]
+ public static int Main(string[] args)
+ {
+ using var log = new FileLogSink(SetupPaths.LogDirectory, "setup");
+ Log.SetSink(log);
+ Log.Info("setup", $"Titano.Setup {typeof(Program).Assembly.GetName().Version} {string.Join(' ', args)}");
+
+ SetupArguments arguments;
+ try
+ {
+ arguments = SetupArguments.Parse(args);
+ }
+ catch (ArgumentException ex)
+ {
+ Log.Error("setup", ex.Message);
+ return (int)SetupExitCode.InvalidArguments;
+ }
+ ApplyLanguage(arguments.Language);
+
+ if (arguments.CleanupTarget is { } uninstaller) return (int)SelfCleanup.Run(uninstaller, arguments.WaitProcessId);
+ if (arguments.Silent) return (int)SilentSetup.RunAsync(arguments).GetAwaiter().GetResult();
+
+ return new App(arguments).Run();
+ }
+
+ /// Sets the UI language: the requested code, else the best match for the Windows display language.
+ public static void ApplyLanguage(string? code)
+ {
+ var requested = CultureInfo.CurrentUICulture;
+ if (code is not null)
+ {
+ try
+ {
+ requested = CultureInfo.GetCultureInfo(code);
+ }
+ catch (CultureNotFoundException)
+ {
+ Log.Warning("setup", $"Unknown language '{code}'");
+ }
+ }
+ var culture = Languages.BestMatch(requested);
+ CultureInfo.DefaultThreadCurrentUICulture = culture;
+ CultureInfo.CurrentUICulture = culture;
+ Loc.SetCulture(culture);
+ }
+}
diff --git a/src/Titano.Setup/Titano.Setup.csproj b/src/Titano.Setup/Titano.Setup.csproj
index 4aa167fd..f18d0311 100644
--- a/src/Titano.Setup/Titano.Setup.csproj
+++ b/src/Titano.Setup/Titano.Setup.csproj
@@ -7,6 +7,12 @@
Titano.Setup
app.manifest
titano
+
+ Titano.Setup.Program
+
+
+
+ true
diff --git a/src/Titano.Setup/Views/ComponentOption.cs b/src/Titano.Setup/Views/ComponentOption.cs
new file mode 100644
index 00000000..062ba257
--- /dev/null
+++ b/src/Titano.Setup/Views/ComponentOption.cs
@@ -0,0 +1,49 @@
+using Titano.Core.Localization;
+using Titano.Core.Packaging;
+using Titano.Ui.Mvvm;
+
+namespace Titano.Setup.Views;
+
+/// A component checkbox: localized name and tooltip (falling back to the manifest), size and selection.
+internal sealed class ComponentOption(PayloadComponent component, bool selected, 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;
+
+ public string ToolTip => 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();
+ }
+ }
+}
+
+/// Language offered in the picker.
+internal sealed record LanguageOption(string Code, string Name);
+
+/// Decimal byte sizes as Explorer shows them for drives ("1.5 MB").
+internal static class ByteSize
+{
+ private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"];
+
+ public static string Format(long bytes)
+ {
+ double value = bytes;
+ var unit = 0;
+ while (value >= 1000 && unit < Units.Length - 1)
+ {
+ value /= 1000;
+ unit++;
+ }
+ return value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture) + " " + Units[unit];
+ }
+}
diff --git a/src/Titano.Setup/Views/SetupViewModel.cs b/src/Titano.Setup/Views/SetupViewModel.cs
new file mode 100644
index 00000000..1b6d4aee
--- /dev/null
+++ b/src/Titano.Setup/Views/SetupViewModel.cs
@@ -0,0 +1,514 @@
+using System.Collections;
+using System.ComponentModel;
+using System.IO;
+using System.Windows.Input;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Core.Packaging;
+using Titano.Setup.Cli;
+using Titano.Setup.Engine;
+using Titano.Ui.Mvvm;
+
+namespace Titano.Setup.Views;
+
+/// What the setup screen currently shows.
+internal enum SetupStage
+{
+ Options,
+ Confirm,
+ Working,
+ Done,
+ Failed,
+}
+
+///
+/// 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 .
+///
+internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
+{
+ private const string FallbackProduct = "Titano";
+ 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 SetupStage _stage;
+ private string _directory = string.Empty;
+ private bool _allUsers;
+ private bool _desktop;
+ private bool _startMenu;
+ private bool _launchAfter;
+ private bool _removeUserData;
+ 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? _operation;
+
+ private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed)
+ {
+ _arguments = arguments;
+ _product = product;
+ _version = version;
+ _payload = payload;
+ _installed = installed;
+ 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), 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);
+
+ public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed) =>
+ new(arguments, installed.Log.Product, installed.Log.Version, null, installed) { Directory = installed.Directory };
+
+ /// A screen that can only report why setup cannot run (no payload, nothing installed…).
+ 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;
+ }
+
+ /// Raised when setup is finished and the window should close; holds the outcome.
+ public event EventHandler? Finished;
+
+ /// Raised with false to hide the window while an elevated copy works, true to show it again.
+ public event EventHandler? VisibilityRequested;
+
+ public event EventHandler? ErrorsChanged;
+
+ /// Shows the folder picker; provided by the view, which owns the window handle.
+ public Func? PickFolder { get; set; }
+
+ /// Window handle that owns the administrator prompt.
+ 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 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 Components { get; }
+
+ private List 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)));
+
+ /// False when upgrading: the existing folder and scope are kept.
+ 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();
+ }
+ }
+
+ public bool IsJustMe
+ {
+ get => !_allUsers;
+ set => IsAllUsers = !value;
+ }
+
+ public string Directory
+ {
+ get => _directory;
+ set
+ {
+ if (!Set(ref _directory, value ?? string.Empty)) return;
+ ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory)));
+ OnPropertyChanged(nameof(DirectoryToolTip));
+ }
+ }
+
+ private bool IsDirectoryValid => SetupPaths.IsUsableInstallDirectory(_directory);
+
+ public string DirectoryToolTip => !CanChangeLocation
+ ? Loc.L("Tooltips.Setup.Locked")
+ : IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : Loc.L("Tooltips.Setup.FolderInvalid");
+
+ 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");
+
+ 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");
+ 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)));
+
+ // ---- Uninstall options ----
+
+ public bool RemoveUserData
+ {
+ get => _removeUserData;
+ set => Set(ref _removeUserData, value);
+ }
+
+ // ---- 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);
+
+ 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[] { Loc.L("Tooltips.Setup.FolderInvalid") } : Array.Empty();
+
+ /// Called once the window is visible: an elevated copy continues the install the user already started.
+ public void OnShown()
+ {
+ if (_arguments.Elevated && IsInstall && CanStart) Start(InstallAsync);
+ }
+
+ public override void Dispose()
+ {
+ foreach (var c in Components) c.Dispose();
+ _payload?.Dispose();
+ base.Dispose();
+ }
+
+ private void Start(Func operation)
+ {
+ _operation = operation;
+ _ = operation();
+ }
+
+ private async Task InstallAsync()
+ {
+ var engine = _engine!;
+ 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, launch);
+ return;
+ }
+ if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory))) return;
+
+ BeginWork(indeterminate: false);
+ var progress = new Progress(ReportProgress);
+ await Task.Run(() => engine.Install(request, progress, CancellationToken.None));
+ _launchProgram = program;
+ Complete();
+ if (launch is not null) Launch();
+ }
+ catch (Exception ex)
+ {
+ Fail(ex);
+ }
+ }
+
+ /// All users without administrator rights: an elevated copy installs with the chosen options.
+ private async Task InstallElevatedAsync(InstallRequest request, string? launch)
+ {
+ 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 = launch is not null,
+ 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, launch));
+ }
+
+ private async Task UninstallAsync()
+ {
+ var installed = _installed!;
+ try
+ {
+ if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files)) return;
+ BeginWork(indeterminate: false);
+ var progress = new Progress(ReportProgress);
+ var removeData = _removeUserData;
+ await Task.Run(() => UninstallEngine.Uninstall(installed, removeData, progress));
+ Complete();
+ }
+ catch (Exception ex)
+ {
+ Fail(ex);
+ }
+ }
+
+ ///
+ /// True when no installed program runs from . Otherwise the first call asks the user
+ /// (Confirm stage); after "Close programs" the programs are asked to close and the operation continues.
+ ///
+ private async Task EnsureProgramsClosedAsync(string directory, IEnumerable programs)
+ {
+ var running = RunningPrograms.Find(directory, programs);
+ try
+ {
+ if (running.Count == 0) return true;
+ _runningPrograms = RunningPrograms.Describe(running);
+ if (!_closeConfirmed)
+ {
+ Stage = SetupStage.Confirm;
+ return false;
+ }
+ _closeConfirmed = false;
+ BeginWork(indeterminate: true);
+ var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout);
+ if (still.Count == 0) return true;
+ _runningPrograms = RunningPrograms.Describe(still);
+ throw new SetupException(SetupExitCode.ProgramRunning, $"Still running: {_runningPrograms}");
+ }
+ finally
+ {
+ foreach (var p in running) p.Dispose();
+ }
+ }
+
+ private void Browse()
+ {
+ if (PickFolder?.Invoke(_directory) is not { } folder) return;
+ // Choosing a parent such as D:\Apps installs into D:\Apps\, 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 void OnComponentsChanged()
+ {
+ OnPropertyChanged(nameof(RequiredSpaceText));
+ OnPropertyChanged(nameof(HasDesktopOption));
+ OnPropertyChanged(nameof(HasStartMenuOption));
+ OnPropertyChanged(nameof(HasLaunchOption));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private IEnumerable 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);
+}
diff --git a/src/Titano.Setup/Views/SetupWindow.xaml b/src/Titano.Setup/Views/SetupWindow.xaml
new file mode 100644
index 00000000..9b4495b6
--- /dev/null
+++ b/src/Titano.Setup/Views/SetupWindow.xaml
@@ -0,0 +1,152 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.Setup/Views/SetupWindow.xaml.cs b/src/Titano.Setup/Views/SetupWindow.xaml.cs
new file mode 100644
index 00000000..680ad6ad
--- /dev/null
+++ b/src/Titano.Setup/Views/SetupWindow.xaml.cs
@@ -0,0 +1,45 @@
+using System.ComponentModel;
+using System.Windows;
+using System.Windows.Interop;
+using Titano.Core.Localization;
+using Titano.Setup.Interop;
+using Titano.Ui.Controls;
+
+namespace Titano.Setup.Views;
+
+/// The one setup screen (~720×520, dialog chrome). Closing is blocked while files are being written.
+internal sealed partial class SetupWindow : TitanoWindow
+{
+ private readonly SetupViewModel _model;
+
+ public SetupWindow(SetupViewModel model)
+ {
+ _model = model;
+ DataContext = model;
+ InitializeComponent();
+ ApplyFlowDirection();
+ Loc.CultureChanged += OnCultureChanged;
+ 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;
+ SourceInitialized += (_, _) => model.WindowHandle = new WindowInteropHelper(this).Handle;
+ 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);
+ }
+
+ protected override void OnClosed(EventArgs e)
+ {
+ Loc.CultureChanged -= OnCultureChanged;
+ base.OnClosed(e);
+ }
+
+ private void OnCultureChanged(object? sender, EventArgs e) => ApplyFlowDirection();
+
+ private void ApplyFlowDirection() => FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
+}