Merge branch 'fix/setup-bundle': .titano project files, per-machine server, services and Run entries handled by setup, per-product data removal

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 11:48:04 +00:00
commit 4c68940ca7
49 files changed
+2741 -128

No files matched your search

+103 -4
View File
@@ -1,6 +1,7 @@
using System.Windows;
using System.Windows.Threading;
using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
@@ -12,11 +13,20 @@ namespace Titano.App;
/// <summary>
/// Titano desktop client. Local mode starts here: settings and language before the first window, then the window,
/// then the index and the job engine (<see cref="AppServices"/>) off the UI thread. <c>--capture &lt;dir&gt;</c>
/// renders every screen with synthetic data in a throw-away data folder and exits.
/// renders every screen with synthetic data in a throw-away data folder and exits. A file argument is a
/// <c>.titano</c> project file (Explorer passes it on a double-click) opened once the index is open. One Titano runs
/// per data folder: a second launch hands its file to the running one and exits, or, when the running one is closing,
/// waits for it to exit and starts with the file (<see cref="SingleInstance"/>).
/// </summary>
public partial class App : Application
{
/// <summary>How long a launch waits for a Titano that is closing (it gives its services up to 10 s to stop).</summary>
private static readonly TimeSpan ClosingWait = TimeSpan.FromSeconds(30);
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
private FileLogSink? _log;
private SingleInstance? _instance;
private bool _windowClosed;
public AppEnvironment Environment { get; private set; } = null!;
public AppSettings Settings { get; private set; } = null!;
@@ -36,6 +46,32 @@ public partial class App : Application
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
var projectFile = capture ? null : ProjectFileArgument(e.Args);
if (!capture)
{
_instance = SingleInstance.TryAcquire(Environment.DataDirectory);
if (_instance is null)
{
if (SingleInstance.HandOver(Environment.DataDirectory, projectFile is null ? [] : [projectFile]))
{
Log.Info("app", "Titano already runs on this data folder; arguments handed over");
Shutdown();
return;
}
// No answer: the running Titano is closing (it stops listening first). Start once it has exited.
_instance = SingleInstance.WaitForTurn(Environment.DataDirectory, ClosingWait);
if (_instance is null)
{
Log.Info("app", "Titano already runs on this data folder and did not answer");
Shutdown();
return;
}
Log.Info("app", "The previous Titano on this data folder has exited");
}
// From now on: a launch while the window and the index open is kept until the shell can take it.
_instance.Listen();
}
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
UiLanguage.Apply(Settings.Language);
ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
@@ -64,12 +100,19 @@ public partial class App : Application
_ = ScreenCapture.RunAsync(window, shell, sample!, dir);
return;
}
// Closing the main window ends Titano: later launches wait for it instead of handing over a file it cannot open.
window.Closed += (_, _) =>
{
_windowClosed = true;
_instance?.StopListening();
};
window.Show();
_ = StartAsync(shell);
_instance?.Receive(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
_ = StartAsync(shell, projectFile);
}
/// <summary>Opens the index and the job engine after the window is visible, then fills the screens.</summary>
private async Task StartAsync(ShellViewModel shell)
/// <summary>Opens the index and the job engine after the window is visible, fills the screens, then opens the project file given.</summary>
private async Task StartAsync(ShellViewModel shell, string? projectFile)
{
try
{
@@ -80,10 +123,63 @@ public partial class App : Application
{
shell.ReportError(ex);
}
finally
{
_started.TrySetResult();
}
if (projectFile is not null) await OpenProjectFileAsync(shell, projectFile);
}
/// <summary>A later launch: its window comes to the front here, and its project file opens.</summary>
private void OnHandOver(ShellViewModel shell, IReadOnlyList<string> args)
{
if (_windowClosed)
{
Log.Warning("app", "A launch arrived while Titano was closing; its arguments are ignored");
return;
}
if (MainWindow is { } window)
{
window.Show();
if (window.WindowState == WindowState.Minimized) window.WindowState = WindowState.Normal;
window.Activate();
}
if (ProjectFileArgument(args) is { } projectFile) _ = OpenProjectFileAsync(shell, projectFile);
}
/// <summary>Opens a project file once the index is open; failures become the usual one-sentence toast.</summary>
private async Task OpenProjectFileAsync(ShellViewModel shell, string path)
{
await _started.Task;
try
{
await new ProjectFiles(shell).OpenAsync(path);
}
catch (Exception ex)
{
shell.ReportError(ex);
}
}
/// <summary>The first argument that is not an option, as a full path (the hand-over crosses working folders).</summary>
private static string? ProjectFileArgument(IReadOnlyList<string> args)
{
if (args.FirstOrDefault(a => !a.StartsWith("--", StringComparison.Ordinal) && a.Length > 0) is not { } file) return null;
try
{
return System.IO.Path.GetFullPath(file);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or System.IO.PathTooLongException)
{
Log.Warning("app", $"Ignoring argument '{file}'", ex);
return null;
}
}
public void SaveSettings()
{
// A launch that handed over to the running Titano exits before loading any settings.
if (Settings is null) return;
try
{
Settings.Save(Environment.SettingsPath);
@@ -96,6 +192,8 @@ public partial class App : Application
protected override void OnExit(ExitEventArgs e)
{
// The mutex stays until the services have stopped, so a launch now waits for this one to exit.
_instance?.StopListening();
SaveSettings();
if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
try
@@ -108,6 +206,7 @@ public partial class App : Application
{
Log.Warning("app", "Services stopped with an error", ex);
}
_instance?.Dispose();
Log.Info("app", "Titano exiting");
_log?.Dispose();
if (Environment.IsCapture) Environment.DeleteCaptureData();
+3
View File
@@ -293,6 +293,9 @@
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
ToolTip="{Binding HistoryText}" />
</DockPanel>
<!-- A .titano project file that opens this sequence with these settings (BRIEF §18). -->
<Button Style="{StaticResource Button.Link}" HorizontalAlignment="Left" Margin="0,8,0,0" Content="{l:Loc Editor.ProjectFile.Save}"
Command="{Binding SaveProjectCommand}" ToolTip="{Binding SaveProjectToolTip}" ToolTipService.ShowOnDisabled="True" />
<!-- This PC's settings kept by "Save both" (sync conflicts): the newest, or another from the menu, becomes the project as one undo step. -->
<v:SplitButton Margin="0,8,0,0" HorizontalAlignment="Left" Content="{Binding RestoreText}" Command="{Binding RestoreCommand}"
ItemsSource="{Binding SavedCopies}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedCopy}" ToolTip="{Binding RestoreToolTip}"
+9
View File
@@ -139,6 +139,7 @@ public sealed class ExportTab : EditorTab
HistoryCommand = new RelayCommand(OpenHistory);
RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => CanReveal);
_restore = new AsyncRelayCommand(RestoreAsync, () => !Editor.IsLocked && SelectedCopy is not null);
SaveProjectCommand = new AsyncRelayCommand(() => new ProjectFiles(Editor.Shell).SaveAsync(Editor.Session), () => !Editor.IsRemote);
ResetFrameRateCommand = new RelayCommand(() => EditOverrides(o => o with { FrameRate = null }));
Width = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Width = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Width"));
Height = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Height = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Height"));
@@ -178,6 +179,14 @@ public sealed class ExportTab : EditorTab
/// <summary>The newest render is a file on this PC (a server's renders stay on the server).</summary>
public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..];
/// <summary>
/// Saves a <c>.titano</c> project file of this sequence and its settings (BRIEF §18); a server sequence has no
/// archive on this PC for the file to name.
/// </summary>
public ICommand SaveProjectCommand { get; }
public string SaveProjectToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.ProjectFile.Remote") : Loc.L("Tooltips.Editor.ProjectFile.Save");
// ---- Export "Sync" (Export.html, next to Save to) ----
/// <summary>Send each render made on this PC to the server the sequence is linked to; remembered in the project.</summary>
+92
View File
@@ -0,0 +1,92 @@
using System.IO;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Data.Processing;
namespace Titano.App.Editor;
/// <summary>
/// <c>.titano</c> project files (BRIEF §18): the editor saves one for the open sequence of this PC's archive, and
/// opening one (a double-click, which Windows passes to Titano.exe) opens its sequence in the editor and gives it the
/// file's settings as one undoable step.
/// </summary>
public sealed class ProjectFiles(ShellViewModel shell)
{
/// <summary>Asks for a folder and saves the session's sequence and current settings there; never replaces a file.</summary>
public async Task SaveAsync(EditorSession session)
{
if (session.IsRemote) return;
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
if (shell.Services.Dialogs.PickFolder(Loc.L("Editor.ProjectFile.Title")) is not { } folder) return;
var bundle = await ProjectBundles.CreateAsync(db, session.Content.Sequence.Id, session.Project, session.Content.Count);
var path = await Task.Run(() =>
{
var free = ProjectBundle.FreePathIn(folder, bundle.Sequence.Title ?? session.Content.Sequence.DisplayTitle);
bundle.Save(free);
return free;
});
Log.Info("project", $"Project file '{path}' saved for sequence {bundle.Sequence.Id}");
shell.Notify(Loc.L("Editor.ProjectFile.Saved"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
() => ShellActions.Reveal(path));
}
/// <summary>
/// Opens the project file at <paramref name="path"/>: its sequence in the editor (found by id, else by archive and
/// folder), then the file's settings as one undo step. Says in one sentence why when the file cannot be read, its
/// sequence is not in the library, or the sequence cannot take the settings now.
/// </summary>
public async Task OpenAsync(string path)
{
ProjectBundle bundle;
try
{
bundle = await Task.Run(() => ProjectBundle.Load(path));
}
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)
{
Log.Warning("project", $"Project file '{path}' not opened", ex);
shell.Notify(Loc.L("Editor.ProjectFile.Unreadable"), Path.GetFileName(path), Loc.L("Common.OpenLogs"), Loc.L("Tooltips.Common.OpenLogs"),
() => ShellActions.Reveal(shell.Services.Environment.LogDirectory), isError: true);
return;
}
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
if (await ProjectBundles.ResolveAsync(db, bundle) is not { } sequence)
{
Log.Info("project", $"Project file '{path}': sequence {bundle.Sequence.Id} ('{bundle.Sequence.Folder}' in archive {bundle.Archive.Id}) not in the index");
shell.Notify(Loc.L("Editor.ProjectFile.NotFound"), bundle.Sequence.Title ?? Path.GetFileName(path), Loc.L("Shell.Nav.Archive"),
Loc.L("Tooltips.Nav.Archive"), () => shell.Navigate(SectionKey.Archive), isError: true);
return;
}
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
if (await shell.Sequence.ShowAsync(sequence.Id) is not { } editor) return;
Apply(editor, bundle);
}
/// <summary>Gives the open sequence the file's settings, unless the editor cannot change them now (a job runs, read-only).</summary>
private void Apply(EditorViewModel editor, ProjectBundle bundle)
{
var session = editor.Session;
var settings = bundle.ProjectFor(session.Project, session.Content.Count);
if (settings.ToJson() == session.Project.ToJson()) return;
if (editor.IsLocked)
{
shell.Notify(Loc.L("Editor.ProjectFile.Locked"), editor.LockedToolTip, Loc.L("Editor.ProjectFile.Retry"), Loc.L("Tooltips.Editor.ProjectFile.Retry"),
() =>
{
// Still the same editor: the file's settings, laid over the project as it is then.
if (ReferenceEquals(shell.Sequence.Editor, editor)) Apply(editor, bundle);
}, isError: true);
return;
}
var before = session.Project;
if (!session.Edit(_ => settings)) return;
session.EndEditRun();
var restore = new ProjectRestore(session, before, session.Project);
Log.Info("project", $"Project file settings applied to sequence {session.Content.Sequence.Id}");
shell.Notify(Loc.L("Editor.ProjectFile.Applied"), session.Content.Sequence.DisplayTitle, Loc.L("Editor.ProjectFile.Undo"),
Loc.L("Tooltips.Editor.ProjectFile.Undo"), () => restore.Undo());
}
}
@@ -0,0 +1,252 @@
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Titano.Core.Diagnostics;
namespace Titano.App.Infrastructure;
/// <summary>
/// One Titano per data folder in a Windows session (two would share one index and job engine): a named mutex marks
/// the running instance, and a later launch (a double-clicked <c>.titano</c> file, the Start menu) hands its file
/// arguments over a named pipe (current user only), lets the running window come to the front and exits. The running
/// instance listens from the moment it holds the mutex, keeping what arrives until its window can take it, and stops
/// listening as soon as it starts closing; a launch that gets no answer waits for it to exit and starts in its place.
/// Same protocol as the Uploader's, kept per program so neither depends on the other.
/// </summary>
public sealed partial class SingleInstance : IDisposable
{
private const string Header = "TITANO/1";
private const int MaxMessageBytes = 1 << 20;
private const int AnyProcess = -1;
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _stop = new();
private readonly Lock _gate = new();
private readonly Queue<IReadOnlyList<string>> _waiting = new();
private Action<IReadOnlyList<string>>? _received;
private Task? _listening;
private bool _disposed;
private SingleInstance(Mutex mutex, string pipeName)
{
_mutex = mutex;
_pipeName = pipeName;
}
/// <summary>
/// The instance guard for <paramref name="dataDirectory"/>, or null when another Titano already uses it in this
/// session (also one running with administrator rights, whose mutex this launch may not even open).
/// </summary>
public static SingleInstance? TryAcquire(string dataDirectory)
{
Mutex mutex;
bool createdNew;
try
{
mutex = new Mutex(initiallyOwned: true, MutexName(dataDirectory), out createdNew);
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Titano runs with administrator rights on this data folder: {ex.Message}");
return null;
}
if (createdNew) return new SingleInstance(mutex, PipeName(dataDirectory));
mutex.Dispose();
return null;
}
/// <summary>
/// Waits up to <paramref name="timeout"/> for the Titano running on <paramref name="dataDirectory"/> to exit (while
/// it closes it no longer answers hand-overs), then becomes the running instance; null when it still runs, or runs
/// with administrator rights.
/// </summary>
public static SingleInstance? WaitForTurn(string dataDirectory, TimeSpan timeout)
{
Mutex mutex;
try
{
mutex = new Mutex(initiallyOwned: false, MutexName(dataDirectory));
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Titano runs with administrator rights on this data folder: {ex.Message}");
return null;
}
try
{
if (mutex.WaitOne(timeout)) return new SingleInstance(mutex, PipeName(dataDirectory));
}
catch (AbandonedMutexException)
{
// The other Titano ended without releasing it (it crashed): this thread owns it now.
Log.Warning("instance", "The previous Titano ended without closing");
return new SingleInstance(mutex, PipeName(dataDirectory));
}
mutex.Dispose();
return null;
}
/// <summary>
/// Sends <paramref name="args"/> (absolute paths; empty = just show the window) to the Titano running on
/// <paramref name="dataDirectory"/>; false when it could not be reached.
/// </summary>
public static bool HandOver(string dataDirectory, IReadOnlyList<string> args)
{
// This launch came from the user, so it may give the running window the right to come to the front.
AllowSetForegroundWindow(AnyProcess);
try
{
using var pipe = new NamedPipeClientStream(".", PipeName(dataDirectory), PipeDirection.Out, PipeOptions.CurrentUserOnly);
pipe.Connect(3000);
pipe.Write(Encode(args));
pipe.Flush();
return true;
}
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException)
{
Log.Warning("instance", "Could not reach the running Titano", ex);
return false;
}
}
/// <summary>Starts receiving messages from later launches; they wait until <see cref="Receive"/> names who takes them.</summary>
public void Listen()
{
lock (_gate)
{
if (_listening is not null || _disposed) return;
_listening = ListenAsync(_pipeName, OnMessage, _stop.Token);
}
}
/// <summary>
/// Hands the messages received so far, then each later one, to <paramref name="received"/>, in order; it runs on a
/// pool thread.
/// </summary>
public void Receive(Action<IReadOnlyList<string>> received)
{
lock (_gate)
{
_received = received;
while (_waiting.TryDequeue(out var args)) received(args);
}
}
/// <summary>
/// Stops answering later launches while keeping the mutex: from now on they wait for this instance to exit instead
/// of handing over arguments it could no longer open.
/// </summary>
public void StopListening()
{
Task? listening;
lock (_gate)
{
if (_disposed) return;
_stop.Cancel();
listening = _listening;
}
// The pipe closes as the loop ends (cancellation ends it quietly).
try
{
listening?.Wait(TimeSpan.FromSeconds(2));
}
catch (AggregateException ex)
{
Log.Warning("instance", "Hand-over listener ended with an error", ex);
}
}
public void Dispose()
{
StopListening();
lock (_gate)
{
if (_disposed) return;
_disposed = true;
}
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
}
/// <summary>UTF-8: a header line, then one argument per line (paths cannot contain line breaks).</summary>
public static byte[] Encode(IReadOnlyList<string> args) =>
Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal))));
/// <summary>Arguments of a message, or null when it is not one of ours.</summary>
public static IReadOnlyList<string>? Decode(ReadOnlySpan<byte> message)
{
if (message.Length > MaxMessageBytes) return null;
var lines = Encoding.UTF8.GetString(message).Split('\n');
if (lines[0] != Header) return null;
return [.. lines.Skip(1).Where(l => l.Length > 0)];
}
private void OnMessage(IReadOnlyList<string> args)
{
lock (_gate)
{
if (_received is null) _waiting.Enqueue(args);
else _received(args);
}
}
/// <summary>The data folder's identity (case-insensitive, as Windows paths are): a portable copy has its own instance.</summary>
private static string Key(string dataDirectory) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(dataDirectory).TrimEnd('\\', '/').ToUpperInvariant())))[..16];
private static string MutexName(string dataDirectory) => @"Local\Titano.App." + Key(dataDirectory);
private static string PipeName(string dataDirectory)
{
using var process = Process.GetCurrentProcess();
return $"Titano.App.{process.SessionId}.{Environment.UserName}.{Key(dataDirectory)}";
}
private static async Task ListenAsync(string pipeName, Action<IReadOnlyList<string>> received, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await using var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
await pipe.CopyToAsync(buffer, ct).ConfigureAwait(false);
if (Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)) is { } args) received(args);
}
catch (OperationCanceledException)
{
return;
}
catch (UnauthorizedAccessException ex)
{
// The pipe name belongs to a Titano running with administrator rights: later launches wait instead.
Log.Warning("instance", "Hand-over pipe not available", ex);
return;
}
catch (IOException ex)
{
// A pipe of the same name still held by a Titano that is exiting, or a broken connection: try again shortly.
Log.Warning("instance", "Hand-over pipe failed; listening again", ex);
try
{
await Task.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
[LibraryImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool AllowSetForegroundWindow(int processId);
}
@@ -75,6 +75,20 @@ public sealed class SequenceViewModel : SectionViewModel
return _switch;
}
/// <summary>
/// Shows <paramref name="sequenceId"/> in the editor, as the Library does, and returns its editor once open; null
/// when it did not open (the reason was reported, or the open sequence's unsaved edit was kept) or waits for its
/// proxies.
/// </summary>
public async Task<EditorViewModel?> ShowAsync(Guid sequenceId)
{
Shell.OpenSequence(sequenceId);
// Already chosen and shown but not open (an earlier open failed): opening it again is what is asked now.
if (_openId != sequenceId && _switch.IsCompleted) _ = OpenAsync(sequenceId);
await Settled(_switch);
return _openId == sequenceId ? Editor : null;
}
/// <summary>
/// Fetches the proxies of server sequence <paramref name="remoteId"/> into this PC's cache (a download job, shown in
/// the job bar and on the Jobs screen) and opens it in the editor once they are here, if it is still the sequence
@@ -155,6 +155,12 @@ public sealed class PayloadComponent
/// <summary>Installed size in bytes (sum of the component's files).</summary>
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>
+3 -2
View File
@@ -5,8 +5,8 @@ using Titano.Core.IO;
namespace Titano.Core.Packaging;
/// <summary>A component to pack: its manifest identity and the folder whose whole tree it installs.</summary>
public sealed record PayloadComponentSource(string Id, string DisplayName, bool DefaultSelected, string Folder);
/// <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, bool AllUsersOnly = false);
/// <summary>Everything the packer needs besides the setup program.</summary>
public sealed class PayloadSource
@@ -48,6 +48,7 @@ public static class PayloadWriter
Id = c.Id,
DisplayName = c.DisplayName,
DefaultSelected = c.DefaultSelected,
AllUsersOnly = c.AllUsersOnly,
EstimatedSize = files.Where(f => f.Component == c.Id).Sum(f => f.Size),
}).ToList();
var manifest = new PayloadManifest
+167
View File
@@ -0,0 +1,167 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Titano.Core.IO;
using Titano.Core.Naming;
namespace Titano.Core.Project;
/// <summary>The archive a project file's sequence lives in: its id, and its name and folder when the file was saved.</summary>
public sealed record BundleArchive(Guid Id, string Name, string? Path);
/// <summary>The sequence a project file applies to: its id, folder (relative to the archive), title and frame count when saved.</summary>
public sealed record BundleSequence(Guid Id, string Folder, string? Title, int Frames);
/// <summary>
/// A <c>.titano</c> project file (BRIEF §18, file associations): which sequence of which archive, and the project
/// settings to open it with. The photos stay in the archive; opening the file opens that sequence in the editor with
/// these settings. UTF-8 JSON with a format name and version, so a newer file is refused rather than misread:
/// <code>{ "format": "titano-project", "formatVersion": 1, "saved": …, "archive": { "id", "name", "path" },
/// "sequence": { "id", "folder", "title", "frames" }, "project": { …project.json… } }</code>
/// </summary>
public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequence, ProjectSettings Project, DateTimeOffset Saved)
{
public const string Extension = ".titano";
public const string FormatName = "titano-project";
public const int CurrentFormatVersion = 1;
/// <summary>Project settings take a few kilobytes; a larger file is not a project file.</summary>
public const int MaxBytes = 4 << 20;
private static readonly JsonWriterOptions Indented = new() { Indented = true };
public string ToJson()
{
using var buffer = new MemoryStream();
using (var w = new Utf8JsonWriter(buffer, Indented))
{
w.WriteStartObject();
w.WriteString("format", FormatName);
w.WriteNumber("formatVersion", CurrentFormatVersion);
w.WriteString("saved", Saved);
w.WriteStartObject("archive");
w.WriteString("id", Archive.Id);
w.WriteString("name", Archive.Name);
if (Archive.Path is not null) w.WriteString("path", Archive.Path);
w.WriteEndObject();
w.WriteStartObject("sequence");
w.WriteString("id", Sequence.Id);
w.WriteString("folder", Sequence.Folder);
if (Sequence.Title is not null) w.WriteString("title", Sequence.Title);
w.WriteNumber("frames", Sequence.Frames);
w.WriteEndObject();
w.WritePropertyName("project");
// The project as project.json holds it, so both are read by the same tolerant reader.
using (var project = JsonDocument.Parse(Project.ToJson())) project.RootElement.WriteTo(w);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length);
}
/// <summary>Reads a project file's text.</summary>
/// <exception cref="InvalidDataException">Not a Titano project file, damaged, or written by a newer Titano.</exception>
public static ProjectBundle Parse(string json)
{
JsonDocument document;
try
{
document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 64 });
}
catch (JsonException ex)
{
throw new InvalidDataException("The project file is not valid JSON.", ex);
}
using (document)
{
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != FormatName) throw new InvalidDataException("Not a Titano project file.");
if (!root.TryGetProperty("formatVersion", out var v) || v.ValueKind != JsonValueKind.Number || !v.TryGetInt32(out var version) || version < 1)
throw new InvalidDataException("The project file has no valid format version.");
if (version > CurrentFormatVersion) throw new InvalidDataException($"The project file uses format {version}, newer than this Titano ({CurrentFormatVersion}).");
var archive = Section(root, "archive");
var sequence = Section(root, "sequence");
var folder = Text(sequence, "folder");
if (string.IsNullOrWhiteSpace(folder)) throw new InvalidDataException("The project file names no sequence folder.");
var frames = sequence.TryGetProperty("frames", out var f) && f.ValueKind == JsonValueKind.Number && f.TryGetInt32(out var count) && count >= 0 ? count : 0;
if (!root.TryGetProperty("project", out var project) || project.ValueKind != JsonValueKind.Object)
throw new InvalidDataException("The project file holds no project settings.");
ProjectSettings settings;
try
{
settings = ProjectSettings.FromJson(project.GetRawText());
}
catch (JsonException ex)
{
throw new InvalidDataException("The project settings in the file cannot be read.", ex);
}
var saved = root.TryGetProperty("saved", out var s) && s.ValueKind == JsonValueKind.String && s.TryGetDateTimeOffset(out var when) ? when : default;
return new ProjectBundle(
new BundleArchive(Id(archive), Text(archive, "name") ?? string.Empty, Text(archive, "path")),
new BundleSequence(Id(sequence), folder, Text(sequence, "title"), frames),
settings,
saved);
}
}
/// <summary>Reads a project file.</summary>
/// <exception cref="InvalidDataException">Not a Titano project file (or too large to be one), damaged, or newer.</exception>
/// <exception cref="IOException">The file cannot be read.</exception>
public static ProjectBundle Load(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
if (stream.Length > MaxBytes) throw new InvalidDataException("The file is too large to be a Titano project file.");
using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
return Parse(reader.ReadToEnd());
}
/// <summary>Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file.</summary>
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
/// <summary>
/// The settings to give the sequence when the file is opened, the sequence having <paramref name="frameCount"/>
/// frames and <paramref name="current"/> settings: the file's settings, except the frame positions (exclusions,
/// hero frame, camera keyframes) when frames were added or removed since the file was saved, as they would now
/// point at other frames; the sequence keeps its own.
/// </summary>
public ProjectSettings ProjectFor(ProjectSettings current, int frameCount) => frameCount == Sequence.Frames
? Project
: Project with
{
ExcludedFrames = current.ExcludedFrames,
HeroFrame = current.HeroFrame,
Camera = Project.Camera with { Keyframes = current.Camera.Keyframes },
};
/// <summary>A file name for the project of a sequence titled <paramref name="title"/>, valid on every file system.</summary>
public static string FileNameFor(string title) =>
(PathTemplate.SanitizeSegment(title) is { Length: > 0 } name ? name : "Titano") + Extension;
/// <summary>
/// A path in <paramref name="folder"/> for the project of <paramref name="title"/> that names no existing file
/// ("Harbour sunset.titano", then "Harbour sunset (2).titano"…): saving never replaces an earlier project file.
/// </summary>
public static string FreePathIn(string folder, string title)
{
var name = Path.GetFileNameWithoutExtension(FileNameFor(title));
var path = Path.Combine(folder, name + Extension);
for (var n = 2; File.Exists(path) || Directory.Exists(path); n++)
path = Path.Combine(folder, string.Create(CultureInfo.InvariantCulture, $"{name} ({n}){Extension}"));
return path;
}
private static JsonElement Section(JsonElement root, string name)
{
if (!root.TryGetProperty(name, out var section) || section.ValueKind != JsonValueKind.Object)
throw new InvalidDataException($"The project file has no '{name}' section.");
return section;
}
private static Guid Id(JsonElement section) =>
section.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String && id.TryGetGuid(out var guid) && guid != Guid.Empty
? guid
: throw new InvalidDataException("The project file has a missing or invalid id.");
private static string? Text(JsonElement section, string name) =>
section.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
}
@@ -0,0 +1,42 @@
using Titano.Core.Model;
using Titano.Core.Project;
namespace Titano.Data.Processing;
/// <summary>
/// <c>.titano</c> project files (BRIEF §18) against this index: the file for a sequence of one of its archives, and
/// the sequence a file names.
/// </summary>
public static class ProjectBundles
{
/// <summary>
/// The project file of <paramref name="sequenceId"/> with <paramref name="project"/> (the editor's current
/// settings), whose frame positions refer to <paramref name="frames"/> frames.
/// </summary>
/// <exception cref="InvalidOperationException">The sequence is not in the index.</exception>
public static async Task<ProjectBundle> CreateAsync(TitanoDatabase db, Guid sequenceId, ProjectSettings project, int frames,
CancellationToken cancellationToken = default)
{
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidOperationException($"Sequence {sequenceId} is not in the index.");
var archive = await db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false);
return new ProjectBundle(
new BundleArchive(sequence.ArchiveId, archive?.Name ?? string.Empty, archive?.RootPath),
new BundleSequence(sequence.Id, sequence.Folder, sequence.DisplayTitle, frames),
project,
DateTimeOffset.UtcNow);
}
/// <summary>
/// The sequence <paramref name="bundle"/> names: by its id, else the sequence in the same folder of the same
/// archive (an index rebuilt elsewhere, or a folder adopted again, gives it a new id). Null when this index has
/// neither: the archive is not added here, or the sequence was deleted.
/// </summary>
public static async Task<Sequence?> ResolveAsync(TitanoDatabase db, ProjectBundle bundle, CancellationToken cancellationToken = default)
{
if (await db.Sequences.GetAsync(bundle.Sequence.Id, cancellationToken).ConfigureAwait(false) is { } byId) return byId;
var locations = await db.Sequences.ListLocationsAsync(bundle.Archive.Id, cancellationToken).ConfigureAwait(false);
var match = locations.FirstOrDefault(l => string.Equals(l.Folder, bundle.Sequence.Folder, StringComparison.OrdinalIgnoreCase));
return match is null ? null : await db.Sequences.GetAsync(match.Id, cancellationToken).ConfigureAwait(false);
}
}
+26 -1
View File
@@ -1,4 +1,5 @@
using System.Text;
using Titano.Setup.Engine;
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>/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
/// uninstaller after the uninstall process exits).
/// uninstaller after the uninstall process exits), <c>/SERVICES=stop,prune,start,remove /NAMES=a,b /DIR=path</c> (the
/// elevated step that stops, starts or deletes the named Windows services of an installation).
/// </summary>
internal sealed record SetupArguments
{
@@ -23,6 +25,10 @@ internal sealed record SetupArguments
public bool Elevated { get; init; }
public string? CleanupTarget { get; init; }
public int WaitProcessId { get; init; }
public ServiceActions Services { get; init; }
/// <summary>The services <see cref="Services"/> applies to (key names, as the unelevated setup found them).</summary>
public IReadOnlyList<string>? ServiceNames { get; init; }
/// <summary>Parses <paramref name="args"/>; throws <see cref="ArgumentException"/> for unknown or malformed switches.</summary>
public static SetupArguments Parse(IEnumerable<string> args)
@@ -48,10 +54,14 @@ internal sealed record SetupArguments
("COMPONENTS", { Length: > 0 }) => result with { Components = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) },
("CLEANUP", { Length: > 0 }) => result with { CleanupTarget = value.Trim('"') },
("WAITPID", { Length: > 0 }) when int.TryParse(value, out var pid) && pid > 0 => result with { WaitProcessId = pid },
("SERVICES", { Length: > 0 }) => result with { Services = ParseServices(value) },
("NAMES", { Length: > 0 }) => result with { ServiceNames = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) },
_ => 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.Services != ServiceActions.None && (result.Directory is null || result.ServiceNames is not { Count: > 0 }))
throw new ArgumentException("/SERVICES needs /DIR and /NAMES.");
return result;
}
@@ -67,9 +77,24 @@ internal sealed record SetupArguments
if (NoStartMenu) yield return "/NOSTARTMENU";
if (Launch) yield return "/LAUNCH";
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 (ServiceNames is not null) yield return "/NAMES=" + string.Join(',', ServiceNames);
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>
/// Joins arguments into one command line that <c>CommandLineToArgvW</c> splits back into the same strings
/// (quotes around spaces, backslashes doubled before a quote).
+87
View File
@@ -0,0 +1,87 @@
using System.IO;
using Titano.Core.Packaging;
namespace Titano.Setup.Engine;
/// <summary>
/// The program a command line registered with Windows starts (a service's image path, a Run value), and whether it is
/// one setup installed: setup changes only what starts a program its log or payload lists, never another program
/// that happens to live in the same folder.
/// </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>
/// Full paths of <paramref name="payloadPaths"/> (an install log's or a manifest's files) under
/// <paramref name="directory"/>, compared ignoring case: the programs setup installs or installed there.
/// </summary>
public static IReadOnlySet<string> FullPaths(string directory, IEnumerable<string> payloadPaths)
{
var paths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var path in payloadPaths.Where(PayloadPath.IsValid)) paths.Add(PayloadPath.Resolve(directory, path));
return paths;
}
/// <summary>True when <paramref name="program"/> (a full path, in any form Windows accepts) is one of <paramref name="programs"/>.</summary>
public static bool IsAmong(string? program, IReadOnlySet<string> programs)
{
if (string.IsNullOrEmpty(program) || !Path.IsPathFullyQualified(program)) return false;
try
{
return programs.Contains(Path.GetFullPath(program));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return false;
}
}
/// <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;
}
}
+58 -11
View File
@@ -1,6 +1,8 @@
using System.Globalization;
using System.IO;
using System.Reflection;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Interop;
@@ -72,9 +74,9 @@ internal sealed class InstallEngine(PayloadReader payload)
// Saved before registration so that an uninstall can always undo whatever follows.
log.Save(directory);
foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name);
foreach (var (link, target, name, _) in shortcuts.Where(s => s.Create)) ShellLink.Create(link, target, name);
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();
var uninstallerPath = Path.Combine(directory, uninstaller);
@@ -86,24 +88,50 @@ internal sealed class InstallEngine(PayloadReader payload)
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 =>
typeof(InstallEngine).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo
? "https://github.com/" + repo
: null;
private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory)
/// <summary>
/// The shortcuts to log, and among them those 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 but logged:
/// neither install retargets or removes the other's, and when the other product is uninstalled it hands the
/// shortcut over to this copy (<see cref="UninstallEngine.DeleteShortcut"/>).
/// </summary>
private List<(string Link, string Target, string Name, bool Create)> PlanShortcuts(InstallRequest request, string directory)
{
var selected = new HashSet<string>(request.Components, StringComparer.OrdinalIgnoreCase);
var result = new List<(string, string, string)>();
var result = new List<(string, string, string, bool)>();
foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component)))
{
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.Desktop && request.DesktopShortcuts) result.Add((Path.Combine(SetupPaths.Desktop(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) Add(Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name);
}
return result;
void Add(string link, string target, string name)
{
var create = true;
if (ShellLink.TargetOf(link) is { } current && !CommandProgram.IsPathInside(current, directory) && File.Exists(current))
{
Log.Info("setup", $"Shortcut '{link}' starts '{current}'; left as it is");
create = false;
}
result.Add((link, target, name, create));
}
}
private List<PayloadAssociation> PlanFileTypes(InstallRequest request)
@@ -112,13 +140,32 @@ internal sealed class InstallEngine(PayloadReader payload)
return Manifest.Associations.Where(a => selected.Contains(a.Component)).ToList();
}
/// <summary>Removes what the previous version installed and this one no longer does (files, shortcuts, file types).</summary>
/// <summary>
/// Removes what the previous version installed and this one no longer does (files, the sign-in entries of those
/// programs, shortcuts, file types).
/// </summary>
private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current)
{
var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList();
if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete);
foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase))
UninstallEngine.DeleteShortcut(link, previous.Scope);
if (obsolete.Count > 0)
{
InstalledFiles.Remove(directory, obsolete);
try
{
// A dropped Uploader no longer starts at sign-in.
SetupRegistry.DeleteStartupEntries(CommandProgram.FullPaths(directory, obsolete));
}
catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("setup", "Sign-in entries not removed", ex);
}
}
var links = previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase).ToList();
if (links.Count > 0)
{
var others = SetupRegistry.OtherInstalls(directory, Publisher);
foreach (var link in links) UninstallEngine.DeleteShortcut(link, previous.Scope, directory, others);
}
foreach (var a in previous.Associations.Except(current.Associations))
{
if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId);
+4 -1
View File
@@ -23,7 +23,10 @@ internal sealed class InstallLog
/// <summary>Installed payload paths, relative to the install folder (the uninstaller and this log excluded).</summary>
public List<string> Files { get; set; } = [];
/// <summary>Full paths of the shortcuts setup created.</summary>
/// <summary>
/// Full paths of the shortcuts setup created, or would have created but found starting an existing program elsewhere
/// (another Titano product's copy, which hands them over to this one when it is uninstalled).
/// </summary>
public List<string> Shortcuts { get; set; } = [];
public List<InstalledAssociation> Associations { get; set; } = [];
+38 -2
View File
@@ -1,3 +1,4 @@
using Titano.Core.Diagnostics;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
@@ -5,7 +6,10 @@ namespace Titano.Setup.Engine;
/// <summary>
/// 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, in a folder inside Program Files; an installation upgraded in place elsewhere (for
/// the current user, or in another folder) cannot take it.
/// </summary>
internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList<string> Components, ExistingInstall? Existing)
{
@@ -13,7 +17,6 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn
{
var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product));
var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser);
var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product);
IReadOnlyList<string> components;
if (arguments.Components is { } requested)
@@ -28,9 +31,42 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn
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)];
}
var allUsersOnly = components.Where(id => manifest.FindComponent(id)!.AllUsersOnly).ToList();
if (allUsersOnly.Count > 0 && existing is null) scope = InstallScope.AllUsers;
var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product);
if (allUsersOnly.Count > 0 && existing is not null && !IsServiceSafe(existing.Scope, existing.Directory))
{
if (arguments.Components is not null)
{
throw new SetupException(SetupExitCode.InvalidArguments,
$"{string.Join(", ", allUsersOnly)} installs for all users inside Program Files only; {manifest.Product} is installed in '{existing.Directory}' for {existing.Scope}.");
}
// An earlier installation elsewhere 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 inside Program Files only");
components = [.. components.Except(allUsersOnly, StringComparer.OrdinalIgnoreCase)];
}
return new InstallPlan(scope, directory, components, existing);
}
/// <summary>
/// False for a component that installs for all users only when an installation that is not an all-users one inside
/// Program Files is upgraded.
/// </summary>
public bool CanInstall(PayloadComponent component) => !component.AllUsersOnly || Existing is null || IsServiceSafe(Existing.Scope, Existing.Directory);
/// <summary>
/// True when <paramref name="components"/> may be installed in <paramref name="directory"/> for
/// <paramref name="scope"/>: a folder setup can use and, when one of them runs as a LocalSystem service, an
/// all-users folder inside Program Files, which standard users cannot change.
/// </summary>
public static bool IsValidDirectory(PayloadManifest manifest, InstallScope scope, string directory, IEnumerable<string> components) =>
SetupPaths.IsUsableInstallDirectory(directory)
&& (!components.Any(id => manifest.FindComponent(id)?.AllUsersOnly == true) || IsServiceSafe(scope, directory));
/// <summary>True for an all-users installation inside Program Files: where a program a LocalSystem service starts may live.</summary>
public static bool IsServiceSafe(InstallScope scope, string directory) => scope == InstallScope.AllUsers && SetupPaths.IsInsideProgramFiles(directory);
/// <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) =>
manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []);
@@ -0,0 +1,309 @@
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.Core.Packaging;
using Titano.Setup.Cli;
using static Titano.Setup.Interop.ServiceNative;
namespace Titano.Setup.Engine;
/// <summary>A Windows service that starts a program setup installed (<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>
internal sealed record InstalledService(string Name, string DisplayName, string Program);
/// <summary>What setup does with the services it is given; 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 stopped ones whose program exists (the ones setup stopped for an upgrade).</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 that start a program setup installed. 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. Only a service
/// whose program is one of the files an install log or the payload lists counts, never any other service that lives
/// in the same folder. 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=… /NAMES=…</c>), which checks each named service again.
/// </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;
/// <summary>A state that could not be read: treated as running, so setup never replaces files a service may hold.</summary>
private const uint StateUnknown = uint.MaxValue;
/// <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 is one of <paramref name="programs"/> (<see cref="CommandProgram.FullPaths"/>); services
/// already marked for deletion are skipped.
/// </summary>
public static IReadOnlyList<InstalledService> Find(IReadOnlySet<string> programs)
{
if (programs.Count == 0) return [];
using var services = Registry.LocalMachine.OpenSubKey(ServicesKey);
return services is null ? [] : Find(services, programs);
}
/// <summary><see cref="Find(IReadOnlySet{string})"/> over the service keys under <paramref name="services"/>.</summary>
public static IReadOnlyList<InstalledService> Find(RegistryKey services, IReadOnlySet<string> programs)
{
var found = new List<InstalledService>();
foreach (var name in services.GetSubKeyNames())
{
if (Read(services, name) is { } service && CommandProgram.IsAmong(service.Program, programs)) found.Add(service);
}
return found;
}
/// <summary>True when the service is not stopped (running, starting, stopping or paused), or its state cannot be read.</summary>
public static bool IsRunning(InstalledService service) => State(service) is { } state && state != StateStopped;
/// <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 => NeedsWork(s, actions));
/// <summary>
/// Applies <paramref name="actions"/> to <paramref name="services"/> (found by <see cref="Find(IReadOnlySet{string})"/>
/// for <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, IReadOnlyList<InstalledService> services, ServiceActions actions, IntPtr owner)
{
var pending = services.Where(s => NeedsWork(s, actions)).ToList();
if (pending.Count == 0) return SetupExitCode.Success;
if (Elevation.IsElevated) return await Task.Run(() => Apply(pending, actions)).ConfigureAwait(false);
if (pending.FirstOrDefault(s => s.Name.Contains(',', StringComparison.Ordinal)) is { } unnamed)
{
// The elevated step takes a comma-separated list; Titano's own service is named TitanoServer.
Log.Error("setup", $"Service '{unnamed.Name}' cannot be passed to the elevated step");
return SetupExitCode.Failed;
}
Log.Info("setup", $"Asking for administrator rights to {actions} {string.Join(", ", pending.Select(s => s.Name))}");
var arguments = new SetupArguments { Services = actions, ServiceNames = [.. pending.Select(s => s.Name)], 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=… /NAMES=… /DIR=…</c>): reads each named service again and applies the actions
/// in this process. A name must still start a program of the folder's install log or of this setup's payload (or,
/// for <see cref="ServiceActions.Prune"/>, a program of the folder that no longer exists); otherwise nothing is done.
/// 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) || arguments.ServiceNames is not { Count: > 0 } names)
return SetupExitCode.InvalidArguments;
if (!Elevation.IsElevated) return SetupExitCode.ElevationDeclined;
var owned = CommandProgram.FullPaths(directory, (InstallLog.TryLoad(directory)?.Files ?? []).Concat(PayloadFiles()));
using var root = Registry.LocalMachine.OpenSubKey(ServicesKey);
var services = new List<InstalledService>();
foreach (var name in names)
{
if ((root is null ? null : Read(root, name)) is not { } service)
{
Log.Info("setup", $"Service {name} no longer exists");
continue;
}
var gone = arguments.Services.HasFlag(ServiceActions.Prune) && CommandProgram.IsPathInside(service.Program, directory) && !File.Exists(service.Program);
if (!CommandProgram.IsAmong(service.Program, owned) && !gone)
{
Log.Error("setup", $"Service {name} starts '{service.Program}', which setup did not install in '{directory}'");
return SetupExitCode.InvalidArguments;
}
services.Add(service);
}
return Apply(services, arguments.Services);
}
/// <summary>
/// Applies <paramref name="actions"/> to <paramref name="services"/> 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). A service that no longer exists is skipped.
/// </summary>
public static unsafe SetupExitCode Apply(IReadOnlyList<InstalledService> services, ServiceActions actions)
{
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) && 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);
}
}
private static bool NeedsWork(InstalledService service, ServiceActions actions)
{
if (actions.HasFlag(ServiceActions.Remove)) return State(service) is not null;
if (actions.HasFlag(ServiceActions.Prune) && !File.Exists(service.Program)) return State(service) is not null;
var state = State(service);
return (actions.HasFlag(ServiceActions.Stop) && state is { } running && running != StateStopped)
|| (actions.HasFlag(ServiceActions.Start) && state == StateStopped && File.Exists(service.Program));
}
/// <summary>
/// The service named <paramref name="name"/> under <paramref name="services"/> when it is a Win32 service not marked
/// for deletion whose command names a full path; null otherwise, or when this account may not read its key.
/// </summary>
private static InstalledService? Read(RegistryKey services, string name)
{
try
{
using var key = services.OpenSubKey(name);
if (key is null || key.GetValue("Type") is not int type || (type & Win32Service) == 0) return null;
if (key.GetValue("DeleteFlag") is int deleting && deleting != 0) return null;
if (key.GetValue("ImagePath") is not string image || CommandProgram.Of(image) is not { } program) return null;
var display = key.GetValue("DisplayName") as string;
return new InstalledService(name, display is { Length: > 0 } && display[0] != '@' ? display : name, program);
}
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 null;
}
}
/// <summary>The service's current state; null when it no longer exists, <see cref="StateUnknown"/> when it cannot be read.</summary>
private static unsafe uint? State(InstalledService service)
{
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) return StateUnknown;
try
{
var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus);
if (handle == 0) return Marshal.GetLastPInvokeError() == ErrorServiceDoesNotExist ? null : StateUnknown;
try
{
return TryQuery(handle, out var status) ? status.CurrentState : StateUnknown;
}
finally
{
CloseServiceHandle(handle);
}
}
finally
{
CloseServiceHandle(manager);
}
}
/// <summary>The files of the payload this setup carries; none for an uninstaller.</summary>
private static IReadOnlyList<string> PayloadFiles()
{
try
{
using var payload = PayloadReader.OpenCurrentProcess();
return [.. payload.Manifest.Files.Select(f => f.Path)];
}
catch (PayloadException)
{
return [];
}
}
/// <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>
/// 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>
internal static class RunningPrograms
{
/// <summary>Processes of <paramref name="executables"/> (payload paths) started from inside <paramref name="directory"/>.</summary>
public static IReadOnlyList<Process> Find(string directory, IEnumerable<string> executables)
/// <summary>
/// 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
.Where(p => p.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !p.Contains('/', StringComparison.Ordinal))
.Select(Path.GetFileNameWithoutExtension)
@@ -23,16 +28,16 @@ internal static class RunningPrograms
foreach (var process in Process.GetProcessesByName(name))
{
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();
}
}
return found;
}
/// <summary>Display names ("Titano", "Titano.Uploader") of the given processes, for the prompt.</summary>
public static string Describe(IReadOnlyList<Process> processes) =>
string.Join(", ", processes.Select(p => p.ProcessName).Distinct(StringComparer.OrdinalIgnoreCase));
/// <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, IReadOnlyCollection<InstalledService>? services = null) =>
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>
public static async Task<IReadOnlyList<Process>> CloseAsync(IReadOnlyList<Process> processes, TimeSpan timeout)
+15
View File
@@ -67,6 +67,21 @@ internal static class SetupPaths
&& !IsSameOrInside(UserData, full);
}
/// <summary>
/// True for a folder inside Program Files (not Program Files itself), where only administrators may change the
/// programs: the only place a program run by a LocalSystem service may live.
/// </summary>
public static bool IsInsideProgramFiles(string? path)
{
if (!IsUsableInstallDirectory(path)) return false;
foreach (var special in (ReadOnlySpan<Environment.SpecialFolder>)[Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86])
{
var programFiles = Environment.GetFolderPath(special);
if (programFiles.Length > 0 && IsSameOrInside(path!, programFiles) && !IsSameOrInside(programFiles, path!)) return true;
}
return false;
}
/// <summary>True when <paramref name="path"/> is <paramref name="folder"/> or lies inside it (case-insensitive).</summary>
public static bool IsSameOrInside(string path, string folder)
{
+54 -4
View File
@@ -9,6 +9,12 @@ namespace Titano.Setup.Engine;
/// <summary>An installation found in Add/Remove Programs.</summary>
internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version);
/// <summary>
/// Another Titano installation registered in Add/Remove Programs: its folder, and its log when that can be read now
/// (null for a drive that is offline, a folder that is gone or a log that cannot be read).
/// </summary>
internal sealed record OtherInstall(string? Directory, InstallLog? Log);
/// <summary>Values written to the Add/Remove Programs entry.</summary>
internal sealed record UninstallEntry(string DisplayName, string Version, string Publisher, string Directory, string UninstallerPath, string DisplayIcon, long EstimatedBytes, string? AboutUrl);
@@ -36,6 +42,39 @@ internal static partial class SetupRegistry
return null;
}
/// <summary>
/// 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 and shortcuts they share).
/// Every registered entry counts, also one whose folder or log cannot be read right now.
/// </summary>
public static IReadOnlyList<OtherInstall> OtherInstalls(string directory, string publisher)
{
var found = new List<OtherInstall>();
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;
var location = key.GetValue("InstallLocation") as string;
if (location is { Length: > 0 } && CommandProgram.IsPathInside(location, directory) && CommandProgram.IsPathInside(directory, location)) continue;
var log = location is { Length: > 0 } && Directory.Exists(location) ? InstallLog.TryLoad(location) : null;
if (log is null) Titano.Core.Diagnostics.Log.Info("setup", $"Installation '{name}' in '{location}' cannot be read now; it counts as using every program");
found.Add(new OtherInstall(location, 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)
{
using var key = Hive(scope).CreateSubKey(UninstallRoot + productKey, writable: true);
@@ -59,16 +98,27 @@ internal static partial class SetupRegistry
/// <summary>
/// Removes the sign-in entries of the client and the Uploader (<c>HKCU\…\Run</c>, written by the programs
/// themselves) that start a program of <paramref name="directory"/>; another copy's entries stay.
/// themselves) that start one of <paramref name="programs"/> (<see cref="CommandProgram.FullPaths"/> of the files an
/// installation lists); another copy's entries, and other programs' values, stay.
/// </summary>
public static void DeleteStartupEntries(string directory)
public static void DeleteStartupEntries(IReadOnlySet<string> programs)
{
using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true);
if (run is null) return;
if (run is not null) DeleteStartupEntries(run, programs);
}
/// <summary><see cref="DeleteStartupEntries(IReadOnlySet{string})"/> in <paramref name="run"/>; returns the names removed.</summary>
public static IReadOnlyList<string> DeleteStartupEntries(RegistryKey run, IReadOnlySet<string> programs)
{
var removed = new List<string>();
foreach (var name in (ReadOnlySpan<string>)[StartupCommand.ClientValue, StartupCommand.UploaderValue])
{
if (StartupCommand.StartsFrom(run.GetValue(name) as string, directory)) run.DeleteValue(name, throwOnMissingValue: false);
if (!CommandProgram.IsAmong(StartupCommand.Executable(run.GetValue(name) as string), programs)) continue;
run.DeleteValue(name, throwOnMissingValue: false);
removed.Add(name);
Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' removed");
}
return removed;
}
/// <summary>Registers <paramref name="extension"/> to open with <c>"program" "%1"</c> under <paramref name="progId"/>.</summary>
+81 -16
View File
@@ -7,8 +7,10 @@ namespace Titano.Setup.Engine;
/// <summary>
/// <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"/>.
/// Silent uninstall never removes user data.
/// Running programs are asked to close; if they do not, setup stops with <see cref="SetupExitCode.ProgramRunning"/>
/// before touching anything. Then the services of the installed programs are stopped (and started again after the
/// upgrade, or when it fails) or deleted with the uninstall, which asks for administrator approval when setup runs
/// without it. Silent uninstall never removes user data.
/// </summary>
internal static class SilentSetup
{
@@ -44,17 +46,43 @@ internal static class SilentSetup
var plan = InstallPlan.Resolve(engine.Manifest, arguments);
if (plan.Existing is not null && arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory))
Log.Warning("setup", $"/DIR ignored: {engine.Manifest.Product} is already installed in '{plan.Directory}'");
if (!SetupPaths.IsUsableInstallDirectory(plan.Directory)) return SetupExitCode.InvalidArguments;
if (!InstallPlan.IsValidDirectory(engine.Manifest, plan.Scope, plan.Directory, plan.Components))
{
Log.Error("setup", $"'{plan.Directory}' cannot take {string.Join(", ", plan.Components)} for {plan.Scope}");
return SetupExitCode.InvalidArguments;
}
if (plan.Components.Count == 0) return SetupExitCode.InvalidArguments;
var launch = arguments.Launch && engine.LaunchTarget(plan.Components) is { } target ? PayloadPath.Resolve(plan.Directory, target) : null;
if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
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))
return SetupExitCode.ProgramRunning;
var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu);
engine.Install(request, null, CancellationToken.None);
// Read before the upgrade rewrites the log, so a program it drops still names its service.
var programs = InstallPlan.Programs(engine.Manifest, plan.Directory).ToList();
var owned = CommandProgram.FullPaths(plan.Directory, programs);
var closed = await CloseProgramsAsync(plan.Directory, programs, owned).ConfigureAwait(false);
if (closed.Code != SetupExitCode.Success) return closed.Code;
var stopped = closed.Services;
try
{
var code = await InstalledServices.ApplyAsync(plan.Directory, stopped, ServiceActions.Stop, IntPtr.Zero).ConfigureAwait(false);
if (code != SetupExitCode.Success)
{
await StartAgainAsync(plan.Directory, stopped).ConfigureAwait(false);
return code;
}
var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu);
engine.Install(request, null, CancellationToken.None);
}
catch
{
await StartAgainAsync(plan.Directory, stopped).ConfigureAwait(false);
throw;
}
// Services whose program the upgrade removed go; the ones stopped for it run again.
var after = InstalledServices.Find(owned).Where(s => !File.Exists(s.Program)).UnionBy(stopped, s => s.Name, StringComparer.OrdinalIgnoreCase).ToList();
var services = await InstalledServices.ApplyAsync(plan.Directory, after, ServiceActions.Prune | ServiceActions.Start, IntPtr.Zero).ConfigureAwait(false);
if (services != SetupExitCode.Success) return services;
if (launch is null) return SetupExitCode.Success;
if (arguments.Elevated) return SetupExitCode.LaunchRequested;
@@ -68,8 +96,18 @@ internal static class SilentSetup
if (product is null) return SetupExitCode.NotInstalled;
if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
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;
UninstallEngine.Uninstall(product, removeUserData: false, null);
var owned = CommandProgram.FullPaths(product.Directory, product.Log.Files);
var closed = await CloseProgramsAsync(product.Directory, product.Log.Files, owned).ConfigureAwait(false);
if (closed.Code != SetupExitCode.Success) return closed.Code;
// Only now that the programs are closed. Services that were not running are still registered: no service may
// outlive its program. If one cannot be deleted, the ones stopped here run again.
var services = await InstalledServices.ApplyAsync(product.Directory, InstalledServices.Find(owned), ServiceActions.Remove, IntPtr.Zero).ConfigureAwait(false);
if (services != SetupExitCode.Success)
{
await StartAgainAsync(product.Directory, closed.Services).ConfigureAwait(false);
return services;
}
UninstallEngine.Uninstall(product, userData: null, null);
return SetupExitCode.Success;
}
@@ -87,13 +125,40 @@ internal static class SilentSetup
}
}
private static async Task<bool> CloseProgramsAsync(string directory, IEnumerable<string> programs)
/// <summary>
/// Asks the running programs of <paramref name="directory"/> to close and returns the running services of
/// <paramref name="owned"/>, which the caller stops or deletes: a program that does not close stops setup before
/// any service is touched.
/// </summary>
private static async Task<(SetupExitCode Code, IReadOnlyList<InstalledService> Services)> CloseProgramsAsync(string directory, IEnumerable<string> programs, IReadOnlySet<string> owned)
{
var running = RunningPrograms.Find(directory, programs);
if (running.Count == 0) return true;
Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close");
var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false);
foreach (var p in running) p.Dispose();
return still.Count == 0;
var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList();
var running = RunningPrograms.Find(directory, programs, services);
try
{
if (running.Count == 0) return (SetupExitCode.Success, services);
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);
}
finally
{
foreach (var p in running) p.Dispose();
}
}
/// <summary>After a failure, starts again the services setup stopped, so a failed upgrade does not leave the server down.</summary>
private static async Task StartAgainAsync(string directory, IReadOnlyList<InstalledService> stopped)
{
if (stopped.Count == 0) return;
try
{
var code = await InstalledServices.ApplyAsync(directory, stopped, ServiceActions.Start, IntPtr.Zero).ConfigureAwait(false);
if (code != SetupExitCode.Success) Log.Warning("setup", $"Stopped services not started again: {code}");
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException)
{
Log.Warning("setup", "Stopped services not started again", ex);
}
}
}
+67 -13
View File
@@ -1,4 +1,5 @@
using System.IO;
using System.Runtime.InteropServices;
using Titano.Core.Diagnostics;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
@@ -10,9 +11,12 @@ namespace Titano.Setup.Engine;
internal sealed record InstalledProduct(string Directory, InstallLog Log);
/// <summary>
/// Removes an installation using only its log: shortcuts, file types, logged files, the log, the Add/Remove
/// Programs entry and the programs' sign-in entries, then the uninstaller itself. Files the log does not list are left alone; the user data folder
/// is deleted only when <c>removeUserData</c> is set by an explicit choice in the window.
/// Removes an installation using only its log: shortcuts that still start its programs (handed to another Titano
/// product that installed the same program and shares them), file types, logged files, the log, the Add/Remove
/// Programs entry and the sign-in entries of its programs, then the uninstaller itself. Files the log does not list,
/// and anything that starts a program it does not list, are left alone; user data is deleted only through a plan the
/// user saw and chose in the window. The Windows services of its programs are stopped and deleted by the caller first
/// (<see cref="InstalledServices.ApplyAsync"/>), as that may need an elevated step.
/// </summary>
internal static class UninstallEngine
{
@@ -29,17 +33,22 @@ internal static class UninstallEngine
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;
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.
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");
Directory.Delete(SetupPaths.UserData, recursive: true);
Log.Info("setup", $"Removing {userData.Entries.Count} entries of '{userData.Folder}' at the user's request");
userData.Remove();
}
if (log.Shortcuts.Count > 0)
{
var others = SetupRegistry.OtherInstalls(directory, InstallEngine.Publisher);
foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope, directory, others);
}
foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope);
progress?.Report(new SetupProgress(0.1, string.Empty));
var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList();
@@ -62,7 +71,7 @@ internal static class UninstallEngine
SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey);
try
{
SetupRegistry.DeleteStartupEntries(directory);
SetupRegistry.DeleteStartupEntries(CommandProgram.FullPaths(directory, log.Files));
}
catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException)
{
@@ -91,8 +100,14 @@ internal static class UninstallEngine
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>
public static void DeleteShortcut(string link, InstallScope scope)
/// <summary>
/// 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. When another installation (<paramref name="others"/>) shares
/// the shortcut and has the same program, the shortcut is pointed at that copy instead, so the program that stays
/// installed keeps its shortcut.
/// </summary>
public static void DeleteShortcut(string link, InstallScope scope, string directory, IReadOnlyList<OtherInstall> others)
{
var folder = Path.GetDirectoryName(link);
var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase)
@@ -105,11 +120,50 @@ internal static class UninstallEngine
}
try
{
if (ShellLink.TargetOf(link) is not { } target) return;
if (!CommandProgram.IsPathInside(target, directory))
{
Log.Info("setup", $"Shortcut '{link}' now starts '{target}'; kept");
return;
}
if (SharedCopy(link, scope, directory, target, others) is { } copy)
{
ShellLink.Create(link, copy, Path.GetFileNameWithoutExtension(link));
Log.Info("setup", $"Shortcut '{link}' now starts '{copy}', which stays installed");
return;
}
File.Delete(link);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or COMException)
{
Log.Warning("setup", $"Shortcut '{link}' not removed", ex);
}
}
/// <summary>
/// The same program as <paramref name="target"/> (the same path inside its folder) installed by another product of
/// the same scope whose log lists <paramref name="link"/> too; null when there is none.
/// </summary>
private static string? SharedCopy(string link, InstallScope scope, string directory, string target, IReadOnlyList<OtherInstall> others)
{
string relative;
try
{
relative = PayloadPath.FromRelative(Path.GetRelativePath(directory, target));
}
catch (Exception ex) when (ex is PayloadException or ArgumentException)
{
return null;
}
foreach (var other in others)
{
if (other is not { Directory: { } otherDirectory, Log: { } log } || log.Scope != scope) continue;
if (!log.Shortcuts.Contains(link, StringComparer.OrdinalIgnoreCase) || !log.Files.Contains(relative, PayloadPath.Comparer)) continue;
// The folder comes from another product's registry entry: one Windows cannot use is skipped.
if (!SetupPaths.IsUsableInstallDirectory(otherDirectory)) continue;
var copy = PayloadPath.Resolve(otherDirectory, relative);
if (File.Exists(copy)) return copy;
}
return null;
}
}
+94 -10
View File
@@ -2,15 +2,17 @@ using System.IO;
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);
/// <summary>
/// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): every top-level
/// entry of the user data folder with its size, largest first. Links are not followed, as the deletion does not
/// follow them either.
/// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): the entries of the
/// user data folder that belong to the programs being removed, with their sizes, largest first. The desktop app and
/// 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>
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 };
@@ -23,13 +25,52 @@ internal sealed record UserDataPlan(IReadOnlyList<UserDataEntry> Entries)
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>
public static UserDataPlan Measure(string folder)
/// <summary>
/// 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);
if (!root.Exists) return new UserDataPlan([]);
var entries = root.EnumerateFileSystemInfos("*", TopLevel).Select(e => new UserDataEntry(e.Name, SizeOf(e)));
return new UserDataPlan([.. entries.OrderByDescending(e => e.Bytes).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)]);
if (!root.Exists || owners.Count == 0) return new UserDataPlan(folder, []);
var whole = UserDataOwners.All.All(owners.Contains);
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
@@ -40,3 +81,46 @@ internal sealed record UserDataPlan(IReadOnlyList<UserDataEntry> Entries)
_ => 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;
}
/// <summary>
/// <see cref="Removable(IEnumerable{string}, IEnumerable{IEnumerable{string}})"/> for the installations registered
/// on this PC: one whose log cannot be read now (a drive that is offline, a damaged log) counts as using every
/// program's data, so its data is never offered for removal.
/// </summary>
public static IReadOnlySet<string> RemovableBeside(IEnumerable<string> components, IEnumerable<OtherInstall> others) =>
Removable(components, others.Select(o => o.Log?.Components ?? (IEnumerable<string>)All));
}
+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;
/// <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
{
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>
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]
[Guid("00021401-0000-0000-C000-000000000046")]
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]
[Guid("000214F9-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+3 -2
View File
@@ -7,8 +7,8 @@ using Titano.Setup.Engine;
namespace Titano.Setup;
/// <summary>
/// Entry point. Silent mode and the uninstaller cleanup helper run without WPF; the interactive window is the
/// <see cref="App"/>. The return value is the process exit code (<see cref="SetupExitCode"/>).
/// Entry point. Silent mode, the uninstaller cleanup helper and the elevated service step run without WPF; the
/// interactive window is the <see cref="App"/>. The return value is the process exit code (<see cref="SetupExitCode"/>).
/// </summary>
internal static class Program
{
@@ -34,6 +34,7 @@ internal static class Program
ApplyLanguage(arguments.Language);
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();
return new App(arguments).Run();
+3
View File
@@ -14,6 +14,9 @@
<PropertyGroup Condition="'$(PublishSingleFile)' == 'true' and '$(SelfContained)' == 'true'">
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Titano.App.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Titano.Core\Titano.Core.csproj" />
<ProjectReference Include="..\Titano.Ui\Titano.Ui.csproj" />
+18 -3
View File
@@ -4,8 +4,13 @@ using Titano.Ui.Mvvm;
namespace Titano.Setup.Views;
/// <summary>A component checkbox: localized name and tooltip (falling back to the manifest), size and selection.</summary>
internal sealed class ComponentOption(PayloadComponent component, bool selected, Action changed) : LocalizedViewModel
/// <summary>
/// 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 an installation that is not an
/// all-users one inside Program Files is upgraded.
/// </summary>
/// <param name="unavailableToolTip">The tooltip key saying why it cannot be added here; null when it can.</param>
internal sealed class ComponentOption(PayloadComponent component, bool selected, string? unavailableToolTip, Action changed) : LocalizedViewModel
{
private bool _selected = selected;
@@ -13,7 +18,17 @@ internal sealed class ComponentOption(PayloadComponent component, bool selected,
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 in Program Files and this installation is not.</summary>
public bool IsAvailable => unavailableToolTip is null;
public string ToolTip => unavailableToolTip is { } reason ? Loc.L(reason)
: 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);
+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>
private static readonly UserDataPlan SamplePlan = new(
private static readonly UserDataPlan SamplePlan = new(SetupPaths.UserData,
[
new UserDataEntry("cache", 2_140_000_000),
new UserDataEntry("backups", 1_210_000_000),
@@ -95,8 +95,10 @@ internal static class SetupCapture
Program.ApplyLanguage(language);
using var payload = PayloadReader.Open(installer);
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(
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)
{
ThemeManager.Apply(theme);
@@ -154,7 +156,7 @@ internal static class SetupCapture
{
Product = Product,
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" })],
}, installer);
return installer;
+138 -29
View File
@@ -42,6 +42,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private readonly InstalledProduct? _installed;
private readonly string _product;
private readonly string? _version;
private readonly IReadOnlySet<string> _dataOwners;
private SetupStage _stage;
private string _directory = string.Empty;
private bool _allUsers;
@@ -61,13 +62,20 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private string? _launchProgram;
private Func<Task>? _operation;
private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed)
/// <summary>The services setup stopped for the current step, started again after the upgrade or when the step fails.</summary>
private IReadOnlyList<InstalledService> _stopped = [];
private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed,
IReadOnlySet<string>? dataOwners = null)
{
_arguments = arguments;
_product = product;
_version = version;
_payload = payload;
_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.RemovableBeside(installed.Log.Components, SetupRegistry.OtherInstalls(installed.Directory, InstallEngine.Publisher));
if (payload is not null)
{
_engine = new InstallEngine(payload);
@@ -80,7 +88,8 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
_launchAfter = arguments.Launch;
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), UnavailableReason(c),
OnComponentsChanged))];
Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))];
PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart);
@@ -99,8 +108,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) =>
new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null);
public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed) =>
new(arguments, installed.Log.Product, installed.Log.Version, null, installed) { Directory = installed.Directory };
/// <param name="dataOwners">Whose user data "Remove my data" covers; null works it out from the installed products.</param>
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>
public static SetupViewModel ForFailure(SetupArguments arguments, SetupExitCode code)
@@ -189,6 +199,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
OnPropertyChanged(nameof(IsJustMe));
// Follow the scope while the folder is still the suggested one.
if (string.Equals(Path.TrimEndingDirectorySeparator(_directory), before, StringComparison.OrdinalIgnoreCase)) Directory = DefaultDirectory();
else OnDirectoryRuleChanged();
}
}
@@ -203,23 +214,38 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
get => _directory;
set
{
if (!Set(ref _directory, value ?? string.Empty)) return;
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory)));
OnPropertyChanged(nameof(DirectoryToolTip));
OnPropertyChanged(nameof(InstallToolTip));
if (Set(ref _directory, value ?? string.Empty)) OnDirectoryRuleChanged();
}
}
private bool IsDirectoryValid => SetupPaths.IsUsableInstallDirectory(_directory);
/// <summary>
/// A folder setup can use; inside Program Files when a selected component runs as a LocalSystem service (a folder
/// such as C:\Titano would let standard users replace the program the service starts).
/// </summary>
private bool IsDirectoryValid => _engine is not null
&& InstallPlan.IsValidDirectory(_engine.Manifest, _allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, _directory, SelectedComponents);
/// <summary>Why the folder cannot be used: not a usable folder, or outside Program Files for a service.</summary>
private string FolderErrorText => SetupPaths.IsUsableInstallDirectory(_directory) && AllUsersComponent is { } component
? Loc.L("Tooltips.Setup.FolderProgramFiles", component.Name)
: Loc.L("Tooltips.Setup.FolderInvalid");
public string DirectoryToolTip => !CanChangeLocation
? Loc.L("Tooltips.Setup.Locked")
: IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : Loc.L("Tooltips.Setup.FolderInvalid");
: IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : FolderErrorText;
/// <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 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 bool DesktopShortcut
@@ -248,11 +274,13 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
/// <summary>What Install does, or why it is disabled: no program selected, or a folder it cannot use.</summary>
public string InstallToolTip => !Components.Any(c => c.IsSelected) ? Loc.L("Tooltips.Setup.NoComponent")
: !IsDirectoryValid ? Loc.L("Tooltips.Setup.FolderInvalid")
: !IsDirectoryValid ? FolderErrorText
: 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>
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));
// ---- Uninstall options ----
@@ -269,6 +297,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;
/// <summary>"Deletes 3.4 GB" over the plan's lines.</summary>
@@ -354,7 +393,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
public bool HasErrors => IsInstall && !IsDirectoryValid;
public IEnumerable GetErrors(string? propertyName) =>
propertyName == nameof(Directory) && HasErrors ? new[] { Loc.L("Tooltips.Setup.FolderInvalid") } : Array.Empty<string>();
propertyName == nameof(Directory) && HasErrors ? new[] { FolderErrorText } : Array.Empty<string>();
/// <summary>Called once the window is visible: an elevated copy continues the install the user already started.</summary>
public void OnShown()
@@ -395,6 +434,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
private async Task InstallAsync()
{
var engine = _engine!;
string? directory = null;
try
{
var request = new InstallRequest(
@@ -412,17 +452,31 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
await InstallElevatedAsync(request, program);
return;
}
if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory))) return;
directory = request.Directory;
// Read before the upgrade rewrites the log, so a program it drops still names its service.
var programs = InstallPlan.Programs(engine.Manifest, request.Directory).ToList();
var owned = CommandProgram.FullPaths(request.Directory, programs);
if (await CloseProgramsAsync(request.Directory, programs, owned) is not { } running) return;
BeginWork(indeterminate: false);
if (running.Count > 0)
{
_stopped = running;
await ApplyToServicesAsync(request.Directory, running, ServiceActions.Stop);
}
var progress = new Progress<SetupProgress>(ReportProgress);
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 = InstalledServices.Find(owned).Where(s => !File.Exists(s.Program)).UnionBy(_stopped, s => s.Name, StringComparer.OrdinalIgnoreCase).ToList();
_stopped = [];
await ApplyToServicesAsync(request.Directory, after, ServiceActions.Prune | ServiceActions.Start);
_launchProgram = program;
Complete();
if (launch is not null) Launch();
}
catch (Exception ex)
{
await StartStoppedAsync(directory);
Fail(ex);
}
}
@@ -454,41 +508,51 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
var installed = _installed!;
try
{
if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files)) return;
var owned = CommandProgram.FullPaths(installed.Directory, installed.Log.Files);
if (await CloseProgramsAsync(installed.Directory, installed.Log.Files, owned) is not { } running) return;
BeginWork(indeterminate: false);
// Only now that the programs are closed. A service that was not running is still registered: none may
// outlive its program. If one cannot be deleted, the ones stopped here run again.
_stopped = running;
await ApplyToServicesAsync(installed.Directory, InstalledServices.Find(owned), ServiceActions.Remove);
_stopped = [];
var progress = new Progress<SetupProgress>(ReportProgress);
var removeData = _removeUserData;
await Task.Run(() => UninstallEngine.Uninstall(installed, removeData, progress));
var userData = _removeUserData ? _dataPlan : null;
await Task.Run(() => UninstallEngine.Uninstall(installed, userData, progress));
Complete();
}
catch (Exception ex)
{
await StartStoppedAsync(installed.Directory);
Fail(ex);
}
}
/// <summary>
/// True when no installed program runs from <paramref name="directory"/>. Otherwise the first call asks the user
/// (Confirm stage); after "Close programs" the programs are asked to close and the operation continues.
/// Null when the user must first confirm (Confirm stage) that the programs and services running from
/// <paramref name="directory"/> may close. Otherwise the running programs have closed, and the result lists the
/// running services of <paramref name="owned"/>, which the caller stops or deletes: a program that does not close
/// stops setup before any service is touched.
/// </summary>
private async Task<bool> EnsureProgramsClosedAsync(string directory, IEnumerable<string> programs)
private async Task<IReadOnlyList<InstalledService>?> CloseProgramsAsync(string directory, IEnumerable<string> programs, IReadOnlySet<string> owned)
{
// A confirmation answers one prompt only; a later attempt asks again.
var confirmed = _closeConfirmed;
_closeConfirmed = false;
var running = RunningPrograms.Find(directory, programs);
var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList();
var running = RunningPrograms.Find(directory, programs, services);
try
{
if (running.Count == 0) return true;
_runningPrograms = RunningPrograms.Describe(running);
if (running.Count == 0 && services.Count == 0) return services;
_runningPrograms = RunningPrograms.Describe(running, services);
if (!confirmed)
{
Stage = SetupStage.Confirm;
return false;
return null;
}
BeginWork(indeterminate: true);
var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout);
if (still.Count == 0) return true;
if (still.Count == 0) return services;
_runningPrograms = RunningPrograms.Describe(still);
throw new SetupException(SetupExitCode.ProgramRunning, $"Still running: {_runningPrograms}");
}
@@ -498,6 +562,32 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
}
}
/// <summary>Applies <paramref name="actions"/> to <paramref name="services"/> (an elevated step when needed); throws when that fails.</summary>
private async Task ApplyToServicesAsync(string directory, IReadOnlyList<InstalledService> services, ServiceActions actions)
{
var code = await InstalledServices.ApplyAsync(directory, services, actions, WindowHandle);
if (code == SetupExitCode.Success) return;
_runningPrograms = RunningPrograms.Describe([], services);
throw new SetupException(code, $"Services not updated ({actions}): {_runningPrograms}");
}
/// <summary>After a failure, starts again the services setup stopped for the step, so a failed upgrade does not leave the server down.</summary>
private async Task StartStoppedAsync(string? directory)
{
var stopped = _stopped;
_stopped = [];
if (directory is null || stopped.Count == 0) return;
try
{
var code = await InstalledServices.ApplyAsync(directory, stopped, ServiceActions.Start, WindowHandle);
if (code != SetupExitCode.Success) Log.Warning("setup", $"Stopped services not started again: {code}");
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or IOException)
{
Log.Warning("setup", "Stopped services not started again", ex);
}
}
private void Browse()
{
if (PickFolder?.Invoke(_directory) is not { } folder) return;
@@ -570,12 +660,12 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
_measuring = true;
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)
{
Log.Warning("setup", $"User data '{SetupPaths.UserData}' not measured", ex);
_dataPlan = new UserDataPlan([]);
_dataPlan = new UserDataPlan(SetupPaths.UserData, []);
}
finally
{
@@ -589,14 +679,33 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo
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(InstallToolTip));
OnPropertyChanged(nameof(HasDesktopOption));
OnPropertyChanged(nameof(HasStartMenuOption));
OnPropertyChanged(nameof(HasLaunchOption));
OnDirectoryRuleChanged();
}
/// <summary>The folder, the scope or the components changed: whether the folder is valid, and why not, may have too.</summary>
private void OnDirectoryRuleChanged()
{
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory)));
OnPropertyChanged(nameof(DirectoryToolTip));
OnPropertyChanged(nameof(InstallToolTip));
CommandManager.InvalidateRequerySuggested();
}
/// <summary>The tooltip key saying why <paramref name="component"/> cannot be added to the installation upgraded here; null when it can.</summary>
private string? UnavailableReason(PayloadComponent component) =>
_plan!.CanInstall(component) ? null
: _plan.Existing is { Scope: InstallScope.CurrentUser } ? "Tooltips.Setup.NeedsAllUsers"
: "Tooltips.Setup.NeedsProgramFiles";
private IEnumerable<PayloadShortcut> SelectedShortcuts()
{
if (_engine is null) return [];
+6 -3
View File
@@ -44,7 +44,8 @@
<DataTemplate>
<DockPanel Margin="0,0,0,6">
<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>
</DataTemplate>
</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" />
<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" />
<RadioButton Content="{l:Loc Setup.Scope.AllUsers}" IsChecked="{Binding IsAllUsers}" IsEnabled="{Binding CanChangeLocation}"
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" />
<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}" />
<!-- 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"
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"
Visibility="{Binding IsDataPlanVisible, Converter={StaticResource BoolToVisibility}}">
<StackPanel>
@@ -60,11 +60,14 @@ internal sealed partial class ChangelogCommand : ICommand
var sb = new StringBuilder();
if (title is not null) sb.Append("# ").AppendLine(title).AppendLine();
// The title alone says nothing about the release: the fallback depends on the entries written, not on the text.
var written = false;
if (breaking.Count > 0)
{
sb.AppendLine("### Breaking changes");
foreach (var e in breaking) sb.AppendLine(e);
sb.AppendLine();
written = true;
}
foreach (var (type, heading) in Sections)
{
@@ -72,8 +75,9 @@ internal sealed partial class ChangelogCommand : ICommand
sb.Append("### ").AppendLine(heading);
foreach (var e in entries) sb.AppendLine(e);
sb.AppendLine();
written = true;
}
if (sb.Length == 0) sb.AppendLine("Maintenance release.");
if (!written) sb.AppendLine("Maintenance release.");
return sb.ToString();
}
@@ -6,18 +6,20 @@ namespace Titano.Tools.Commands;
/// <summary>
/// <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
/// 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>
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)
{
["Titano"] = new("Titano", true, "Titano.exe", Desktop: true,
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),
["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";
@@ -49,7 +51,7 @@ internal sealed class PackInstallerCommand : ICommand
components.Add(new PayloadComponentSource(id, id, true, folder));
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)))
{
Console.Error.WriteLine($"warning: {id} has no {known.Program}; no shortcut or file type registered.");
@@ -1,6 +1,7 @@
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
namespace Titano.Uploader.Infrastructure;
@@ -14,12 +15,13 @@ public interface IStartupRegistration
/// <summary>
/// <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 when
/// it starts the Uploader the uninstaller removes (<see cref="StartupCommand"/> names it for both).
/// </summary>
public sealed class RunKeyStartupRegistration : IStartupRegistration
{
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ValueName = "Titano Uploader";
private const string RunKey = StartupCommand.RunKey;
private const string ValueName = StartupCommand.UploaderValue;
public bool IsEnabled
{