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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user