diff --git a/src/Titano.App/Infrastructure/StartWithWindows.cs b/src/Titano.App/Infrastructure/StartWithWindows.cs index ae3991b2..1140c26c 100644 --- a/src/Titano.App/Infrastructure/StartWithWindows.cs +++ b/src/Titano.App/Infrastructure/StartWithWindows.cs @@ -1,6 +1,8 @@ +using System.IO; using System.Security; using Microsoft.Win32; using Titano.Core.Diagnostics; +using Titano.Core.IO; namespace Titano.App.Infrastructure; @@ -11,50 +13,36 @@ public interface IStartWithWindows void SetEnabled(bool enabled); - /// Points an existing entry at the current executable (after an update moved it). + /// Points this copy's entry at the current executable (after an update renamed it). void Refresh(); } /// /// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts Titano minimised at sign-in, so inserted /// cards are noticed (BRIEF §12.4) without a window in the way. The registry stays the source of truth because Task -/// Manager can turn it off; the uninstaller removes it with the Uploader's. +/// Manager can turn it off. There is one value for every copy of Titano: a copy shows it as on only when it starts +/// that copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller +/// removes it with the Uploader's when it starts a program of the folder it removes. /// -public sealed class RunKeyStartWithWindows : IStartWithWindows +public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWithWindows { /// Starts the main window minimised on the taskbar. public const string MinimizedOption = "--minimized"; - private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; - private const string ValueName = "Titano"; + private readonly string? _executable = executable ?? Environment.ProcessPath; - public bool IsEnabled - { - get - { - try - { - using var key = Registry.CurrentUser.OpenSubKey(RunKey); - return key?.GetValue(ValueName) is string { Length: > 0 }; - } - catch (SecurityException) - { - return false; - } - } - } - - private static string Command => $"\"{Environment.ProcessPath}\" {MinimizedOption}"; + public bool IsEnabled => StartupCommand.Starts(Read(), _executable); public void SetEnabled(bool enabled) { + if (_executable is null) return; try { - using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true); - if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String); - else key.DeleteValue(ValueName, throwOnMissingValue: false); + using var key = Registry.CurrentUser.CreateSubKey(StartupCommand.RunKey, writable: true); + if (enabled) key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(_executable, MinimizedOption), RegistryValueKind.String); + else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, _executable)) key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false); } - catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException) + catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException) { Log.Warning("startup", "Run key not updated", ex); } @@ -62,11 +50,36 @@ public sealed class RunKeyStartWithWindows : IStartWithWindows public void Refresh() { - if (IsEnabled) SetEnabled(true); + if (Follows(Read(), _executable, File.Exists)) SetEnabled(true); + } + + /// + /// The entry should now start : the program it names is gone from the folder + /// runs from (an update renamed it). An entry of another copy, still on disk or + /// elsewhere (a second install, a portable copy, a development build), is left alone. + /// + internal static bool Follows(string? command, string? current, Func exists) + { + if (current is null || StartupCommand.Executable(command) is not { } stored || StartupCommand.Starts(command, current)) return false; + return !exists(stored) && StartupCommand.FolderOf(current) is { } folder + && string.Equals(StartupCommand.Folder(command), folder, StringComparison.OrdinalIgnoreCase); + } + + private static string? Read() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey); + return key?.GetValue(StartupCommand.ClientValue) as string; + } + catch (Exception ex) when (ex is SecurityException or IOException) + { + return null; + } } } -/// Screenshots and tests never touch the user's sign-in programs. +/// Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs. public sealed class MemoryStartWithWindows : IStartWithWindows { public bool IsEnabled { get; private set; } diff --git a/src/Titano.App/Sections/SettingsView.xaml b/src/Titano.App/Sections/SettingsView.xaml index 0d78b8e8..d6a16083 100644 --- a/src/Titano.App/Sections/SettingsView.xaml +++ b/src/Titano.App/Sections/SettingsView.xaml @@ -134,7 +134,8 @@ - + diff --git a/src/Titano.App/Sections/SettingsViewModel.cs b/src/Titano.App/Sections/SettingsViewModel.cs index e52323e0..9126b786 100644 --- a/src/Titano.App/Sections/SettingsViewModel.cs +++ b/src/Titano.App/Sections/SettingsViewModel.cs @@ -41,11 +41,11 @@ public sealed class SettingsViewModel : SectionViewModel { Shell = shell; _s = shell.Services.Settings; - Startup = shell.Services.Environment.IsCapture ? new MemoryStartWithWindows() : new RunKeyStartWithWindows(); + Startup = shell.Services.Environment is { IsCapture: false, IsPortable: false } ? new RunKeyStartWithWindows() : new MemoryStartWithWindows(); AllPages = [ - new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", "Settings.General.Startup", "Settings.General.Notifications", - .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]), + new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", .. ShowsStartup ? (string[])["Settings.General.Startup"] : [], + "Settings.General.Notifications", .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]), new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies"]), new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]), new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]), @@ -249,9 +249,12 @@ public sealed class SettingsViewModel : SectionViewModel } } - /// Where "Start with Windows" is kept (the Run key); screenshots and tests keep it in memory. + /// Where "Start with Windows" is kept (the Run key); screenshots, tests and portable copies keep it in memory. internal IStartWithWindows Startup { get; set; } + /// A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row. + public bool ShowsStartup => !Shell.Services.Environment.IsPortable; + /// Titano starts minimised when the user signs in to Windows. public bool StartWithWindows { diff --git a/src/Titano.Core/IO/StartupCommand.cs b/src/Titano.Core/IO/StartupCommand.cs new file mode 100644 index 00000000..6e023874 --- /dev/null +++ b/src/Titano.Core/IO/StartupCommand.cs @@ -0,0 +1,61 @@ +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. +/// +public static class StartupCommand +{ + public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + + /// The client's value (Settings › General › Startup). + public const string ClientValue = "Titano"; + + /// The Uploader's value (its "Start with Windows"). + public const string UploaderValue = "Titano Uploader"; + + /// The command that starts with . + public static string Format(string executable, string option) => $"\"{executable}\" {option}"; + + /// + /// The program starts: its quoted first part, or the text up to the first space when it + /// is not quoted; null for an empty or malformed command. + /// + public static string? Executable(string? command) + { + var text = command?.Trim(); + if (string.IsNullOrEmpty(text)) return null; + if (text[0] == '"') + { + var end = text.IndexOf('"', 1); + return end > 1 ? text[1..end] : null; + } + var space = text.IndexOf(' ', StringComparison.Ordinal); + return space < 0 ? text : text[..space]; + } + + /// starts , not another copy of the program. + 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) + { + 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 '/'; + } + + /// The folder of the program starts; null when it names none. + public static string? Folder(string? command) => Executable(command) is { } exe ? FolderOf(exe) : null; + + /// The folder part of a Windows path (on any platform); null when it has none. + public static string? FolderOf(string path) + { + ArgumentNullException.ThrowIfNull(path); + var slash = path.LastIndexOfAny(['\\', '/']); + return slash > 0 ? path[..slash] : null; + } +} diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs index 006c7703..a407d2d0 100644 --- a/src/Titano.Setup/Engine/SetupRegistry.cs +++ b/src/Titano.Setup/Engine/SetupRegistry.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.IO; using System.Text.RegularExpressions; using Microsoft.Win32; +using Titano.Core.IO; namespace Titano.Setup.Engine; @@ -56,6 +57,20 @@ internal static partial class SetupRegistry 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 a program of ; another copy's entries stay. + /// + public static void DeleteStartupEntries(string directory) + { + using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true); + if (run is null) return; + foreach (var name in (ReadOnlySpan)[StartupCommand.ClientValue, StartupCommand.UploaderValue]) + { + if (StartupCommand.StartsFrom(run.GetValue(name) as string, directory)) run.DeleteValue(name, throwOnMissingValue: false); + } + } + /// Registers to open with "program" "%1" under . public static void RegisterFileType(InstallScope scope, string extension, string progId, string description, string program) { diff --git a/src/Titano.Setup/Engine/UninstallEngine.cs b/src/Titano.Setup/Engine/UninstallEngine.cs index d793b225..c06bf1ea 100644 --- a/src/Titano.Setup/Engine/UninstallEngine.cs +++ b/src/Titano.Setup/Engine/UninstallEngine.cs @@ -10,8 +10,8 @@ namespace Titano.Setup.Engine; internal sealed record InstalledProduct(string Directory, InstallLog Log); /// -/// 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 +/// Removes an installation using only its log: shortcuts, file types, logged files, the log, the Add/Remove +/// Programs entry and the programs' sign-in entries, then the uninstaller itself. Files the log does not list are left alone; the user data folder /// is deleted only when removeUserData is set by an explicit choice in the window. /// internal static class UninstallEngine @@ -60,6 +60,15 @@ internal static class UninstallEngine } SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey); + try + { + SetupRegistry.DeleteStartupEntries(directory); + } + catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) + { + // Windows skips a sign-in entry whose program is gone; not worth failing the removal. + Log.Warning("setup", "Sign-in entries not removed", ex); + } File.Delete(Path.Combine(directory, InstallLog.FileName)); var uninstaller = Path.Combine(directory, log.UninstallerName); try diff --git a/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs b/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs new file mode 100644 index 00000000..7148dc8a --- /dev/null +++ b/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs @@ -0,0 +1,45 @@ +using Titano.App.Infrastructure; +using Titano.Core.IO; +using Titano.Testing; + +namespace Titano.App.Tests.Infrastructure; + +/// Settings › General › Startup: one sign-in entry shared by every copy of Titano, which no copy takes over by starting. +public sealed class StartWithWindowsTests +{ + private const string Installed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe"; + + [Test] + public void AStartFollowsOnlyAnEntryAnUpdateLeftBehindInItsOwnFolder() + { + static bool Gone(string path) => false; + static bool Present(string path) => true; + var installed = StartupCommand.Format(Installed, RunKeyStartWithWindows.MinimizedOption); + + // The entry already starts this copy: nothing to write. + Assert.False(RunKeyStartWithWindows.Follows(installed, Installed, Gone)); + // An update renamed the program in its folder: the entry follows it. + Assert.True(RunKeyStartWithWindows.Follows(StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano\Titano.old.exe", "--minimized"), + Installed, Gone)); + // The installed copy is still there: a portable copy, a second install or a development build that starts leaves it alone. + Assert.False(RunKeyStartWithWindows.Follows(installed, @"E:\Titano\Titano.exe", Present)); + Assert.False(RunKeyStartWithWindows.Follows(installed, @"C:\src\Titano\bin\Debug\Titano.exe", Present)); + // Gone from another folder (a USB stick that is not plugged in): still not this copy's entry. + Assert.False(RunKeyStartWithWindows.Follows(installed, @"E:\Titano\Titano.exe", Gone)); + // No entry, or no executable path: nothing to follow. + Assert.False(RunKeyStartWithWindows.Follows(null, Installed, Gone)); + Assert.False(RunKeyStartWithWindows.Follows(installed, null, Gone)); + } + + [Test] + public void ScreenshotsAndPortableCopiesKeepTheChoiceInMemory() + { + var startup = new MemoryStartWithWindows(); + Assert.False(startup.IsEnabled); + startup.SetEnabled(true); + startup.Refresh(); + Assert.True(startup.IsEnabled); + startup.SetEnabled(false); + Assert.False(startup.IsEnabled); + } +} diff --git a/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs new file mode 100644 index 00000000..6a24ece3 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs @@ -0,0 +1,58 @@ +using Titano.Core.IO; +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. +public sealed class StartupCommandTests +{ + private const string Installed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe"; + + [Test] + public void TheCommandNamesItsProgram() + { + var command = StartupCommand.Format(Installed, "--minimized"); + Assert.Equal("\"" + Installed + "\" --minimized", command); + Assert.Equal(Installed, StartupCommand.Executable(command)); + Assert.Equal(@"C:\Users\ada\AppData\Local\Programs\Titano", StartupCommand.Folder(command)); + // Written by hand or by an older tool: unquoted, or with spaces around. + Assert.Equal(@"D:\Titano\Titano.exe", StartupCommand.Executable(@" D:\Titano\Titano.exe --minimized ")); + Assert.Equal(@"D:\Titano\Titano.exe", StartupCommand.Executable(@"D:\Titano\Titano.exe")); + Assert.Null(StartupCommand.Executable(null)); + Assert.Null(StartupCommand.Executable(" ")); + Assert.Null(StartupCommand.Executable("\"unterminated --minimized")); + Assert.Null(StartupCommand.Executable("\"\" --minimized")); + Assert.Null(StartupCommand.Folder("Titano.exe")); + Assert.Equal(@"D:\Titano", StartupCommand.FolderOf(@"D:\Titano\Titano.exe")); + } + + [Test] + public void AnEntryBelongsToTheCopyItStarts() + { + var command = StartupCommand.Format(Installed, "--minimized"); + Assert.True(StartupCommand.Starts(command, Installed)); + Assert.True(StartupCommand.Starts(command, Installed.ToUpperInvariant()), "Windows paths ignore case"); + // A portable copy on a USB stick, a second install or a development build is another program. + Assert.False(StartupCommand.Starts(command, @"E:\Titano\Titano.exe")); + Assert.False(StartupCommand.Starts(command, @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe.old")); + Assert.False(StartupCommand.Starts(command, null)); + Assert.False(StartupCommand.Starts(null, Installed)); + } + + [Test] + public void TheUninstallerRemovesOnlyTheEntriesOfItsFolder() + { + 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, @"\")); + } +}