fix(app): Start with Windows belongs to the copy that set it; the uninstaller removes sign-in entries

The client's HKCU Run value now counts as on only when it starts this executable, so a portable copy, a
second install or a development build no longer shows the box ticked, and starting one no longer rewrites the
entry to itself. Refresh only follows an entry whose program an update renamed in this copy's folder, and
unticking removes only this copy's entry. Portable copies keep the choice in memory and hide the Startup row,
since they leave nothing in the registry.

The uninstaller removes the client's and the Uploader's sign-in entries when they start a program of the folder
it removes. StartupCommand in Titano.Core holds the Run key, the value names and the command parsing shared by
both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 10:35:13 +00:00
1 parent d25ecca64e
commit 97c6484c74
8 files changed
+240 -35

No files matched your search

@@ -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);
/// <summary>Points an existing entry at the current executable (after an update moved it).</summary>
/// <summary>Points this copy's entry at the current executable (after an update renamed it).</summary>
void Refresh();
}
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> 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.
/// </summary>
public sealed class RunKeyStartWithWindows : IStartWithWindows
public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWithWindows
{
/// <summary>Starts the main window minimised on the taskbar.</summary>
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);
}
/// <summary>
/// The entry should now start <paramref name="current"/>: the program it names is gone from the folder
/// <paramref name="current"/> 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.
/// </summary>
internal static bool Follows(string? command, string? current, Func<string, bool> 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;
}
}
}
/// <summary>Screenshots and tests never touch the user's sign-in programs.</summary>
/// <summary>Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs.</summary>
public sealed class MemoryStartWithWindows : IStartWithWindows
{
public bool IsEnabled { get; private set; }
+2 -1
View File
@@ -134,7 +134,8 @@
<RadioButton Content="{l:Loc Settings.General.Theme.System}" IsChecked="{Binding IsSystemTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeSystem}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Startup}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Startup}"
Visibility="{Binding ShowsStartup, Converter={StaticResource BoolToVisibility}}">
<CheckBox Content="{l:Loc Settings.General.StartWithWindows}" IsChecked="{Binding StartWithWindows}" ToolTip="{l:Loc Tooltips.Settings.StartWithWindows}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Notifications}">
+7 -4
View File
@@ -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
}
}
/// <summary>Where "Start with Windows" is kept (the Run key); screenshots and tests keep it in memory.</summary>
/// <summary>Where "Start with Windows" is kept (the Run key); screenshots, tests and portable copies keep it in memory.</summary>
internal IStartWithWindows Startup { get; set; }
/// <summary>A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row.</summary>
public bool ShowsStartup => !Shell.Services.Environment.IsPortable;
/// <summary>Titano starts minimised when the user signs in to Windows.</summary>
public bool StartWithWindows
{
+61
View File
@@ -0,0 +1,61 @@
namespace Titano.Core.IO;
/// <summary>
/// The sign-in entries of Titano's programs: <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> values whose
/// command starts one executable with one option (<c>"C:\…\Titano.exe" --minimized</c>). Shared by the programs that
/// write them and the uninstaller that removes them; the paths are Windows paths, compared ignoring case.
/// </summary>
public static class StartupCommand
{
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// <summary>The client's value (Settings › General › Startup).</summary>
public const string ClientValue = "Titano";
/// <summary>The Uploader's value (its "Start with Windows").</summary>
public const string UploaderValue = "Titano Uploader";
/// <summary>The command that starts <paramref name="executable"/> with <paramref name="option"/>.</summary>
public static string Format(string executable, string option) => $"\"{executable}\" {option}";
/// <summary>
/// The program <paramref name="command"/> 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.
/// </summary>
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];
}
/// <summary><paramref name="command"/> starts <paramref name="executable"/>, not another copy of the program.</summary>
public static bool Starts(string? command, string? executable) =>
executable is { Length: > 0 } && string.Equals(Executable(command), executable, StringComparison.OrdinalIgnoreCase);
/// <summary>The program <paramref name="command"/> starts lies in <paramref name="directory"/> or one of its folders.</summary>
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 '/';
}
/// <summary>The folder of the program <paramref name="command"/> starts; null when it names none.</summary>
public static string? Folder(string? command) => Executable(command) is { } exe ? FolderOf(exe) : null;
/// <summary>The folder part of a Windows path (on any platform); null when it has none.</summary>
public static string? FolderOf(string path)
{
ArgumentNullException.ThrowIfNull(path);
var slash = path.LastIndexOfAny(['\\', '/']);
return slash > 0 ? path[..slash] : null;
}
}
+15
View File
@@ -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);
/// <summary>
/// Removes the sign-in entries of the client and the Uploader (<c>HKCU\…\Run</c>, written by the programs
/// themselves) that start a program of <paramref name="directory"/>; another copy's entries stay.
/// </summary>
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<string>)[StartupCommand.ClientValue, StartupCommand.UploaderValue])
{
if (StartupCommand.StartsFrom(run.GetValue(name) as string, directory)) run.DeleteValue(name, throwOnMissingValue: false);
}
}
/// <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)
{
+11 -2
View File
@@ -10,8 +10,8 @@ namespace Titano.Setup.Engine;
internal sealed record InstalledProduct(string Directory, InstallLog Log);
/// <summary>
/// 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 <c>removeUserData</c> is set by an explicit choice in the window.
/// </summary>
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
@@ -0,0 +1,45 @@
using Titano.App.Infrastructure;
using Titano.Core.IO;
using Titano.Testing;
namespace Titano.App.Tests.Infrastructure;
/// <summary>Settings › General › Startup: one sign-in entry shared by every copy of Titano, which no copy takes over by starting.</summary>
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);
}
}
@@ -0,0 +1,58 @@
using Titano.Core.IO;
using Titano.Testing;
namespace Titano.Core.Tests.Foundation;
/// <summary>The sign-in entries of the client and the Uploader: which copy they start, and which folder the uninstaller may clean.</summary>
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, @"\"));
}
}