diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 02d2be82..75869f2d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -46,7 +46,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Model` | Domain entities and enums (§5) shared by Data, Server and clients | | `Packaging` | TPK1 installer payload writer/reader, staged install transaction | | `Diagnostics` | `Log`, file sink, synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) | -| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, `StartupCommand` (sign-in entries of the programs, removed by the uninstaller), CRC-32/SHA helpers, brand mark geometry | +| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, `StartupCommand` (sign-in entries of the programs, moved or removed by setup), CRC-32/SHA helpers, brand mark geometry | ### 2.2 Titano.Data @@ -95,7 +95,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) | | Titano Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `TITANO_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (renders only managed formats and MP4 jobs no render node can take, BRIEF §14.7); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host; daily backups of an SQLite index (`DatabaseBackupService`) | | Titano Uploader | `Uploader/App.xaml.cs` | `TitanoClient`, persisted queue, watch folders; no database | -| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses | +| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs moved to the program an upgrade renamed or removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses | ### 2.6 Job kinds and their handlers diff --git a/src/Titano.Core/IO/StartupCommand.cs b/src/Titano.Core/IO/StartupCommand.cs index 6e023874..4e0652ac 100644 --- a/src/Titano.Core/IO/StartupCommand.cs +++ b/src/Titano.Core/IO/StartupCommand.cs @@ -3,7 +3,8 @@ namespace Titano.Core.IO; /// /// The sign-in entries of Titano's programs: HKCU\Software\Microsoft\Windows\CurrentVersion\Run values whose /// command starts one executable with one option ("C:\…\Titano.exe" --minimized). Shared by the programs that -/// write them and the uninstaller that removes them; the paths are Windows paths, compared ignoring case. +/// write them and setup, which moves or removes them with the programs it installed; the paths are Windows paths, +/// compared ignoring case. /// public static class StartupCommand { @@ -39,13 +40,18 @@ public static class StartupCommand public static bool Starts(string? command, string? executable) => executable is { Length: > 0 } && string.Equals(Executable(command), executable, StringComparison.OrdinalIgnoreCase); - /// The program starts lies in or one of its folders. - public static bool StartsFrom(string? command, string directory) + /// + /// made to start with the same options (setup moves an entry + /// to the program an update renamed); null when names no program. + /// + public static string? Retarget(string? command, string executable) { - ArgumentNullException.ThrowIfNull(directory); - var folder = directory.TrimEnd('\\', '/'); - return Executable(command) is { } exe && folder.Length > 0 && exe.Length > folder.Length + 1 - && exe.StartsWith(folder, StringComparison.OrdinalIgnoreCase) && exe[folder.Length] is '\\' or '/'; + ArgumentNullException.ThrowIfNull(executable); + if (Executable(command) is null) return null; + var text = command!.Trim(); + var end = text[0] == '"' ? text.IndexOf('"', 1) + 1 : text.IndexOf(' ', StringComparison.Ordinal); + var options = end < 0 ? string.Empty : text[end..].Trim(); + return options.Length == 0 ? $"\"{executable}\"" : Format(executable, options); } /// The folder of the program starts; null when it names none. diff --git a/src/Titano.Setup/Engine/InstallEngine.cs b/src/Titano.Setup/Engine/InstallEngine.cs index ca050ccc..92a8cf52 100644 --- a/src/Titano.Setup/Engine/InstallEngine.cs +++ b/src/Titano.Setup/Engine/InstallEngine.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.IO; using System.Reflection; using Titano.Core.Diagnostics; +using Titano.Core.IO; using Titano.Core.Localization; using Titano.Core.Packaging; using Titano.Setup.Cli; @@ -24,6 +25,10 @@ internal sealed class InstallEngine(PayloadReader payload) { private const double ExtractShare = 0.9; + /// Each sign-in entry and the component (as pack-installer names it) whose program it starts. + private static readonly (string Value, string Component)[] StartupComponents = + [(StartupCommand.ClientValue, "Titano"), (StartupCommand.UploaderValue, "Uploader")]; + public PayloadManifest Manifest => payload.Manifest; /// Bytes the selected components occupy once installed, uninstaller included. @@ -141,10 +146,28 @@ internal sealed class InstallEngine(PayloadReader payload) } /// - /// Removes what the previous version installed and this one no longer does (files, the sign-in entries of those - /// programs, shortcuts, file types). + /// The program each sign-in entry ('s value names) starts once + /// are installed in : the shortcut target of the entry's + /// component, for the components among them that have one. /// - private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current) + internal static IReadOnlyDictionary StartupPrograms(PayloadManifest manifest, string directory, IEnumerable components) + { + var selected = new HashSet(components, StringComparer.OrdinalIgnoreCase); + var programs = new Dictionary(StringComparer.Ordinal); + foreach (var (value, component) in StartupComponents) + { + if (!selected.Contains(component)) continue; + if (manifest.Shortcuts.FirstOrDefault(s => s.Component.Equals(component, StringComparison.OrdinalIgnoreCase)) is { } shortcut) + programs[value] = PayloadPath.Resolve(directory, shortcut.Target); + } + return programs; + } + + /// + /// Removes what the previous version installed and this one no longer does (files, shortcuts, file types). The + /// sign-in entries of the removed programs move to the program that replaces them, or go with a dropped component. + /// + private 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) @@ -152,12 +175,14 @@ internal sealed class InstallEngine(PayloadReader payload) InstalledFiles.Remove(directory, obsolete); try { - // A dropped Uploader no longer starts at sign-in. - SetupRegistry.DeleteStartupEntries(CommandProgram.FullPaths(directory, obsolete)); + // A renamed program keeps starting at sign-in (without its entry, the new program has nothing to + // follow); a dropped Uploader no longer does. + var programs = StartupPrograms(Manifest, directory, current.Components).Where(p => File.Exists(p.Value)).ToDictionary(StringComparer.Ordinal); + SetupRegistry.MoveStartupEntries(CommandProgram.FullPaths(directory, obsolete), programs); } catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) { - Log.Warning("setup", "Sign-in entries not removed", ex); + Log.Warning("setup", "Sign-in entries not updated", ex); } } var links = previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase).ToList(); diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs index 9d1f161d..e1800d36 100644 --- a/src/Titano.Setup/Engine/SetupRegistry.cs +++ b/src/Titano.Setup/Engine/SetupRegistry.cs @@ -28,6 +28,9 @@ 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. @@ -101,24 +104,47 @@ internal static partial class SetupRegistry /// themselves) that start one of ( of the files an /// installation lists); another copy's entries, and other programs' values, stay. /// - public static void DeleteStartupEntries(IReadOnlySet programs) - { - using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true); - if (run is not null) DeleteStartupEntries(run, programs); - } + public static void DeleteStartupEntries(IReadOnlySet programs) => MoveStartupEntries(programs, NoPrograms); /// in ; returns the names removed. - public static IReadOnlyList DeleteStartupEntries(RegistryKey run, IReadOnlySet programs) + public static IReadOnlyList DeleteStartupEntries(RegistryKey run, IReadOnlySet programs) => MoveStartupEntries(run, 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) { - var removed = new List(); + using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true); + if (run is not null) MoveStartupEntries(run, dropped, programs); + } + + /// + /// in + /// ; returns the names moved or removed. + /// + public static IReadOnlyList MoveStartupEntries(RegistryKey run, IReadOnlySet dropped, IReadOnlyDictionary programs) + { + var changed = new List(); foreach (var name in (ReadOnlySpan)[StartupCommand.ClientValue, StartupCommand.UploaderValue]) { - if (!CommandProgram.IsAmong(StartupCommand.Executable(run.GetValue(name) as string), programs)) continue; - run.DeleteValue(name, throwOnMissingValue: false); - removed.Add(name); - Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' removed"); + 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); + Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' removed"); + } + changed.Add(name); } - return removed; + return changed; } /// Registers to open with "program" "%1" under . diff --git a/tests/Titano.App.Tests/Setup/SetupEngineTests.cs b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs index a51a54cf..385ed7ef 100644 --- a/tests/Titano.App.Tests/Setup/SetupEngineTests.cs +++ b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs @@ -178,6 +178,46 @@ public sealed class SetupEngineTests(TestContext context) } } + [Test] + [WindowsOnly] + public void AnUpgradeMovesTheSignInEntryOfARenamedProgramAndRemovesThatOfADroppedOne() + { + var folder = Path.Combine(context.CreateTempDirectory("upgrade"), "Apps"); + var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N"); + // This version ships the client as Titano.exe (the previous one as Titano.old.exe), and the user left out the Uploader. + var manifest = Manifest(); + manifest.Components.Add(new PayloadComponent { Id = "Uploader", DisplayName = "Titano Uploader", DefaultSelected = true }); + manifest.Shortcuts.Add(new PayloadShortcut { Component = "Titano", Name = "Titano", Target = "Titano.exe", StartMenu = true }); + manifest.Shortcuts.Add(new PayloadShortcut { Component = "Uploader", Name = "Titano Uploader", Target = "Titano.Uploader.exe", StartMenu = true }); + var programs = InstallEngine.StartupPrograms(manifest, folder, ["Titano", "Server"]); + Assert.SequenceEqual(["Titano"], programs.Keys); + Assert.Equal(Path.Combine(folder, "Titano.exe"), programs["Titano"]); + try + { + using (var run = Registry.CurrentUser.CreateSubKey(keyPath, writable: true)) + { + run.SetValue("Titano", $"\"{Path.Combine(folder, "Titano.old.exe")}\" --minimized"); + run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Titano.Uploader.exe")}\" --tray"); + run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background"); + + var dropped = CommandProgram.FullPaths(folder, ["Titano.old.exe", "Titano.Uploader.exe", "Other.exe"]); + Assert.SequenceEqual(["Titano", "Titano Uploader"], SetupRegistry.MoveStartupEntries(run, dropped, programs)); + // The new client finds its entry on, with its option; the Uploader no longer starts; other values stay. + Assert.Equal($"\"{Path.Combine(folder, "Titano.exe")}\" --minimized", run.GetValue("Titano")); + Assert.SequenceEqual(["Other", "Titano"], run.GetValueNames().Order(StringComparer.Ordinal)); + // An entry that starts another copy is not this upgrade's to move. + var other = $"\"{Path.Combine(folder + " 2", "Titano.old.exe")}\" --minimized"; + run.SetValue("Titano", other); + Assert.Empty(SetupRegistry.MoveStartupEntries(run, dropped, programs)); + Assert.Equal(other, run.GetValue("Titano")); + } + } + finally + { + DeleteTestKey(keyPath); + } + } + [Test] [WindowsOnly] public void AShortcutTellsWhichProgramItStarts() diff --git a/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs index 6a24ece3..a2908d1b 100644 --- a/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs +++ b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs @@ -3,7 +3,7 @@ using Titano.Testing; namespace Titano.Core.Tests.Foundation; -/// The sign-in entries of the client and the Uploader: which copy they start, and which folder the uninstaller may clean. +/// The sign-in entries of the client and the Uploader: which copy they start, and how setup moves them to a renamed program. public sealed class StartupCommandTests { private const string Installed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe"; @@ -40,19 +40,22 @@ public sealed class StartupCommandTests } [Test] - public void TheUninstallerRemovesOnlyTheEntriesOfItsFolder() + public void SetupMovesAnEntryToTheRenamedProgramWithItsOption() { - var client = StartupCommand.Format(Installed, "--minimized"); - var uploader = StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano\Uploader\Titano.Uploader.exe", "--tray"); - const string folder = @"C:\Users\ada\AppData\Local\Programs\Titano"; - Assert.True(StartupCommand.StartsFrom(client, folder)); - Assert.True(StartupCommand.StartsFrom(client, folder + @"\")); - Assert.True(StartupCommand.StartsFrom(uploader, folder.ToLowerInvariant())); - // A sibling folder that shares the name's start, another drive, or nothing at all stay. - Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano2\Titano.exe", "--minimized"), folder)); - Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(@"E:\Titano\Titano.exe", "--minimized"), folder)); - Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(folder, "--minimized"), folder)); - Assert.False(StartupCommand.StartsFrom(null, folder)); - Assert.False(StartupCommand.StartsFrom(client, @"\")); + // Setup matches an entry by the program it starts (one its install log lists, never any program under the + // folder) and, when an update renamed that program, points the entry at the new one. + const string renamed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.old.exe"; + var moved = StartupCommand.Retarget(StartupCommand.Format(renamed, "--minimized"), Installed); + Assert.Equal(StartupCommand.Format(Installed, "--minimized"), moved); + Assert.True(StartupCommand.Starts(moved, Installed)); + // Written by hand or by an older tool: unquoted, without an option, or with more than one. + Assert.Equal(StartupCommand.Format(Installed, "--tray"), StartupCommand.Retarget(@" D:\Titano\Titano.Uploader.exe --tray ", Installed)); + Assert.Equal("\"" + Installed + "\"", StartupCommand.Retarget(@"D:\Titano\Titano.exe", Installed)); + Assert.Equal("\"" + Installed + "\"", StartupCommand.Retarget("\"" + renamed + "\"", Installed)); + Assert.Equal(StartupCommand.Format(Installed, "--minimized --verbose"), StartupCommand.Retarget("\"" + renamed + "\" --minimized --verbose", Installed)); + // Nothing to move. + Assert.Null(StartupCommand.Retarget(null, Installed)); + Assert.Null(StartupCommand.Retarget(" ", Installed)); + Assert.Null(StartupCommand.Retarget("\"unterminated --minimized", Installed)); } }