diff --git a/src/Titano.App/Infrastructure/StartWithWindows.cs b/src/Titano.App/Infrastructure/StartWithWindows.cs index 1140c26c..72e54c2f 100644 --- a/src/Titano.App/Infrastructure/StartWithWindows.cs +++ b/src/Titano.App/Infrastructure/StartWithWindows.cs @@ -20,37 +20,48 @@ public interface IStartWithWindows /// /// 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. 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. +/// Manager can turn it off: an entry it turned off () shows as off, and ticking the box +/// turns it on again. 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(string? executable = null) : IStartWithWindows +/// This copy's program; the running one by default. +/// The registry hive holding the entries; HKEY_CURRENT_USER by default (tests pass a scratch key). +public sealed class RunKeyStartWithWindows(string? executable = null, RegistryKey? root = null) : IStartWithWindows { /// Starts the main window minimised on the taskbar. public const string MinimizedOption = "--minimized"; private readonly string? _executable = executable ?? Environment.ProcessPath; + private readonly RegistryKey _root = root ?? Registry.CurrentUser; - public bool IsEnabled => StartupCommand.Starts(Read(), _executable); + /// The entry starts this copy and Task Manager has not turned it off. + public bool IsEnabled => StartupCommand.Starts(Read(), _executable) && !StartupApproval.IsTurnedOff(ReadApproval()); public void SetEnabled(bool enabled) { - if (_executable is null) return; - try + if (_executable is not { } executable) return; + Update(key => { - 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 or IOException) - { - Log.Warning("startup", "Run key not updated", ex); - } + if (enabled) + { + key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String); + // Task Manager's "Disable" outlives a new command: ticking the box undoes it. + DeleteApproval(); + } + else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, executable)) + { + key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false); + DeleteApproval(); + } + }); } + /// The command follows a renamed program; an entry Task Manager turned off stays off. public void Refresh() { - if (Follows(Read(), _executable, File.Exists)) SetEnabled(true); + if (_executable is { } executable && Follows(Read(), executable, File.Exists)) + Update(key => key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String)); } /// @@ -65,11 +76,11 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi && string.Equals(StartupCommand.Folder(command), folder, StringComparison.OrdinalIgnoreCase); } - private static string? Read() + private string? Read() { try { - using var key = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey); + using var key = _root.OpenSubKey(StartupCommand.RunKey); return key?.GetValue(StartupCommand.ClientValue) as string; } catch (Exception ex) when (ex is SecurityException or IOException) @@ -77,6 +88,39 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi return null; } } + + /// Task Manager's switch for the entry; null when it never touched it. + private byte[]? ReadApproval() + { + try + { + using var key = _root.OpenSubKey(StartupApproval.RunKey); + return key?.GetValue(StartupCommand.ClientValue) as byte[]; + } + catch (Exception ex) when (ex is SecurityException or IOException) + { + return null; + } + } + + private void DeleteApproval() + { + using var key = _root.OpenSubKey(StartupApproval.RunKey, writable: true); + key?.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false); + } + + private void Update(Action change) + { + try + { + using var key = _root.CreateSubKey(StartupCommand.RunKey, writable: true); + change(key); + } + catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException) + { + Log.Warning("startup", "Run key not updated", ex); + } + } } /// Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs. diff --git a/src/Titano.Core/IO/StartupApproval.cs b/src/Titano.Core/IO/StartupApproval.cs new file mode 100644 index 00000000..8d1eae74 --- /dev/null +++ b/src/Titano.Core/IO/StartupApproval.cs @@ -0,0 +1,16 @@ +namespace Titano.Core.IO; + +/// +/// Whether Windows runs a sign-in entry (). Task Manager's Startup tab and Settings › Apps › +/// Startup turn an entry off without touching its Run value: they write a binary value of the same name under +/// whose first byte is odd while the entry is off (0x03) and even once it is on again (0x02). An +/// entry without that value is on. Rewriting the Run value leaves it as it is, so turning an entry back on means +/// removing it. +/// +public static class StartupApproval +{ + public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"; + + /// The entry is turned off according to its StartupApproved (null when it has none). + public static bool IsTurnedOff(byte[]? state) => state is { Length: > 0 } && (state[0] & 1) != 0; +} diff --git a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs index 4badfff3..ed5eedee 100644 --- a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs +++ b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs @@ -1,3 +1,4 @@ +using System.IO; using System.Security; using Microsoft.Win32; using Titano.Core.Diagnostics; @@ -15,49 +16,65 @@ public interface IStartupRegistration /// /// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts the uploader in the tray at sign-in. -/// The registry stays the source of truth because Task Manager can turn it off. Uninstalling removes the value when -/// it starts the Uploader the uninstaller removes ( names it for both). +/// The registry stays the source of truth because Task Manager can turn it off: an entry it turned off +/// () shows as off, and ticking the box turns it on again. Uninstalling removes the value +/// when it starts the Uploader the uninstaller removes ( names it for both). /// -public sealed class RunKeyStartupRegistration : IStartupRegistration +/// The Uploader's program; the running one by default. +/// The registry hive holding the entries; HKEY_CURRENT_USER by default (tests pass a scratch key). +public sealed class RunKeyStartupRegistration(string? executable = null, RegistryKey? root = null) : IStartupRegistration { private const string RunKey = StartupCommand.RunKey; private const string ValueName = StartupCommand.UploaderValue; - public bool IsEnabled + private readonly string? _executable = executable ?? Environment.ProcessPath; + private readonly RegistryKey _root = root ?? Registry.CurrentUser; + + /// The entry exists and Task Manager has not turned it off. + public bool IsEnabled => HasEntry && !StartupApproval.IsTurnedOff(Read(StartupApproval.RunKey) as byte[]); + + private bool HasEntry => Read(RunKey) is string { Length: > 0 }; + + private string Command => StartupCommand.Format(_executable ?? string.Empty, CommandLine.TrayOption); + + public void SetEnabled(bool enabled) => Update(key => { - get - { - try - { - using var key = Registry.CurrentUser.OpenSubKey(RunKey); - return key?.GetValue(ValueName) is string { Length: > 0 }; - } - catch (SecurityException) - { - return false; - } - } + if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String); + else key.DeleteValue(ValueName, throwOnMissingValue: false); + // Task Manager's "Disable" outlives a new command: ticking the box undoes it, and unticking leaves nothing behind. + using var approval = _root.OpenSubKey(StartupApproval.RunKey, writable: true); + approval?.DeleteValue(ValueName, throwOnMissingValue: false); + }); + + /// Points an existing entry at the current executable (after an update moved it); one Task Manager turned off stays off. + public void Refresh() + { + if (HasEntry) Update(key => key.SetValue(ValueName, Command, RegistryValueKind.String)); } - private static string Command => $"\"{Environment.ProcessPath}\" {CommandLine.TrayOption}"; - - public void SetEnabled(bool enabled) + private object? Read(string subKey) { 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 = _root.OpenSubKey(subKey); + return key?.GetValue(ValueName); } - catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException) + catch (Exception ex) when (ex is SecurityException or IOException) + { + return null; + } + } + + private void Update(Action change) + { + try + { + using var key = _root.CreateSubKey(RunKey, writable: true); + change(key); + } + catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException) { Log.Warning("startup", "Run key not updated", ex); } } - - /// Points an existing entry at the current executable (after an update moved it). - public void Refresh() - { - if (IsEnabled) SetEnabled(true); - } } diff --git a/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs b/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs index 7148dc8a..a0ef5c86 100644 --- a/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs +++ b/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs @@ -1,6 +1,8 @@ +using Microsoft.Win32; using Titano.App.Infrastructure; using Titano.Core.IO; using Titano.Testing; +using Titano.Uploader.Infrastructure; namespace Titano.App.Tests.Infrastructure; @@ -31,6 +33,77 @@ public sealed class StartWithWindowsTests Assert.False(RunKeyStartWithWindows.Follows(installed, null, Gone)); } + [Test] + [WindowsOnly] + public void AnEntryTaskManagerTurnedOffShowsOffUntilTheBoxIsTickedAgain() + { + // A scratch hive of its own: the user's sign-in entries are never touched. + var hive = @"Software\Titano.StartupTests." + Guid.NewGuid().ToString("N"); + try + { + using var root = Registry.CurrentUser.CreateSubKey(hive, writable: true); + var startup = new RunKeyStartWithWindows(Installed, root); + startup.SetEnabled(true); + Assert.True(startup.IsEnabled); + + // Task Manager › Startup › Disable keeps the Run value and writes the switch apart. + TurnOff(root, StartupCommand.ClientValue); + Assert.False(startup.IsEnabled, "shown as off"); + Assert.True(StartupCommand.Starts(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue) as string, Installed), "the command stays"); + + // An update renamed the program: the command follows it, and the entry stays off. + const string renamed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.next.exe"; + var updated = new RunKeyStartWithWindows(renamed, root); + updated.Refresh(); + Assert.True(StartupCommand.Starts(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue) as string, renamed)); + Assert.False(updated.IsEnabled, "still off after the update"); + + // Ticking the box turns it on again; unticking leaves nothing behind. + updated.SetEnabled(true); + Assert.True(updated.IsEnabled); + Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.ClientValue)); + TurnOff(root, StartupCommand.ClientValue); + updated.SetEnabled(false); + Assert.Null(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue)); + Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.ClientValue)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false); + } + } + + [Test] + [WindowsOnly] + public void TheUploadersEntryHonoursTaskManagerToo() + { + var hive = @"Software\Titano.StartupTests." + Guid.NewGuid().ToString("N"); + try + { + using var root = Registry.CurrentUser.CreateSubKey(hive, writable: true); + var uploader = @"C:\Users\ada\AppData\Local\Programs\Titano\Uploader\Titano.Uploader.exe"; + var startup = new RunKeyStartupRegistration(uploader, root); + startup.SetEnabled(true); + Assert.True(startup.IsEnabled); + + TurnOff(root, StartupCommand.UploaderValue); + Assert.False(startup.IsEnabled, "shown as off"); + startup.Refresh(); + Assert.False(startup.IsEnabled, "a refresh keeps it off"); + + startup.SetEnabled(true); + Assert.True(startup.IsEnabled); + TurnOff(root, StartupCommand.UploaderValue); + startup.SetEnabled(false); + Assert.Null(Value(root, StartupCommand.RunKey, StartupCommand.UploaderValue)); + Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.UploaderValue)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false); + } + } + [Test] public void ScreenshotsAndPortableCopiesKeepTheChoiceInMemory() { @@ -42,4 +115,17 @@ public sealed class StartWithWindowsTests startup.SetEnabled(false); Assert.False(startup.IsEnabled); } + + /// What Task Manager writes when the user disables an entry: 0x03, three zero bytes, then when. + private static void TurnOff(RegistryKey root, string name) + { + using var approved = root.CreateSubKey(StartupApproval.RunKey, writable: true); + approved.SetValue(name, new byte[] { 0x03, 0, 0, 0, 0x60, 0x1B, 0x3C, 0x92, 0x8A, 0x3F, 0xDB, 0x01 }, RegistryValueKind.Binary); + } + + private static object? Value(RegistryKey root, string subKey, string name) + { + using var key = root.OpenSubKey(subKey); + return key?.GetValue(name); + } } diff --git a/tests/Titano.Core.Tests/Foundation/StartupApprovalTests.cs b/tests/Titano.Core.Tests/Foundation/StartupApprovalTests.cs new file mode 100644 index 00000000..1edaea59 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/StartupApprovalTests.cs @@ -0,0 +1,21 @@ +using Titano.Core.IO; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +/// The switch Task Manager's Startup tab keeps apart from a sign-in entry's command. +public sealed class StartupApprovalTests +{ + [Test] + public void AnOddFirstByteMeansTurnedOff() + { + // As Task Manager writes them: a state, three zero bytes, then the time it was turned off. + Assert.True(StartupApproval.IsTurnedOff([0x03, 0, 0, 0, 0x60, 0x1B, 0x3C, 0x92, 0x8A, 0x3F, 0xDB, 0x01])); + Assert.True(StartupApproval.IsTurnedOff([0x01, 0, 0, 0])); + Assert.False(StartupApproval.IsTurnedOff([0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); + Assert.False(StartupApproval.IsTurnedOff([0x06, 0, 0, 0])); + // Never touched in Task Manager, or a value of another type: the entry is on. + Assert.False(StartupApproval.IsTurnedOff(null)); + Assert.False(StartupApproval.IsTurnedOff([])); + } +}