using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using Titano.Core.IO;
namespace Titano.Setup.Engine;
/// An installation found in Add/Remove Programs.
internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version);
///
/// 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).
///
internal sealed record OtherInstall(string? Directory, InstallLog? Log);
/// Values written to the Add/Remove Programs entry.
internal sealed record UninstallEntry(string DisplayName, string Version, string Publisher, string Directory, string UninstallerPath, string DisplayIcon, long EstimatedBytes, string? AboutUrl);
///
/// Registry state owned by setup: the Add/Remove Programs entry under
/// Software\Microsoft\Windows\CurrentVersion\Uninstall\<key> and file types under Software\Classes,
/// in HKCU for per-user installs and HKLM for all-users installs.
///
internal static partial class SetupRegistry
{
private const string UninstallRoot = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\";
private const string ClassesRoot = @"Software\Classes\";
/// No replacement program: every matching sign-in entry is removed.
private static readonly IReadOnlyDictionary NoPrograms = new Dictionary();
private static RegistryKey Hive(InstallScope scope) => scope == InstallScope.AllUsers ? Registry.LocalMachine : Registry.CurrentUser;
/// The installation registered under whose folder still exists, current user first.
public static ExistingInstall? FindInstall(string productKey)
{
foreach (var scope in (ReadOnlySpan)[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;
}
///
/// The other installations by (any product, either scope) except the one in
/// : 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.
///
public static IReadOnlyList OtherInstalls(string directory, string publisher)
{
var found = new List();
foreach (var scope in (ReadOnlySpan)[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);
///
/// Removes the sign-in entries of the client and the Uploader (HKCU\…\Run, written by the programs
/// themselves) that start one of ( of the files an
/// installation lists), with the on/off state Task Manager keeps for them (); another
/// copy's entries, and other programs' values, stay.
///
public static void DeleteStartupEntries(IReadOnlySet programs) => MoveStartupEntries(programs, NoPrograms);
///
/// in and ;
/// returns the names removed.
///
public static IReadOnlyList DeleteStartupEntries(RegistryKey run, RegistryKey? approval, IReadOnlySet programs) =>
MoveStartupEntries(run, approval, programs, NoPrograms);
///
/// After an upgrade: a sign-in entry of the client or the Uploader that starts one of
/// (programs the previous version installed and this one does not) starts the program
/// 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).
///
public static void MoveStartupEntries(IReadOnlySet dropped, IReadOnlyDictionary 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);
}
///
/// in
/// ; a removed entry's on/off state goes from too, a moved one keeps
/// it. Returns the names moved or removed.
///
public static IReadOnlyList MoveStartupEntries(RegistryKey run, RegistryKey? approval, IReadOnlySet dropped,
IReadOnlyDictionary programs)
{
var changed = new List();
foreach (var name in (ReadOnlySpan)[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;
}
/// Registers to open with "program" "%1" under .
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);
}
/// Removes the ProgID and detaches the extension, leaving other programs' registrations intact.
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);
}
/// Guards registry paths built from a log file: an extension and a dotted ProgID, nothing else.
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();
}