Files
Chronos/src/Titano.Setup/Engine/InstallEngine.cs
T
Claude c97b4fb82c 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
2026-10-02 10:16:20 +00:00

150 lines
8.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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));
}
}