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:
49 files changed
+2741
-128
No files matched your search
@@ -41,13 +41,15 @@ for community review. Development happens elsewhere; please use the issues here
|
||||
`Get-FileHash .\Titano-Setup-<version>.exe -Algorithm SHA256` and compare the value with the line for that file
|
||||
in `SHA256SUMS` of the same release.
|
||||
3. Run the setup. It installs for the current user into `%LOCALAPPDATA%\Programs\Titano` without administrator
|
||||
rights; choose *All users* to install into `Program Files` (Windows asks for permission).
|
||||
rights; choose *All users* to install into `Program Files` (Windows asks for permission). The *Server* component
|
||||
runs as a Windows service, so choosing it installs for all users, in a folder inside `Program Files`.
|
||||
|
||||
- **Upgrade:** Titano checks this repository at start (you can turn this off in Settings › Updates) and shows a notice
|
||||
when a new version exists. *Download* fetches the setup, verifies it against `SHA256SUMS` and shows it in Explorer;
|
||||
run it to upgrade in place. Your archive, settings and index are kept.
|
||||
- **Uninstall:** Windows Settings › Apps › Installed apps › Titano › Uninstall. Your photos and archive are never
|
||||
touched; the program data folder (`%LOCALAPPDATA%\Titano`) is removed only if you tick the option to do so.
|
||||
touched; the program data in `%LOCALAPPDATA%\Titano` is removed only if you tick the option to do so, and only the
|
||||
part no other installed Titano program still uses. A Titano Server service of that folder is stopped and removed.
|
||||
- **Silent install** (IT deployment): `Titano-Setup-<version>.exe /S [/DIR="D:\Apps\Titano"] [/ALLUSERS]
|
||||
[/COMPONENTS=Titano,Uploader,Server] [/NODESKTOP] [/NOSTARTMENU] [/LANG=it]`. Silent uninstall:
|
||||
`"%LOCALAPPDATA%\Programs\Titano\Uninstall Titano.exe" /uninstall /S`.
|
||||
|
||||
@@ -36,7 +36,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| `Advice` | `Advisor`: recommendations with localisable reasons, apply/optimise, sequence presets |
|
||||
| `Motion` | FFT, phase correlation, pyramids, optical flow, motion blur, stabiliser, virtual camera, interpolation, stacking |
|
||||
| `Math` (namespace `Titano.Core.Mathematics`) | Splines, LOWESS, statistics, solar position, 3×3 colour matrices |
|
||||
| `Project` | `ProjectSettings` (Auto/manual values), export presets |
|
||||
| `Project` | `ProjectSettings` (Auto/manual values), export presets, `ProjectBundle` (the `.titano` project file: sequence reference and settings) |
|
||||
| `Render` | Render plan (timing modes), preparation pass, geometry, `RenderPipeline`, self-test suite |
|
||||
| `Export` | Preset resolution, encoder selection with fallbacks, output naming |
|
||||
| `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) |
|
||||
@@ -57,7 +57,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| `Repositories` | `TitanoDatabase` facade: archives, sequences, frames, tags, renders, jobs, cards, users, tokens, uploads, render nodes, settings, audit; `DatabaseBackups` (daily `VACUUM INTO` copies of an SQLite index kept ×3, restore staged for the next start and carried out before the index opens, so it also recovers one that no longer opens) |
|
||||
| `Jobs` | `JobEngine` (its number of workers can change while it runs), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs) |
|
||||
| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages`, `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer`, `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails), job handlers |
|
||||
| `Processing` | `ProcessingService`, `SequenceAnalyser`, `SequenceRender`, `ProjectStore`, `RenderNodeClient`, job handlers |
|
||||
| `Processing` | `ProcessingService`, `SequenceAnalyser`, `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.titano` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers |
|
||||
| `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `TitanoSyncRemote` over `TitanoClient`) |
|
||||
|
||||
### 2.3 Titano.App areas
|
||||
@@ -67,12 +67,12 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| `Shell` | `MainWindow` (rail and its shortcuts, taskbar progress), `ShellViewModel` (rail, sections, first run), `OsNotifications` (toasts as Windows notifications while the window is minimised or in the background), dialogs, `ErrorText` (the sentence of an error toast), `ScreenCapture` (`--capture` scenes), `SectionTemplates.xaml` (view model → view) |
|
||||
| `Sections` | One `XxxView.xaml` + `XxxViewModel` per screen: Welcome, Library, Sequence (editor), Import, Archive, Jobs, Server, Settings, About |
|
||||
| `Library` | Filter, facets, pager, timeline, saved views, quick and mass actions, remote cards and thumbnails, thumbnail cache, list export |
|
||||
| `Editor` | `EditorSession` (project, undo/redo, saving, merges), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`), tabs (Frames, Exposure, Camera, Motion, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs` |
|
||||
| `Editor` | `EditorSession` (project, undo/redo, saving, merges), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`), tabs (Frames, Exposure, Camera, Motion, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.titano` project files) |
|
||||
| `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) |
|
||||
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, mass rename and move, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`), `ArchiveFailures` |
|
||||
| `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` |
|
||||
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); settings rows, encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job), `InterfacePriority`, language catalog, naming preview; update check and download |
|
||||
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), device monitor |
|
||||
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Titano per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
|
||||
| `DesignTime` | `SampleData`: the archive, jobs and server the screenshots and smoke tests run on, dated from the fixed `SampleData.Now` |
|
||||
|
||||
### 2.4 Titano.Ui and Titano.Server
|
||||
@@ -95,7 +95,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|
||||
| Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) |
|
||||
| Titano Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `TITANO_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (renders only managed formats and MP4 jobs no render node can take, BRIEF §14.7); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host; daily backups of an SQLite index (`DatabaseBackupService`) |
|
||||
| Titano Uploader | `Uploader/App.xaml.cs` | `TitanoClient`, persisted queue, watch folders; no database |
|
||||
| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, silent mode, uninstaller |
|
||||
| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses |
|
||||
|
||||
### 2.6 Job kinds and their handlers
|
||||
|
||||
|
||||
@@ -184,6 +184,15 @@
|
||||
<data name="Editor.Preview.Unreadable" xml:space="preserve"><value>This frame cannot be read.</value></data>
|
||||
<data name="Editor.Preview.Vectors" xml:space="preserve"><value>Vectors</value></data>
|
||||
<data name="Editor.Preview.Wipe" xml:space="preserve"><value>original | corrected</value></data>
|
||||
<data name="Editor.ProjectFile.Applied" xml:space="preserve"><value>Project file applied</value></data>
|
||||
<data name="Editor.ProjectFile.Locked" xml:space="preserve"><value>The project file’s settings were not applied.</value><comment>long</comment></data>
|
||||
<data name="Editor.ProjectFile.NotFound" xml:space="preserve"><value>The sequence of this project file is not in the library.</value><comment>long</comment></data>
|
||||
<data name="Editor.ProjectFile.Retry" xml:space="preserve"><value>Retry</value></data>
|
||||
<data name="Editor.ProjectFile.Save" xml:space="preserve"><value>Save project file</value></data>
|
||||
<data name="Editor.ProjectFile.Saved" xml:space="preserve"><value>Project file saved</value></data>
|
||||
<data name="Editor.ProjectFile.Title" xml:space="preserve"><value>Project file folder</value></data>
|
||||
<data name="Editor.ProjectFile.Undo" xml:space="preserve"><value>Undo</value></data>
|
||||
<data name="Editor.ProjectFile.Unreadable" xml:space="preserve"><value>This file is not a Titano project or cannot be read.</value><comment>long</comment></data>
|
||||
<data name="Editor.Proxies.Failed" xml:space="preserve"><value>Proxies not received</value></data>
|
||||
<data name="Editor.Proxies.Fetching" xml:space="preserve"><value>Getting the proxies</value></data>
|
||||
<data name="Editor.Regions.Auto" xml:space="preserve"><value>Auto</value></data>
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
<data name="Setup.Field.Language" xml:space="preserve"><value>Language</value></data>
|
||||
<data name="Setup.Field.Options" xml:space="preserve"><value>Options</value></data>
|
||||
<data name="Setup.Field.Scope" xml:space="preserve"><value>Install for</value></data>
|
||||
<data name="Setup.FileType.Project" xml:space="preserve"><value>Titano project</value></data>
|
||||
<data name="Setup.Folder.Browse" xml:space="preserve"><value>Browse</value></data>
|
||||
<data name="Setup.Header.Upgrade" xml:space="preserve"><value>Version {0} · installed {1}</value></data>
|
||||
<data name="Setup.Header.Version" xml:space="preserve"><value>Version {0}</value></data>
|
||||
|
||||
@@ -211,6 +211,10 @@
|
||||
<data name="Tooltips.Editor.Preview.ShotData" xml:space="preserve"><value>Show or hide the shot data</value></data>
|
||||
<data name="Tooltips.Editor.Preview.Vectors" xml:space="preserve"><value>Overlay the motion to the next frame measured by the engine</value></data>
|
||||
<data name="Tooltips.Editor.Preview.View" xml:space="preserve"><value>Drag the line to compare · drag to pan · wheel zooms · double-click 1:1</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Remote" xml:space="preserve"><value>Project files are for sequences in an archive on this PC</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Retry" xml:space="preserve"><value>Apply the project file’s settings again</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Save" xml:space="preserve"><value>Save a .titano file that opens this sequence with these settings when double-clicked</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Undo" xml:space="preserve"><value>Bring back the settings the sequence had before the file was opened · Ctrl+Z</value></data>
|
||||
<data name="Tooltips.Editor.ReadOnly" xml:space="preserve"><value>Your account can look at this server sequence but not change it</value></data>
|
||||
<data name="Tooltips.Editor.Remote" xml:space="preserve"><value>Edited with proxies on this PC; changes are saved on {0} and analyses and renders run there</value></data>
|
||||
<data name="Tooltips.Editor.RemoteReadOnly" xml:space="preserve"><value>Shown from {0}; your account can look at this sequence but not change it</value></data>
|
||||
@@ -593,6 +597,7 @@
|
||||
<data name="Tooltips.Settings.WorkersAuto" xml:space="preserve"><value>Auto: half the logical cores run jobs at once, each with its own number of threads</value></data>
|
||||
<data name="Tooltips.Settings.WorkersReset" xml:space="preserve"><value>Back to Auto: half the logical cores</value></data>
|
||||
<data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Install in Program Files for every account · asks for administrator approval</value></data>
|
||||
<data name="Tooltips.Setup.AllUsersOnly" xml:space="preserve"><value>{0} · it runs as a Windows service, so it installs for all users in Program Files</value></data>
|
||||
<data name="Tooltips.Setup.Back" xml:space="preserve"><value>Return to the options without changing anything</value></data>
|
||||
<data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Choose the installation folder</value></data>
|
||||
<data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Close setup without changing anything</value></data>
|
||||
@@ -605,15 +610,21 @@
|
||||
<data name="Tooltips.Setup.Desktop" xml:space="preserve"><value>Add shortcuts to the desktop</value></data>
|
||||
<data name="Tooltips.Setup.Folder" xml:space="preserve"><value>Where the programs are installed · your data stays in its own folder</value></data>
|
||||
<data name="Tooltips.Setup.FolderInvalid" xml:space="preserve"><value>Enter a full folder path that is not a drive root or a system folder</value></data>
|
||||
<data name="Tooltips.Setup.FolderProgramFiles" xml:space="preserve"><value>{0} runs as a Windows service, so choose a folder inside Program Files</value></data>
|
||||
<data name="Tooltips.Setup.Install" xml:space="preserve"><value>Copy the selected programs and register them with Windows</value></data>
|
||||
<data name="Tooltips.Setup.Installed" xml:space="preserve"><value>Folder of the installed programs</value></data>
|
||||
<data name="Tooltips.Setup.JustMe" xml:space="preserve"><value>Install in your user folder · no administrator rights needed</value></data>
|
||||
<data name="Tooltips.Setup.JustMeLocked" xml:space="preserve"><value>{0} runs as a Windows service, so it installs for all users only</value></data>
|
||||
<data name="Tooltips.Setup.Language" xml:space="preserve"><value>Language of this setup</value></data>
|
||||
<data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Open the program when setup finishes</value></data>
|
||||
<data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Open the installed program</value></data>
|
||||
<data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Already installed here · uninstall it first to change folder or scope</value></data>
|
||||
<data name="Tooltips.Setup.NeedsAllUsers" xml:space="preserve"><value>Runs as a Windows service, so it installs for all users only · this copy is installed for you alone; uninstall it first to add it</value></data>
|
||||
<data name="Tooltips.Setup.NeedsProgramFiles" xml:space="preserve"><value>Runs as a Windows service, so it installs inside Program Files only · this copy is installed elsewhere; uninstall it first to add it</value></data>
|
||||
<data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Select at least one program to install</value></data>
|
||||
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Also delete %LOCALAPPDATA%\Titano: database, backups, cache, settings, logs, the uploader queue and sign-in · photos in archives are kept</value></data>
|
||||
<data name="Tooltips.Setup.RemoveDataTitano" xml:space="preserve"><value>Also delete Titano’s database, backups, cache, settings and logs in %LOCALAPPDATA%\Titano · the Uploader’s files and photos in archives are kept</value></data>
|
||||
<data name="Tooltips.Setup.RemoveDataUploader" xml:space="preserve"><value>Also delete the Uploader’s queue, settings, sign-in and logs in %LOCALAPPDATA%\Titano · Titano’s files and photos in archives are kept</value></data>
|
||||
<data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Run the same step again</value></data>
|
||||
<data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Add the programs to the Start menu</value></data>
|
||||
<data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Remove programs, shortcuts and file types · your data is kept unless selected</value></data>
|
||||
|
||||
@@ -173,6 +173,15 @@
|
||||
<data name="Editor.Preview.Unreadable" xml:space="preserve"><value>Questo fotogramma non si può leggere.</value></data>
|
||||
<data name="Editor.Preview.Vectors" xml:space="preserve"><value>Vettori</value></data>
|
||||
<data name="Editor.Preview.Wipe" xml:space="preserve"><value>originale | corretto</value></data>
|
||||
<data name="Editor.ProjectFile.Applied" xml:space="preserve"><value>File di progetto applicato</value></data>
|
||||
<data name="Editor.ProjectFile.Locked" xml:space="preserve"><value>Le impostazioni del file di progetto non sono state applicate.</value><comment>long</comment></data>
|
||||
<data name="Editor.ProjectFile.NotFound" xml:space="preserve"><value>La sequenza di questo file di progetto non è nella libreria.</value><comment>long</comment></data>
|
||||
<data name="Editor.ProjectFile.Retry" xml:space="preserve"><value>Riprova</value></data>
|
||||
<data name="Editor.ProjectFile.Save" xml:space="preserve"><value>Salva file progetto</value></data>
|
||||
<data name="Editor.ProjectFile.Saved" xml:space="preserve"><value>File di progetto salvato</value></data>
|
||||
<data name="Editor.ProjectFile.Title" xml:space="preserve"><value>Cartella file progetto</value></data>
|
||||
<data name="Editor.ProjectFile.Undo" xml:space="preserve"><value>Annulla</value></data>
|
||||
<data name="Editor.ProjectFile.Unreadable" xml:space="preserve"><value>Questo file non è un progetto Titano o non si può leggere.</value><comment>long</comment></data>
|
||||
<data name="Editor.Proxies.Failed" xml:space="preserve"><value>Proxy non ricevuti</value></data>
|
||||
<data name="Editor.Proxies.Fetching" xml:space="preserve"><value>Scaricamento dei proxy</value></data>
|
||||
<data name="Editor.Regions.Auto" xml:space="preserve"><value>Auto</value></data>
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
<data name="Setup.Field.Language" xml:space="preserve"><value>Lingua</value></data>
|
||||
<data name="Setup.Field.Options" xml:space="preserve"><value>Opzioni</value></data>
|
||||
<data name="Setup.Field.Scope" xml:space="preserve"><value>Installa per</value></data>
|
||||
<data name="Setup.FileType.Project" xml:space="preserve"><value>Progetto Titano</value></data>
|
||||
<data name="Setup.Folder.Browse" xml:space="preserve"><value>Sfoglia</value></data>
|
||||
<data name="Setup.Header.Upgrade" xml:space="preserve"><value>Versione {0} · installata {1}</value></data>
|
||||
<data name="Setup.Header.Version" xml:space="preserve"><value>Versione {0}</value></data>
|
||||
|
||||
@@ -211,6 +211,10 @@
|
||||
<data name="Tooltips.Editor.Preview.ShotData" xml:space="preserve"><value>Mostra o nasconde i dati di scatto</value></data>
|
||||
<data name="Tooltips.Editor.Preview.Vectors" xml:space="preserve"><value>Sovrappone il movimento verso il fotogramma successivo misurato dal motore</value></data>
|
||||
<data name="Tooltips.Editor.Preview.View" xml:space="preserve"><value>Trascina la linea per confrontare · trascina per spostare · la rotellina ingrandisce · doppio clic 1:1</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Remote" xml:space="preserve"><value>I file di progetto sono per le sequenze di un archivio su questo PC</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Retry" xml:space="preserve"><value>Applica di nuovo le impostazioni del file di progetto</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Save" xml:space="preserve"><value>Salva un file .titano che, con un doppio clic, apre questa sequenza con queste impostazioni</value></data>
|
||||
<data name="Tooltips.Editor.ProjectFile.Undo" xml:space="preserve"><value>Ripristina le impostazioni che la sequenza aveva prima di aprire il file · Ctrl+Z</value></data>
|
||||
<data name="Tooltips.Editor.ReadOnly" xml:space="preserve"><value>Il tuo account può vedere questa sequenza del server ma non modificarla</value></data>
|
||||
<data name="Tooltips.Editor.Remote" xml:space="preserve"><value>Modificata con i proxy su questo PC; le modifiche si salvano su {0} e analisi e render vengono eseguiti lì</value></data>
|
||||
<data name="Tooltips.Editor.RemoteReadOnly" xml:space="preserve"><value>Mostrata da {0}; il tuo account può vedere questa sequenza ma non modificarla</value></data>
|
||||
@@ -593,6 +597,7 @@
|
||||
<data name="Tooltips.Settings.WorkersAuto" xml:space="preserve"><value>Auto: metà dei core logici esegue attività insieme, ognuna con il proprio numero di thread</value></data>
|
||||
<data name="Tooltips.Settings.WorkersReset" xml:space="preserve"><value>Torna ad Auto: metà dei core logici</value></data>
|
||||
<data name="Tooltips.Setup.AllUsers" xml:space="preserve"><value>Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore</value></data>
|
||||
<data name="Tooltips.Setup.AllUsersOnly" xml:space="preserve"><value>{0} · è un servizio di Windows, quindi si installa per tutti gli utenti in Programmi</value></data>
|
||||
<data name="Tooltips.Setup.Back" xml:space="preserve"><value>Torna alle opzioni senza modificare nulla</value></data>
|
||||
<data name="Tooltips.Setup.Browse" xml:space="preserve"><value>Scegli la cartella di installazione</value></data>
|
||||
<data name="Tooltips.Setup.Cancel" xml:space="preserve"><value>Chiudi l'installazione senza modificare nulla</value></data>
|
||||
@@ -605,15 +610,21 @@
|
||||
<data name="Tooltips.Setup.Desktop" xml:space="preserve"><value>Aggiungi collegamenti al desktop</value></data>
|
||||
<data name="Tooltips.Setup.Folder" xml:space="preserve"><value>Dove vengono installati i programmi · i tuoi dati restano nella loro cartella</value></data>
|
||||
<data name="Tooltips.Setup.FolderInvalid" xml:space="preserve"><value>Inserisci il percorso completo di una cartella che non sia la radice di un'unità o una cartella di sistema</value></data>
|
||||
<data name="Tooltips.Setup.FolderProgramFiles" xml:space="preserve"><value>{0} è un servizio di Windows, quindi scegli una cartella dentro Programmi</value></data>
|
||||
<data name="Tooltips.Setup.Install" xml:space="preserve"><value>Copia i programmi selezionati e registrali in Windows</value></data>
|
||||
<data name="Tooltips.Setup.Installed" xml:space="preserve"><value>Cartella dei programmi installati</value></data>
|
||||
<data name="Tooltips.Setup.JustMe" xml:space="preserve"><value>Installa nella tua cartella utente · non servono diritti di amministratore</value></data>
|
||||
<data name="Tooltips.Setup.JustMeLocked" xml:space="preserve"><value>{0} è un servizio di Windows, quindi si installa solo per tutti gli utenti</value></data>
|
||||
<data name="Tooltips.Setup.Language" xml:space="preserve"><value>Lingua di questa installazione</value></data>
|
||||
<data name="Tooltips.Setup.Launch" xml:space="preserve"><value>Apri il programma al termine dell'installazione</value></data>
|
||||
<data name="Tooltips.Setup.LaunchNow" xml:space="preserve"><value>Apri il programma installato</value></data>
|
||||
<data name="Tooltips.Setup.Locked" xml:space="preserve"><value>Già installato qui · disinstallalo prima per cambiare cartella o ambito</value></data>
|
||||
<data name="Tooltips.Setup.NeedsAllUsers" xml:space="preserve"><value>È un servizio di Windows, quindi si installa solo per tutti gli utenti · questa copia è installata solo per te; disinstallala prima per aggiungerlo</value></data>
|
||||
<data name="Tooltips.Setup.NeedsProgramFiles" xml:space="preserve"><value>È un servizio di Windows, quindi si installa solo dentro Programmi · questa copia è installata altrove; disinstallala prima per aggiungerlo</value></data>
|
||||
<data name="Tooltips.Setup.NoComponent" xml:space="preserve"><value>Seleziona almeno un programma da installare</value></data>
|
||||
<data name="Tooltips.Setup.RemoveData" xml:space="preserve"><value>Elimina anche %LOCALAPPDATA%\Titano: database, backup, cache, impostazioni, log, coda e accesso dell'uploader · le foto negli archivi restano</value></data>
|
||||
<data name="Tooltips.Setup.RemoveDataTitano" xml:space="preserve"><value>Elimina anche database, backup, cache, impostazioni e log di Titano in %LOCALAPPDATA%\Titano · i file dell'uploader e le foto negli archivi restano</value></data>
|
||||
<data name="Tooltips.Setup.RemoveDataUploader" xml:space="preserve"><value>Elimina anche coda, impostazioni, accesso e log dell'uploader in %LOCALAPPDATA%\Titano · i file di Titano e le foto negli archivi restano</value></data>
|
||||
<data name="Tooltips.Setup.Retry" xml:space="preserve"><value>Esegui di nuovo lo stesso passaggio</value></data>
|
||||
<data name="Tooltips.Setup.StartMenu" xml:space="preserve"><value>Aggiungi i programmi al menu Start</value></data>
|
||||
<data name="Tooltips.Setup.Uninstall" xml:space="preserve"><value>Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta</value></data>
|
||||
|
||||
+103
-4
@@ -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 <dir></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();
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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.<last part of the ProgID></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);
|
||||
|
||||
@@ -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; } = [];
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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)]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 [];
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using Titano.App.DesignTime;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.App.Tests.Windows;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Theming;
|
||||
|
||||
namespace Titano.App.Tests.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// <c>.titano</c> project files (BRIEF §18) in the real main window on the editor sample: the editor saves one, and
|
||||
/// opening one shows its sequence with the file's settings as one undo step, or says in one sentence why not.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
public sealed class ProjectFilesTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public Task AProjectFileSavesAndOpensItsSequenceWithItsSettings() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
var folder = context.CreateTempDirectory("project-files");
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
UiLanguage.Apply("en");
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new FolderDialogs(folder));
|
||||
var sample = SampleData.Configure(services);
|
||||
var shell = new ShellViewModel(services);
|
||||
var toasts = new List<Toast>();
|
||||
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
|
||||
var window = new MainWindow(shell)
|
||||
{
|
||||
WindowStartupLocation = WindowStartupLocation.Manual,
|
||||
Left = -20000,
|
||||
Top = -20000,
|
||||
Width = 1200,
|
||||
Height = 788,
|
||||
ShowActivated = false,
|
||||
ShowInTaskbar = false,
|
||||
};
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
await sample.OpenEmptyAsync();
|
||||
await shell.StartAsync();
|
||||
var id = await sample.FillEditorAsync();
|
||||
var files = new ProjectFiles(shell);
|
||||
|
||||
// Saved under the sequence's title, never over an earlier file.
|
||||
var editor = Assert.NotNull(await shell.Sequence.ShowAsync(id));
|
||||
await files.SaveAsync(editor.Session);
|
||||
await files.SaveAsync(editor.Session);
|
||||
var path = Path.Combine(folder, "Harbour sunset.titano");
|
||||
Assert.FileExists(path);
|
||||
Assert.FileExists(Path.Combine(folder, "Harbour sunset (2).titano"));
|
||||
Assert.Equal(Loc.L("Editor.ProjectFile.Saved"), toasts[^1].Title);
|
||||
var bundle = ProjectBundle.Load(path);
|
||||
Assert.Equal(id, bundle.Sequence.Id);
|
||||
Assert.Equal(editor.FrameCount, bundle.Sequence.Frames);
|
||||
Assert.Equal(editor.Session.Project.ToJson(), bundle.Project.ToJson());
|
||||
|
||||
// Opening it with other settings shows the sequence with them, as one step Undo takes back.
|
||||
var before = editor.Session.Project;
|
||||
bundle.ExposureOffset(0.7).Save(path);
|
||||
await files.OpenAsync(path);
|
||||
Assert.Same(editor, shell.Sequence.Editor);
|
||||
Assert.Equal(0.7, editor.Session.Project.Exposure.ExposureOffsetEv);
|
||||
var applied = toasts[^1];
|
||||
Assert.Equal(Loc.L("Editor.ProjectFile.Applied"), applied.Title);
|
||||
Assert.False(applied.IsError);
|
||||
applied.ActionCommand!.Execute(null);
|
||||
Assert.Equal(before.ToJson(), editor.Session.Project.ToJson());
|
||||
|
||||
// A sequence this library does not have, and a file that is not a project: one sentence each.
|
||||
var elsewhere = bundle with
|
||||
{
|
||||
Archive = bundle.Archive with { Id = Guid.CreateVersion7() },
|
||||
Sequence = bundle.Sequence with { Id = Guid.CreateVersion7(), Folder = "2026/elsewhere" },
|
||||
};
|
||||
var missing = Path.Combine(folder, "Elsewhere.titano");
|
||||
elsewhere.Save(missing);
|
||||
await files.OpenAsync(missing);
|
||||
Assert.Equal(Loc.L("Editor.ProjectFile.NotFound"), toasts[^1].Title);
|
||||
Assert.True(toasts[^1].IsError);
|
||||
|
||||
var text = Path.Combine(folder, "notes.titano");
|
||||
await File.WriteAllTextAsync(text, "not a project");
|
||||
await files.OpenAsync(text);
|
||||
Assert.Equal(Loc.L("Editor.ProjectFile.Unreadable"), toasts[^1].Title);
|
||||
Assert.True(toasts[^1].IsError);
|
||||
Assert.Same(editor, shell.Sequence.Editor, "the open sequence stays");
|
||||
await editor.Session.FlushAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
await shell.Sequence.CloseAsync();
|
||||
shell.Dispose();
|
||||
await services.DisposeAsync();
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void AHandOverMessageRoundTrips()
|
||||
{
|
||||
string[] args = [@"C:\Users\me\Desktop\Harbour sunset.titano"];
|
||||
Assert.SequenceEqual(args, SingleInstance.Decode(SingleInstance.Encode(args))!);
|
||||
Assert.Empty(SingleInstance.Decode(SingleInstance.Encode([]))!);
|
||||
Assert.Null(SingleInstance.Decode("TITANO-UPLOADER/1\nE:\\"u8));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASecondLaunchOnTheSameDataFolderHandsItsFileToTheFirst()
|
||||
{
|
||||
var data = context.CreateTempDirectory("instance");
|
||||
var first = Assert.NotNull(SingleInstance.TryAcquire(data));
|
||||
try
|
||||
{
|
||||
first.Listen();
|
||||
Assert.Null(SingleInstance.TryAcquire(data), "one Titano per data folder");
|
||||
using (var other = SingleInstance.TryAcquire(context.CreateTempDirectory("other-copy")))
|
||||
Assert.NotNull(other, "a portable copy with its own data folder runs on its own");
|
||||
|
||||
// Launches while the first one is still opening its window are kept until the window takes them. The pipe
|
||||
// takes one launch at a time, so once the second hand-over is through, the first one is already waiting.
|
||||
Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Early.titano"]));
|
||||
Assert.True(SingleInstance.HandOver(data, []));
|
||||
using var received = new System.Collections.Concurrent.BlockingCollection<IReadOnlyList<string>>();
|
||||
first.Receive(received.Add);
|
||||
Assert.True(received.TryTake(out var early, TimeSpan.FromSeconds(10)), "the hand-over that came first is delivered");
|
||||
Assert.SequenceEqual([@"D:\Projects\Early.titano"], early!);
|
||||
Assert.True(received.TryTake(out var show, TimeSpan.FromSeconds(10)), "then the plain launch");
|
||||
Assert.Empty(show!);
|
||||
|
||||
Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"]));
|
||||
Assert.True(received.TryTake(out var later, TimeSpan.FromSeconds(10)), "the running instance received the hand-over");
|
||||
Assert.SequenceEqual([@"D:\Projects\Roof.titano"], later!);
|
||||
}
|
||||
finally
|
||||
{
|
||||
first.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALaunchWhileTitanoClosesWaitsForItAndStartsInItsPlace()
|
||||
{
|
||||
var data = context.CreateTempDirectory("closing");
|
||||
var first = Assert.NotNull(SingleInstance.TryAcquire(data));
|
||||
first.Listen();
|
||||
first.Receive(_ => { });
|
||||
// Closing: it no longer answers, but it still holds the data folder until its services have stopped.
|
||||
first.StopListening();
|
||||
Assert.False(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"]), "a closing Titano takes no file it could not open");
|
||||
Assert.Null(SingleInstance.TryAcquire(data));
|
||||
|
||||
// The next launch waits (the mutex belongs to a thread, so it waits on its own) and gets its turn once the first exits.
|
||||
var next = Task.Run(() =>
|
||||
{
|
||||
using var instance = SingleInstance.WaitForTurn(data, TimeSpan.FromSeconds(20));
|
||||
return instance is not null;
|
||||
});
|
||||
Assert.False(next.Wait(TimeSpan.FromMilliseconds(300)), "it waits while the first one still runs");
|
||||
first.Dispose();
|
||||
Assert.True(next.Wait(TimeSpan.FromSeconds(20)) && next.Result, "it starts once the first one has exited");
|
||||
|
||||
// Nobody exits in time: the launch gives up.
|
||||
var holder = Assert.NotNull(SingleInstance.TryAcquire(data));
|
||||
try
|
||||
{
|
||||
Assert.False(Task.Run(() => SingleInstance.WaitForTurn(data, TimeSpan.FromMilliseconds(200)) is { } got && Dispose(got)).Result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
holder.Dispose();
|
||||
}
|
||||
|
||||
static bool Dispose(SingleInstance instance)
|
||||
{
|
||||
instance.Dispose();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dialogs that pick one folder and cancel everything else.</summary>
|
||||
private sealed class FolderDialogs(string folder) : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => folder;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ProjectBundleTestExtensions
|
||||
{
|
||||
/// <summary>The same file with another exposure offset.</summary>
|
||||
public static ProjectBundle ExposureOffset(this ProjectBundle bundle, double ev) =>
|
||||
bundle with { Project = bundle.Project with { Exposure = bundle.Project.Exposure with { ExposureOffsetEv = ev } } };
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Microsoft.Win32;
|
||||
using Titano.Core.Packaging;
|
||||
using Titano.Setup.Cli;
|
||||
using Titano.Setup.Engine;
|
||||
using Titano.Setup.Interop;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// What setup leaves behind and what it registers: services and startup entries of the programs it installed, never
|
||||
/// of other programs in the same folder (SETUP-1, SETUP-2), shortcuts another product owns or takes over (SRS-09), the
|
||||
/// Server's all-users scope inside Program Files (SRS-06) and the file type name in setup's language (SRS-04).
|
||||
/// </summary>
|
||||
public sealed class SetupEngineTests(TestContext context)
|
||||
{
|
||||
private const string TestsKey = @"Software\Titano.Tests";
|
||||
|
||||
[Theory]
|
||||
[Case(@"""C:\Program Files\Titano\Titano.Server.exe"" --service", @"C:\Program Files\Titano\Titano.Server.exe")]
|
||||
[Case(@"C:\Program Files\Titano\Titano.Server.exe --service", @"C:\Program Files\Titano\Titano.Server.exe")]
|
||||
[Case(@"""C:\Program Files\dotnet\dotnet.exe"" ""C:\Apps\Titano\Titano.Server.dll"" --service", @"C:\Apps\Titano\Titano.Server.dll")]
|
||||
[Case(@"C:\Windows\system32\svchost.exe -k netsvcs", @"C:\Windows\system32\svchost.exe")]
|
||||
[Case(@"Titano.Uploader.exe --tray", null)]
|
||||
[Case("", null)]
|
||||
public void TheProgramOfACommandLineIsItsFirstFullPath(string commandLine, string? program) =>
|
||||
Assert.Equal(program, CommandProgram.Of(commandLine));
|
||||
|
||||
[Test]
|
||||
public void ServiceStepsTravelToTheElevatedCopyWithTheirServices()
|
||||
{
|
||||
var arguments = new SetupArguments
|
||||
{
|
||||
Services = ServiceActions.Prune | ServiceActions.Start,
|
||||
ServiceNames = ["TitanoServer"],
|
||||
Directory = @"C:\Program Files\Titano",
|
||||
Elevated = true,
|
||||
};
|
||||
var switches = arguments.ToSwitches().ToList();
|
||||
Assert.Contains("/SERVICES=prune,start", switches);
|
||||
Assert.Contains("/NAMES=TitanoServer", switches);
|
||||
var parsed = SetupArguments.Parse(switches);
|
||||
Assert.Equal(arguments.Services, parsed.Services);
|
||||
Assert.Equal(arguments.Directory, parsed.Directory);
|
||||
Assert.SequenceEqual(["TitanoServer"], parsed.ServiceNames!);
|
||||
Assert.True(parsed.Elevated);
|
||||
|
||||
Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]).Services);
|
||||
// The step acts only on services the unelevated setup named.
|
||||
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/NAMES=TitanoServer"]));
|
||||
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/DIR=C:\\Apps\\Titano"]));
|
||||
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=kill", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]));
|
||||
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=none", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void OnlyTheServicesOfProgramsSetupInstalledAreFound()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("services"), "Apps");
|
||||
var owned = CommandProgram.FullPaths(folder, ["Titano.Server.exe", "Titano.exe", "lib/Titano.Core.dll"]);
|
||||
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
|
||||
try
|
||||
{
|
||||
using var services = Registry.CurrentUser.CreateSubKey(keyPath, writable: true);
|
||||
Service(services, "TitanoServer", 0x10, $"\"{Path.Combine(folder, "Titano.Server.exe")}\" --service");
|
||||
Service(services, "TitanoServerUnquoted", 0x10, Path.Combine(folder, "TITANO.SERVER.EXE") + " --service");
|
||||
// Another vendor's service, and a driver, that live in the same folder (a shared D:\Apps): never Titano's.
|
||||
Service(services, "OtherVendor", 0x10, $"\"{Path.Combine(folder, "Other", "Other.exe")}\"");
|
||||
Service(services, "OtherBeside", 0x10, $"\"{Path.Combine(folder, "Helper.exe")}\" /run");
|
||||
Service(services, "Driver", 0x1, Path.Combine(folder, "Titano.Server.exe"));
|
||||
using (var deleting = services.CreateSubKey("Deleting", writable: true))
|
||||
{
|
||||
deleting.SetValue("Type", 0x10, RegistryValueKind.DWord);
|
||||
deleting.SetValue("DeleteFlag", 1, RegistryValueKind.DWord);
|
||||
deleting.SetValue("ImagePath", Path.Combine(folder, "Titano.Server.exe"), RegistryValueKind.ExpandString);
|
||||
}
|
||||
|
||||
var found = InstalledServices.Find(services, owned);
|
||||
Assert.SequenceEqual(["TitanoServer", "TitanoServerUnquoted"], found.Select(s => s.Name).Order(StringComparer.Ordinal));
|
||||
Assert.True(found.All(s => s.Program.Equals(Path.Combine(folder, "Titano.Server.exe"), StringComparison.OrdinalIgnoreCase)));
|
||||
Assert.Empty(InstalledServices.Find(services, CommandProgram.FullPaths(folder, ["Titano.exe"])));
|
||||
}
|
||||
finally
|
||||
{
|
||||
DeleteTestKey(keyPath);
|
||||
}
|
||||
|
||||
static void Service(RegistryKey services, string name, int type, string imagePath)
|
||||
{
|
||||
using var key = services.CreateSubKey(name, writable: true);
|
||||
key.SetValue("Type", type, RegistryValueKind.DWord);
|
||||
key.SetValue("ImagePath", imagePath, RegistryValueKind.ExpandString);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AServiceThatIsNotRegisteredNeedsNothing()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("services");
|
||||
// No service starts a program of a fresh folder, and nothing is asked of the Service Control Manager.
|
||||
Assert.Empty(InstalledServices.Find(CommandProgram.FullPaths(folder, ["Titano.Server.exe"])));
|
||||
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([], ServiceActions.Remove));
|
||||
|
||||
var gone = new InstalledService("TitanoTest" + Guid.NewGuid().ToString("N"), "Titano Server", Path.Combine(folder, "Titano.Server.exe"));
|
||||
Assert.False(InstalledServices.IsRunning(gone));
|
||||
foreach (var action in (ServiceActions[])[ServiceActions.Stop, ServiceActions.Prune, ServiceActions.Start, ServiceActions.Remove])
|
||||
Assert.False(InstalledServices.NeedsWork([gone], action), $"{action} of a service that does not exist");
|
||||
// Applying to it skips it: a service deleted meanwhile is not a failure.
|
||||
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([gone], ServiceActions.Remove | ServiceActions.Start));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void UninstallRemovesOnlyTheSignInEntriesOfTheProgramsItRemoves()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("startup"), "Apps");
|
||||
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
|
||||
try
|
||||
{
|
||||
using (var run = Registry.CurrentUser.CreateSubKey(keyPath, writable: true))
|
||||
{
|
||||
run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Uploader", "Titano.Uploader.exe")}\" --tray");
|
||||
// A portable Titano unpacked in a subfolder of the same folder: not a program this installation lists.
|
||||
run.SetValue("Titano", $"\"{Path.Combine(folder, "Portable", "Titano.exe")}\" --minimized");
|
||||
// Another program in the same folder, and a copy in a sibling folder.
|
||||
run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background");
|
||||
run.SetValue("Sibling", $"\"{folder} 2\\Titano.Uploader.exe\"");
|
||||
|
||||
var programs = CommandProgram.FullPaths(folder, ["Titano.exe", "Uploader/Titano.Uploader.exe", "Other.exe"]);
|
||||
Assert.SequenceEqual(["Titano Uploader"], SetupRegistry.DeleteStartupEntries(run, programs));
|
||||
Assert.SequenceEqual(["Other", "Sibling", "Titano"], run.GetValueNames().Order(StringComparer.Ordinal));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
DeleteTestKey(keyPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AShortcutTellsWhichProgramItStarts()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("links");
|
||||
var target = Path.Combine(folder, "Product A", "Titano.Uploader.exe");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
File.WriteAllBytes(target, [0x4D, 0x5A]);
|
||||
var link = Path.Combine(folder, "Titano Uploader.lnk");
|
||||
ShellLink.Create(link, target, "Titano Uploader");
|
||||
|
||||
// The shell may store the long form of a short (8.3) temporary path: the same file either way.
|
||||
var stored = Assert.NotNull(ShellLink.TargetOf(link));
|
||||
Assert.Equal(Path.GetFileName(target), Path.GetFileName(stored));
|
||||
Assert.FileExists(stored);
|
||||
var productA = Path.GetDirectoryName(stored)!;
|
||||
Assert.True(CommandProgram.IsPathInside(stored, productA));
|
||||
Assert.False(CommandProgram.IsPathInside(stored, Path.Combine(Path.GetDirectoryName(productA)!, "Product B")));
|
||||
Assert.False(CommandProgram.IsPathInside(stored, productA + " 2"));
|
||||
Assert.Null(ShellLink.TargetOf(Path.Combine(folder, "missing.lnk")));
|
||||
var notALink = Path.Combine(folder, "not a link.lnk");
|
||||
File.WriteAllText(notALink, "plain text");
|
||||
Assert.Null(ShellLink.TargetOf(notALink));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnUninstalledProductHandsItsShortcutToTheProductThatKeepsTheProgram()
|
||||
{
|
||||
var root = context.CreateTempDirectory("handover");
|
||||
foreach (var product in (string[])["Product A", "Product B"])
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(root, product));
|
||||
File.WriteAllBytes(Path.Combine(root, product, "Titano.Uploader.exe"), [0x4D, 0x5A]);
|
||||
}
|
||||
// A uniquely named shortcut in the user's own Start menu, the only folder setup deletes shortcuts from.
|
||||
var link = Path.Combine(SetupPaths.StartMenu(InstallScope.CurrentUser), "Titano Test " + Guid.NewGuid().ToString("N") + ".lnk");
|
||||
try
|
||||
{
|
||||
ShellLink.Create(link, Path.Combine(root, "Product A", "Titano.Uploader.exe"), "Titano Test");
|
||||
// The folders as the shell stores them (the long form of a short temporary path).
|
||||
var productA = Path.GetDirectoryName(Assert.NotNull(ShellLink.TargetOf(link)))!;
|
||||
var productB = Path.Combine(Path.GetDirectoryName(productA)!, "Product B");
|
||||
var logB = new InstallLog { Product = "Titano Uploader", Version = "1.0.0", Scope = InstallScope.CurrentUser, Files = ["Titano.Uploader.exe"], Shortcuts = [link] };
|
||||
|
||||
// Product B also has the program and lists the shortcut: uninstalling A points it at B's copy.
|
||||
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, logB)]);
|
||||
var handed = Assert.NotNull(ShellLink.TargetOf(link));
|
||||
Assert.Equal("Product B", Path.GetFileName(Path.GetDirectoryName(handed)));
|
||||
|
||||
// Uninstalling A again leaves B's shortcut alone; uninstalling B with nobody left deletes it.
|
||||
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, []);
|
||||
Assert.FileExists(link);
|
||||
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productB, [new OtherInstall(productA, null)]);
|
||||
Assert.FileMissing(link);
|
||||
|
||||
// A product that does not list the shortcut, or whose folder cannot be read now, takes nothing over.
|
||||
ShellLink.Create(link, Path.Combine(productA, "Titano.Uploader.exe"), "Titano Test");
|
||||
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, new InstallLog { Product = "Titano", Version = "1.0.0", Files = ["Titano.Uploader.exe"] })]);
|
||||
Assert.FileMissing(link);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(link)) File.Delete(link);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheServerMakesANewInstallationAnAllUsersOneInsideProgramFiles()
|
||||
{
|
||||
var manifest = Manifest();
|
||||
var plan = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano", "Server"] });
|
||||
Assert.Equal(InstallScope.AllUsers, plan.Scope);
|
||||
Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.AllUsers, manifest.Product), plan.Directory);
|
||||
Assert.True(InstallPlan.IsValidDirectory(manifest, plan.Scope, plan.Directory, plan.Components));
|
||||
|
||||
// A folder standard users can change (C:\Titano, D:\Apps\Titano) would let them replace what the service starts.
|
||||
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
var custom = Path.Combine(Path.GetPathRoot(programFiles)!, "Titano");
|
||||
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano", "Server"]));
|
||||
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano"]));
|
||||
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, custom, ["Titano"]));
|
||||
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, Path.Combine(programFiles, "Titano"), ["Server"]));
|
||||
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, Path.Combine(programFiles, "Vendor", "Titano"), ["Server"]));
|
||||
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles), "Program Files itself is shared by every program");
|
||||
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles + " Extra" + Path.DirectorySeparatorChar + "Titano"));
|
||||
|
||||
var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano"] });
|
||||
Assert.Equal(InstallScope.CurrentUser, desktop.Scope);
|
||||
Assert.True(desktop.CanInstall(manifest.FindComponent("Server")!));
|
||||
|
||||
// A per-user installation upgraded in place keeps its scope, so it cannot take the Server; nor can an
|
||||
// all-users one in a folder outside Program Files.
|
||||
var perUser = desktop with { Existing = new ExistingInstall(InstallScope.CurrentUser, desktop.Directory, "0.9.0") };
|
||||
Assert.False(perUser.CanInstall(manifest.FindComponent("Server")!));
|
||||
Assert.True(perUser.CanInstall(manifest.FindComponent("Titano")!));
|
||||
var elsewhere = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, custom, "0.9.0") };
|
||||
Assert.False(elsewhere.CanInstall(manifest.FindComponent("Server")!));
|
||||
var protectedFolder = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, Path.Combine(programFiles, "Titano"), "0.9.0") };
|
||||
Assert.True(protectedFolder.CanInstall(manifest.FindComponent("Server")!));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheProjectFileTypeIsNamedInSetupsLanguage()
|
||||
{
|
||||
var association = new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" };
|
||||
Assert.Equal("Titano project", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("en")));
|
||||
Assert.Equal("Progetto Titano", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("it")));
|
||||
|
||||
var unknown = new PayloadAssociation { Component = "Titano", Extension = ".tlx", ProgId = "Titano.Unknown", Description = "Something else", Target = "Titano.exe" };
|
||||
Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it")));
|
||||
}
|
||||
|
||||
/// <summary>Deletes a scratch key under <see cref="TestsKey"/>, and that key too once it is empty.</summary>
|
||||
private static void DeleteTestKey(string keyPath)
|
||||
{
|
||||
Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
|
||||
bool empty;
|
||||
using (var tests = Registry.CurrentUser.OpenSubKey(TestsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 };
|
||||
if (empty) Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false);
|
||||
}
|
||||
|
||||
/// <summary>A manifest under a product name no machine has installed, so the registry holds no installation of it.</summary>
|
||||
private static PayloadManifest Manifest() => new()
|
||||
{
|
||||
Product = "TitanoTest" + Guid.NewGuid().ToString("N")[..12],
|
||||
Version = "1.0.0",
|
||||
Components =
|
||||
[
|
||||
new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true },
|
||||
new PayloadComponent { Id = "Server", DisplayName = "Titano Server", AllUsersOnly = true },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.IO;
|
||||
using Titano.Setup.Engine;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// "Remove my data" covers only the programs being removed (SRS-05): the desktop app and the Uploader share
|
||||
/// %LOCALAPPDATA%\Titano and its logs folder, and uninstalling one product never deletes what another still uses.
|
||||
/// </summary>
|
||||
public sealed class UserDataPlanTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheDesktopAppsPlanLeavesTheUploadersFiles()
|
||||
{
|
||||
var folder = SampleFolder();
|
||||
var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Titano));
|
||||
|
||||
Assert.SequenceEqual(
|
||||
["backups", "cache", "logs" + Path.DirectorySeparatorChar + "titano-20261012.log", "settings.json", "titano.db"],
|
||||
plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
|
||||
Assert.Equal(4000L + 3000 + 300 + 20 + 100, plan.TotalBytes);
|
||||
|
||||
plan.Remove();
|
||||
Assert.SequenceEqual(
|
||||
["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"],
|
||||
Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(folder, f)).Order(StringComparer.Ordinal));
|
||||
Assert.False(Directory.Exists(Path.Combine(folder, "cache")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheUploadersPlanLeavesTheDesktopAppsFilesAndEmptiedFoldersGo()
|
||||
{
|
||||
var folder = SampleFolder();
|
||||
var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Uploader));
|
||||
|
||||
Assert.SequenceEqual(
|
||||
["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"],
|
||||
plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
|
||||
|
||||
plan.Remove();
|
||||
Assert.True(File.Exists(Path.Combine(folder, "titano.db")));
|
||||
Assert.True(File.Exists(Path.Combine(folder, "logs", "titano-20261012.log")));
|
||||
Assert.FileMissing(Path.Combine(folder, "uploader.json"));
|
||||
Assert.FileMissing(Path.Combine(folder, "logs", "uploader-20261012.log"));
|
||||
|
||||
// Once the desktop app's data goes too, nothing is left of the folder.
|
||||
UserDataPlan.Measure(folder, Owners(UserDataOwners.Titano)).Remove();
|
||||
Assert.False(Directory.Exists(folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BothProgramsDataIsTheWholeFolderAndNoOwnerIsAnEmptyPlan()
|
||||
{
|
||||
var folder = SampleFolder();
|
||||
var whole = UserDataPlan.Measure(folder, UserDataOwners.All);
|
||||
Assert.SequenceEqual(
|
||||
["backups", "cache", "logs", "settings.json", "titano.db", "uploader-queue.json", "uploader.json"],
|
||||
whole.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
|
||||
Assert.Empty(UserDataPlan.Measure(folder, Owners()).Entries);
|
||||
|
||||
whole.Remove();
|
||||
Assert.False(Directory.Exists(folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AProductRemovesTheDataOfItsProgramsThatNoOtherInstalledProductHas()
|
||||
{
|
||||
string[] titano = ["Titano", "Uploader", "Server"];
|
||||
string[] uploader = ["Uploader"];
|
||||
|
||||
Assert.SequenceEqual(["Titano", "Uploader"], UserDataOwners.Removable(titano, []).Order(StringComparer.Ordinal));
|
||||
Assert.SequenceEqual(["Titano"], UserDataOwners.Removable(titano, [uploader]).Order(StringComparer.Ordinal));
|
||||
Assert.Empty(UserDataOwners.Removable(uploader, [titano]));
|
||||
Assert.SequenceEqual(["Uploader"], UserDataOwners.Removable(uploader, [["titano"]]));
|
||||
// Titano Server keeps its data elsewhere: a Server-only product removes nothing here.
|
||||
Assert.Empty(UserDataOwners.Removable(["Server"], []));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnInstallationThatCannotBeReadNowKeepsEveryProgramsData()
|
||||
{
|
||||
string[] titano = ["Titano", "Uploader", "Server"];
|
||||
var uploader = new InstallLog { Product = "Titano Uploader", Version = "1.0.0", Components = ["Uploader"] };
|
||||
|
||||
Assert.SequenceEqual(["Titano"], UserDataOwners.RemovableBeside(titano, [new OtherInstall(@"D:\Titano Uploader", uploader)]).Order(StringComparer.Ordinal));
|
||||
// Its drive is offline, its folder is gone or its log is damaged: it may still use the desktop app's index.
|
||||
Assert.Empty(UserDataOwners.RemovableBeside(titano, [new OtherInstall(@"E:\Titano Uploader", null)]));
|
||||
Assert.Empty(UserDataOwners.RemovableBeside(titano, [new OtherInstall(null, null)]));
|
||||
}
|
||||
|
||||
private static HashSet<string> Owners(params string[] owners) => new(owners, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private string SampleFolder()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("userdata"), "Titano");
|
||||
Write(folder, "titano.db", 4000);
|
||||
Write(folder, "settings.json", 20);
|
||||
Write(folder, Path.Combine("cache", "proxies", "a.jpg"), 3000);
|
||||
Write(folder, Path.Combine("backups", "titano-1.db"), 100);
|
||||
Write(folder, Path.Combine("logs", "titano-20261012.log"), 300);
|
||||
Write(folder, Path.Combine("logs", "uploader-20261012.log"), 200);
|
||||
Write(folder, "uploader.json", 10);
|
||||
Write(folder, "uploader-queue.json", 50);
|
||||
return folder;
|
||||
}
|
||||
|
||||
private static void Write(string folder, string relative, int bytes)
|
||||
{
|
||||
var path = Path.Combine(folder, relative);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllBytes(path, new byte[bytes]);
|
||||
}
|
||||
}
|
||||
@@ -9,5 +9,6 @@
|
||||
<ProjectReference Include="..\Titano.Testing\Titano.Testing.csproj" />
|
||||
<ProjectReference Include="..\..\src\Titano.App\Titano.App.csproj" />
|
||||
<ProjectReference Include="..\..\src\Titano.Uploader\Titano.Uploader.csproj" />
|
||||
<ProjectReference Include="..\..\src\Titano.Setup\Titano.Setup.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,104 @@
|
||||
using Titano.Core.Project;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Project;
|
||||
|
||||
/// <summary>The <c>.titano</c> project file (BRIEF §18): a sequence reference plus the settings to open it with.</summary>
|
||||
public sealed class ProjectBundleTests(TestContext context)
|
||||
{
|
||||
private static readonly Guid ArchiveId = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
private static readonly Guid SequenceId = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a02");
|
||||
|
||||
[Test]
|
||||
public void ARoundTripKeepsTheReferenceAndTheSettings()
|
||||
{
|
||||
var bundle = Sample();
|
||||
var path = Path.Combine(context.CreateTempDirectory("bundle"), ProjectBundle.FileNameFor("Harbour sunset"));
|
||||
bundle.Save(path);
|
||||
|
||||
var back = ProjectBundle.Load(path);
|
||||
Assert.Equal(bundle.Archive, back.Archive);
|
||||
Assert.Equal(bundle.Sequence, back.Sequence);
|
||||
Assert.Equal(bundle.Saved, back.Saved);
|
||||
Assert.Equal(bundle.Project.ToJson(), back.Project.ToJson());
|
||||
Assert.Equal(0.8, back.Project.Exposure.DeflickerStrength.Resolve(1.0));
|
||||
Assert.SequenceEqual([3, 7], back.Project.ExcludedFrames);
|
||||
|
||||
var json = File.ReadAllText(path);
|
||||
Assert.Contains("\"format\": \"titano-project\"", json);
|
||||
Assert.Contains("\"formatVersion\": 1", json);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OtherFilesAreRefusedAsNotProjectFiles()
|
||||
{
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse("not json"));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse("[1, 2]"));
|
||||
// The archive's own meta files are JSON too, but not project files.
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse("""{ "schemaVersion": 1, "id": "0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01" }"""));
|
||||
var json = Sample().ToJson();
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"formatVersion\": 1", "\"formatVersion\": 2", StringComparison.Ordinal)));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace(SequenceId.ToString(), "not-a-guid", StringComparison.Ordinal)));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"version\": 1", "\"version\": 99", StringComparison.Ordinal)));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"folder\"", "\"place\"", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFileTooLargeToBeAProjectIsNotRead()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory("bundle"), "huge.titano");
|
||||
using (var stream = File.Create(path)) stream.SetLength(ProjectBundle.MaxBytes + 1L);
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Load(path));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FramePositionsApplyOnlyToTheFramesTheyWereSavedFor()
|
||||
{
|
||||
var bundle = Sample();
|
||||
var current = new ProjectSettings
|
||||
{
|
||||
ExcludedFrames = [1],
|
||||
HeroFrame = 2,
|
||||
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0)] },
|
||||
};
|
||||
|
||||
Assert.Same(bundle.Project, bundle.ProjectFor(current, frameCount: 3600));
|
||||
|
||||
var changed = bundle.ProjectFor(current, frameCount: 3610);
|
||||
Assert.SequenceEqual([1], changed.ExcludedFrames);
|
||||
Assert.Equal(2, changed.HeroFrame);
|
||||
Assert.Same(current.Camera.Keyframes, changed.Camera.Keyframes);
|
||||
// Everything else comes from the file.
|
||||
Assert.Equal(0.8, changed.Exposure.DeflickerStrength.Resolve(1.0));
|
||||
Assert.Equal(bundle.Project.Camera.Crop, changed.Camera.Crop);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("Harbour sunset", "Harbour sunset.titano")]
|
||||
[Case("Roof: 12/03 \"storm\"?", "Roof_ 12_03 _storm__.titano")]
|
||||
[Case("CON", "_CON.titano")]
|
||||
[Case(" ", "Titano.titano")]
|
||||
public void TheFileNameComesFromTheTitle(string title, string expected) => Assert.Equal(expected, ProjectBundle.FileNameFor(title));
|
||||
|
||||
[Test]
|
||||
public void SavingNeverReplacesAnEarlierProjectFile()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("bundle");
|
||||
Assert.Equal(Path.Combine(folder, "Harbour sunset.titano"), ProjectBundle.FreePathIn(folder, "Harbour sunset"));
|
||||
File.WriteAllText(Path.Combine(folder, "Harbour sunset.titano"), "{}");
|
||||
Directory.CreateDirectory(Path.Combine(folder, "Harbour sunset (2).titano"));
|
||||
Assert.Equal(Path.Combine(folder, "Harbour sunset (3).titano"), ProjectBundle.FreePathIn(folder, "Harbour sunset"));
|
||||
}
|
||||
|
||||
private static ProjectBundle Sample() => new(
|
||||
new BundleArchive(ArchiveId, "Main archive", @"D:\Timelapse"),
|
||||
new BundleSequence(SequenceId, "2026/2026-09-28 Harbour sunset", "Harbour sunset", 3600),
|
||||
new ProjectSettings
|
||||
{
|
||||
Exposure = new ExposureSettings { DeflickerStrength = new Auto<double>().WithManual(0.8) },
|
||||
Camera = new CameraSettings { Crop = [0.1, 0.1, 0.9, 0.9], Keyframes = [new CameraKey(120, 0.4, 0.5, 1.2, 0)] },
|
||||
ExcludedFrames = [3, 7],
|
||||
HeroFrame = 1800,
|
||||
},
|
||||
new DateTimeOffset(2026, 10, 12, 9, 30, 0, TimeSpan.Zero));
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Data.Tests.Infrastructure;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Processing;
|
||||
|
||||
/// <summary>A <c>.titano</c> project file names a sequence of this index, found again by id or by its folder (BRIEF §18).</summary>
|
||||
public abstract class ProjectBundlesTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheFileNamesTheSequenceAndItsArchive()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive("Main");
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id, title: "Harbour sunset");
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var project = new ProjectSettings { ExcludedFrames = [2] };
|
||||
|
||||
var bundle = await ProjectBundles.CreateAsync(db, sequence.Id, project, frames: 120, Ct);
|
||||
|
||||
Assert.Equal(new BundleArchive(archive.Id, "Main", archive.RootPath), bundle.Archive);
|
||||
Assert.Equal(new BundleSequence(sequence.Id, sequence.Folder, "Harbour sunset", 120), bundle.Sequence);
|
||||
Assert.Same(project, bundle.Project);
|
||||
Assert.Equal(sequence.Id, (await ProjectBundles.ResolveAsync(db, ProjectBundle.Parse(bundle.ToJson()), Ct))!.Id);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => ProjectBundles.CreateAsync(db, Guid.CreateVersion7(), project, 0, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceWithANewIdIsFoundByItsFolderInTheSameArchive()
|
||||
{
|
||||
var db = await OpenTitanoAsync();
|
||||
var archive = TestData.Archive("Main");
|
||||
var other = TestData.Archive("Other");
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
await db.Archives.UpsertAsync(other, Ct);
|
||||
var adoptedAgain = TestData.Sequence(archive.Id) with { Folder = "2026/2026-09-28 Harbour" };
|
||||
var elsewhere = TestData.Sequence(other.Id) with { Folder = "2026/2026-09-28 Roof" };
|
||||
await db.Sequences.UpsertAsync(adoptedAgain, Ct);
|
||||
await db.Sequences.UpsertAsync(elsewhere, Ct);
|
||||
|
||||
var bundle = Bundle(archive.Id, Guid.CreateVersion7(), "2026/2026-09-28 HARBOUR");
|
||||
Assert.Equal(adoptedAgain.Id, (await ProjectBundles.ResolveAsync(db, bundle, Ct))!.Id);
|
||||
|
||||
// A folder of another archive, an unknown folder or an archive this index does not have: not found.
|
||||
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(archive.Id, Guid.CreateVersion7(), "2026/2026-09-28 Roof"), Ct));
|
||||
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(archive.Id, Guid.CreateVersion7(), "2025/missing"), Ct));
|
||||
Assert.Null(await ProjectBundles.ResolveAsync(db, Bundle(Guid.CreateVersion7(), Guid.CreateVersion7(), "2026/2026-09-28 Harbour"), Ct));
|
||||
}
|
||||
|
||||
private static ProjectBundle Bundle(Guid archiveId, Guid sequenceId, string folder) =>
|
||||
new(new BundleArchive(archiveId, "Main", null), new BundleSequence(sequenceId, folder, "Harbour", 10), new ProjectSettings(), TestData.Now);
|
||||
}
|
||||
|
||||
public sealed class SqliteProjectBundlesTests(TestContext context) : ProjectBundlesTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresProjectBundlesTests(TestContext context) : ProjectBundlesTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Tools.Commands;
|
||||
|
||||
namespace Titano.Tools.Tests;
|
||||
|
||||
/// <summary>Release notes from Conventional Commits (BRIEF §19.3), as release.yml renders them with a title.</summary>
|
||||
public sealed class ChangelogCommandTests
|
||||
{
|
||||
[Test]
|
||||
public void EntriesAreGroupedByTypeUnderTheTitle()
|
||||
{
|
||||
var notes = ChangelogCommand.Render(["abc1234\tfeat(editor): save the project as a .titano file", "def5678\tfix: keep user data", "0a1b2c3\tchore: bump"], "Titano 1.2.0");
|
||||
Assert.Equal(
|
||||
"# Titano 1.2.0\n\n### Added\n- **editor**: save the project as a .titano file (abc1234)\n\n### Fixed\n- keep user data (def5678)\n\n",
|
||||
notes.ReplaceLineEndings("\n"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATitledReleaseWithoutListedChangesSaysItIsAMaintenanceRelease()
|
||||
{
|
||||
string[] lines = ["abc1234\tchore: bump", "def5678\tci: cache", "0a1b2c3\ttest(setup): cover uninstall", "not a conventional subject"];
|
||||
Assert.Equal("# Titano 1.2.1\n\nMaintenance release.\n", ChangelogCommand.Render(lines, "Titano 1.2.1").ReplaceLineEndings("\n"));
|
||||
Assert.Equal("Maintenance release.\n", ChangelogCommand.Render(lines, null).ReplaceLineEndings("\n"));
|
||||
Assert.Equal("Maintenance release.\n", ChangelogCommand.Render([], null).ReplaceLineEndings("\n"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ABreakingChangeOfAnUnlistedTypeIsStillWritten()
|
||||
{
|
||||
var notes = ChangelogCommand.Render(["abc1234\trefactor(core)!: rename the archive layout"], "Titano 2.0.0").ReplaceLineEndings("\n");
|
||||
Assert.Equal("# Titano 2.0.0\n\n### Breaking changes\n- **core**: rename the archive layout (abc1234)\n\n", notes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Titano.Core.Packaging;
|
||||
using Titano.Testing;
|
||||
using Titano.Tools.Commands;
|
||||
|
||||
namespace Titano.Tools.Tests;
|
||||
|
||||
/// <summary>pack-installer writes the components, shortcuts and file types setup installs (BRIEF §18).</summary>
|
||||
public sealed class PackInstallerCommandTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheServerInstallsOnlyForAllUsersAndTitanoOwnsTheProjectFileType()
|
||||
{
|
||||
var root = context.CreateTempDirectory("pack");
|
||||
var stub = Path.Combine(root, "Titano.Setup.exe");
|
||||
var bytes = new byte[4096];
|
||||
new Random(5).NextBytes(bytes);
|
||||
"MZ"u8.CopyTo(bytes);
|
||||
await File.WriteAllBytesAsync(stub, bytes);
|
||||
var app = Program(root, "app", "Titano.exe");
|
||||
var server = Program(root, "server", "Titano.Server.exe");
|
||||
var output = Path.Combine(root, "out", "Titano-Setup.exe");
|
||||
|
||||
Assert.Equal(0, await new PackInstallerCommand().RunAsync(
|
||||
["--setup", stub, "--product", "Titano", "--version", "1.2.3", "--component", "Titano=" + app, "--component", "Server=" + server, "--out", output]));
|
||||
|
||||
using var reader = PayloadReader.Open(output);
|
||||
var manifest = reader.Manifest;
|
||||
Assert.False(manifest.FindComponent("Titano")!.AllUsersOnly);
|
||||
var serverComponent = manifest.FindComponent("Server")!;
|
||||
Assert.True(serverComponent.AllUsersOnly);
|
||||
Assert.False(serverComponent.DefaultSelected);
|
||||
var association = Assert.Contains(manifest.Associations, a => a.Extension == ".titano");
|
||||
Assert.Equal("Titano.Project", association.ProgId);
|
||||
Assert.Equal("Titano.exe", association.Target);
|
||||
Assert.Equal("Titano", association.Component);
|
||||
}
|
||||
|
||||
private static string Program(string root, string folder, string name)
|
||||
{
|
||||
var dir = Directory.CreateDirectory(Path.Combine(root, folder)).FullName;
|
||||
File.WriteAllText(Path.Combine(dir, name), "MZ " + name);
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user