Files
Chronos/src/Titano.Setup/Engine/SetupRegistry.cs
T
Claude 0d11802466 fix(setup): remove the Task Manager state of a sign-in entry setup removes
Uninstalling (or an upgrade dropping a program) deleted the client's or the
Uploader's Run value but left its StartupApproved\Run value behind. A moved
entry keeps that state, so an entry the user turned off stays off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 16:58:55 +00:00

213 lines
12 KiB
C#

using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using Titano.Core.IO;
namespace Titano.Setup.Engine;
/// <summary>An installation found in Add/Remove Programs.</summary>
internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version);
/// <summary>
/// Another Titano installation registered in Add/Remove Programs: its folder, and its log when that can be read now
/// (null for a drive that is offline, a folder that is gone or a log that cannot be read).
/// </summary>
internal sealed record OtherInstall(string? Directory, InstallLog? Log);
/// <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\&lt;key&gt;</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\";
/// <summary>No replacement program: every matching sign-in entry is removed.</summary>
private static readonly IReadOnlyDictionary<string, string> NoPrograms = new Dictionary<string, string>();
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;
}
/// <summary>
/// The other installations by <paramref name="publisher"/> (any product, either scope) except the one in
/// <paramref name="directory"/>: what an uninstall must leave working (the user data and shortcuts they share).
/// Every registered entry counts, also one whose folder or log cannot be read right now.
/// </summary>
public static IReadOnlyList<OtherInstall> OtherInstalls(string directory, string publisher)
{
var found = new List<OtherInstall>();
foreach (var scope in (ReadOnlySpan<InstallScope>)[InstallScope.CurrentUser, InstallScope.AllUsers])
{
using var root = Hive(scope).OpenSubKey(UninstallRoot.TrimEnd('\\'));
if (root is null) continue;
foreach (var name in root.GetSubKeyNames())
{
try
{
using var key = root.OpenSubKey(name);
if (key?.GetValue("Publisher") is not string p || !p.Equals(publisher, StringComparison.Ordinal)) continue;
var location = key.GetValue("InstallLocation") as string;
if (location is { Length: > 0 } && CommandProgram.IsPathInside(location, directory) && CommandProgram.IsPathInside(directory, location)) continue;
var log = location is { Length: > 0 } && Directory.Exists(location) ? InstallLog.TryLoad(location) : null;
if (log is null) Titano.Core.Diagnostics.Log.Info("setup", $"Installation '{name}' in '{location}' cannot be read now; it counts as using every program");
found.Add(new OtherInstall(location, log));
}
catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException)
{
// Another program's entry this account may not read.
}
}
}
return found;
}
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>
/// Removes the sign-in entries of the client and the Uploader (<c>HKCU\…\Run</c>, written by the programs
/// themselves) that start one of <paramref name="programs"/> (<see cref="CommandProgram.FullPaths"/> of the files an
/// installation lists), with the on/off state Task Manager keeps for them (<see cref="StartupApproval"/>); another
/// copy's entries, and other programs' values, stay.
/// </summary>
public static void DeleteStartupEntries(IReadOnlySet<string> programs) => MoveStartupEntries(programs, NoPrograms);
/// <summary>
/// <see cref="DeleteStartupEntries(IReadOnlySet{string})"/> in <paramref name="run"/> and <paramref name="approval"/>;
/// returns the names removed.
/// </summary>
public static IReadOnlyList<string> DeleteStartupEntries(RegistryKey run, RegistryKey? approval, IReadOnlySet<string> programs) =>
MoveStartupEntries(run, approval, programs, NoPrograms);
/// <summary>
/// After an upgrade: a sign-in entry of the client or the Uploader that starts one of <paramref name="dropped"/>
/// (programs the previous version installed and this one does not) starts the program <paramref name="programs"/>
/// gives for its value name instead, with the same options, when this version installs one (an update renamed or
/// moved it, and the program would find no entry to follow); otherwise it is removed (the component was dropped).
/// </summary>
public static void MoveStartupEntries(IReadOnlySet<string> dropped, IReadOnlyDictionary<string, string> programs)
{
using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true);
if (run is null) return;
using var approval = Registry.CurrentUser.OpenSubKey(StartupApproval.RunKey, writable: true);
MoveStartupEntries(run, approval, dropped, programs);
}
/// <summary>
/// <see cref="MoveStartupEntries(IReadOnlySet{string}, IReadOnlyDictionary{string, string})"/> in
/// <paramref name="run"/>; a removed entry's on/off state goes from <paramref name="approval"/> too, a moved one keeps
/// it. Returns the names moved or removed.
/// </summary>
public static IReadOnlyList<string> MoveStartupEntries(RegistryKey run, RegistryKey? approval, IReadOnlySet<string> dropped,
IReadOnlyDictionary<string, string> programs)
{
var changed = new List<string>();
foreach (var name in (ReadOnlySpan<string>)[StartupCommand.ClientValue, StartupCommand.UploaderValue])
{
var command = run.GetValue(name) as string;
if (!CommandProgram.IsAmong(StartupCommand.Executable(command), dropped)) continue;
if (programs.TryGetValue(name, out var program) && StartupCommand.Retarget(command, program) is { } moved)
{
run.SetValue(name, moved, RegistryValueKind.String);
Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' now starts '{program}'");
}
else
{
run.DeleteValue(name, throwOnMissingValue: false);
// Its Task Manager state goes with it: nothing of the entry stays behind.
approval?.DeleteValue(name, throwOnMissingValue: false);
Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' removed");
}
changed.Add(name);
}
return changed;
}
/// <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();
}