feat(setup): add one-screen installer, uninstaller and silent mode
Titano.Setup reads the TPK1 payload from its own executable and installs per user (%LOCALAPPDATA%\Programs) or for all users (Program Files, relaunched elevated through ShellExecuteEx "runas"). Extraction is hash-verified into a staging folder and committed with rollback; upgrades replace files in place, remove obsolete ones and never touch %LOCALAPPDATA%\Titano. - Components, scope, folder (IFileOpenDialog picker), desktop and Start menu shortcuts (IShellLinkW), start-after-install, language picker - Add/Remove Programs entry, .titano file type, install log - /uninstall [/S] removes only logged files, shortcuts and registry entries; user data only when "Remove my data" is ticked; the uninstaller deletes itself through a temporary helper copy - Silent switches /S /DIR= /COMPONENTS= /ALLUSERS /NODESKTOP /NOSTARTMENU /LAUNCH /LANG= with documented exit codes; running programs are asked to close, never killed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
25 files changed
+2183
-11
No files matched your search
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interactive setup: opens the payload (or, for <c>/uninstall</c>, the installation), elevates an all-users
|
||||
/// uninstall up front, and shows the setup window. The exit code is the view model's outcome.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The uninstall window, or null when this process handed over to an elevated copy and is shutting down.</summary>
|
||||
private async Task<SetupViewModel?> 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);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
<Application x:Class="Titano.Setup.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
</Application>
|
||||
@@ -1,7 +0,0 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace Titano.Setup;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Setup.Cli;
|
||||
|
||||
/// <summary>
|
||||
/// Command-line switches, case-insensitive, with <c>/</c> or <c>-</c>:
|
||||
/// <c>/S</c> silent · <c>/DIR=path</c> · <c>/COMPONENTS=Titano,Uploader</c> · <c>/ALLUSERS</c> · <c>/NODESKTOP</c> ·
|
||||
/// <c>/NOSTARTMENU</c> · <c>/LAUNCH</c> · <c>/LANG=it</c> · <c>/uninstall</c>.
|
||||
/// Internal: <c>/ELEVATED</c> (relaunched for administrator rights), <c>/CLEANUP=path /WAITPID=n</c> (removes the
|
||||
/// uninstaller after the uninstall process exits).
|
||||
/// </summary>
|
||||
internal sealed record SetupArguments
|
||||
{
|
||||
public bool Silent { get; init; }
|
||||
public bool Uninstall { get; init; }
|
||||
public string? Directory { get; init; }
|
||||
public IReadOnlyList<string>? 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; }
|
||||
|
||||
/// <summary>Parses <paramref name="args"/>; throws <see cref="ArgumentException"/> for unknown or malformed switches.</summary>
|
||||
public static SetupArguments Parse(IEnumerable<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>The switches that reproduce these arguments, for relaunching with administrator rights.</summary>
|
||||
public IEnumerable<string> 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";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Joins arguments into one command line that <c>CommandLineToArgvW</c> splits back into the same strings
|
||||
/// (quotes around spaces, backslashes doubled before a quote).
|
||||
/// </summary>
|
||||
public static string JoinCommandLine(IEnumerable<string> 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace Titano.Setup.Cli;
|
||||
|
||||
/// <summary>Process exit codes of Titano.Setup (stable contract for silent deployments).</summary>
|
||||
internal enum SetupExitCode
|
||||
{
|
||||
Success = 0,
|
||||
|
||||
/// <summary>Installation or removal did not complete; the setup log in %TEMP%\Titano Setup has details.</summary>
|
||||
Failed = 1,
|
||||
|
||||
InvalidArguments = 2,
|
||||
|
||||
/// <summary>The installer carries no payload or the payload is damaged.</summary>
|
||||
PayloadInvalid = 3,
|
||||
|
||||
/// <summary>All-users operation and the administrator prompt was declined.</summary>
|
||||
ElevationDeclined = 4,
|
||||
|
||||
/// <summary>An installed program did not close when asked to.</summary>
|
||||
ProgramRunning = 5,
|
||||
|
||||
/// <summary><c>/uninstall</c> found no installation.</summary>
|
||||
NotInstalled = 6,
|
||||
|
||||
DiskFull = 7,
|
||||
|
||||
/// <summary>The window was closed before anything changed.</summary>
|
||||
Cancelled = 8,
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Success"/>.
|
||||
/// </summary>
|
||||
LaunchRequested = 100,
|
||||
}
|
||||
|
||||
/// <summary>A setup failure that maps to a specific exit code and message.</summary>
|
||||
internal sealed class SetupException(SetupExitCode code, string message) : Exception(message)
|
||||
{
|
||||
public SetupExitCode Code { get; } = code;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Administrator rights for all-users operations. Setup runs <c>asInvoker</c> and, only when needed, starts itself
|
||||
/// again through ShellExecuteEx with the <c>runas</c> verb (the UAC prompt) and the same switches plus <c>/ELEVATED</c>.
|
||||
/// </summary>
|
||||
internal static class Elevation
|
||||
{
|
||||
public static bool IsElevated
|
||||
{
|
||||
get
|
||||
{
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
return new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs this program elevated with <paramref name="arguments"/> and waits for it; see <see cref="WaitAsync"/>.
|
||||
/// Returns <see cref="SetupExitCode.ElevationDeclined"/> when the prompt was refused.
|
||||
/// </summary>
|
||||
public static async Task<SetupExitCode> RunElevatedAsync(SetupArguments arguments, string? launchProgram) =>
|
||||
Start(arguments, IntPtr.Zero) is { } child ? await WaitAsync(child, launchProgram).ConfigureAwait(false) : SetupExitCode.ElevationDeclined;
|
||||
|
||||
/// <summary>Starts this program elevated (UAC prompt owned by <paramref name="owner"/>); null when the user declines.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the elevated copy and returns its exit code; when it asks for it, starts
|
||||
/// <paramref name="launchProgram"/> from this unelevated process so the program does not run as administrator.
|
||||
/// </summary>
|
||||
public static async Task<SetupExitCode> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Starts an installed program the way Explorer does.</summary>
|
||||
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)!,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>What to install, where and with which shortcuts.</summary>
|
||||
internal sealed record InstallRequest(string Directory, InstallScope Scope, IReadOnlyList<string> Components, bool DesktopShortcuts, bool StartMenuShortcuts);
|
||||
|
||||
/// <summary>Overall progress (0–1) and the file being written.</summary>
|
||||
internal readonly record struct SetupProgress(double Fraction, string CurrentFile);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class InstallEngine(PayloadReader payload)
|
||||
{
|
||||
private const double ExtractShare = 0.9;
|
||||
|
||||
public PayloadManifest Manifest => payload.Manifest;
|
||||
|
||||
/// <summary>Bytes the selected components occupy once installed, uninstaller included.</summary>
|
||||
public long RequiredBytes(IEnumerable<string> components) => Manifest.FilesFor(components).Sum(f => f.Size) + payload.PayloadOffset;
|
||||
|
||||
/// <summary>Payload path of the program to start after installing: the first shortcut target among the components.</summary>
|
||||
public string? LaunchTarget(IEnumerable<string> components)
|
||||
{
|
||||
var selected = new HashSet<string>(components, StringComparer.OrdinalIgnoreCase);
|
||||
return Manifest.Shortcuts.FirstOrDefault(s => selected.Contains(s.Component))?.Target;
|
||||
}
|
||||
|
||||
public InstallLog Install(InstallRequest request, IProgress<SetupProgress>? 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<AssemblyCompanyAttribute>()?.Company ?? "Titano";
|
||||
|
||||
private static string? AboutUrl =>
|
||||
typeof(InstallEngine).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>().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<string>(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<PayloadAssociation> PlanFileTypes(InstallRequest request)
|
||||
{
|
||||
var selected = new HashSet<string>(request.Components, StringComparer.OrdinalIgnoreCase);
|
||||
return Manifest.Associations.Where(a => selected.Contains(a.Component)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>Removes what the previous version installed and this one no longer does (files, shortcuts, file types).</summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>Maps extraction progress onto a slice of the overall bar.</summary>
|
||||
private sealed class MappedProgress(IProgress<SetupProgress> target, double from, double to) : IProgress<PayloadProgress>
|
||||
{
|
||||
public void Report(PayloadProgress value) =>
|
||||
target.Report(new SetupProgress(from + (to - from) * (value.Total == 0 ? 1 : (double)value.Done / value.Total), value.CurrentPath));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Core.IO;
|
||||
|
||||
namespace Titano.Setup.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Record of one installation, kept as <c>install-log.json</c> 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.
|
||||
/// </summary>
|
||||
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<string> Components { get; set; } = [];
|
||||
|
||||
/// <summary>Installed payload paths, relative to the install folder (the uninstaller and this log excluded).</summary>
|
||||
public List<string> Files { get; set; } = [];
|
||||
|
||||
/// <summary>Full paths of the shortcuts setup created.</summary>
|
||||
public List<string> Shortcuts { get; set; } = [];
|
||||
public List<InstalledAssociation> Associations { get; set; } = [];
|
||||
|
||||
[JsonIgnore]
|
||||
public string ProductKey => SetupPaths.ProductKey(Product);
|
||||
|
||||
[JsonIgnore]
|
||||
public string UninstallerName => SetupPaths.UninstallerName(Product);
|
||||
|
||||
/// <summary>The log in <paramref name="directory"/>, or null when there is none or it is unreadable.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>A file type registered by setup.</summary>
|
||||
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;
|
||||
@@ -0,0 +1,37 @@
|
||||
using Titano.Core.Packaging;
|
||||
using Titano.Setup.Cli;
|
||||
|
||||
namespace Titano.Setup.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList<string> 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<string> 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<PayloadComponent>().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);
|
||||
}
|
||||
|
||||
/// <summary>Executables to look for among running processes: the new payload's and the previous install's.</summary>
|
||||
public static IEnumerable<string> Programs(PayloadManifest manifest, string directory) =>
|
||||
manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using Titano.Setup.Interop;
|
||||
|
||||
namespace Titano.Setup.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class RunningPrograms
|
||||
{
|
||||
/// <summary>Processes of <paramref name="executables"/> (payload paths) started from inside <paramref name="directory"/>.</summary>
|
||||
public static IReadOnlyList<Process> Find(string directory, IEnumerable<string> 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<Process>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Display names ("Titano", "Titano.Uploader") of the given processes, for the prompt.</summary>
|
||||
public static string Describe(IReadOnlyList<Process> processes) =>
|
||||
string.Join(", ", processes.Select(p => p.ProcessName).Distinct(StringComparer.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Asks each process to close and waits up to <paramref name="timeout"/>; returns those still running.</summary>
|
||||
public static async Task<IReadOnlyList<Process>> CloseAsync(IReadOnlyList<Process> 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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Removes the uninstaller, which cannot delete its own running executable. It copies itself to a fresh folder in
|
||||
/// %TEMP% and starts the copy with <c>/CLEANUP=<uninstaller> /WAITPID=<its id></c>; 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.
|
||||
/// </summary>
|
||||
internal static class SelfCleanup
|
||||
{
|
||||
private const string Prefix = "Uninstall ";
|
||||
|
||||
/// <summary>Starts the helper that deletes <paramref name="uninstallerPath"/> once this process has exited.</summary>
|
||||
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}'");
|
||||
}
|
||||
|
||||
/// <summary>The helper side: waits for <paramref name="processId"/>, then removes the uninstaller and its empty folder.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.IO;
|
||||
using Titano.Core.Packaging;
|
||||
|
||||
namespace Titano.Setup.Engine;
|
||||
|
||||
/// <summary>Per-user (no administrator rights) or machine-wide installation.</summary>
|
||||
internal enum InstallScope
|
||||
{
|
||||
CurrentUser,
|
||||
AllUsers,
|
||||
}
|
||||
|
||||
/// <summary>Folders and names that depend on the product and the install scope.</summary>
|
||||
internal static class SetupPaths
|
||||
{
|
||||
private static string LocalAppData => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
|
||||
/// <summary><c>%LOCALAPPDATA%\Programs\<product></c> for the current user, <c>Program Files\<product></c> for all users.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// <c>%LOCALAPPDATA%\Titano</c>: database, settings, logs and caches of the desktop programs. Installing and
|
||||
/// upgrading never touch it; uninstall removes it only when the user asks.
|
||||
/// </summary>
|
||||
public static string UserData => Path.Combine(LocalAppData, "Titano");
|
||||
|
||||
/// <summary>Setup's own log files (<c>%TEMP%\Titano Setup</c>), outside the user data folder.</summary>
|
||||
public static string LogDirectory => Path.Combine(Path.GetTempPath(), "Titano Setup");
|
||||
|
||||
/// <summary>Registry key name under <c>…\CurrentVersion\Uninstall</c>: the product name without spaces or symbols.</summary>
|
||||
public static string ProductKey(string product) => string.Concat(product.Where(char.IsAsciiLetterOrDigit));
|
||||
|
||||
public static string UninstallerName(string product) => $"Uninstall {product}.exe";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="path"/> is <paramref name="folder"/> or lies inside it (case-insensitive).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace Titano.Setup.Engine;
|
||||
|
||||
/// <summary>An installation found in Add/Remove Programs.</summary>
|
||||
internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version);
|
||||
|
||||
/// <summary>Values written to the Add/Remove Programs entry.</summary>
|
||||
internal sealed record UninstallEntry(string DisplayName, string Version, string Publisher, string Directory, string UninstallerPath, string DisplayIcon, long EstimatedBytes, string? AboutUrl);
|
||||
|
||||
/// <summary>
|
||||
/// Registry state owned by setup: the Add/Remove Programs entry under
|
||||
/// <c>Software\Microsoft\Windows\CurrentVersion\Uninstall\<key></c> and file types under <c>Software\Classes</c>,
|
||||
/// in HKCU for per-user installs and HKLM for all-users installs.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>The installation registered under <paramref name="productKey"/> whose folder still exists, current user first.</summary>
|
||||
public static ExistingInstall? FindInstall(string productKey)
|
||||
{
|
||||
foreach (var scope in (ReadOnlySpan<InstallScope>)[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);
|
||||
|
||||
/// <summary>Registers <paramref name="extension"/> to open with <c>"program" "%1"</c> under <paramref name="progId"/>.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Removes the ProgID and detaches the extension, leaving other programs' registrations intact.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Guards registry paths built from a log file: an extension and a dotted ProgID, nothing else.</summary>
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.IO;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Packaging;
|
||||
using Titano.Setup.Cli;
|
||||
|
||||
namespace Titano.Setup.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/S</c>: 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 <see cref="SetupExitCode.ProgramRunning"/>.
|
||||
/// Silent uninstall never removes user data.
|
||||
/// </summary>
|
||||
internal static class SilentSetup
|
||||
{
|
||||
public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(20);
|
||||
|
||||
public static async Task<SetupExitCode> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Exit code for a failure.</summary>
|
||||
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<SetupExitCode> 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<SetupExitCode> 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;
|
||||
}
|
||||
|
||||
/// <summary>The product named by this program's payload, when it has one (a full installer run with /uninstall).</summary>
|
||||
public static string? PayloadProduct()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var payload = PayloadReader.OpenCurrentProcess();
|
||||
return payload.Manifest.Product;
|
||||
}
|
||||
catch (PayloadException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> CloseProgramsAsync(string directory, IEnumerable<string> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>An installation found on disk: its folder and log.</summary>
|
||||
internal sealed record InstalledProduct(string Directory, InstallLog Log);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>removeUserData</c> is set by an explicit choice in the window.
|
||||
/// </summary>
|
||||
internal static class UninstallEngine
|
||||
{
|
||||
/// <summary>The installation to remove: <c>/DIR</c>, the uninstaller's own folder, or the registered location.</summary>
|
||||
public static InstalledProduct? Locate(string? directory, string? productFromPayload)
|
||||
{
|
||||
var candidates = new List<string?> { 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<SetupProgress>? 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));
|
||||
}
|
||||
|
||||
/// <summary>Deletes a shortcut recorded in a log, but only a <c>.lnk</c> directly in the Start menu or desktop folder.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Setup.Interop;
|
||||
|
||||
/// <summary>The Windows folder picker: <c>IFileOpenDialog</c> with <c>FOS_PICKFOLDERS</c> (no WinForms).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Shows the picker owned by <paramref name="owner"/>; returns the chosen folder or null when cancelled.</summary>
|
||||
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;
|
||||
|
||||
/// <summary><c>IModalWindow</c> → <c>IFileDialog</c> → <c>IFileOpenDialog</c>, flattened in vtable order.</summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Setup.Interop;
|
||||
|
||||
/// <summary>Win32 entry points used by setup (shell notification, delayed delete, process image path).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Tells Explorer that file associations changed so icons and "open with" refresh.</summary>
|
||||
public static void NotifyAssociationsChanged() => SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
|
||||
|
||||
/// <summary>Asks Windows to delete a file or empty folder at the next restart (needs administrator rights).</summary>
|
||||
public static bool DeleteAtReboot(string path) => MoveFileExW(path, null, MOVEFILE_DELAY_UNTIL_REBOOT);
|
||||
|
||||
/// <summary>Full path of the executable of process <paramref name="processId"/>, or null when it cannot be queried.</summary>
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.InteropServices.ComTypes;
|
||||
|
||||
namespace Titano.Setup.Interop;
|
||||
|
||||
/// <summary>Creates <c>.lnk</c> shortcuts through the shell's <c>IShellLinkW</c> and <c>IPersistFile</c> COM interfaces.</summary>
|
||||
internal static class ShellLink
|
||||
{
|
||||
/// <summary>Writes a shortcut at <paramref name="linkPath"/> that starts <paramref name="target"/> in its own folder.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Vtable-ordered declaration; only the setters are called, so getters take raw pointers.</summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace Titano.Setup.Interop;
|
||||
|
||||
/// <summary>Runs work on a short-lived single-threaded apartment, as the apartment-threaded shell COM objects expect.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Entry point. Silent mode and the uninstaller cleanup helper run without WPF; the interactive window is the
|
||||
/// <see cref="App"/>. The return value is the process exit code (<see cref="SetupExitCode"/>).
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Sets the UI language: the requested code, else the best match for the Windows display language.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,12 @@
|
||||
<AssemblyName>Titano.Setup</AssemblyName>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<TitanoIconVariant>titano</TitanoIconVariant>
|
||||
<!-- Program.Main is the entry point (exit codes, silent mode without WPF); there is no App.xaml. -->
|
||||
<StartupObject>Titano.Setup.Program</StartupObject>
|
||||
</PropertyGroup>
|
||||
<!-- The setup program is the stub of every installer and the uninstaller copy: keep it small. -->
|
||||
<PropertyGroup Condition="'$(PublishSingleFile)' == 'true' and '$(SelfContained)' == 'true'">
|
||||
<EnableCompressionInSingleFileBundle>true</EnableCompressionInSingleFileBundle>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Titano.Core\Titano.Core.csproj" />
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Packaging;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.Setup.Views;
|
||||
|
||||
/// <summary>A component checkbox: localized name and tooltip (falling back to the manifest), size and selection.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Language offered in the picker.</summary>
|
||||
internal sealed record LanguageOption(string Code, string Name);
|
||||
|
||||
/// <summary>Decimal byte sizes as Explorer shows them for drives ("1.5 MB").</summary>
|
||||
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];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <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 = "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<Task>? _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 };
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
|
||||
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<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);
|
||||
}
|
||||
|
||||
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!;
|
||||
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<SetupProgress>(ReportProgress);
|
||||
await Task.Run(() => engine.Install(request, progress, CancellationToken.None));
|
||||
_launchProgram = program;
|
||||
Complete();
|
||||
if (launch is not null) Launch();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>All users without administrator rights: an elevated copy installs with the chosen options.</summary>
|
||||
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<SetupProgress>(ReportProgress);
|
||||
var removeData = _removeUserData;
|
||||
await Task.Run(() => UninstallEngine.Uninstall(installed, removeData, progress));
|
||||
Complete();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when no installed program runs from <paramref name="directory"/>. Otherwise the first call asks the user
|
||||
/// (Confirm stage); after "Close programs" the programs are asked to close and the operation continues.
|
||||
/// </summary>
|
||||
private async Task<bool> EnsureProgramsClosedAsync(string directory, IEnumerable<string> 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\<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 void OnComponentsChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(RequiredSpaceText));
|
||||
OnPropertyChanged(nameof(HasDesktopOption));
|
||||
OnPropertyChanged(nameof(HasStartMenuOption));
|
||||
OnPropertyChanged(nameof(HasLaunchOption));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<ui:TitanoWindow x:Class="Titano.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:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
Style="{StaticResource {x:Type ui:TitanoWindow}}"
|
||||
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" />
|
||||
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" ToolTip="{Binding ToolTip}" />
|
||||
</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 GroupName="Scope" Content="{l:Loc Setup.Scope.JustMe}" IsChecked="{Binding IsJustMe}" IsEnabled="{Binding CanChangeLocation}"
|
||||
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding JustMeToolTip}" Margin="0,0,20,0" />
|
||||
<RadioButton GroupName="Scope" Content="{l:Loc Setup.Scope.AllUsers}" IsChecked="{Binding IsAllUsers}" IsEnabled="{Binding CanChangeLocation}"
|
||||
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding AllUsersToolTip}" />
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Grid.Row="2" Text="{l:Loc Setup.Field.Folder}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
|
||||
<DockPanel Grid.Row="2" Grid.Column="1" VerticalAlignment="Center">
|
||||
<Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{l:Loc Setup.Folder.Browse}" Command="{Binding BrowseCommand}"
|
||||
ToolTipService.ShowOnDisabled="True" ToolTip="{l:Loc Tooltips.Setup.Browse}" />
|
||||
<TextBox Text="{Binding Directory, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding CanChangeLocation}"
|
||||
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding DirectoryToolTip}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
|
||||
</DockPanel>
|
||||
|
||||
<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 -->
|
||||
<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" />
|
||||
</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}"
|
||||
ToolTip="{l:Loc Tooltips.Setup.Installed}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
|
||||
<CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}"
|
||||
Foreground="{DynamicResource Brush.Warning}" ToolTip="{l:Loc Tooltips.Setup.RemoveData}" />
|
||||
</Grid>
|
||||
|
||||
<!-- Programs still running -->
|
||||
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}">
|
||||
<ui:Icon Glyph="{StaticResource Icon.Warning}" Size="20" Foreground="{DynamicResource Brush.Warning}" Margin="0,0,12,0" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding ConfirmText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- Progress -->
|
||||
<StackPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{Binding WorkingText}" Style="{StaticResource Text.Title}" Margin="0,0,0,14" />
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding ProgressText}" Style="{StaticResource Text.Secondary}" MinWidth="40" TextAlignment="Right" Margin="12,0,0,0" VerticalAlignment="Center" />
|
||||
<ProgressBar Minimum="0" Maximum="1" Value="{Binding Progress, Mode=OneWay}" IsIndeterminate="{Binding IsIndeterminate}" VerticalAlignment="Center" />
|
||||
</DockPanel>
|
||||
<TextBlock Text="{Binding ProgressFile}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" Margin="0,8,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Success -->
|
||||
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsDone, Converter={StaticResource BoolToVisibility}}">
|
||||
<ui:Icon Glyph="{StaticResource Icon.SuccessCircle}" Size="20" Foreground="{DynamicResource Brush.Success}" Margin="0,0,12,0" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding DoneText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- Failure -->
|
||||
<DockPanel Grid.Row="1" VerticalAlignment="Center" Visibility="{Binding IsFailed, Converter={StaticResource BoolToVisibility}}">
|
||||
<ui:Icon Glyph="{StaticResource Icon.ErrorCircle}" Size="20" Foreground="{DynamicResource Brush.Error}" Margin="0,0,12,0" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding ErrorText}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" VerticalAlignment="Center" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- Footer: space needed and at most two actions per state -->
|
||||
<DockPanel Grid.Row="2" LastChildFill="False" Margin="0,16,0,0">
|
||||
<TextBlock DockPanel.Dock="Left" Text="{Binding RequiredSpaceText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center"
|
||||
Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
|
||||
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
|
||||
<Button Style="{StaticResource Button.Primary}" MinWidth="104" Content="{Binding InstallText}" Command="{Binding PrimaryCommand}" ToolTip="{Binding InstallToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" IsDefault="True" Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Destructive}" MinWidth="104" Content="{l:Loc Setup.Action.Uninstall}" Command="{Binding PrimaryCommand}" ToolTip="{l:Loc Tooltips.Setup.Uninstall}"
|
||||
Visibility="{Binding IsUninstallOptions, Converter={StaticResource BoolToVisibility}}" />
|
||||
|
||||
<Button Content="{l:Loc Setup.Action.Cancel}" Command="{Binding BackCommand}" ToolTip="{l:Loc Tooltips.Setup.Back}" IsCancel="True" Margin="0,0,8,0"
|
||||
Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Setup.Action.ClosePrograms}" Command="{Binding CloseProgramsCommand}" ToolTip="{l:Loc Tooltips.Setup.ClosePrograms}"
|
||||
Visibility="{Binding IsConfirm, Converter={StaticResource BoolToVisibility}}" />
|
||||
|
||||
<Button Content="{l:Loc Setup.Action.Close}" MinWidth="88" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Close}"
|
||||
Visibility="{Binding IsDone, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Primary}" MinWidth="88" Content="{l:Loc Setup.Action.Launch}" Command="{Binding LaunchCommand}" ToolTip="{l:Loc Tooltips.Setup.LaunchNow}" Margin="8,0,0,0"
|
||||
Visibility="{Binding CanLaunch, Converter={StaticResource BoolToVisibility}}" />
|
||||
|
||||
<Button Content="{l:Loc Setup.Action.Close}" MinWidth="88" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Setup.Close}"
|
||||
Visibility="{Binding IsFailed, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Primary}" MinWidth="88" Content="{l:Loc Setup.Action.Retry}" Command="{Binding RetryCommand}" ToolTip="{l:Loc Tooltips.Setup.Retry}" Margin="8,0,0,0"
|
||||
Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</Grid>
|
||||
</ui:TitanoWindow>
|
||||
@@ -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;
|
||||
|
||||
/// <summary>The one setup screen (~720×520, dialog chrome). Closing is blocked while files are being written.</summary>
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user