fix(setup): handle install-folder services, startup entries, shared shortcuts and data

- Windows services whose program lies in the install folder (Titano.Server
  --install-service) are found in the registry and, through the Service
  Control Manager, stopped before files are replaced (they join the
  "programs running" prompt), started again after an upgrade that stopped
  them, deleted when an upgrade drops their program and on uninstall. An
  unelevated setup runs that step in an elevated copy (/SERVICES=...).
- The Server component installs for all users only (manifest allUsersOnly):
  choosing it moves a new install to Program Files and disables "Just me"
  with the reason; a per-user install cannot take it.
- Uninstall removes every HKCU Run value that starts a program in the folder
  (the Uploader's "Start with Windows").
- A shortcut that already starts an existing program elsewhere is neither
  retargeted nor logged, and a logged shortcut is deleted only while it
  still starts a program of this folder, so the two products no longer
  remove each other's "Titano Uploader" shortcuts.
- "Remove my data" lists and deletes only the data of this product's
  programs that no other installed Titano product uses (the desktop app and
  the Uploader share %LOCALAPPDATA%\Titano and its logs folder).
- The .titano file type is named in setup's language (Setup.FileType.*).

Setup tests run in Titano.App.Tests on Windows CI.

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:29:16 +00:00
1 parent 81f10379c8
commit 4f6bbfba5d
32 files changed
+1175 -88

No files matched your search

+4 -2
View File
@@ -41,13 +41,15 @@ for community review. Development happens elsewhere; please use the issues here
`Get-FileHash .\Titano-Setup-<version>.exe -Algorithm SHA256` and compare the value with the line for that file `Get-FileHash .\Titano-Setup-<version>.exe -Algorithm SHA256` and compare the value with the line for that file
in `SHA256SUMS` of the same release. in `SHA256SUMS` of the same release.
3. Run the setup. It installs for the current user into `%LOCALAPPDATA%\Programs\Titano` without administrator 3. Run the setup. It installs for the current user into `%LOCALAPPDATA%\Programs\Titano` without administrator
rights; choose *All users* to install into `Program Files` (Windows asks for permission). rights; choose *All users* to install into `Program Files` (Windows asks for permission). The *Server* component
runs as a Windows service, so choosing it installs for all users.
- **Upgrade:** Titano checks this repository at start (you can turn this off in Settings › Updates) and shows a notice - **Upgrade:** Titano checks this repository at start (you can turn this off in Settings › Updates) and shows a notice
when a new version exists. *Download* fetches the setup, verifies it against `SHA256SUMS` and shows it in Explorer; when a new version exists. *Download* fetches the setup, verifies it against `SHA256SUMS` and shows it in Explorer;
run it to upgrade in place. Your archive, settings and index are kept. run it to upgrade in place. Your archive, settings and index are kept.
- **Uninstall:** Windows Settings › Apps › Installed apps › Titano › Uninstall. Your photos and archive are never - **Uninstall:** Windows Settings › Apps › Installed apps › Titano › Uninstall. Your photos and archive are never
touched; the program data folder (`%LOCALAPPDATA%\Titano`) is removed only if you tick the option to do so. touched; the program data in `%LOCALAPPDATA%\Titano` is removed only if you tick the option to do so, and only the
part no other installed Titano program still uses. A Titano Server service of that folder is stopped and removed.
- **Silent install** (IT deployment): `Titano-Setup-<version>.exe /S [/DIR="D:\Apps\Titano"] [/ALLUSERS] - **Silent install** (IT deployment): `Titano-Setup-<version>.exe /S [/DIR="D:\Apps\Titano"] [/ALLUSERS]
[/COMPONENTS=Titano,Uploader,Server] [/NODESKTOP] [/NOSTARTMENU] [/LANG=it]`. Silent uninstall: [/COMPONENTS=Titano,Uploader,Server] [/NODESKTOP] [/NOSTARTMENU] [/LANG=it]`. Silent uninstall:
`"%LOCALAPPDATA%\Programs\Titano\Uninstall Titano.exe" /uninstall /S`. `"%LOCALAPPDATA%\Programs\Titano\Uninstall Titano.exe" /uninstall /S`.
+1
View File
@@ -31,6 +31,7 @@
<data name="Setup.Field.Language" xml:space="preserve"><value>Language</value></data> <data name="Setup.Field.Language" xml:space="preserve"><value>Language</value></data>
<data name="Setup.Field.Options" xml:space="preserve"><value>Options</value></data> <data name="Setup.Field.Options" xml:space="preserve"><value>Options</value></data>
<data name="Setup.Field.Scope" xml:space="preserve"><value>Install for</value></data> <data name="Setup.Field.Scope" xml:space="preserve"><value>Install for</value></data>
<data name="Setup.FileType.Project" xml:space="preserve"><value>Titano project</value></data>
<data name="Setup.Folder.Browse" xml:space="preserve"><value>Browse</value></data> <data name="Setup.Folder.Browse" xml:space="preserve"><value>Browse</value></data>
<data name="Setup.Header.Upgrade" xml:space="preserve"><value>Version {0} · installed {1}</value></data> <data name="Setup.Header.Upgrade" xml:space="preserve"><value>Version {0} · installed {1}</value></data>
<data name="Setup.Header.Version" xml:space="preserve"><value>Version {0}</value></data> <data name="Setup.Header.Version" xml:space="preserve"><value>Version {0}</value></data>
+5
View File
@@ -560,6 +560,7 @@
<data name="Tooltips.Settings.ThumbnailMemory" xml:space="preserve"><value>Decoded thumbnails kept in memory; more scrolls faster and uses more RAM · Enter applies</value></data> <data name="Tooltips.Settings.ThumbnailMemory" xml:space="preserve"><value>Decoded thumbnails kept in memory; more scrolls faster and uses more RAM · Enter applies</value></data>
<data name="Tooltips.Settings.UsageCounts" xml:space="preserve"><value>Send a daily anonymous count of versions and languages in use; nothing else, off by default</value></data> <data name="Tooltips.Settings.UsageCounts" xml:space="preserve"><value>Send a daily anonymous count of versions and languages in use; nothing else, off by default</value></data>
<data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Install in Program Files for every account · asks for administrator approval</value></data> <data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Install in Program Files for every account · asks for administrator approval</value></data>
<data name="Tooltips.Setup.AllUsersOnly" xml:space="preserve"><value>{0} · it runs as a Windows service, so it installs for all users in Program Files</value></data>
<data name="Tooltips.Setup.Back" xml:space="preserve"><value>Return to the options without changing anything</value></data> <data name="Tooltips.Setup.Back" xml:space="preserve"><value>Return to the options without changing anything</value></data>
<data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Choose the installation folder</value></data> <data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Choose the installation folder</value></data>
<data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Close setup without changing anything</value></data> <data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Close setup without changing anything</value></data>
@@ -575,12 +576,16 @@
<data name="Tooltips.Setup.Install" xml:space="preserve"><value>Copy the selected programs and register them with Windows</value></data> <data name="Tooltips.Setup.Install" xml:space="preserve"><value>Copy the selected programs and register them with Windows</value></data>
<data name="Tooltips.Setup.Installed" xml:space="preserve"><value>Folder of the installed programs</value></data> <data name="Tooltips.Setup.Installed" xml:space="preserve"><value>Folder of the installed programs</value></data>
<data name="Tooltips.Setup.JustMe" xml:space="preserve"><value>Install in your user folder · no administrator rights needed</value></data> <data name="Tooltips.Setup.JustMe" xml:space="preserve"><value>Install in your user folder · no administrator rights needed</value></data>
<data name="Tooltips.Setup.JustMeLocked" xml:space="preserve"><value>{0} runs as a Windows service, so it installs for all users only</value></data>
<data name="Tooltips.Setup.Language" xml:space="preserve"><value>Language of this setup</value></data> <data name="Tooltips.Setup.Language" xml:space="preserve"><value>Language of this setup</value></data>
<data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Open the program when setup finishes</value></data> <data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Open the program when setup finishes</value></data>
<data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Open the installed program</value></data> <data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Open the installed program</value></data>
<data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Already installed here · uninstall it first to change folder or scope</value></data> <data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Already installed here · uninstall it first to change folder or scope</value></data>
<data name="Tooltips.Setup.NeedsAllUsers" xml:space="preserve"><value>Runs as a Windows service, so it installs for all users only · this copy is installed for you alone; uninstall it first to add it</value></data>
<data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Select at least one program to install</value></data> <data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Select at least one program to install</value></data>
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Also delete %LOCALAPPDATA%\Titano: database, backups, cache, settings, logs, the uploader queue and sign-in · photos in archives are kept</value></data> <data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Also delete %LOCALAPPDATA%\Titano: database, backups, cache, settings, logs, the uploader queue and sign-in · photos in archives are kept</value></data>
<data name="Tooltips.Setup.RemoveDataTitano" xml:space="preserve"><value>Also delete Titano’s database, backups, cache, settings and logs in %LOCALAPPDATA%\Titano · the Uploader’s files and photos in archives are kept</value></data>
<data name="Tooltips.Setup.RemoveDataUploader" xml:space="preserve"><value>Also delete the Uploader’s queue, settings, sign-in and logs in %LOCALAPPDATA%\Titano · Titano’s files and photos in archives are kept</value></data>
<data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Run the same step again</value></data> <data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Run the same step again</value></data>
<data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Add the programs to the Start menu</value></data> <data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Add the programs to the Start menu</value></data>
<data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Remove programs, shortcuts and file types · your data is kept unless selected</value></data> <data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Remove programs, shortcuts and file types · your data is kept unless selected</value></data>
+1
View File
@@ -31,6 +31,7 @@
<data name="Setup.Field.Language" xml:space="preserve"><value>Lingua</value></data> <data name="Setup.Field.Language" xml:space="preserve"><value>Lingua</value></data>
<data name="Setup.Field.Options" xml:space="preserve"><value>Opzioni</value></data> <data name="Setup.Field.Options" xml:space="preserve"><value>Opzioni</value></data>
<data name="Setup.Field.Scope" xml:space="preserve"><value>Installa per</value></data> <data name="Setup.Field.Scope" xml:space="preserve"><value>Installa per</value></data>
<data name="Setup.FileType.Project" xml:space="preserve"><value>Progetto Titano</value></data>
<data name="Setup.Folder.Browse" xml:space="preserve"><value>Sfoglia</value></data> <data name="Setup.Folder.Browse" xml:space="preserve"><value>Sfoglia</value></data>
<data name="Setup.Header.Upgrade" xml:space="preserve"><value>Versione {0} · installata {1}</value></data> <data name="Setup.Header.Upgrade" xml:space="preserve"><value>Versione {0} · installata {1}</value></data>
<data name="Setup.Header.Version" xml:space="preserve"><value>Versione {0}</value></data> <data name="Setup.Header.Version" xml:space="preserve"><value>Versione {0}</value></data>
+5
View File
@@ -560,6 +560,7 @@
<data name="Tooltips.Settings.ThumbnailMemory" xml:space="preserve"><value>Miniature decodificate tenute in memoria; più sono, più lo scorrimento è veloce e più RAM serve · Invio applica</value></data> <data name="Tooltips.Settings.ThumbnailMemory" xml:space="preserve"><value>Miniature decodificate tenute in memoria; più sono, più lo scorrimento è veloce e più RAM serve · Invio applica</value></data>
<data name="Tooltips.Settings.UsageCounts" xml:space="preserve"><value>Invia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinita</value></data> <data name="Tooltips.Settings.UsageCounts" xml:space="preserve"><value>Invia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinita</value></data>
<data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore</value></data> <data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore</value></data>
<data name="Tooltips.Setup.AllUsersOnly" xml:space="preserve"><value>{0} · è un servizio di Windows, quindi si installa per tutti gli utenti in Programmi</value></data>
<data name="Tooltips.Setup.Back" xml:space="preserve"><value>Torna alle opzioni senza modificare nulla</value></data> <data name="Tooltips.Setup.Back" xml:space="preserve"><value>Torna alle opzioni senza modificare nulla</value></data>
<data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Scegli la cartella di installazione</value></data> <data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Scegli la cartella di installazione</value></data>
<data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Chiudi l'installazione senza modificare nulla</value></data> <data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Chiudi l'installazione senza modificare nulla</value></data>
@@ -575,12 +576,16 @@
<data name="Tooltips.Setup.Install" xml:space="preserve"><value>Copia i programmi selezionati e registrali in Windows</value></data> <data name="Tooltips.Setup.Install" xml:space="preserve"><value>Copia i programmi selezionati e registrali in Windows</value></data>
<data name="Tooltips.Setup.Installed" xml:space="preserve"><value>Cartella dei programmi installati</value></data> <data name="Tooltips.Setup.Installed" xml:space="preserve"><value>Cartella dei programmi installati</value></data>
<data name="Tooltips.Setup.JustMe" xml:space="preserve"><value>Installa nella tua cartella utente · non servono diritti di amministratore</value></data> <data name="Tooltips.Setup.JustMe" xml:space="preserve"><value>Installa nella tua cartella utente · non servono diritti di amministratore</value></data>
<data name="Tooltips.Setup.JustMeLocked" xml:space="preserve"><value>{0} è un servizio di Windows, quindi si installa solo per tutti gli utenti</value></data>
<data name="Tooltips.Setup.Language" xml:space="preserve"><value>Lingua di questa installazione</value></data> <data name="Tooltips.Setup.Language" xml:space="preserve"><value>Lingua di questa installazione</value></data>
<data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Apri il programma al termine dell'installazione</value></data> <data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Apri il programma al termine dell'installazione</value></data>
<data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Apri il programma installato</value></data> <data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Apri il programma installato</value></data>
<data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Già installato qui · disinstallalo prima per cambiare cartella o ambito</value></data> <data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Già installato qui · disinstallalo prima per cambiare cartella o ambito</value></data>
<data name="Tooltips.Setup.NeedsAllUsers" xml:space="preserve"><value>È un servizio di Windows, quindi si installa solo per tutti gli utenti · questa copia è installata solo per te; disinstallala prima per aggiungerlo</value></data>
<data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Seleziona almeno un programma da installare</value></data> <data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Seleziona almeno un programma da installare</value></data>
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Elimina anche %LOCALAPPDATA%\Titano: database, backup, cache, impostazioni, log, coda e accesso dell'uploader · le foto negli archivi restano</value></data> <data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Elimina anche %LOCALAPPDATA%\Titano: database, backup, cache, impostazioni, log, coda e accesso dell'uploader · le foto negli archivi restano</value></data>
<data name="Tooltips.Setup.RemoveDataTitano" xml:space="preserve"><value>Elimina anche database, backup, cache, impostazioni e log di Titano in %LOCALAPPDATA%\Titano · i file dell'uploader e le foto negli archivi restano</value></data>
<data name="Tooltips.Setup.RemoveDataUploader" xml:space="preserve"><value>Elimina anche coda, impostazioni, accesso e log dell'uploader in %LOCALAPPDATA%\Titano · i file di Titano e le foto negli archivi restano</value></data>
<data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Esegui di nuovo lo stesso passaggio</value></data> <data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Esegui di nuovo lo stesso passaggio</value></data>
<data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Aggiungi i programmi al menu Start</value></data> <data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Aggiungi i programmi al menu Start</value></data>
<data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta</value></data> <data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta</value></data>
@@ -155,6 +155,12 @@ public sealed class PayloadComponent
/// <summary>Installed size in bytes (sum of the component's files).</summary> /// <summary>Installed size in bytes (sum of the component's files).</summary>
public long EstimatedSize { get; init; } public long EstimatedSize { get; init; }
/// <summary>
/// Installs only for all users (Program Files): the component runs as a Windows service under LocalSystem, which
/// must not start a program from a folder its user can write to.
/// </summary>
public bool AllUsersOnly { get; init; }
} }
/// <summary>One installed file and where its bytes live in the data region.</summary> /// <summary>One installed file and where its bytes live in the data region.</summary>
+3 -2
View File
@@ -5,8 +5,8 @@ using Titano.Core.IO;
namespace Titano.Core.Packaging; namespace Titano.Core.Packaging;
/// <summary>A component to pack: its manifest identity and the folder whose whole tree it installs.</summary> /// <summary>A component to pack: its manifest identity, the folder whose whole tree it installs and whether it needs an all-users install.</summary>
public sealed record PayloadComponentSource(string Id, string DisplayName, bool DefaultSelected, string Folder); public sealed record PayloadComponentSource(string Id, string DisplayName, bool DefaultSelected, string Folder, bool AllUsersOnly = false);
/// <summary>Everything the packer needs besides the setup program.</summary> /// <summary>Everything the packer needs besides the setup program.</summary>
public sealed class PayloadSource public sealed class PayloadSource
@@ -48,6 +48,7 @@ public static class PayloadWriter
Id = c.Id, Id = c.Id,
DisplayName = c.DisplayName, DisplayName = c.DisplayName,
DefaultSelected = c.DefaultSelected, DefaultSelected = c.DefaultSelected,
AllUsersOnly = c.AllUsersOnly,
EstimatedSize = files.Where(f => f.Component == c.Id).Sum(f => f.Size), EstimatedSize = files.Where(f => f.Component == c.Id).Sum(f => f.Size),
}).ToList(); }).ToList();
var manifest = new PayloadManifest var manifest = new PayloadManifest
+20 -1
View File
@@ -1,4 +1,5 @@
using System.Text; using System.Text;
using Titano.Setup.Engine;
namespace Titano.Setup.Cli; namespace Titano.Setup.Cli;
@@ -7,7 +8,8 @@ namespace Titano.Setup.Cli;
/// <c>/S</c> silent · <c>/DIR=path</c> · <c>/COMPONENTS=Titano,Uploader</c> · <c>/ALLUSERS</c> · <c>/NODESKTOP</c> · /// <c>/S</c> silent · <c>/DIR=path</c> · <c>/COMPONENTS=Titano,Uploader</c> · <c>/ALLUSERS</c> · <c>/NODESKTOP</c> ·
/// <c>/NOSTARTMENU</c> · <c>/LAUNCH</c> · <c>/LANG=it</c> · <c>/uninstall</c>. /// <c>/NOSTARTMENU</c> · <c>/LAUNCH</c> · <c>/LANG=it</c> · <c>/uninstall</c>.
/// Internal: <c>/ELEVATED</c> (relaunched for administrator rights), <c>/CLEANUP=path /WAITPID=n</c> (removes the /// Internal: <c>/ELEVATED</c> (relaunched for administrator rights), <c>/CLEANUP=path /WAITPID=n</c> (removes the
/// uninstaller after the uninstall process exits). /// uninstaller after the uninstall process exits), <c>/SERVICES=stop,prune,start,remove /DIR=path</c> (the elevated
/// step that stops, starts or deletes the Windows services of an installation).
/// </summary> /// </summary>
internal sealed record SetupArguments internal sealed record SetupArguments
{ {
@@ -23,6 +25,7 @@ internal sealed record SetupArguments
public bool Elevated { get; init; } public bool Elevated { get; init; }
public string? CleanupTarget { get; init; } public string? CleanupTarget { get; init; }
public int WaitProcessId { get; init; } public int WaitProcessId { get; init; }
public ServiceActions Services { get; init; }
/// <summary>Parses <paramref name="args"/>; throws <see cref="ArgumentException"/> for unknown or malformed switches.</summary> /// <summary>Parses <paramref name="args"/>; throws <see cref="ArgumentException"/> for unknown or malformed switches.</summary>
public static SetupArguments Parse(IEnumerable<string> args) public static SetupArguments Parse(IEnumerable<string> args)
@@ -48,10 +51,12 @@ internal sealed record SetupArguments
("COMPONENTS", { Length: > 0 }) => result with { Components = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) }, ("COMPONENTS", { Length: > 0 }) => result with { Components = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) },
("CLEANUP", { Length: > 0 }) => result with { CleanupTarget = value.Trim('"') }, ("CLEANUP", { Length: > 0 }) => result with { CleanupTarget = value.Trim('"') },
("WAITPID", { Length: > 0 }) when int.TryParse(value, out var pid) && pid > 0 => result with { WaitProcessId = pid }, ("WAITPID", { Length: > 0 }) when int.TryParse(value, out var pid) && pid > 0 => result with { WaitProcessId = pid },
("SERVICES", { Length: > 0 }) => result with { Services = ParseServices(value) },
_ => throw new ArgumentException($"Unknown or malformed switch '{arg}'."), _ => throw new ArgumentException($"Unknown or malformed switch '{arg}'."),
}; };
} }
if (result.CleanupTarget is not null && result.WaitProcessId == 0) throw new ArgumentException("/CLEANUP needs /WAITPID."); if (result.CleanupTarget is not null && result.WaitProcessId == 0) throw new ArgumentException("/CLEANUP needs /WAITPID.");
if (result.Services != ServiceActions.None && result.Directory is null) throw new ArgumentException("/SERVICES needs /DIR.");
return result; return result;
} }
@@ -67,9 +72,23 @@ internal sealed record SetupArguments
if (NoStartMenu) yield return "/NOSTARTMENU"; if (NoStartMenu) yield return "/NOSTARTMENU";
if (Launch) yield return "/LAUNCH"; if (Launch) yield return "/LAUNCH";
if (Language is not null) yield return "/LANG=" + Language; if (Language is not null) yield return "/LANG=" + Language;
if (Services != ServiceActions.None) yield return "/SERVICES=" + Services.ToString().Replace(" ", string.Empty, StringComparison.Ordinal).ToLowerInvariant();
if (Elevated) yield return "/ELEVATED"; if (Elevated) yield return "/ELEVATED";
} }
/// <summary>A comma-separated list of <see cref="ServiceActions"/> names, in any case.</summary>
private static ServiceActions ParseServices(string value)
{
var actions = ServiceActions.None;
foreach (var name in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (!Enum.TryParse<ServiceActions>(name, ignoreCase: true, out var action) || action == ServiceActions.None || !Enum.IsDefined(action))
throw new ArgumentException($"Unknown service action '{name}'.");
actions |= action;
}
return actions;
}
/// <summary> /// <summary>
/// Joins arguments into one command line that <c>CommandLineToArgvW</c> splits back into the same strings /// Joins arguments into one command line that <c>CommandLineToArgvW</c> splits back into the same strings
/// (quotes around spaces, backslashes doubled before a quote). /// (quotes around spaces, backslashes doubled before a quote).
+60
View File
@@ -0,0 +1,60 @@
using System.IO;
namespace Titano.Setup.Engine;
/// <summary>The program a command line registered with Windows starts: a service's image path, a Run value.</summary>
internal static class CommandProgram
{
/// <summary>
/// The first token, quoted or up to <c>.exe</c>, with environment variables expanded; for the <c>dotnet</c> host,
/// the assembly it runs. Null when the line names no full path.
/// </summary>
public static string? Of(string commandLine)
{
var line = Environment.ExpandEnvironmentVariables(commandLine).Trim();
var first = NextToken(ref line);
if (first is null) return null;
if (Path.GetFileNameWithoutExtension(first).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) first = NextToken(ref line);
return first is not null && Path.IsPathFullyQualified(first) ? first : null;
}
/// <summary>True when <paramref name="commandLine"/> starts a program inside <paramref name="directory"/>.</summary>
public static bool IsInside(string commandLine, string directory) => Of(commandLine) is { } program && IsPathInside(program, directory);
/// <summary><see cref="SetupPaths.IsSameOrInside"/> that answers false for a path Windows cannot normalise.</summary>
public static bool IsPathInside(string path, string directory)
{
try
{
return SetupPaths.IsSameOrInside(path, directory);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return false;
}
}
/// <summary>Takes the next token of a command line: quoted, or up to <c>.exe</c> followed by a space, or up to the next space.</summary>
private static string? NextToken(ref string line)
{
line = line.TrimStart();
if (line.Length == 0) return null;
string token;
if (line[0] == '"')
{
var close = line.IndexOf('"', 1);
token = close < 0 ? line[1..] : line[1..close];
line = close < 0 ? string.Empty : line[(close + 1)..];
}
else
{
// An unquoted path with spaces ("C:\Program Files\Titano\Titano.Server.exe --service") ends at its extension.
var exe = line.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);
var space = line.IndexOf(' ');
var end = exe >= 0 && (exe + 4 == line.Length || line[exe + 4] == ' ') ? exe + 4 : space >= 0 ? space : line.Length;
token = line[..end];
line = line[end..];
}
return token.Length == 0 ? null : token;
}
}
+31 -5
View File
@@ -1,6 +1,8 @@
using System.Globalization;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using Titano.Core.Diagnostics; using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Packaging; using Titano.Core.Packaging;
using Titano.Setup.Cli; using Titano.Setup.Cli;
using Titano.Setup.Interop; using Titano.Setup.Interop;
@@ -74,7 +76,7 @@ internal sealed class InstallEngine(PayloadReader payload)
foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name); foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name);
foreach (var a in fileTypes) foreach (var a in fileTypes)
SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, a.Description, PayloadPath.Resolve(directory, a.Target)); SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, FileTypeName(a), PayloadPath.Resolve(directory, a.Target));
if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged(); if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged();
var uninstallerPath = Path.Combine(directory, uninstaller); var uninstallerPath = Path.Combine(directory, uninstaller);
@@ -86,13 +88,27 @@ internal sealed class InstallEngine(PayloadReader payload)
return log; return log;
} }
private static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute<AssemblyCompanyAttribute>()?.Company ?? "Titano"; /// <summary>The Add/Remove Programs publisher of every Titano product (they share the user data folder).</summary>
public static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute<AssemblyCompanyAttribute>()?.Company ?? "Titano";
/// <summary>
/// The file type name Explorer shows, in setup's language (or <paramref name="culture"/>):
/// <c>Setup.FileType.&lt;last part of the ProgID&gt;</c> ("Titano.Project" → <c>Setup.FileType.Project</c>), else the
/// manifest's English description.
/// </summary>
public static string FileTypeName(PayloadAssociation association, CultureInfo? culture = null) =>
Loc.Get("Setup.FileType." + association.ProgId[(association.ProgId.LastIndexOf('.') + 1)..], culture ?? Loc.Culture) ?? association.Description;
private static string? AboutUrl => private static string? AboutUrl =>
typeof(InstallEngine).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo typeof(InstallEngine).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo
? "https://github.com/" + repo ? "https://github.com/" + repo
: null; : null;
/// <summary>
/// The shortcuts to create. A shortcut of the same name that starts an existing program elsewhere (the same
/// program installed by another Titano product, or the user's own) is left as it is and not logged, so neither
/// install retargets or removes the other's.
/// </summary>
private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory) private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory)
{ {
var selected = new HashSet<string>(request.Components, StringComparer.OrdinalIgnoreCase); var selected = new HashSet<string>(request.Components, StringComparer.OrdinalIgnoreCase);
@@ -100,10 +116,20 @@ internal sealed class InstallEngine(PayloadReader payload)
foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component))) foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component)))
{ {
var target = PayloadPath.Resolve(directory, s.Target); var target = PayloadPath.Resolve(directory, s.Target);
if (s.StartMenu && request.StartMenuShortcuts) result.Add((Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name)); if (s.StartMenu && request.StartMenuShortcuts) Add(Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name);
if (s.Desktop && request.DesktopShortcuts) result.Add((Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name)); if (s.Desktop && request.DesktopShortcuts) Add(Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name);
} }
return result; return result;
void Add(string link, string target, string name)
{
if (ShellLink.TargetOf(link) is { } current && !CommandProgram.IsPathInside(current, directory) && File.Exists(current))
{
Log.Info("setup", $"Shortcut '{link}' starts '{current}'; left as it is");
return;
}
result.Add((link, target, name));
}
} }
private List<PayloadAssociation> PlanFileTypes(InstallRequest request) private List<PayloadAssociation> PlanFileTypes(InstallRequest request)
@@ -118,7 +144,7 @@ internal sealed class InstallEngine(PayloadReader payload)
var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList(); var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList();
if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete); if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete);
foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase)) foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase))
UninstallEngine.DeleteShortcut(link, previous.Scope); UninstallEngine.DeleteShortcut(link, previous.Scope, directory);
foreach (var a in previous.Associations.Except(current.Associations)) foreach (var a in previous.Associations.Except(current.Associations))
{ {
if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId); if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId);
+28 -2
View File
@@ -1,3 +1,4 @@
using Titano.Core.Diagnostics;
using Titano.Core.Packaging; using Titano.Core.Packaging;
using Titano.Setup.Cli; using Titano.Setup.Cli;
@@ -5,7 +6,9 @@ namespace Titano.Setup.Engine;
/// <summary> /// <summary>
/// Where and what to install before the user changes anything: an existing installation fixes folder and scope /// Where and what to install before the user changes anything: an existing installation fixes folder and scope
/// (upgrade in place) and suggests its components; otherwise the switches, then the manifest defaults, apply. /// (upgrade in place) and suggests its components; otherwise the switches, then the manifest defaults, apply. A
/// component that installs for all users only (<see cref="PayloadComponent.AllUsersOnly"/>, the Server) makes a new
/// installation an all-users one; a per-user installation upgraded in place cannot take it.
/// </summary> /// </summary>
internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList<string> Components, ExistingInstall? Existing) internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList<string> Components, ExistingInstall? Existing)
{ {
@@ -13,7 +16,6 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn
{ {
var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product)); var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product));
var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser);
var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product);
IReadOnlyList<string> components; IReadOnlyList<string> components;
if (arguments.Components is { } requested) if (arguments.Components is { } requested)
@@ -28,9 +30,33 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn
var kept = previous?.Select(manifest.FindComponent).OfType<PayloadComponent>().Select(c => c.Id).ToList(); var kept = previous?.Select(manifest.FindComponent).OfType<PayloadComponent>().Select(c => c.Id).ToList();
components = kept is { Count: > 0 } ? kept : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)]; components = kept is { Count: > 0 } ? kept : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)];
} }
var allUsersOnly = components.Where(id => manifest.FindComponent(id)!.AllUsersOnly).ToList();
if (allUsersOnly.Count > 0 && scope == InstallScope.CurrentUser)
{
if (existing is null)
{
scope = InstallScope.AllUsers;
}
else if (arguments.Components is not null)
{
throw new SetupException(SetupExitCode.InvalidArguments,
$"{string.Join(", ", allUsersOnly)} installs for all users only; {manifest.Product} is installed for the current user.");
}
else
{
// An earlier per-user install carried it: the upgrade drops it, and its service with it (Prune).
Log.Warning("setup", $"{string.Join(", ", allUsersOnly)} not kept: it installs for all users only");
components = [.. components.Except(allUsersOnly, StringComparer.OrdinalIgnoreCase)];
}
}
var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product);
return new InstallPlan(scope, directory, components, existing); return new InstallPlan(scope, directory, components, existing);
} }
/// <summary>False for a component that installs for all users only when a per-user installation is upgraded.</summary>
public bool CanInstall(PayloadComponent component) => !(component.AllUsersOnly && Existing is { Scope: InstallScope.CurrentUser });
/// <summary>Executables to look for among running processes: the new payload's and the previous install's.</summary> /// <summary>Executables to look for among running processes: the new payload's and the previous install's.</summary>
public static IEnumerable<string> Programs(PayloadManifest manifest, string directory) => public static IEnumerable<string> Programs(PayloadManifest manifest, string directory) =>
manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []); manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []);
@@ -0,0 +1,238 @@
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Setup.Cli;
using static Titano.Setup.Interop.ServiceNative;
namespace Titano.Setup.Engine;
/// <summary>A Windows service whose program lies inside an installation folder (<c>Titano.Server.exe --install-service</c>).</summary>
/// <param name="Name">Service key name (<c>TitanoServer</c>).</param>
/// <param name="Program">Full path of the program the service starts.</param>
/// <param name="AutoStart">Starts with Windows (start type automatic).</param>
internal sealed record InstalledService(string Name, string DisplayName, string Program, bool AutoStart);
/// <summary>What setup does with the services of an installation; several may be combined.</summary>
[Flags]
internal enum ServiceActions
{
None = 0,
/// <summary>Stops the running ones, before their files are replaced.</summary>
Stop = 1,
/// <summary>Deletes the ones whose program no longer exists (an upgrade dropped the component).</summary>
Prune = 2,
/// <summary>Starts the automatic ones that are stopped (after an upgrade that stopped them).</summary>
Start = 4,
/// <summary>Stops and deletes them all (uninstall), so no service is left pointing at a deleted program.</summary>
Remove = 8,
}
/// <summary>
/// Services registered from an installation folder. Setup ignored them before: an upgrade failed while the service
/// kept its files open, and an uninstall left an automatic LocalSystem service pointing at a deleted path. They are
/// found in the registry (no administrator rights needed) and stopped, started or deleted through the Service
/// Control Manager, which needs administrator rights: an unelevated setup runs that step in an elevated copy of
/// itself (<c>/SERVICES=…</c>).
/// </summary>
internal static class InstalledServices
{
private const string ServicesKey = @"SYSTEM\CurrentControlSet\Services";
/// <summary>SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS: programs, not drivers.</summary>
private const int Win32Service = 0x30;
private const int AutoStartType = 2;
/// <summary>How long a service may take to stop and its process to exit (as programs asked to close).</summary>
public static readonly TimeSpan StopTimeout = TimeSpan.FromSeconds(30);
/// <summary>Services whose program lies inside <paramref name="directory"/>; services already marked for deletion are skipped.</summary>
public static IReadOnlyList<InstalledService> Find(string directory)
{
var found = new List<InstalledService>();
using var services = Registry.LocalMachine.OpenSubKey(ServicesKey);
if (services is null) return found;
foreach (var name in services.GetSubKeyNames())
{
try
{
using var key = services.OpenSubKey(name);
if (key is null || key.GetValue("Type") is not int type || (type & Win32Service) == 0) continue;
if (key.GetValue("DeleteFlag") is int deleting && deleting != 0) continue;
if (key.GetValue("ImagePath") is not string image || CommandProgram.Of(image) is not { } program || !CommandProgram.IsPathInside(program, directory)) continue;
var display = key.GetValue("DisplayName") as string;
found.Add(new InstalledService(name, display is { Length: > 0 } && display[0] != '@' ? display : name, program, key.GetValue("Start") is AutoStartType));
}
catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException)
{
// A key this account may not read is not one setup registered.
Log.Debug("setup", $"Service key {name} not read: {ex.Message}");
}
}
return found;
}
/// <summary>True when the service is not stopped (running, starting, stopping or paused), or its state cannot be read.</summary>
public static unsafe bool IsRunning(InstalledService service)
{
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) return true;
try
{
var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus);
if (handle == 0) return Marshal.GetLastPInvokeError() != ErrorServiceDoesNotExist;
try
{
return !TryQuery(handle, out var status) || status.CurrentState != StateStopped;
}
finally
{
CloseServiceHandle(handle);
}
}
finally
{
CloseServiceHandle(manager);
}
}
/// <summary>True when <paramref name="actions"/> would change something about <paramref name="services"/>.</summary>
public static bool NeedsWork(IReadOnlyList<InstalledService> services, ServiceActions actions) => services.Any(s =>
actions.HasFlag(ServiceActions.Remove)
|| (actions.HasFlag(ServiceActions.Prune) && !File.Exists(s.Program))
|| (actions.HasFlag(ServiceActions.Stop) && IsRunning(s))
|| (actions.HasFlag(ServiceActions.Start) && s.AutoStart && File.Exists(s.Program) && !IsRunning(s)));
/// <summary>
/// Applies <paramref name="actions"/> to the services of <paramref name="directory"/>: in this process when it has
/// administrator rights, otherwise in an elevated copy (UAC prompt owned by <paramref name="owner"/>). Success
/// when there is nothing to do.
/// </summary>
public static async Task<SetupExitCode> ApplyAsync(string directory, ServiceActions actions, IntPtr owner)
{
if (!NeedsWork(Find(directory), actions)) return SetupExitCode.Success;
if (Elevation.IsElevated) return await Task.Run(() => Apply(directory, actions)).ConfigureAwait(false);
Log.Info("setup", $"Asking for administrator rights to {actions} the services of '{directory}'");
var arguments = new SetupArguments { Services = actions, Directory = directory, Language = Loc.Culture.Name };
return Elevation.Start(arguments, owner) is { } child ? await Elevation.WaitAsync(child, null).ConfigureAwait(false) : SetupExitCode.ElevationDeclined;
}
/// <summary>
/// The elevated step (<c>/SERVICES=… /DIR=…</c>): applies the actions in this process. Refuses a folder setup would not
/// install to, and needs administrator rights.
/// </summary>
public static SetupExitCode RunStep(SetupArguments arguments)
{
if (arguments.Directory is not { } directory || !SetupPaths.IsUsableInstallDirectory(directory)) return SetupExitCode.InvalidArguments;
return Elevation.IsElevated ? Apply(directory, arguments.Services) : SetupExitCode.ElevationDeclined;
}
/// <summary>
/// Applies <paramref name="actions"/> in this process (administrator rights). Returns
/// <see cref="SetupExitCode.ProgramRunning"/> when a service did not stop in time, <see cref="SetupExitCode.Failed"/>
/// when the Service Control Manager refused a step (logged).
/// </summary>
public static unsafe SetupExitCode Apply(string directory, ServiceActions actions)
{
var services = Find(directory);
if (services.Count == 0) return SetupExitCode.Success;
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) return Failure("Service Control Manager not opened", null);
try
{
foreach (var service in services)
{
var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus | ServiceStop | ServiceStart | Delete);
if (handle == 0)
{
if (Marshal.GetLastPInvokeError() == ErrorServiceDoesNotExist) continue;
return Failure("Service not opened", service);
}
try
{
var remove = actions.HasFlag(ServiceActions.Remove) || (actions.HasFlag(ServiceActions.Prune) && !File.Exists(service.Program));
if ((remove || actions.HasFlag(ServiceActions.Stop)) && !Stop(handle, service)) return SetupExitCode.ProgramRunning;
if (remove)
{
if (!DeleteService(handle) && Marshal.GetLastPInvokeError() != ErrorServiceMarkedForDelete) return Failure("Service not deleted", service);
Log.Info("setup", $"Service {service.Name} deleted");
}
else if (actions.HasFlag(ServiceActions.Start) && service.AutoStart && File.Exists(service.Program))
{
if (!StartServiceW(handle, 0, 0) && Marshal.GetLastPInvokeError() != ErrorServiceAlreadyRunning) return Failure("Service not started", service);
Log.Info("setup", $"Service {service.Name} started");
}
}
finally
{
CloseServiceHandle(handle);
}
}
return SetupExitCode.Success;
}
finally
{
CloseServiceHandle(manager);
}
}
/// <summary>Stops the service and waits for its process to exit, so its files can be replaced; false on timeout.</summary>
private static unsafe bool Stop(nint handle, InstalledService service)
{
if (!TryQuery(handle, out var status)) return false;
if (status.CurrentState == StateStopped) return true;
var processId = (int)status.ProcessId;
ServiceStatus stopped;
if (!ControlService(handle, ControlStop, &stopped) && Marshal.GetLastPInvokeError() is var error && error != ErrorServiceNotActive)
Log.Warning("setup", $"Service {service.Name} refused to stop (error {error}); waiting for it");
var deadline = Stopwatch.StartNew();
while (TryQuery(handle, out status) && status.CurrentState != StateStopped)
{
if (deadline.Elapsed > StopTimeout)
{
Log.Warning("setup", $"Service {service.Name} did not stop within {StopTimeout.TotalSeconds:0} s");
return false;
}
Thread.Sleep(250);
}
if (processId != 0) WaitForExit(processId, StopTimeout - deadline.Elapsed);
Log.Info("setup", $"Service {service.Name} stopped");
return true;
}
private static void WaitForExit(int processId, TimeSpan timeout)
{
try
{
using var process = Process.GetProcessById(processId);
process.WaitForExit(timeout > TimeSpan.Zero ? timeout : TimeSpan.Zero);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception)
{
// Already gone, or not ours to wait for: the stopped state is what counts.
}
}
private static unsafe bool TryQuery(nint handle, out ServiceStatusProcess status)
{
ServiceStatusProcess value;
var ok = QueryServiceStatusEx(handle, StatusProcessInfo, &value, sizeof(ServiceStatusProcess), out _);
status = value;
return ok;
}
private static SetupExitCode Failure(string what, InstalledService? service)
{
var error = Marshal.GetLastPInvokeError();
Log.Error("setup", $"{what}{(service is null ? string.Empty : " (" + service.Name + ")")}: error {error}");
return SetupExitCode.Failed;
}
}
+12 -7
View File
@@ -6,13 +6,18 @@ namespace Titano.Setup.Engine;
/// <summary> /// <summary>
/// Installed programs that are running. Setup only ever asks them to close (WM_CLOSE to the main window, as when /// Installed programs that are running. Setup only ever asks them to close (WM_CLOSE to the main window, as when
/// the user clicks ✕); it never terminates a process. /// the user clicks ✕); it never terminates a process. A program running as a Windows service is stopped through
/// the Service Control Manager instead (<see cref="InstalledServices"/>).
/// </summary> /// </summary>
internal static class RunningPrograms internal static class RunningPrograms
{ {
/// <summary>Processes of <paramref name="executables"/> (payload paths) started from inside <paramref name="directory"/>.</summary> /// <summary>
public static IReadOnlyList<Process> Find(string directory, IEnumerable<string> executables) /// Processes of <paramref name="executables"/> (payload paths) started from inside <paramref name="directory"/>,
/// except the programs of <paramref name="services"/>, which ignore WM_CLOSE.
/// </summary>
public static IReadOnlyList<Process> Find(string directory, IEnumerable<string> executables, IReadOnlyCollection<InstalledService>? services = null)
{ {
var servicePrograms = new HashSet<string>((services ?? []).Select(s => s.Program), StringComparer.OrdinalIgnoreCase);
var names = executables var names = executables
.Where(p => p.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !p.Contains('/', StringComparison.Ordinal)) .Where(p => p.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !p.Contains('/', StringComparison.Ordinal))
.Select(Path.GetFileNameWithoutExtension) .Select(Path.GetFileNameWithoutExtension)
@@ -23,16 +28,16 @@ internal static class RunningPrograms
foreach (var process in Process.GetProcessesByName(name)) foreach (var process in Process.GetProcessesByName(name))
{ {
var image = process.Id == Environment.ProcessId ? null : NativeMethods.ProcessImagePath(process.Id); var image = process.Id == Environment.ProcessId ? null : NativeMethods.ProcessImagePath(process.Id);
if (image is not null && SetupPaths.IsSameOrInside(image, directory)) found.Add(process); if (image is not null && SetupPaths.IsSameOrInside(image, directory) && !servicePrograms.Contains(image)) found.Add(process);
else process.Dispose(); else process.Dispose();
} }
} }
return found; return found;
} }
/// <summary>Display names ("Titano", "Titano.Uploader") of the given processes, for the prompt.</summary> /// <summary>Display names ("Titano", "Titano.Uploader", a service's "Titano Server") of what must close, for the prompt.</summary>
public static string Describe(IReadOnlyList<Process> processes) => public static string Describe(IReadOnlyList<Process> processes, IReadOnlyCollection<InstalledService>? services = null) =>
string.Join(", ", processes.Select(p => p.ProcessName).Distinct(StringComparer.OrdinalIgnoreCase)); string.Join(", ", processes.Select(p => p.ProcessName).Concat((services ?? []).Select(s => s.DisplayName)).Distinct(StringComparer.OrdinalIgnoreCase));
/// <summary>Asks each process to close and waits up to <paramref name="timeout"/>; returns those still running.</summary> /// <summary>Asks each process to close and waits up to <paramref name="timeout"/>; returns those still running.</summary>
public static async Task<IReadOnlyList<Process>> CloseAsync(IReadOnlyList<Process> processes, TimeSpan timeout) public static async Task<IReadOnlyList<Process>> CloseAsync(IReadOnlyList<Process> processes, TimeSpan timeout)
+30
View File
@@ -35,6 +35,36 @@ internal static partial class SetupRegistry
return null; return null;
} }
/// <summary>
/// The logs of the other installations by <paramref name="publisher"/> (any product, either scope) except the one in
/// <paramref name="directory"/>: what an uninstall must leave working (the user data they share).
/// </summary>
public static IReadOnlyList<InstallLog> OtherInstalls(string directory, string publisher)
{
var found = new List<InstallLog>();
foreach (var scope in (ReadOnlySpan<InstallScope>)[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;
if (key.GetValue("InstallLocation") is not string location || !Directory.Exists(location)) continue;
if (CommandProgram.IsPathInside(location, directory) && CommandProgram.IsPathInside(directory, location)) continue;
if (InstallLog.TryLoad(location) is { } log) found.Add(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) public static void WriteUninstallEntry(InstallScope scope, string productKey, UninstallEntry entry)
{ {
using var key = Hive(scope).CreateSubKey(UninstallRoot + productKey, writable: true); using var key = Hive(scope).CreateSubKey(UninstallRoot + productKey, writable: true);
+38 -12
View File
@@ -8,7 +8,8 @@ namespace Titano.Setup.Engine;
/// <summary> /// <summary>
/// <c>/S</c>: install or uninstall without a window, reporting only through the exit code and the setup log. /// <c>/S</c>: install or uninstall without a window, reporting only through the exit code and the setup log.
/// Running programs are asked to close; if they do not, setup stops with <see cref="SetupExitCode.ProgramRunning"/>. /// Running programs are asked to close; if they do not, setup stops with <see cref="SetupExitCode.ProgramRunning"/>.
/// Silent uninstall never removes user data. /// Services of the installation are stopped (and started again after an upgrade, or deleted with the uninstall),
/// which asks for administrator approval when setup runs without it. Silent uninstall never removes user data.
/// </summary> /// </summary>
internal static class SilentSetup internal static class SilentSetup
{ {
@@ -51,10 +52,14 @@ internal static class SilentSetup
if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated) if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false); return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false);
if (!await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory)).ConfigureAwait(false)) var closed = await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory), ServiceActions.Stop).ConfigureAwait(false);
return SetupExitCode.ProgramRunning; if (closed.Code != SetupExitCode.Success) return closed.Code;
var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu); var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu);
engine.Install(request, null, CancellationToken.None); engine.Install(request, null, CancellationToken.None);
// Services whose program the upgrade removed go; the ones stopped for it run again.
var services = await InstalledServices.ApplyAsync(plan.Directory, ServiceActions.Prune | (closed.StoppedServices ? ServiceActions.Start : ServiceActions.None), IntPtr.Zero)
.ConfigureAwait(false);
if (services != SetupExitCode.Success) return services;
if (launch is null) return SetupExitCode.Success; if (launch is null) return SetupExitCode.Success;
if (arguments.Elevated) return SetupExitCode.LaunchRequested; if (arguments.Elevated) return SetupExitCode.LaunchRequested;
@@ -68,8 +73,12 @@ internal static class SilentSetup
if (product is null) return SetupExitCode.NotInstalled; if (product is null) return SetupExitCode.NotInstalled;
if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated) if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null).ConfigureAwait(false); return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null).ConfigureAwait(false);
if (!await CloseProgramsAsync(product.Directory, product.Log.Files).ConfigureAwait(false)) return SetupExitCode.ProgramRunning; var closed = await CloseProgramsAsync(product.Directory, product.Log.Files, ServiceActions.Remove).ConfigureAwait(false);
UninstallEngine.Uninstall(product, removeUserData: false, null); if (closed.Code != SetupExitCode.Success) return closed.Code;
// Services that were not running are still registered: no service may outlive its program.
var services = await InstalledServices.ApplyAsync(product.Directory, ServiceActions.Remove, IntPtr.Zero).ConfigureAwait(false);
if (services != SetupExitCode.Success) return services;
UninstallEngine.Uninstall(product, userData: null, null);
return SetupExitCode.Success; return SetupExitCode.Success;
} }
@@ -87,13 +96,30 @@ internal static class SilentSetup
} }
} }
private static async Task<bool> CloseProgramsAsync(string directory, IEnumerable<string> programs) /// <summary>
/// Applies <paramref name="toServices"/> to the running services of <paramref name="directory"/> (an elevated step
/// when needed), then asks the running programs to close.
/// </summary>
private static async Task<(SetupExitCode Code, bool StoppedServices)> CloseProgramsAsync(string directory, IEnumerable<string> programs, ServiceActions toServices)
{ {
var running = RunningPrograms.Find(directory, programs); var services = InstalledServices.Find(directory).Where(InstalledServices.IsRunning).ToList();
if (running.Count == 0) return true; var running = RunningPrograms.Find(directory, programs, services);
Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close"); try
var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false); {
foreach (var p in running) p.Dispose(); if (services.Count > 0)
return still.Count == 0; {
Log.Info("setup", $"Stopping {RunningPrograms.Describe([], services)}");
var code = await InstalledServices.ApplyAsync(directory, toServices, IntPtr.Zero).ConfigureAwait(false);
if (code != SetupExitCode.Success) return (code, false);
}
if (running.Count == 0) return (SetupExitCode.Success, services.Count > 0);
Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close");
var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false);
return (still.Count == 0 ? SetupExitCode.Success : SetupExitCode.ProgramRunning, services.Count > 0);
}
finally
{
foreach (var p in running) p.Dispose();
}
} }
} }
+46
View File
@@ -0,0 +1,46 @@
using System.IO;
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
namespace Titano.Setup.Engine;
/// <summary>
/// "Start with Windows" values under <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> (the Uploader writes
/// "Titano Uploader"). An uninstall removes every value that starts a program inside the folder it removes: Windows
/// would otherwise try to start a deleted program at each sign-in. Values of other programs are left alone.
/// </summary>
internal static class StartupEntries
{
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// <summary>Removes the current user's Run values that start a program inside <paramref name="directory"/>; returns their names.</summary>
public static IReadOnlyList<string> RemoveInside(string directory)
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RunKey, writable: true);
return key is null ? [] : RemoveInside(key, directory);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
// A leftover entry is harmless (Windows skips a missing program); it must not fail the uninstall.
Log.Warning("setup", "Startup entries not checked", ex);
return [];
}
}
/// <summary>Removes the values of <paramref name="runKey"/> that start a program inside <paramref name="directory"/>.</summary>
public static IReadOnlyList<string> RemoveInside(RegistryKey runKey, string directory)
{
var removed = new List<string>();
foreach (var name in runKey.GetValueNames())
{
if (runKey.GetValue(name) is not string command || !CommandProgram.IsInside(command, directory)) continue;
runKey.DeleteValue(name, throwOnMissingValue: false);
removed.Add(name);
Log.Info("setup", $"Startup entry '{name}' removed");
}
return removed;
}
}
+25 -11
View File
@@ -10,9 +10,11 @@ namespace Titano.Setup.Engine;
internal sealed record InstalledProduct(string Directory, InstallLog Log); internal sealed record InstalledProduct(string Directory, InstallLog Log);
/// <summary> /// <summary>
/// Removes an installation using only its log: shortcuts, file types, logged files, the log and the Add/Remove /// Removes an installation using only its log: shortcuts that still start its programs, "Start with Windows" entries
/// Programs entry, then the uninstaller itself. Files the log does not list are left alone; the user data folder /// pointing into its folder, file types, logged files, the log and the Add/Remove Programs entry, then the
/// is deleted only when <c>removeUserData</c> is set by an explicit choice in the window. /// uninstaller itself. Files the log does not list are left alone; user data is deleted only through a plan the user
/// saw and chose in the window. Windows services of the folder are stopped and deleted by the caller first
/// (<see cref="InstalledServices.ApplyAsync"/>), as that may need an elevated step.
/// </summary> /// </summary>
internal static class UninstallEngine internal static class UninstallEngine
{ {
@@ -29,17 +31,19 @@ internal static class UninstallEngine
return null; return null;
} }
public static void Uninstall(InstalledProduct product, bool removeUserData, IProgress<SetupProgress>? progress) /// <param name="userData">The "Remove my data" plan the user confirmed; null keeps the user data.</param>
public static void Uninstall(InstalledProduct product, UserDataPlan? userData, IProgress<SetupProgress>? progress)
{ {
var (directory, log) = product; var (directory, log) = product;
Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {removeUserData})"); Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {userData is not null})");
// First, so that a failure here leaves the program installed and the uninstaller able to retry. // First, so that a failure here leaves the program installed and the uninstaller able to retry.
if (removeUserData && Directory.Exists(SetupPaths.UserData)) if (userData is { Entries.Count: > 0 })
{ {
Log.Info("setup", $"Removing user data '{SetupPaths.UserData}' at the user's request"); Log.Info("setup", $"Removing {userData.Entries.Count} entries of '{userData.Folder}' at the user's request");
Directory.Delete(SetupPaths.UserData, recursive: true); userData.Remove();
} }
foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope); foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope, directory);
StartupEntries.RemoveInside(directory);
progress?.Report(new SetupProgress(0.1, string.Empty)); progress?.Report(new SetupProgress(0.1, string.Empty));
var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList(); var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList();
@@ -82,8 +86,12 @@ internal static class UninstallEngine
progress?.Report(new SetupProgress(1, string.Empty)); progress?.Report(new SetupProgress(1, string.Empty));
} }
/// <summary>Deletes a shortcut recorded in a log, but only a <c>.lnk</c> directly in the Start menu or desktop folder.</summary> /// <summary>
public static void DeleteShortcut(string link, InstallScope scope) /// Deletes a shortcut recorded in a log, but only a <c>.lnk</c> directly in the Start menu or desktop folder that
/// still starts a program inside <paramref name="directory"/>: another product installing a program of the same
/// name may have pointed it at its own copy since.
/// </summary>
public static void DeleteShortcut(string link, InstallScope scope, string directory)
{ {
var folder = Path.GetDirectoryName(link); var folder = Path.GetDirectoryName(link);
var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase)
@@ -96,6 +104,12 @@ internal static class UninstallEngine
} }
try try
{ {
if (ShellLink.TargetOf(link) is not { } target) return;
if (!CommandProgram.IsPathInside(target, directory))
{
Log.Info("setup", $"Shortcut '{link}' now starts '{target}'; kept");
return;
}
File.Delete(link); File.Delete(link);
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+86 -10
View File
@@ -2,15 +2,17 @@ using System.IO;
namespace Titano.Setup.Engine; namespace Titano.Setup.Engine;
/// <summary>One top-level file or folder of the user data folder and the bytes it holds.</summary> /// <summary>One file or folder of the user data folder (its path relative to that folder) and the bytes it holds.</summary>
internal sealed record UserDataEntry(string Name, long Bytes); internal sealed record UserDataEntry(string Name, long Bytes);
/// <summary> /// <summary>
/// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): every top-level /// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): the entries of the
/// entry of the user data folder with its size, largest first. Links are not followed, as the deletion does not /// user data folder that belong to the programs being removed, with their sizes, largest first. The desktop app and
/// follow them either. /// the Uploader share the folder (and its <c>logs</c>), so uninstalling one product never lists what another
/// installed product still uses (<see cref="UserDataOwners"/>). <see cref="Remove"/> deletes exactly these entries.
/// Links are not followed, as the deletion does not follow them either.
/// </summary> /// </summary>
internal sealed record UserDataPlan(IReadOnlyList<UserDataEntry> Entries) internal sealed record UserDataPlan(string Folder, IReadOnlyList<UserDataEntry> Entries)
{ {
private static readonly EnumerationOptions TopLevel = new() { IgnoreInaccessible = true, AttributesToSkip = 0 }; private static readonly EnumerationOptions TopLevel = new() { IgnoreInaccessible = true, AttributesToSkip = 0 };
@@ -23,13 +25,52 @@ internal sealed record UserDataPlan(IReadOnlyList<UserDataEntry> Entries)
public long TotalBytes => Entries.Sum(e => e.Bytes); public long TotalBytes => Entries.Sum(e => e.Bytes);
/// <summary>Measures <paramref name="folder"/>; empty when it does not exist. Reads sizes only, changes nothing.</summary> /// <summary>
public static UserDataPlan Measure(string folder) /// Measures what of <paramref name="folder"/> belongs to <paramref name="owners"/> (component ids); empty when the
/// folder does not exist or no owner is given. Reads sizes only, changes nothing.
/// </summary>
public static UserDataPlan Measure(string folder, IReadOnlySet<string> owners)
{ {
var root = new DirectoryInfo(folder); var root = new DirectoryInfo(folder);
if (!root.Exists) return new UserDataPlan([]); if (!root.Exists || owners.Count == 0) return new UserDataPlan(folder, []);
var entries = root.EnumerateFileSystemInfos("*", TopLevel).Select(e => new UserDataEntry(e.Name, SizeOf(e))); var whole = UserDataOwners.All.All(owners.Contains);
return new UserDataPlan([.. entries.OrderByDescending(e => e.Bytes).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)]); var entries = new List<UserDataEntry>();
foreach (var entry in root.EnumerateFileSystemInfos("*", TopLevel))
{
if (!whole && entry is DirectoryInfo shared && UserDataOwners.IsShared(shared))
{
// A folder both programs write to: only this product's files in it.
entries.AddRange(shared.EnumerateFileSystemInfos("*", TopLevel)
.Where(e => owners.Contains(UserDataOwners.OwnerOf(e.Name)))
.Select(e => new UserDataEntry(Path.Combine(shared.Name, e.Name), SizeOf(e))));
}
else if (owners.Contains(UserDataOwners.OwnerOf(entry.Name)))
{
entries.Add(new UserDataEntry(entry.Name, SizeOf(entry)));
}
}
return new UserDataPlan(folder, [.. entries.OrderByDescending(e => e.Bytes).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)]);
}
/// <summary>
/// Deletes the listed entries (a link, not what it points to), then the folders they leave empty. Throws on the
/// first entry that cannot be deleted, before anything else of the uninstall changes.
/// </summary>
public void Remove()
{
foreach (var entry in Entries)
{
var path = Path.GetFullPath(Path.Combine(Folder, entry.Name));
// The plan comes from this folder's listing; anything else is never deleted.
if (!SetupPaths.IsSameOrInside(path, Folder) || SetupPaths.IsSameOrInside(Folder, path)) continue;
var info = new FileInfo(path);
if (!info.Exists && !Directory.Exists(path)) continue;
if (!info.Attributes.HasFlag(FileAttributes.Directory)) File.Delete(path);
else Directory.Delete(path, recursive: !info.Attributes.HasFlag(FileAttributes.ReparsePoint));
var parent = Path.GetDirectoryName(path)!;
if (!SetupPaths.IsSameOrInside(Folder, parent) && !Directory.EnumerateFileSystemEntries(parent).Any()) Directory.Delete(parent);
}
if (Directory.Exists(Folder) && !Directory.EnumerateFileSystemEntries(Folder).Any()) Directory.Delete(Folder);
} }
private static long SizeOf(FileSystemInfo entry) => entry switch private static long SizeOf(FileSystemInfo entry) => entry switch
@@ -40,3 +81,38 @@ internal sealed record UserDataPlan(IReadOnlyList<UserDataEntry> Entries)
_ => 0, _ => 0,
}; };
} }
/// <summary>
/// Which program each entry of the user data folder (<c>%LOCALAPPDATA%\Titano</c>) belongs to: the Uploader's files
/// start with <c>uploader</c> (settings and sign-in, queue, watch memory, its logs); everything else is the desktop
/// app's (index, settings, backups, cache, its logs). Titano Server keeps its data elsewhere.
/// </summary>
internal static class UserDataOwners
{
public const string Titano = "Titano";
public const string Uploader = "Uploader";
/// <summary>The folder both programs write their logs to.</summary>
private const string SharedFolder = "logs";
/// <summary>The components that keep data in the folder.</summary>
public static readonly IReadOnlySet<string> All = new HashSet<string>([Titano, Uploader], StringComparer.OrdinalIgnoreCase);
/// <summary>The component that owns the top-level entry, or the file inside the shared logs folder, called <paramref name="name"/>.</summary>
public static string OwnerOf(string name) => name.StartsWith("uploader", StringComparison.OrdinalIgnoreCase) ? Uploader : Titano;
/// <summary>True for the logs folder both programs write to (a real folder, not a link to one).</summary>
public static bool IsShared(DirectoryInfo folder) =>
folder.Name.Equals(SharedFolder, StringComparison.OrdinalIgnoreCase) && !folder.Attributes.HasFlag(FileAttributes.ReparsePoint);
/// <summary>
/// The owners whose data uninstalling a product with <paramref name="components"/> may remove: its components that
/// keep data, minus those another installed product still has (<paramref name="others"/>' components).
/// </summary>
public static IReadOnlySet<string> Removable(IEnumerable<string> components, IEnumerable<IEnumerable<string>> others)
{
var owners = new HashSet<string>(components.Where(All.Contains), StringComparer.OrdinalIgnoreCase);
foreach (var other in others) owners.ExceptWith(other);
return owners;
}
}
+74
View File
@@ -0,0 +1,74 @@
using System.Runtime.InteropServices;
namespace Titano.Setup.Interop;
/// <summary>Service Control Manager functions of advapi32: query, stop, start and delete one service by name.</summary>
internal static unsafe partial class ServiceNative
{
public const uint ScManagerConnect = 0x1;
public const uint ServiceQueryStatus = 0x4;
public const uint ServiceStart = 0x10;
public const uint ServiceStop = 0x20;
public const uint Delete = 0x10000;
public const uint ControlStop = 1;
public const uint StateStopped = 1;
public const int StatusProcessInfo = 0;
public const int ErrorServiceDoesNotExist = 1060;
public const int ErrorServiceNotActive = 1062;
public const int ErrorServiceAlreadyRunning = 1056;
public const int ErrorServiceMarkedForDelete = 1072;
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatus
{
public uint ServiceType;
public uint CurrentState;
public uint ControlsAccepted;
public uint Win32ExitCode;
public uint ServiceSpecificExitCode;
public uint CheckPoint;
public uint WaitHint;
}
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatusProcess
{
public uint ServiceType;
public uint CurrentState;
public uint ControlsAccepted;
public uint Win32ExitCode;
public uint ServiceSpecificExitCode;
public uint CheckPoint;
public uint WaitHint;
public uint ProcessId;
public uint ServiceFlags;
}
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool QueryServiceStatusEx(nint service, int infoLevel, ServiceStatusProcess* buffer, int bufferSize, out int bytesNeeded);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ControlService(nint service, uint control, ServiceStatus* status);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool StartServiceW(nint service, uint argumentCount, nint arguments);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeleteService(nint service);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool CloseServiceHandle(nint handle);
}
+45 -2
View File
@@ -4,9 +4,15 @@ using System.Runtime.InteropServices.ComTypes;
namespace Titano.Setup.Interop; namespace Titano.Setup.Interop;
/// <summary>Creates <c>.lnk</c> shortcuts through the shell's <c>IShellLinkW</c> and <c>IPersistFile</c> COM interfaces.</summary> /// <summary>Creates and reads <c>.lnk</c> shortcuts through the shell's <c>IShellLinkW</c> and <c>IPersistFile</c> COM interfaces.</summary>
internal static class ShellLink internal static class ShellLink
{ {
private const int StgmRead = 0;
private const uint SlgpRawPath = 0x4;
/// <summary>Characters of the target buffer: the longest path Windows accepts.</summary>
private const int MaxTarget = 32768;
/// <summary>Writes a shortcut at <paramref name="linkPath"/> that starts <paramref name="target"/> in its own folder.</summary> /// <summary>Writes a shortcut at <paramref name="linkPath"/> that starts <paramref name="target"/> in its own folder.</summary>
public static void Create(string linkPath, string target, string description) public static void Create(string linkPath, string target, string description)
{ {
@@ -29,11 +35,48 @@ internal static class ShellLink
}); });
} }
/// <summary>
/// The program a shortcut starts, as stored in the file (the target need not exist); null when the file is
/// missing or is not a shortcut to a file.
/// </summary>
public static string? TargetOf(string linkPath)
{
if (!File.Exists(linkPath)) return null;
string? target = null;
StaThread.Run(() =>
{
var link = (IShellLinkW)new ShellLinkObject();
try
{
((IPersistFile)link).Load(linkPath, StgmRead);
var buffer = Marshal.AllocHGlobal(MaxTarget * sizeof(char));
try
{
link.GetPath(buffer, MaxTarget, IntPtr.Zero, SlgpRawPath);
target = Marshal.PtrToStringUni(buffer);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
catch (COMException)
{
// Not a shortcut, or a shortcut to a shell item that is not a file.
}
finally
{
Marshal.FinalReleaseComObject(link);
}
});
return string.IsNullOrEmpty(target) ? null : Environment.ExpandEnvironmentVariables(target);
}
[ComImport] [ComImport]
[Guid("00021401-0000-0000-C000-000000000046")] [Guid("00021401-0000-0000-C000-000000000046")]
private class ShellLinkObject; private class ShellLinkObject;
/// <summary>Vtable-ordered declaration; only the setters are called, so getters take raw pointers.</summary> /// <summary>Vtable-ordered declaration; setters take strings, getters raw buffers.</summary>
[ComImport] [ComImport]
[Guid("000214F9-0000-0000-C000-000000000046")] [Guid("000214F9-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+3 -2
View File
@@ -7,8 +7,8 @@ using Titano.Setup.Engine;
namespace Titano.Setup; namespace Titano.Setup;
/// <summary> /// <summary>
/// Entry point. Silent mode and the uninstaller cleanup helper run without WPF; the interactive window is the /// Entry point. Silent mode, the uninstaller cleanup helper and the elevated service step run without WPF; the
/// <see cref="App"/>. The return value is the process exit code (<see cref="SetupExitCode"/>). /// interactive window is the <see cref="App"/>. The return value is the process exit code (<see cref="SetupExitCode"/>).
/// </summary> /// </summary>
internal static class Program internal static class Program
{ {
@@ -34,6 +34,7 @@ internal static class Program
ApplyLanguage(arguments.Language); ApplyLanguage(arguments.Language);
if (arguments.CleanupTarget is { } uninstaller) return (int)SelfCleanup.Run(uninstaller, arguments.WaitProcessId); if (arguments.CleanupTarget is { } uninstaller) return (int)SelfCleanup.Run(uninstaller, arguments.WaitProcessId);
if (arguments.Services != ServiceActions.None) return (int)InstalledServices.RunStep(arguments);
if (arguments.Silent) return (int)SilentSetup.RunAsync(arguments).GetAwaiter().GetResult(); if (arguments.Silent) return (int)SilentSetup.RunAsync(arguments).GetAwaiter().GetResult();
return new App(arguments).Run(); return new App(arguments).Run();
+3
View File
@@ -14,6 +14,9 @@
<PropertyGroup Condition="'$(PublishSingleFile)' == 'true' and '$(SelfContained)' == 'true'"> <PropertyGroup Condition="'$(PublishSingleFile)' == 'true' and '$(SelfContained)' == 'true'">
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile> <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Titano.App.Tests" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Titano.Core\Titano.Core.csproj" /> <ProjectReference Include="..\Titano.Core\Titano.Core.csproj" />
<ProjectReference Include="..\Titano.Ui\Titano.Ui.csproj" /> <ProjectReference Include="..\Titano.Ui\Titano.Ui.csproj" />
+16 -3
View File
@@ -4,8 +4,11 @@ using Titano.Ui.Mvvm;
namespace Titano.Setup.Views; namespace Titano.Setup.Views;
/// <summary>A component checkbox: localized name and tooltip (falling back to the manifest), size and selection.</summary> /// <summary>
internal sealed class ComponentOption(PayloadComponent component, bool selected, Action changed) : LocalizedViewModel /// A component checkbox: localized name and tooltip (falling back to the manifest), size and selection. A component
/// that installs for all users only says so in its tooltip, and is unavailable when a per-user installation is upgraded.
/// </summary>
internal sealed class ComponentOption(PayloadComponent component, bool selected, bool available, Action changed) : LocalizedViewModel
{ {
private bool _selected = selected; private bool _selected = selected;
@@ -13,7 +16,17 @@ internal sealed class ComponentOption(PayloadComponent component, bool selected,
public string Name => Loc.Get("Setup.Component." + component.Id, Loc.Culture) ?? component.DisplayName; public string Name => Loc.Get("Setup.Component." + component.Id, Loc.Culture) ?? component.DisplayName;
public string ToolTip => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component"); /// <summary>Installs for all users only (the Server runs as a LocalSystem service from Program Files).</summary>
public bool AllUsersOnly => component.AllUsersOnly;
/// <summary>False when it cannot be installed here: it needs all users and this installation is for the current user.</summary>
public bool IsAvailable { get; } = available;
public string ToolTip => !IsAvailable ? Loc.L("Tooltips.Setup.NeedsAllUsers")
: AllUsersOnly ? Loc.L("Tooltips.Setup.AllUsersOnly", Description)
: Description;
private string Description => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component");
public string SizeText => ByteSize.Format(component.EstimatedSize); public string SizeText => ByteSize.Format(component.EstimatedSize);
+5 -3
View File
@@ -31,7 +31,7 @@ internal static class SetupCapture
]; ];
/// <summary>What a user data folder typically holds; eight entries, so the plan also shows its "more" line.</summary> /// <summary>What a user data folder typically holds; eight entries, so the plan also shows its "more" line.</summary>
private static readonly UserDataPlan SamplePlan = new( private static readonly UserDataPlan SamplePlan = new(SetupPaths.UserData,
[ [
new UserDataEntry("cache", 2_140_000_000), new UserDataEntry("cache", 2_140_000_000),
new UserDataEntry("backups", 1_210_000_000), new UserDataEntry("backups", 1_210_000_000),
@@ -95,8 +95,10 @@ internal static class SetupCapture
Program.ApplyLanguage(language); Program.ApplyLanguage(language);
using var payload = PayloadReader.Open(installer); using var payload = PayloadReader.Open(installer);
using var install = SetupViewModel.ForInstall(new SetupArguments(), payload); using var install = SetupViewModel.ForInstall(new SetupArguments(), payload);
// Both programs' data, whatever this machine has installed, so every capture shows the same screen.
using var uninstall = SetupViewModel.ForUninstall(new SetupArguments(), new InstalledProduct( using var uninstall = SetupViewModel.ForUninstall(new SetupArguments(), new InstalledProduct(
SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product), new InstallLog { Product = Product, Version = "1.0.0" })); SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product), new InstallLog { Product = Product, Version = "1.0.0", Components = ["Titano", "Uploader"] }),
UserDataOwners.All);
foreach (var theme in themes) foreach (var theme in themes)
{ {
ThemeManager.Apply(theme); ThemeManager.Apply(theme);
@@ -154,7 +156,7 @@ internal static class SetupCapture
{ {
Product = Product, Product = Product,
Version = "1.0.0", Version = "1.0.0",
Components = [.. components.Select(c => new PayloadComponentSource(c.Id, c.DisplayName, c.Selected, Path.Combine(work, c.Id)))], Components = [.. components.Select(c => new PayloadComponentSource(c.Id, c.DisplayName, c.Selected, Path.Combine(work, c.Id), AllUsersOnly: c.Id == "Server"))],
Shortcuts = [.. components.Select(c => new PayloadShortcut { Component = c.Id, Name = c.DisplayName, Target = c.Program, StartMenu = true, Desktop = c.Id != "Server" })], Shortcuts = [.. components.Select(c => new PayloadShortcut { Component = c.Id, Name = c.DisplayName, Target = c.Program, StartMenu = true, Desktop = c.Id != "Server" })],
}, installer); }, installer);
return installer; return installer;
+73 -18
View File
@@ -42,6 +42,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private readonly InstalledProduct? _installed; private readonly InstalledProduct? _installed;
private readonly string _product; private readonly string _product;
private readonly string? _version; private readonly string? _version;
private readonly IReadOnlySet<string> _dataOwners;
private SetupStage _stage; private SetupStage _stage;
private string _directory = string.Empty; private string _directory = string.Empty;
private bool _allUsers; private bool _allUsers;
@@ -60,14 +61,20 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private bool _accessDenied; private bool _accessDenied;
private string? _launchProgram; private string? _launchProgram;
private Func<Task>? _operation; private Func<Task>? _operation;
private bool _stoppedServices;
private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed) private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed,
IReadOnlySet<string>? dataOwners = null)
{ {
_arguments = arguments; _arguments = arguments;
_product = product; _product = product;
_version = version; _version = version;
_payload = payload; _payload = payload;
_installed = installed; _installed = installed;
// "Remove my data" covers the programs this product installed that no other installed Titano product still has.
_dataOwners = installed is null ? new HashSet<string>()
: dataOwners ?? UserDataOwners.Removable(installed.Log.Components,
SetupRegistry.OtherInstalls(installed.Directory, InstallEngine.Publisher).Select(l => (IEnumerable<string>)l.Components));
if (payload is not null) if (payload is not null)
{ {
_engine = new InstallEngine(payload); _engine = new InstallEngine(payload);
@@ -80,7 +87,8 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
_launchAfter = arguments.Launch; _launchAfter = arguments.Launch;
Components = _engine is null Components = _engine is null
? [] ? []
: [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), OnComponentsChanged))]; : [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), _plan.CanInstall(c),
OnComponentsChanged))];
Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))]; Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))];
PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart); PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart);
@@ -99,8 +107,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) => public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) =>
new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null); new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null);
public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed) => /// <param name="dataOwners">Whose user data "Remove my data" covers; null works it out from the installed products.</param>
new(arguments, installed.Log.Product, installed.Log.Version, null, installed) { Directory = installed.Directory }; public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed, IReadOnlySet<string>? dataOwners = null) =>
new(arguments, installed.Log.Product, installed.Log.Version, null, installed, dataOwners) { Directory = installed.Directory };
/// <summary>A screen that can only report why setup cannot run (no payload, nothing installed…).</summary> /// <summary>A screen that can only report why setup cannot run (no payload, nothing installed…).</summary>
public static SetupViewModel ForFailure(SetupArguments arguments, SetupExitCode code) public static SetupViewModel ForFailure(SetupArguments arguments, SetupExitCode code)
@@ -219,7 +228,15 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
/// <summary>Browse is disabled when upgrading; its tooltip then says why (DESIGN §4).</summary> /// <summary>Browse is disabled when upgrading; its tooltip then says why (DESIGN §4).</summary>
public string BrowseToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Browse") : Loc.L("Tooltips.Setup.Locked"); public string BrowseToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Browse") : Loc.L("Tooltips.Setup.Locked");
public string JustMeToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.JustMe") : Loc.L("Tooltips.Setup.Locked"); /// <summary>A selected component installs for all users only (the Server runs as a LocalSystem service from Program Files).</summary>
private ComponentOption? AllUsersComponent => Components.FirstOrDefault(c => c.IsSelected && c.AllUsersOnly);
/// <summary>"Just me" is offered unless the location is fixed (upgrade) or a selected component needs all users.</summary>
public bool CanChooseJustMe => CanChangeLocation && AllUsersComponent is null;
public string JustMeToolTip => !CanChangeLocation ? Loc.L("Tooltips.Setup.Locked")
: AllUsersComponent is { } component ? Loc.L("Tooltips.Setup.JustMeLocked", component.Name)
: Loc.L("Tooltips.Setup.JustMe");
public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked"); public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked");
public bool DesktopShortcut public bool DesktopShortcut
@@ -252,7 +269,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
: CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update"); : CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update");
/// <summary>Removing user data waits for its plan, so the user has seen what goes before choosing Uninstall.</summary> /// <summary>Removing user data waits for its plan, so the user has seen what goes before choosing Uninstall.</summary>
private bool CanStart => IsOptions && (IsUninstall ? !_removeUserData || _dataPlan is not null : IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected)); private bool CanStart => IsOptions && (IsUninstall
? !_removeUserData || _dataPlan is not null
: IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected) && (_allUsers || AllUsersComponent is null));
// ---- Uninstall options ---- // ---- Uninstall options ----
@@ -269,6 +288,17 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
} }
} }
/// <summary>
/// "Remove my data" is offered when this product's programs keep data no other installed Titano product still uses
/// (the desktop app and the Uploader share the folder).
/// </summary>
public bool HasRemoveDataOption => _dataOwners.Count > 0;
/// <summary>What "Remove my data" deletes: both programs' data, or only the desktop app's or the Uploader's.</summary>
public string RemoveDataToolTip => Loc.L(UserDataOwners.All.All(_dataOwners.Contains) ? "Tooltips.Setup.RemoveData"
: _dataOwners.Contains(UserDataOwners.Uploader) ? "Tooltips.Setup.RemoveDataUploader"
: "Tooltips.Setup.RemoveDataTitano");
public bool IsDataPlanVisible => _removeUserData && _dataPlan is not null; public bool IsDataPlanVisible => _removeUserData && _dataPlan is not null;
/// <summary>"Deletes 3.4 GB" over the plan's lines.</summary> /// <summary>"Deletes 3.4 GB" over the plan's lines.</summary>
@@ -412,11 +442,16 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
await InstallElevatedAsync(request, program); await InstallElevatedAsync(request, program);
return; return;
} }
if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory))) return; if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory), ServiceActions.Stop)) return;
BeginWork(indeterminate: false); BeginWork(indeterminate: false);
var progress = new Progress<SetupProgress>(ReportProgress); var progress = new Progress<SetupProgress>(ReportProgress);
await Task.Run(() => engine.Install(request, progress, CancellationToken.None)); await Task.Run(() => engine.Install(request, progress, CancellationToken.None));
// Services whose program the upgrade removed go; the ones stopped for it run again.
var after = ServiceActions.Prune | (_stoppedServices ? ServiceActions.Start : ServiceActions.None);
var services = await InstalledServices.ApplyAsync(request.Directory, after, WindowHandle);
if (services != SetupExitCode.Success) throw new SetupException(services, $"Services not updated: {services}");
_stoppedServices = false;
_launchProgram = program; _launchProgram = program;
Complete(); Complete();
if (launch is not null) Launch(); if (launch is not null) Launch();
@@ -454,11 +489,14 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
var installed = _installed!; var installed = _installed!;
try try
{ {
if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files)) return; if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files, ServiceActions.Remove)) return;
BeginWork(indeterminate: false); BeginWork(indeterminate: false);
// A service that was not running is still registered: none may outlive its program.
var services = await InstalledServices.ApplyAsync(installed.Directory, ServiceActions.Remove, WindowHandle);
if (services != SetupExitCode.Success) throw new SetupException(services, $"Services not removed: {services}");
var progress = new Progress<SetupProgress>(ReportProgress); var progress = new Progress<SetupProgress>(ReportProgress);
var removeData = _removeUserData; var userData = _removeUserData ? _dataPlan : null;
await Task.Run(() => UninstallEngine.Uninstall(installed, removeData, progress)); await Task.Run(() => UninstallEngine.Uninstall(installed, userData, progress));
Complete(); Complete();
} }
catch (Exception ex) catch (Exception ex)
@@ -468,25 +506,37 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
} }
/// <summary> /// <summary>
/// True when no installed program runs from <paramref name="directory"/>. Otherwise the first call asks the user /// True when no installed program or service runs from <paramref name="directory"/>. Otherwise the first call asks
/// (Confirm stage); after "Close programs" the programs are asked to close and the operation continues. /// the user (Confirm stage); after "Close programs" the services get <paramref name="toServices"/> (stopped, or
/// stopped and deleted; an elevated step when needed), the programs are asked to close and the operation continues.
/// </summary> /// </summary>
private async Task<bool> EnsureProgramsClosedAsync(string directory, IEnumerable<string> programs) private async Task<bool> EnsureProgramsClosedAsync(string directory, IEnumerable<string> programs, ServiceActions toServices)
{ {
// A confirmation answers one prompt only; a later attempt asks again. // A confirmation answers one prompt only; a later attempt asks again.
var confirmed = _closeConfirmed; var confirmed = _closeConfirmed;
_closeConfirmed = false; _closeConfirmed = false;
var running = RunningPrograms.Find(directory, programs); var services = InstalledServices.Find(directory).Where(InstalledServices.IsRunning).ToList();
var running = RunningPrograms.Find(directory, programs, services);
try try
{ {
if (running.Count == 0) return true; if (running.Count == 0 && services.Count == 0) return true;
_runningPrograms = RunningPrograms.Describe(running); _runningPrograms = RunningPrograms.Describe(running, services);
if (!confirmed) if (!confirmed)
{ {
Stage = SetupStage.Confirm; Stage = SetupStage.Confirm;
return false; return false;
} }
BeginWork(indeterminate: true); BeginWork(indeterminate: true);
if (services.Count > 0)
{
var code = await InstalledServices.ApplyAsync(directory, toServices, WindowHandle);
if (code != SetupExitCode.Success)
{
_runningPrograms = RunningPrograms.Describe([], services);
throw new SetupException(code, $"Services not stopped: {_runningPrograms}");
}
_stoppedServices = true;
}
var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout); var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout);
if (still.Count == 0) return true; if (still.Count == 0) return true;
_runningPrograms = RunningPrograms.Describe(still); _runningPrograms = RunningPrograms.Describe(still);
@@ -570,12 +620,12 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
_measuring = true; _measuring = true;
try try
{ {
_dataPlan = await Task.Run(() => UserDataPlan.Measure(SetupPaths.UserData)); _dataPlan = await Task.Run(() => UserDataPlan.Measure(SetupPaths.UserData, _dataOwners));
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
Log.Warning("setup", $"User data '{SetupPaths.UserData}' not measured", ex); Log.Warning("setup", $"User data '{SetupPaths.UserData}' not measured", ex);
_dataPlan = new UserDataPlan([]); _dataPlan = new UserDataPlan(SetupPaths.UserData, []);
} }
finally finally
{ {
@@ -589,6 +639,11 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private void OnComponentsChanged() private void OnComponentsChanged()
{ {
// The Server runs as a LocalSystem service, which must not start a program its user can replace: selecting it
// moves a new installation to all users (Program Files).
if (AllUsersComponent is not null && !_allUsers && CanChangeLocation) IsAllUsers = true;
OnPropertyChanged(nameof(CanChooseJustMe));
OnPropertyChanged(nameof(JustMeToolTip));
OnPropertyChanged(nameof(RequiredSpaceText)); OnPropertyChanged(nameof(RequiredSpaceText));
OnPropertyChanged(nameof(InstallToolTip)); OnPropertyChanged(nameof(InstallToolTip));
OnPropertyChanged(nameof(HasDesktopOption)); OnPropertyChanged(nameof(HasDesktopOption));
+6 -3
View File
@@ -44,7 +44,8 @@
<DataTemplate> <DataTemplate>
<DockPanel Margin="0,0,0,6"> <DockPanel Margin="0,0,0,6">
<TextBlock DockPanel.Dock="Right" Text="{Binding SizeText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" /> <TextBlock DockPanel.Dock="Right" Text="{Binding SizeText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" ToolTip="{Binding ToolTip}" /> <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" IsEnabled="{Binding IsAvailable}" ToolTip="{Binding ToolTip}"
ToolTipService.ShowOnDisabled="True" />
</DockPanel> </DockPanel>
</DataTemplate> </DataTemplate>
</ItemsControl.ItemTemplate> </ItemsControl.ItemTemplate>
@@ -52,7 +53,7 @@
<TextBlock Grid.Row="1" Text="{l:Loc Setup.Field.Scope}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" /> <TextBlock Grid.Row="1" Text="{l:Loc Setup.Field.Scope}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center"> <StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<RadioButton Content="{l:Loc Setup.Scope.JustMe}" IsChecked="{Binding IsJustMe}" IsEnabled="{Binding CanChangeLocation}" <RadioButton Content="{l:Loc Setup.Scope.JustMe}" IsChecked="{Binding IsJustMe}" IsEnabled="{Binding CanChooseJustMe}"
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding JustMeToolTip}" Margin="0,0,20,0" /> ToolTipService.ShowOnDisabled="True" ToolTip="{Binding JustMeToolTip}" Margin="0,0,20,0" />
<RadioButton Content="{l:Loc Setup.Scope.AllUsers}" IsChecked="{Binding IsAllUsers}" IsEnabled="{Binding CanChangeLocation}" <RadioButton Content="{l:Loc Setup.Scope.AllUsers}" IsChecked="{Binding IsAllUsers}" IsEnabled="{Binding CanChangeLocation}"
ToolTipService.ShowOnDisabled="True" ToolTip="{Binding AllUsersToolTip}" /> ToolTipService.ShowOnDisabled="True" ToolTip="{Binding AllUsersToolTip}" />
@@ -96,8 +97,10 @@
<TextBlock Text="{l:Loc Setup.Field.Folder}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" /> <TextBlock Text="{l:Loc Setup.Field.Folder}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,16,0" />
<TextBox Grid.Column="1" VerticalAlignment="Center" IsReadOnly="True" Text="{Binding Directory, Mode=OneWay}" FlowDirection="LeftToRight" <TextBox Grid.Column="1" VerticalAlignment="Center" IsReadOnly="True" Text="{Binding Directory, Mode=OneWay}" FlowDirection="LeftToRight"
ToolTip="{l:Loc Tooltips.Setup.Installed}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" /> ToolTip="{l:Loc Tooltips.Setup.Installed}" AutomationProperties.Name="{l:Loc Setup.Field.Folder}" />
<!-- Only this product's data, and only what no other installed Titano product still uses. -->
<CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}" VerticalAlignment="Center" <CheckBox Grid.Row="1" Grid.Column="1" Content="{l:Loc Setup.Uninstall.RemoveData}" IsChecked="{Binding RemoveUserData}" VerticalAlignment="Center"
Foreground="{DynamicResource Brush.Warning}" ToolTip="{l:Loc Tooltips.Setup.RemoveData}" /> Foreground="{DynamicResource Brush.Warning}" ToolTip="{Binding RemoveDataToolTip}"
Visibility="{Binding HasRemoveDataOption, Converter={StaticResource BoolToVisibility}}" />
<Border Grid.Row="2" Grid.Column="1" Style="{StaticResource Border.Card}" Padding="12,8" <Border Grid.Row="2" Grid.Column="1" Style="{StaticResource Border.Card}" Padding="12,8"
Visibility="{Binding IsDataPlanVisible, Converter={StaticResource BoolToVisibility}}"> Visibility="{Binding IsDataPlanVisible, Converter={StaticResource BoolToVisibility}}">
<StackPanel> <StackPanel>
@@ -6,18 +6,20 @@ namespace Titano.Tools.Commands;
/// <summary> /// <summary>
/// <c>pack-installer --setup Titano.Setup.exe --product Titano --version 1.2.3 --component Id=folder … --out file</c>: /// <c>pack-installer --setup Titano.Setup.exe --product Titano --version 1.2.3 --component Id=folder … --out file</c>:
/// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default /// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default
/// selection, shortcuts and file types; unknown ids are packed as plain, preselected components. /// selection, shortcuts and file types; unknown ids are packed as plain, preselected components. The Server
/// installs only for all users: it is registered as a LocalSystem service, which must run from Program Files.
/// </summary> /// </summary>
internal sealed class PackInstallerCommand : ICommand internal sealed class PackInstallerCommand : ICommand
{ {
private sealed record KnownComponent(string DisplayName, bool DefaultSelected, string Program, bool Desktop, PayloadAssociation? Association); private sealed record KnownComponent(string DisplayName, bool DefaultSelected, string Program, bool Desktop, PayloadAssociation? Association, bool AllUsersOnly = false);
/// <remarks>The file type's description is the English fallback; setup writes it in its own language (<c>Setup.FileType.*</c>).</remarks>
private static readonly Dictionary<string, KnownComponent> Known = new(StringComparer.OrdinalIgnoreCase) private static readonly Dictionary<string, KnownComponent> Known = new(StringComparer.OrdinalIgnoreCase)
{ {
["Titano"] = new("Titano", true, "Titano.exe", Desktop: true, ["Titano"] = new("Titano", true, "Titano.exe", Desktop: true,
new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }), new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }),
["Uploader"] = new("Titano Uploader", true, "Titano.Uploader.exe", Desktop: true, null), ["Uploader"] = new("Titano Uploader", true, "Titano.Uploader.exe", Desktop: true, null),
["Server"] = new("Titano Server", false, "Titano.Server.exe", Desktop: false, null), ["Server"] = new("Titano Server", false, "Titano.Server.exe", Desktop: false, null, AllUsersOnly: true),
}; };
public string Name => "pack-installer"; public string Name => "pack-installer";
@@ -49,7 +51,7 @@ internal sealed class PackInstallerCommand : ICommand
components.Add(new PayloadComponentSource(id, id, true, folder)); components.Add(new PayloadComponentSource(id, id, true, folder));
continue; continue;
} }
components.Add(new PayloadComponentSource(id, known.DisplayName, known.DefaultSelected, folder)); components.Add(new PayloadComponentSource(id, known.DisplayName, known.DefaultSelected, folder, known.AllUsersOnly));
if (!File.Exists(Path.Combine(folder, known.Program))) if (!File.Exists(Path.Combine(folder, known.Program)))
{ {
Console.Error.WriteLine($"warning: {id} has no {known.Program}; no shortcut or file type registered."); Console.Error.WriteLine($"warning: {id} has no {known.Program}; no shortcut or file type registered.");
@@ -14,7 +14,8 @@ public interface IStartupRegistration
/// <summary> /// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> value that starts the uploader in the tray at sign-in. /// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> 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. /// The registry stays the source of truth because Task Manager can turn it off. Uninstalling removes the value, as
/// setup deletes every Run value that starts a program in the folder it removes.
/// </summary> /// </summary>
public sealed class RunKeyStartupRegistration : IStartupRegistration public sealed class RunKeyStartupRegistration : IStartupRegistration
{ {
@@ -0,0 +1,156 @@
using System.Globalization;
using System.IO;
using Microsoft.Win32;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Engine;
using Titano.Setup.Interop;
using Titano.Testing;
namespace Titano.App.Tests.Setup;
/// <summary>
/// What setup leaves behind and what it registers: services and startup entries of the install folder (SETUP-1,
/// SETUP-2), shortcuts another product owns (SRS-09), the Server's all-users scope (SRS-06) and the file type name
/// in setup's language (SRS-04).
/// </summary>
public sealed class SetupEngineTests(TestContext context)
{
[Theory]
[Case(@"""C:\Program Files\Titano\Titano.Server.exe"" --service", @"C:\Program Files\Titano\Titano.Server.exe")]
[Case(@"C:\Program Files\Titano\Titano.Server.exe --service", @"C:\Program Files\Titano\Titano.Server.exe")]
[Case(@"""C:\Program Files\dotnet\dotnet.exe"" ""C:\Apps\Titano\Titano.Server.dll"" --service", @"C:\Apps\Titano\Titano.Server.dll")]
[Case(@"C:\Windows\system32\svchost.exe -k netsvcs", @"C:\Windows\system32\svchost.exe")]
[Case(@"Titano.Uploader.exe --tray", null)]
[Case("", null)]
public void TheProgramOfACommandLineIsItsFirstFullPath(string commandLine, string? program) =>
Assert.Equal(program, CommandProgram.Of(commandLine));
[Test]
public void ServiceStepsTravelToTheElevatedCopy()
{
var arguments = new SetupArguments { Services = ServiceActions.Prune | ServiceActions.Start, Directory = @"C:\Program Files\Titano", Elevated = true };
var switches = arguments.ToSwitches().ToList();
Assert.Contains("/SERVICES=prune,start", switches);
Assert.Equal(arguments, SetupArguments.Parse(switches));
Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/DIR=C:\\Apps\\Titano"]).Services);
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=kill", "/DIR=C:\\Apps\\Titano"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=none", "/DIR=C:\\Apps\\Titano"]));
}
[Test]
[WindowsOnly]
public void AServiceWhoseProgramIsGoneIsPrunedAndNothingStartsIt()
{
var folder = context.CreateTempDirectory("services");
// No service is registered from a fresh folder, and nothing is asked of the Service Control Manager.
Assert.Empty(InstalledServices.Find(folder));
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply(folder, ServiceActions.Remove));
var gone = new InstalledService("TitanoTest" + Guid.NewGuid().ToString("N"), "Titano Server", Path.Combine(folder, "Titano.Server.exe"), AutoStart: true);
Assert.False(InstalledServices.IsRunning(gone));
Assert.True(InstalledServices.NeedsWork([gone], ServiceActions.Prune));
Assert.True(InstalledServices.NeedsWork([gone], ServiceActions.Remove));
Assert.False(InstalledServices.NeedsWork([gone], ServiceActions.Stop));
Assert.False(InstalledServices.NeedsWork([gone], ServiceActions.Start));
Assert.False(InstalledServices.NeedsWork([], ServiceActions.Remove));
}
[Test]
[WindowsOnly]
public void UninstallRemovesOnlyTheStartupEntriesOfItsFolder()
{
var folder = Path.Combine(context.CreateTempDirectory("startup"), "Titano Uploader");
const string testsKey = @"Software\Titano.Tests";
var keyPath = testsKey + @"\" + Guid.NewGuid().ToString("N");
try
{
using (var run = Registry.CurrentUser.CreateSubKey(keyPath, writable: true))
{
run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Titano.Uploader.exe")}\" --tray");
run.SetValue("Unquoted", Path.Combine(folder, "tools", "Helper.exe") + " /quiet");
run.SetValue("Other", @"""C:\Program Files\Other\Other.exe"" --background");
run.SetValue("Sibling", $"\"{folder} 2\\Titano.Uploader.exe\"");
Assert.SequenceEqual(["Titano Uploader", "Unquoted"], StartupEntries.RemoveInside(run, folder).Order(StringComparer.Ordinal));
Assert.SequenceEqual(["Other", "Sibling"], run.GetValueNames().Order(StringComparer.Ordinal));
}
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
bool empty;
using (var tests = Registry.CurrentUser.OpenSubKey(testsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 };
if (empty) Registry.CurrentUser.DeleteSubKey(testsKey, throwOnMissingSubKey: false);
}
}
[Test]
[WindowsOnly]
public void AShortcutTellsWhichProgramItStarts()
{
var folder = context.CreateTempDirectory("links");
var target = Path.Combine(folder, "Product A", "Titano.Uploader.exe");
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.WriteAllBytes(target, [0x4D, 0x5A]);
var link = Path.Combine(folder, "Titano Uploader.lnk");
ShellLink.Create(link, target, "Titano Uploader");
// The shell may store the long form of a short (8.3) temporary path: the same file either way.
var stored = Assert.NotNull(ShellLink.TargetOf(link));
Assert.Equal(Path.GetFileName(target), Path.GetFileName(stored));
Assert.FileExists(stored);
var productA = Path.GetDirectoryName(stored)!;
Assert.True(CommandProgram.IsPathInside(stored, productA));
Assert.False(CommandProgram.IsPathInside(stored, Path.Combine(Path.GetDirectoryName(productA)!, "Product B")));
Assert.False(CommandProgram.IsPathInside(stored, productA + " 2"));
Assert.Null(ShellLink.TargetOf(Path.Combine(folder, "missing.lnk")));
var notALink = Path.Combine(folder, "not a link.lnk");
File.WriteAllText(notALink, "plain text");
Assert.Null(ShellLink.TargetOf(notALink));
}
[Test]
[WindowsOnly]
public void TheServerMakesANewInstallationAnAllUsersOne()
{
var manifest = Manifest();
var plan = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano", "Server"] });
Assert.Equal(InstallScope.AllUsers, plan.Scope);
Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.AllUsers, manifest.Product), plan.Directory);
var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano"] });
Assert.Equal(InstallScope.CurrentUser, desktop.Scope);
Assert.True(desktop.CanInstall(manifest.FindComponent("Server")!));
// A per-user installation upgraded in place keeps its scope, so it cannot take the Server.
var perUser = desktop with { Existing = new ExistingInstall(InstallScope.CurrentUser, desktop.Directory, "0.9.0") };
Assert.False(perUser.CanInstall(manifest.FindComponent("Server")!));
Assert.True(perUser.CanInstall(manifest.FindComponent("Titano")!));
}
[Test]
public void TheProjectFileTypeIsNamedInSetupsLanguage()
{
var association = new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" };
Assert.Equal("Titano project", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("en")));
Assert.Equal("Progetto Titano", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("it")));
var unknown = new PayloadAssociation { Component = "Titano", Extension = ".tlx", ProgId = "Titano.Unknown", Description = "Something else", Target = "Titano.exe" };
Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it")));
}
/// <summary>A manifest under a product name no machine has installed, so the registry holds no installation of it.</summary>
private static PayloadManifest Manifest() => new()
{
Product = "TitanoTest" + Guid.NewGuid().ToString("N")[..12],
Version = "1.0.0",
Components =
[
new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true },
new PayloadComponent { Id = "Server", DisplayName = "Titano Server", AllUsersOnly = true },
],
};
}
@@ -0,0 +1,102 @@
using System.IO;
using Titano.Setup.Engine;
using Titano.Testing;
namespace Titano.App.Tests.Setup;
/// <summary>
/// "Remove my data" covers only the programs being removed (SRS-05): the desktop app and the Uploader share
/// %LOCALAPPDATA%\Titano and its logs folder, and uninstalling one product never deletes what another still uses.
/// </summary>
public sealed class UserDataPlanTests(TestContext context)
{
[Test]
public void TheDesktopAppsPlanLeavesTheUploadersFiles()
{
var folder = SampleFolder();
var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Titano));
Assert.SequenceEqual(
["backups", "cache", "logs" + Path.DirectorySeparatorChar + "titano-20261012.log", "settings.json", "titano.db"],
plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
Assert.Equal(4000L + 3000 + 300 + 20 + 100, plan.TotalBytes);
plan.Remove();
Assert.SequenceEqual(
["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"],
Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(folder, f)).Order(StringComparer.Ordinal));
Assert.False(Directory.Exists(Path.Combine(folder, "cache")));
}
[Test]
public void TheUploadersPlanLeavesTheDesktopAppsFilesAndEmptiedFoldersGo()
{
var folder = SampleFolder();
var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Uploader));
Assert.SequenceEqual(
["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"],
plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
plan.Remove();
Assert.True(File.Exists(Path.Combine(folder, "titano.db")));
Assert.True(File.Exists(Path.Combine(folder, "logs", "titano-20261012.log")));
Assert.FileMissing(Path.Combine(folder, "uploader.json"));
Assert.FileMissing(Path.Combine(folder, "logs", "uploader-20261012.log"));
// Once the desktop app's data goes too, nothing is left of the folder.
UserDataPlan.Measure(folder, Owners(UserDataOwners.Titano)).Remove();
Assert.False(Directory.Exists(folder));
}
[Test]
public void BothProgramsDataIsTheWholeFolderAndNoOwnerIsAnEmptyPlan()
{
var folder = SampleFolder();
var whole = UserDataPlan.Measure(folder, UserDataOwners.All);
Assert.SequenceEqual(
["backups", "cache", "logs", "settings.json", "titano.db", "uploader-queue.json", "uploader.json"],
whole.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
Assert.Empty(UserDataPlan.Measure(folder, Owners()).Entries);
whole.Remove();
Assert.False(Directory.Exists(folder));
}
[Test]
public void AProductRemovesTheDataOfItsProgramsThatNoOtherInstalledProductHas()
{
string[] titano = ["Titano", "Uploader", "Server"];
string[] uploader = ["Uploader"];
Assert.SequenceEqual(["Titano", "Uploader"], UserDataOwners.Removable(titano, []).Order(StringComparer.Ordinal));
Assert.SequenceEqual(["Titano"], UserDataOwners.Removable(titano, [uploader]).Order(StringComparer.Ordinal));
Assert.Empty(UserDataOwners.Removable(uploader, [titano]));
Assert.SequenceEqual(["Uploader"], UserDataOwners.Removable(uploader, [["titano"]]));
// Titano Server keeps its data elsewhere: a Server-only product removes nothing here.
Assert.Empty(UserDataOwners.Removable(["Server"], []));
}
private static HashSet<string> Owners(params string[] owners) => new(owners, StringComparer.OrdinalIgnoreCase);
private string SampleFolder()
{
var folder = Path.Combine(context.CreateTempDirectory("userdata"), "Titano");
Write(folder, "titano.db", 4000);
Write(folder, "settings.json", 20);
Write(folder, Path.Combine("cache", "proxies", "a.jpg"), 3000);
Write(folder, Path.Combine("backups", "titano-1.db"), 100);
Write(folder, Path.Combine("logs", "titano-20261012.log"), 300);
Write(folder, Path.Combine("logs", "uploader-20261012.log"), 200);
Write(folder, "uploader.json", 10);
Write(folder, "uploader-queue.json", 50);
return folder;
}
private static void Write(string folder, string relative, int bytes)
{
var path = Path.Combine(folder, relative);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, new byte[bytes]);
}
}
@@ -9,5 +9,6 @@
<ProjectReference Include="..\Titano.Testing\Titano.Testing.csproj" /> <ProjectReference Include="..\Titano.Testing\Titano.Testing.csproj" />
<ProjectReference Include="..\..\src\Titano.App\Titano.App.csproj" /> <ProjectReference Include="..\..\src\Titano.App\Titano.App.csproj" />
<ProjectReference Include="..\..\src\Titano.Uploader\Titano.Uploader.csproj" /> <ProjectReference Include="..\..\src\Titano.Uploader\Titano.Uploader.csproj" />
<ProjectReference Include="..\..\src\Titano.Setup\Titano.Setup.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -0,0 +1,44 @@
using Titano.Core.Packaging;
using Titano.Testing;
using Titano.Tools.Commands;
namespace Titano.Tools.Tests;
/// <summary>pack-installer writes the components, shortcuts and file types setup installs (BRIEF §18).</summary>
public sealed class PackInstallerCommandTests(TestContext context)
{
[Test]
public async Task TheServerInstallsOnlyForAllUsersAndTitanoOwnsTheProjectFileType()
{
var root = context.CreateTempDirectory("pack");
var stub = Path.Combine(root, "Titano.Setup.exe");
var bytes = new byte[4096];
new Random(5).NextBytes(bytes);
"MZ"u8.CopyTo(bytes);
await File.WriteAllBytesAsync(stub, bytes);
var app = Program(root, "app", "Titano.exe");
var server = Program(root, "server", "Titano.Server.exe");
var output = Path.Combine(root, "out", "Titano-Setup.exe");
Assert.Equal(0, await new PackInstallerCommand().RunAsync(
["--setup", stub, "--product", "Titano", "--version", "1.2.3", "--component", "Titano=" + app, "--component", "Server=" + server, "--out", output]));
using var reader = PayloadReader.Open(output);
var manifest = reader.Manifest;
Assert.False(manifest.FindComponent("Titano")!.AllUsersOnly);
var serverComponent = manifest.FindComponent("Server")!;
Assert.True(serverComponent.AllUsersOnly);
Assert.False(serverComponent.DefaultSelected);
var association = Assert.Contains(manifest.Associations, a => a.Extension == ".titano");
Assert.Equal("Titano.Project", association.ProgId);
Assert.Equal("Titano.exe", association.Target);
Assert.Equal("Titano", association.Component);
}
private static string Program(string root, string folder, string name)
{
var dir = Directory.CreateDirectory(Path.Combine(root, folder)).FullName;
File.WriteAllText(Path.Combine(dir, name), "MZ " + name);
return dir;
}
}