using System.IO;
using System.Reflection;
using Titano.Core.Diagnostics;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Interop;
namespace Titano.Setup.Engine;
/// What to install, where and with which shortcuts.
internal sealed record InstallRequest(string Directory, InstallScope Scope, IReadOnlyList Components, bool DesktopShortcuts, bool StartMenuShortcuts);
/// Overall progress (0–1) and the file being written.
internal readonly record struct SetupProgress(double Fraction, string CurrentFile);
///
/// Installs or upgrades in place from the payload: verified extraction into staging, an all-or-nothing move into
/// the folder, removal of files the previous version shipped and this one does not, then shortcuts, file types and
/// the Add/Remove Programs entry. The user data folder is never touched.
///
internal sealed class InstallEngine(PayloadReader payload)
{
private const double ExtractShare = 0.9;
public PayloadManifest Manifest => payload.Manifest;
/// Bytes the selected components occupy once installed, uninstaller included.
public long RequiredBytes(IEnumerable components) => Manifest.FilesFor(components).Sum(f => f.Size) + payload.PayloadOffset;
/// Payload path of the program to start after installing: the first shortcut target among the components.
public string? LaunchTarget(IEnumerable components)
{
var selected = new HashSet(components, StringComparer.OrdinalIgnoreCase);
return Manifest.Shortcuts.FirstOrDefault(s => selected.Contains(s.Component))?.Target;
}
public InstallLog Install(InstallRequest request, IProgress? progress, CancellationToken cancellationToken)
{
var directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(request.Directory));
var product = Manifest.Product;
var uninstaller = SetupPaths.UninstallerName(product);
var files = Manifest.FilesFor(request.Components);
if (files.Any(f => PayloadPath.Comparer.Equals(f.Path, uninstaller) || PayloadPath.Comparer.Equals(f.Path, InstallLog.FileName)))
throw new PayloadException(PayloadError.Corrupt, "The payload overwrites setup's own files.");
EnsureFreeSpace(directory, RequiredBytes(request.Components));
var previous = InstallLog.TryLoad(directory);
Log.Info("setup", $"Installing {product} {Manifest.Version} ({string.Join(",", request.Components)}) to '{directory}' for {request.Scope}");
using (var transaction = new InstallTransaction(directory))
{
var extractProgress = progress is null ? null : new MappedProgress(progress, 0, ExtractShare);
payload.Extract(files, transaction.StagingDirectory, extractProgress, cancellationToken);
payload.WriteStub(Path.Combine(transaction.StagingDirectory, uninstaller));
cancellationToken.ThrowIfCancellationRequested();
transaction.Commit([.. files.Select(f => f.Path), uninstaller]);
}
progress?.Report(new SetupProgress(ExtractShare, string.Empty));
var shortcuts = PlanShortcuts(request, directory);
var fileTypes = PlanFileTypes(request);
var log = new InstallLog
{
Product = product,
Version = Manifest.Version,
Scope = request.Scope,
Components = [.. request.Components],
Files = [.. files.Select(f => f.Path)],
Shortcuts = [.. shortcuts.Select(s => s.Link)],
Associations = [.. fileTypes.Select(a => new InstalledAssociation(a.Extension, a.ProgId))],
};
if (previous is not null) RemoveLeftovers(directory, previous, log);
// Saved before registration so that an uninstall can always undo whatever follows.
log.Save(directory);
foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name);
foreach (var a in fileTypes)
SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, a.Description, PayloadPath.Resolve(directory, a.Target));
if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged();
var uninstallerPath = Path.Combine(directory, uninstaller);
var icon = LaunchTarget(request.Components) is { } main ? PayloadPath.Resolve(directory, main) : uninstallerPath;
SetupRegistry.WriteUninstallEntry(request.Scope, SetupPaths.ProductKey(product), new UninstallEntry(
product, Manifest.Version, Publisher, directory, uninstallerPath, icon, RequiredBytes(request.Components), AboutUrl));
progress?.Report(new SetupProgress(1, string.Empty));
Log.Info("setup", $"Installed {files.Count} files");
return log;
}
private static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute()?.Company ?? "Titano";
private static string? AboutUrl =>
typeof(InstallEngine).Assembly.GetCustomAttributes().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo
? "https://github.com/" + repo
: null;
private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory)
{
var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase);
var result = new List<(string, string, string)>();
foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component)))
{
var target = PayloadPath.Resolve(directory, s.Target);
if (s.StartMenu && request.StartMenuShortcuts) result.Add((Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name));
if (s.Desktop && request.DesktopShortcuts) result.Add((Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name));
}
return result;
}
private List PlanFileTypes(InstallRequest request)
{
var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase);
return Manifest.Associations.Where(a => selected.Contains(a.Component)).ToList();
}
/// Removes what the previous version installed and this one no longer does (files, shortcuts, file types).
private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current)
{
var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList();
if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete);
foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase))
UninstallEngine.DeleteShortcut(link, previous.Scope);
foreach (var a in previous.Associations.Except(current.Associations))
{
if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId);
}
}
private static void EnsureFreeSpace(string directory, long required)
{
long available;
try
{
available = new DriveInfo(Path.GetPathRoot(directory)!).AvailableFreeSpace;
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
{
// Network shares have no DriveInfo; the copy itself reports a full disk.
return;
}
if (available < required) throw new SetupException(SetupExitCode.DiskFull, $"{required:N0} bytes needed, {available:N0} available.");
}
/// Maps extraction progress onto a slice of the overall bar.
private sealed class MappedProgress(IProgress target, double from, double to) : IProgress
{
public void Report(PayloadProgress value) =>
target.Report(new SetupProgress(from + (to - from) * (value.Total == 0 ? 1 : (double)value.Done / value.Total), value.CurrentPath));
}
}