From 7d0c6554a463bc4938b04d3b3e24e281693de361 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sun, 15 Nov 2026 13:13:54 +0100 Subject: [PATCH] feat(setup): one setup for Chronos Desktop and Chronos Uploader Chronos Server now ships as a Docker image only, so the Windows setup no longer offers it and the separate Uploader setup goes: one setup installs, updates, adds and removes Chronos Desktop and Chronos Uploader in place. - Install log format 2 records each component's files, shortcuts, version and SHA-256; format 1 logs (1.0) are still read. A file of a removed program that changed since setup installed it is kept, never deleted. - A Chronos Server 1.0 for Windows installed by 1.0 is retained as "no longer offered": its files and service are untouched until the user unticks it or explicit /COMPONENTS leave it out; then it is removed with its service. A format 1 log keeps every file the payload does not know. - The separate 1.0 Chronos Uploader product is replaced: the Uploader is preselected, its sign-in entry moves to the new copy (Task Manager state kept), its shortcut is handed over and the old product is uninstalled. An all-users copy under a per-user install stays and is said so. - The setup window shows the dry-run plan (Changes: adds, removes, replaces) before Update; with every program unticked the primary action becomes Uninstall. /COMPONENTS=Desktop names the desktop app. - pack-installer refuses Server (--legacy packs a 1.0 one for the CI test); release.yml publishes only Chronos-Setup-.exe and the portable zip; the installer test covers add/remove in place, the Uploader replacement and the retained Server. Refs #64 Co-Authored-By: Claude Opus 5.5 --- .gitea/scripts/installer-test.ps1 | 108 ++++- .gitea/workflows/ci.yml | 14 +- .gitea/workflows/release.yml | 29 +- i18n/ar/Tooltips.ar.resx | 1 - i18n/bg/Tooltips.bg.resx | 1 - i18n/cs/Tooltips.cs.resx | 1 - i18n/da/Tooltips.da.resx | 1 - i18n/de/Tooltips.de.resx | 1 - i18n/el/Tooltips.el.resx | 1 - i18n/en/Setup.resx | 16 +- i18n/en/Tooltips.resx | 14 +- i18n/es/Tooltips.es.resx | 1 - i18n/et/Tooltips.et.resx | 1 - i18n/fi/Tooltips.fi.resx | 1 - i18n/fr/Tooltips.fr.resx | 1 - i18n/he/Tooltips.he.resx | 1 - i18n/hi/Tooltips.hi.resx | 1 - i18n/hr/Tooltips.hr.resx | 1 - i18n/hu/Tooltips.hu.resx | 1 - i18n/id/Tooltips.id.resx | 1 - i18n/it/Setup.it.resx | 16 +- i18n/it/Tooltips.it.resx | 14 +- i18n/ja/Tooltips.ja.resx | 1 - i18n/ko/Tooltips.ko.resx | 1 - i18n/lt/Tooltips.lt.resx | 1 - i18n/lv/Tooltips.lv.resx | 1 - i18n/ms/Tooltips.ms.resx | 1 - i18n/nb/Tooltips.nb.resx | 1 - i18n/nl/Tooltips.nl.resx | 1 - i18n/pl/Tooltips.pl.resx | 1 - i18n/pt-BR/Tooltips.pt-BR.resx | 1 - i18n/pt-PT/Tooltips.pt-PT.resx | 1 - i18n/ro/Tooltips.ro.resx | 1 - i18n/ru/Tooltips.ru.resx | 1 - i18n/sk/Tooltips.sk.resx | 1 - i18n/sl/Tooltips.sl.resx | 1 - i18n/sv/Tooltips.sv.resx | 1 - i18n/th/Tooltips.th.resx | 1 - i18n/tr/Tooltips.tr.resx | 1 - i18n/uk/Tooltips.uk.resx | 1 - i18n/vi/Tooltips.vi.resx | 1 - i18n/zh-Hans/Tooltips.zh-Hans.resx | 1 - i18n/zh-Hant/Tooltips.zh-Hant.resx | 1 - src/Chronos.Setup/Cli/SetupArguments.cs | 5 +- src/Chronos.Setup/Engine/InstallEngine.cs | 120 ++++-- src/Chronos.Setup/Engine/InstallLog.cs | 50 ++- src/Chronos.Setup/Engine/InstallPlan.cs | 101 ++++- src/Chronos.Setup/Engine/LegacyProducts.cs | 134 ++++++ src/Chronos.Setup/Engine/RunningPrograms.cs | 12 + src/Chronos.Setup/Engine/SilentSetup.cs | 37 +- src/Chronos.Setup/Views/ComponentOption.cs | 77 +++- src/Chronos.Setup/Views/SetupCapture.cs | 48 ++- src/Chronos.Setup/Views/SetupViewModel.cs | 228 ++++++++-- src/Chronos.Setup/Views/SetupWindow.xaml | 54 ++- src/Chronos.Setup/Views/SetupWindow.xaml.cs | 6 +- .../Commands/PackInstallerCommand.cs | 45 +- .../Setup/SingleSetupTests.cs | 398 ++++++++++++++++++ .../PackInstallerCommandTests.cs | 72 +++- 58 files changed, 1401 insertions(+), 233 deletions(-) create mode 100644 src/Chronos.Setup/Engine/LegacyProducts.cs create mode 100644 tests/Chronos.App.Tests/Setup/SingleSetupTests.cs diff --git a/.gitea/scripts/installer-test.ps1 b/.gitea/scripts/installer-test.ps1 index 126ecbcd..44b3eebf 100644 --- a/.gitea/scripts/installer-test.ps1 +++ b/.gitea/scripts/installer-test.ps1 @@ -1,10 +1,13 @@ # Installs, runs, upgrades and removes the packed installers on a clean Windows runner (BRIEF §18): silent mode, # folder with a space, Add/Remove Programs entry, shortcuts, the .chronos file type, upgrade in place (files of the -# previous version removed), user data kept, the uninstaller removing itself, and the documented exit codes. +# previous version removed), user data kept, the uninstaller removing itself, and the documented exit codes. Then the +# single setup: a program added to and removed from an installation in place (a changed file is kept), the separate +# 1.0 Uploader replaced, and a 1.0 Server for Windows retained until the switches leave it out. param( [Parameter(Mandatory)] [string] $Setup1, [Parameter(Mandatory)] [string] $Setup2, - [Parameter(Mandatory)] [string] $UploaderSetup, + [Parameter(Mandatory)] [string] $LegacyUploaderSetup, + [Parameter(Mandatory)] [string] $ServerSetup, [Parameter(Mandatory)] [string] $Version1, [Parameter(Mandatory)] [string] $Version2, [Parameter(Mandatory)] [string] $Screenshots @@ -17,7 +20,8 @@ Set-StrictMode -Version Latest # Set-Location does not move, and the programs get the screenshot folder as an argument. $Setup1 = (Resolve-Path -LiteralPath $Setup1).Path $Setup2 = (Resolve-Path -LiteralPath $Setup2).Path -$UploaderSetup = (Resolve-Path -LiteralPath $UploaderSetup).Path +$LegacyUploaderSetup = (Resolve-Path -LiteralPath $LegacyUploaderSetup).Path +$ServerSetup = (Resolve-Path -LiteralPath $ServerSetup).Path $Screenshots = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Screenshots) function Invoke-Program([string] $Exe, [string[]] $Arguments) { @@ -48,6 +52,14 @@ function Get-DefaultValue([string] $Key) { return (Get-Item -LiteralPath $Key).GetValue('') } +function Get-LinkTarget([string] $Link) { + return (New-Object -ComObject WScript.Shell).CreateShortcut($Link).TargetPath +} + +function Get-InstallLog([string] $Directory) { + return Get-Content -Raw -LiteralPath (Join-Path $Directory 'install-log.json') | ConvertFrom-Json +} + $dir = Join-Path $env:RUNNER_TEMP 'Chronos Test' $entryKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Chronos' $programs = [Environment]::GetFolderPath('Programs') @@ -63,9 +75,10 @@ Set-Content -LiteralPath $userFile -Value 'user data' Write-Host '--- Arguments' Assert-True ((Invoke-Program $Setup1 @('/BOGUS')) -eq 2) 'an unknown switch exits with 2 (invalid arguments)' Assert-True ((Invoke-Program $Setup1 @('/S', '/uninstall')) -eq 6) 'removing a product that is not installed exits with 6' +Assert-True ((Invoke-Program $Setup2 @('/S', '/COMPONENTS=Server')) -eq 2) 'a component the setup does not ship and nothing retains exits with 2' Write-Host "--- Install $Version1 into '$dir'" -Assert-True ((Invoke-Program $Setup1 @('/S', "/DIR=$dir")) -eq 0) 'silent install exits with 0' +Assert-True ((Invoke-Program $Setup1 @('/S', "/DIR=$dir", '/COMPONENTS=Desktop,Uploader')) -eq 0) 'silent install exits with 0' foreach ($file in 'Chronos.exe', 'Chronos.Uploader.exe', 'Uninstall Chronos.exe', 'install-log.json', 'legacy.txt') { Assert-True (Test-Path -LiteralPath (Join-Path $dir $file)) "$file installed" } @@ -76,6 +89,8 @@ Assert-True ($entry.QuietUninstallString -eq "`"$(Join-Path $dir 'Uninstall Chro foreach ($link in $links) { Assert-True (Test-Path -LiteralPath $link) "shortcut '$link' created" } Assert-True ((Get-DefaultValue 'HKCU:\Software\Classes\.chronos') -eq 'Chronos.Project') '.chronos opens with Chronos' Assert-True ((Get-DefaultValue 'HKCU:\Software\Classes\Chronos.Project\shell\open\command') -eq "`"$(Join-Path $dir 'Chronos.exe')`" `"%1`"") 'Chronos.Project opens the installed Chronos.exe' +$log = Get-InstallLog $dir +Assert-True ($log.formatVersion -eq 2 -and $null -ne $log.hashes.'Chronos.exe') 'the install log records each file with its SHA-256 (format 2)' Write-Host '--- Run the installed programs' foreach ($program in 'Chronos.exe', 'Chronos.Uploader.exe') { @@ -88,8 +103,9 @@ foreach ($program in 'Chronos.exe', 'Chronos.Uploader.exe') { Write-Host "--- Upgrade in place to $Version2" Assert-True ((Invoke-Program $Setup2 @('/S')) -eq 0) 'silent upgrade exits with 0' Assert-True ((Get-ItemProperty -LiteralPath $entryKey).DisplayVersion -eq $Version2) "Add/Remove Programs lists version $Version2" -Assert-True ((Get-Content -Raw -LiteralPath (Join-Path $dir 'install-log.json') | ConvertFrom-Json).version -eq $Version2) "install log records version $Version2" +Assert-True ((Get-InstallLog $dir).version -eq $Version2) "install log records version $Version2" Assert-True (Test-Path -LiteralPath (Join-Path $dir 'Chronos.exe')) 'Chronos.exe still installed' +Assert-True (Test-Path -LiteralPath (Join-Path $dir 'Chronos.Uploader.exe')) 'the Uploader installed before is kept by the upgrade' Assert-True (-not (Test-Path -LiteralPath (Join-Path $dir 'legacy.txt'))) 'a file only the previous version had is removed' foreach ($link in $links) { Assert-True (Test-Path -LiteralPath $link) "shortcut '$link' kept" } Assert-True (Test-Path -LiteralPath $userFile) 'user data kept by the upgrade' @@ -103,15 +119,79 @@ Assert-True (-not (Test-Path -LiteralPath 'HKCU:\Software\Classes\Chronos.Projec Assert-True ($null -eq (Get-DefaultValue 'HKCU:\Software\Classes\.chronos')) '.chronos no longer opens with Chronos' Assert-True (Test-Path -LiteralPath $userFile) 'user data kept by the uninstall' -Write-Host '--- Uploader installer: default folder, removal through the installer itself' -$uploaderDir = Join-Path $env:LOCALAPPDATA 'Programs\Chronos Uploader' -$uploaderKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\ChronosUploader' -Assert-True ((Invoke-Program $UploaderSetup @('/S')) -eq 0) 'silent Uploader install exits with 0' -Assert-True (Test-Path -LiteralPath (Join-Path $uploaderDir 'Chronos.Uploader.exe')) 'Uploader installed in %LOCALAPPDATA%\Programs\Chronos Uploader' -Assert-True (Test-Path -LiteralPath $uploaderKey) 'Uploader listed in Add/Remove Programs' -Assert-True ((Invoke-Program $UploaderSetup @('/uninstall', '/S')) -eq 0) 'silent Uploader removal exits with 0' -Assert-True (Wait-Removed $uploaderDir) 'Uploader folder removed' -Assert-True (-not (Test-Path -LiteralPath $uploaderKey)) 'Uploader entry removed' +$single = Join-Path $env:LOCALAPPDATA 'Programs\Chronos' +$uploaderLinks = @((Join-Path $programs 'Chronos Uploader.lnk'), (Join-Path $desktop 'Chronos Uploader.lnk')) +$desktopLinks = @((Join-Path $programs 'Chronos.lnk'), (Join-Path $desktop 'Chronos.lnk')) + +Write-Host '--- One setup: the Uploader alone, then the desktop app added, then the Uploader removed' +Assert-True ((Invoke-Program $Setup2 @('/S', '/COMPONENTS=Uploader')) -eq 0) 'silent install of the Uploader alone exits with 0' +Assert-True (Test-Path -LiteralPath (Join-Path $single 'Chronos.Uploader.exe')) 'Uploader installed in %LOCALAPPDATA%\Programs\Chronos' +Assert-True (-not (Test-Path -LiteralPath (Join-Path $single 'Chronos.exe'))) 'the desktop app is not installed' +foreach ($link in $desktopLinks) { Assert-True (-not (Test-Path -LiteralPath $link)) "no shortcut '$link'" } +Assert-True ($null -eq (Get-DefaultValue 'HKCU:\Software\Classes\.chronos')) '.chronos is not registered without the desktop app' +Assert-True ((Invoke-Program $Setup2 @('/S', '/COMPONENTS=Desktop,Uploader')) -eq 0) 'adding the desktop app in place exits with 0' +Assert-True (Test-Path -LiteralPath (Join-Path $single 'Chronos.exe')) 'the desktop app is added in place' +foreach ($link in $desktopLinks) { Assert-True (Test-Path -LiteralPath $link) "shortcut '$link' created" } +Assert-True ((Get-DefaultValue 'HKCU:\Software\Classes\.chronos') -eq 'Chronos.Project') '.chronos opens with the added desktop app' +# A changed file of a removed program is never deleted: setup checks it against the SHA-256 it recorded. +$changed = Join-Path $single 'Chronos.Uploader.exe' +[System.IO.File]::AppendAllText($changed, 'changed after setup') +Assert-True ((Invoke-Program $Setup2 @('/S', '/COMPONENTS=Desktop')) -eq 0) 'removing the Uploader in place exits with 0' +Assert-True (Test-Path -LiteralPath $changed) 'the Uploader file changed since setup installed it is kept' +Assert-True (-not ((Get-InstallLog $single).components -contains 'Uploader')) 'the install log no longer lists the Uploader' +foreach ($link in $uploaderLinks) { Assert-True (-not (Test-Path -LiteralPath $link)) "shortcut '$link' removed with the Uploader" } +Remove-Item -LiteralPath $changed +Assert-True ((Invoke-Program (Join-Path $single 'Uninstall Chronos.exe') @('/uninstall', '/S')) -eq 0) 'silent uninstall exits with 0' +Assert-True (Wait-Removed $single) 'install folder removed' + +Write-Host '--- One setup replaces the separate 1.0 Uploader' +$legacyDir = Join-Path $env:LOCALAPPDATA 'Programs\Chronos Uploader' +$legacyKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\ChronosUploader' +$runKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' +$approvedKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run' +Assert-True ((Invoke-Program $LegacyUploaderSetup @('/S')) -eq 0) 'the separate Uploader installs' +Assert-True (Test-Path -LiteralPath (Join-Path $legacyDir 'Chronos.Uploader.exe')) 'separate Uploader in %LOCALAPPDATA%\Programs\Chronos Uploader' +# Its sign-in entry, turned off in Task Manager, as the Uploader and Windows write them. +New-Item -Force -Path $runKey | Out-Null +New-Item -Force -Path $approvedKey | Out-Null +Set-ItemProperty -LiteralPath $runKey -Name 'Chronos Uploader' -Value "`"$(Join-Path $legacyDir 'Chronos.Uploader.exe')`" --tray" +Set-ItemProperty -LiteralPath $approvedKey -Name 'Chronos Uploader' -Type Binary -Value ([byte[]](3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) +Assert-True ((Invoke-Program $Setup2 @('/S')) -eq 0) 'the single setup exits with 0' +Assert-True (Test-Path -LiteralPath (Join-Path $single 'Chronos.Uploader.exe')) 'the Uploader is now in %LOCALAPPDATA%\Programs\Chronos' +Assert-True (-not (Test-Path -LiteralPath (Join-Path $single 'Chronos.exe'))) 'only the Uploader is installed: it replaces the separate one' +Assert-True (-not (Test-Path -LiteralPath $legacyKey)) 'the separate Uploader entry is gone' +Assert-True (Wait-Removed $legacyDir) 'the separate Uploader folder is gone' +Assert-True ((Get-ItemProperty -LiteralPath $runKey).'Chronos Uploader' -eq "`"$(Join-Path $single 'Chronos.Uploader.exe')`" --tray") 'the sign-in entry starts the new copy with its option' +Assert-True ($null -ne (Get-ItemProperty -LiteralPath $approvedKey -Name 'Chronos Uploader' -ErrorAction SilentlyContinue)) 'the sign-in entry stays turned off' +$link = Join-Path $programs 'Chronos Uploader.lnk' +Assert-True ((Test-Path -LiteralPath $link) -and ((Get-LinkTarget $link) -eq (Join-Path $single 'Chronos.Uploader.exe'))) 'the Start menu shortcut starts the new copy' +Assert-True (Test-Path -LiteralPath $userFile) 'user data kept by the replacement' +Assert-True ((Invoke-Program (Join-Path $single 'Uninstall Chronos.exe') @('/uninstall', '/S')) -eq 0) 'silent uninstall exits with 0' +Assert-True (Wait-Removed $single) 'install folder removed' +Assert-True ($null -eq (Get-ItemProperty -LiteralPath $runKey -Name 'Chronos Uploader' -ErrorAction SilentlyContinue)) 'the sign-in entry goes with the uninstall' + +Write-Host '--- One setup keeps a 1.0 Server for Windows until the switches leave it out' +Assert-True ((Invoke-Program $ServerSetup @('/S', '/COMPONENTS=Desktop,Server')) -eq 0) 'the 1.0 Server installs' +$serverLink = Join-Path $programs 'Chronos Server.lnk' +Assert-True (Test-Path -LiteralPath $serverLink) 'its Start menu shortcut is created' +# As Chronos 1.0 wrote it: format 1, no record of which component installed what, no hashes. +$log = Get-InstallLog $single +foreach ($name in 'componentFiles', 'componentShortcuts', 'componentVersions', 'hashes') { $log.PSObject.Properties.Remove($name) } +$log.formatVersion = 1 +[System.IO.File]::WriteAllText((Join-Path $single 'install-log.json'), ($log | ConvertTo-Json -Depth 5)) +Assert-True ((Invoke-Program $Setup2 @('/S')) -eq 0) 'the upgrade exits with 0' +Assert-True (Test-Path -LiteralPath (Join-Path $single 'Chronos.Server.exe')) 'Chronos.Server.exe is kept' +Assert-True (Test-Path -LiteralPath (Join-Path $single 'legacy.txt')) 'a file the 1.0 log lists and this setup does not ship is kept with it' +Assert-True (Test-Path -LiteralPath $serverLink) 'its shortcut is kept' +$log = Get-InstallLog $single +Assert-True (($log.components -contains 'Server') -and ($log.componentVersions.Server -eq $Version1)) 'the install log keeps the Server at its own version' +Assert-True ((Invoke-Program $Setup2 @('/S', '/COMPONENTS=Desktop')) -eq 0) 'switches that leave the Server out exit with 0' +Assert-True (-not (Test-Path -LiteralPath (Join-Path $single 'Chronos.Server.exe'))) 'Chronos.Server.exe is removed' +Assert-True (-not (Test-Path -LiteralPath (Join-Path $single 'legacy.txt'))) 'the files kept with it are removed' +Assert-True (-not (Test-Path -LiteralPath $serverLink)) 'its shortcut is removed' +Assert-True (-not ((Get-InstallLog $single).components -contains 'Server')) 'the install log no longer lists the Server' +Assert-True ((Invoke-Program (Join-Path $single 'Uninstall Chronos.exe') @('/uninstall', '/S')) -eq 0) 'silent uninstall exits with 0' +Assert-True (Wait-Removed $single) 'install folder removed' Assert-True (Test-Path -LiteralPath $userFile) 'user data kept' Write-Host 'Installer test passed.' diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 27a340f7..771dab67 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -307,20 +307,26 @@ jobs: -p:IncludeNativeLibrariesForSelfExtract=true -p:PublishReadyToRun=false -o "out/publish/$p" if ($LASTEXITCODE -ne 0) { throw "dotnet publish $p failed" } } - Remove-Item -Recurse -Force out/app-v1, out/installers -ErrorAction SilentlyContinue + Remove-Item -Recurse -Force out/app-v1, out/server-v1, out/installers -ErrorAction SilentlyContinue Copy-Item -Recurse out/publish/Chronos.App out/app-v1 Set-Content -LiteralPath out/app-v1/legacy.txt -Value 'only in version 1' + # Stands in for Chronos Server 1.0 for Windows, which the single setup no longer ships (a program it retains). + New-Item -ItemType Directory -Force -Path out/server-v1 | Out-Null + Copy-Item -LiteralPath out/publish/Chronos.Uploader/Chronos.Uploader.exe -Destination out/server-v1/Chronos.Server.exe $tools = 'src/Chronos.Tools/bin/Release/net10.0/Chronos.Tools.dll' $installers = @( @('--product', 'Chronos', '--version', '1.0.0', '--component', 'Chronos=out/app-v1', '--component', 'Uploader=out/publish/Chronos.Uploader', '--out', 'out/installers/Chronos-Setup-1.0.0.exe'), @('--product', 'Chronos', '--version', '1.0.1', '--component', 'Chronos=out/publish/Chronos.App', '--component', 'Uploader=out/publish/Chronos.Uploader', '--out', 'out/installers/Chronos-Setup-1.0.1.exe'), - @('--product', 'Chronos Uploader', '--version', '1.0.1', '--component', 'Uploader=out/publish/Chronos.Uploader', - '--out', 'out/installers/Chronos-Uploader-Setup-1.0.1.exe')) + @('--product', 'Chronos Uploader', '--version', '1.0.0', '--component', 'Uploader=out/publish/Chronos.Uploader', + '--out', 'out/installers/Chronos-Uploader-Setup-1.0.0.exe'), + @('--product', 'Chronos', '--version', '1.0.0', '--component', 'Chronos=out/app-v1', '--component', 'Server=out/server-v1', '--legacy', + '--out', 'out/installers/Chronos-Server-Setup-1.0.0.exe')) foreach ($installer in $installers) { dotnet $tools pack-installer --setup out/publish/Chronos.Setup/Chronos.Setup.exe @installer if ($LASTEXITCODE -ne 0) { throw "pack-installer $installer failed" } } ./.gitea/scripts/installer-test.ps1 -Setup1 out/installers/Chronos-Setup-1.0.0.exe -Setup2 out/installers/Chronos-Setup-1.0.1.exe ` - -UploaderSetup out/installers/Chronos-Uploader-Setup-1.0.1.exe -Version1 1.0.0 -Version2 1.0.1 -Screenshots out/installer-screenshots + -LegacyUploaderSetup out/installers/Chronos-Uploader-Setup-1.0.0.exe -ServerSetup out/installers/Chronos-Server-Setup-1.0.0.exe ` + -Version1 1.0.0 -Version2 1.0.1 -Screenshots out/installer-screenshots diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 06e2f23a..0aeb4465 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -1,7 +1,7 @@ name: Release # A tag vMAJOR.MINOR.PATCH[-PRERELEASE] builds, tests and publishes everything (BRIEF §19.3, amended 2026-10-26, R1) -# on the Linux runner: the Windows programs cross-compiled (installers, portable and server zips), SHA256SUMS and +# on the Linux runner: the Windows programs cross-compiled (the one setup and the portable zip), SHA256SUMS and # release notes on the Gitea release, then the server image in the Gitea container registry. The image's :latest # follows the highest stable release, or the highest pre-release while no stable one exists; the public releases # repository and the in-app update check follow stable releases only. @@ -111,7 +111,6 @@ jobs: common="-c Release -r win-x64 --self-contained -p:ChronosVersion=$VERSION -p:ChronosReleasesUrl=$CHRONOS_RELEASES_URL -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none -m:$BUILD_CPUS" dotnet publish src/Chronos.App/Chronos.App.csproj $common -p:PublishReadyToRun=true -o out/publish/app dotnet publish src/Chronos.Uploader/Chronos.Uploader.csproj $common -p:PublishReadyToRun=true -o out/publish/uploader - dotnet publish src/Chronos.Server/Chronos.Server.csproj $common -o out/publish/server dotnet publish src/Chronos.Setup/Chronos.Setup.csproj $common -p:PublishReadyToRun=true -o out/publish/setup dotnet "$TOOLS" pe-check out/publish/app/Chronos.exe out/publish/uploader/Chronos.Uploader.exe out/publish/setup/Chronos.Setup.exe @@ -131,15 +130,14 @@ jobs: mv "$exe.signed" "$exe" done - - name: Package installers and archives + # One setup installs, updates, adds and removes Chronos Desktop and Chronos Uploader; Chronos Server ships only as + # the Docker image. The portable zip stays beside it: portable copies update through it. + - name: Package the setup and the portable zip run: | mkdir -p out/release dotnet "$TOOLS" pack-installer --setup out/publish/setup/Chronos.Setup.exe --product Chronos \ - --component "Chronos=out/publish/app" --component "Uploader=out/publish/uploader" --component "Server=out/publish/server" \ + --component "Chronos=out/publish/app" --component "Uploader=out/publish/uploader" \ --version "$VERSION" --out "out/release/Chronos-Setup-$VERSION.exe" - dotnet "$TOOLS" pack-installer --setup out/publish/setup/Chronos.Setup.exe --product "Chronos Uploader" \ - --component "Uploader=out/publish/uploader" --version "$VERSION" --out "out/release/Chronos-Uploader-Setup-$VERSION.exe" - dotnet "$TOOLS" zip out/publish/server --out "out/release/Chronos-Server-win-x64-$VERSION.zip" # The portable build keeps its data next to Chronos.exe because of portable.txt (never inside the installer). cp -R out/publish/app out/portable printf 'Chronos portable mode: settings, index and logs are kept in the data folder next to Chronos.exe.\r\n' > out/portable/portable.txt @@ -147,6 +145,23 @@ jobs: dotnet "$TOOLS" pe-check out/release/*.exe ls -l out/release + # The release holds exactly the setup and the portable zip (SHA256SUMS follows): an Uploader-only setup or a + # Windows server package must never be published again. + - name: Check the release assets + working-directory: out/release + run: | + if ls | grep -E 'Uploader-Setup|Server-win' ; then + echo "::error title=Release assets::an Uploader-only setup or a Windows server package was produced" + exit 1 + fi + expected="$(printf '%s\n' "Chronos-Setup-$VERSION.exe" "Chronos-win-x64-portable-$VERSION.zip" | sort)" + actual="$(ls -1 | sort)" + if [ "$actual" != "$expected" ]; then + echo "::error title=Release assets::expected:"; echo "$expected"; echo "found:"; echo "$actual" + exit 1 + fi + echo "Release assets: $(echo "$actual" | tr '\n' ' ')" + - name: Sign installers if: env.HAS_SIGNING == 'true' env: diff --git a/i18n/ar/Tooltips.ar.resx b/i18n/ar/Tooltips.ar.resx index 23efc0a9..ea47809e 100644 --- a/i18n/ar/Tooltips.ar.resx +++ b/i18n/ar/Tooltips.ar.resx @@ -1005,7 +1005,6 @@ طلب إغلاق البرامج قيد التشغيل · يتولى كل برنامج عمله غير المحفوظ تثبيت هذا البرنامج تطبيق سطح المكتب لاستيراد مقاطع الفاصل الزمني وأرشفتها وتصييرها - يشغّل خادم Chronos على هذا الكمبيوتر للأجهزة الأخرى وعقد التصيير يرسل الصور من المجلدات المراقَبة إلى خادم Chronos إضافة اختصارات إلى سطح المكتب مكان تثبيت البرامج · تبقى بياناتك في مجلدها الخاص diff --git a/i18n/bg/Tooltips.bg.resx b/i18n/bg/Tooltips.bg.resx index e1c5acc3..c45d9dc2 100644 --- a/i18n/bg/Tooltips.bg.resx +++ b/i18n/bg/Tooltips.bg.resx @@ -963,7 +963,6 @@ Иска от работещите програми да се затворят · всяка от тях се грижи за незаписаната си работа Инсталира тази програма Настолното приложение за импортиране, архивиране и рендериране на таймлапси - Изпълнява Chronos Server на този компютър за други устройства и възли за рендериране Изпраща снимки от наблюдавани папки към Chronos Server Добавя преки пътища на работния плот Къде се инсталират програмите · данните ви остават в собствена папка diff --git a/i18n/cs/Tooltips.cs.resx b/i18n/cs/Tooltips.cs.resx index e764486d..98d3a7f7 100644 --- a/i18n/cs/Tooltips.cs.resx +++ b/i18n/cs/Tooltips.cs.resx @@ -984,7 +984,6 @@ Požádá spuštěné programy o zavření · každý si sám poradí s neuloženou prací Nainstaluje tento program Desktopová aplikace pro import, archivaci a renderování časosběrů - Spouští Chronos Server v tomto počítači pro další zařízení a renderovací uzly Odesílá fotografie ze sledovaných složek na Chronos Server Přidá zástupce na plochu Kam se programy nainstalují · vaše data zůstanou ve vlastní složce diff --git a/i18n/da/Tooltips.da.resx b/i18n/da/Tooltips.da.resx index 5a82c4ef..ec946b26 100644 --- a/i18n/da/Tooltips.da.resx +++ b/i18n/da/Tooltips.da.resx @@ -963,7 +963,6 @@ Bed de kørende programmer om at lukke · hvert program håndterer selv sit ikke-gemte arbejde Installer dette program Desktopappen til at importere, arkivere og rendere time-lapses - Kører Chronos Server på denne pc til andre enheder og renderingsnoder Sender fotos fra overvågede mapper til en Chronos Server Føj genveje til skrivebordet Hvor programmerne installeres · dine data bliver i deres egen mappe diff --git a/i18n/de/Tooltips.de.resx b/i18n/de/Tooltips.de.resx index 12984ee5..47be5707 100644 --- a/i18n/de/Tooltips.de.resx +++ b/i18n/de/Tooltips.de.resx @@ -963,7 +963,6 @@ Die laufenden Programme zum Schließen auffordern · jedes kümmert sich selbst um seine ungespeicherte Arbeit Dieses Programm installieren Die Desktop-App zum Importieren, Archivieren und Rendern von Zeitraffern - Führt Chronos Server auf diesem PC für andere Geräte und Render-Knoten aus Sendet Fotos aus überwachten Ordnern an einen Chronos Server Verknüpfungen auf dem Desktop hinzufügen Wo die Programme installiert werden · Ihre Daten bleiben in einem eigenen Ordner diff --git a/i18n/el/Tooltips.el.resx b/i18n/el/Tooltips.el.resx index c67ba2b2..5af1a63a 100644 --- a/i18n/el/Tooltips.el.resx +++ b/i18n/el/Tooltips.el.resx @@ -963,7 +963,6 @@ Αίτημα κλεισίματος προς τα προγράμματα που εκτελούνται · το καθένα χειρίζεται τη μη αποθηκευμένη εργασία του Εγκατάσταση αυτού του προγράμματος Η εφαρμογή υπολογιστή για εισαγωγή, αρχειοθέτηση και απόδοση time-lapse - Εκτελεί το Chronos Server σε αυτόν τον υπολογιστή για άλλες συσκευές και κόμβους απόδοσης Στέλνει φωτογραφίες από φακέλους παρακολούθησης σε ένα Chronos Server Προσθήκη συντομεύσεων στην επιφάνεια εργασίας Πού εγκαθίστανται τα προγράμματα · τα δεδομένα σας μένουν στον δικό τους φάκελο diff --git a/i18n/en/Setup.resx b/i18n/en/Setup.resx index 141ff574..22761d84 100644 --- a/i18n/en/Setup.resx +++ b/i18n/en/Setup.resx @@ -12,10 +12,19 @@ Retry Uninstall Update - Server for Windows - Chronos - Uploader + Adds {0} + {0} stays + Removes {0} + Replaces {0} {1} + Chronos Server + Chronos Desktop + Installed · {0} + No longer offered + Chronos Uploader + {0} {1} {0} is installed. + {0:N0} changed file kept + {0:N0} changed files kept {0} was removed. Windows denied access to the folder.long The command line is not valid.long @@ -26,6 +35,7 @@ This installer is damaged; download it again.long {0} did not close.long Some files could not be removed.long + Changes Components Folder Language diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 3be6f60e..d417d13a 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -862,13 +862,20 @@ Return to the options without changing anything Choose the installation folder Close setup without changing anything + Installs this program in the same folder + The separate copy in {0} is installed for all users, so it stays · remove it in Settings › Apps + Removes its files and shortcuts · a file changed since setup installed it is kept · your data is kept + Removes {0} and the Windows service that runs it · its data in %ProgramData%\Chronos Server is kept + Moves the separate copy in {0} here with its sign-in entry and shortcuts, then removes it · your data is kept Close setup Ask the running programs to close · each one handles its unsaved work Install this program - Runs Chronos Server on this PC for other devices and render nodes The desktop app to import, archive and render time-lapses + {0} · version {1} is installed · untick to remove it + Installed {0} · no longer updated: Chronos Server now ships as a Docker image · untick to remove it and its Windows service Sends photos from watched folders to a Chronos Server Add shortcuts to the desktop + Files changed since setup installed them are never deleted · they stay in the install folder Where the programs are installed · your data stays in its own folder Enter a full folder path that is not a drive root or a system folder {0} runs as a Windows service, so choose a folder inside Program Files @@ -882,14 +889,15 @@ Already installed here · uninstall it first to change folder or scope 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 Runs as a Windows service, so it installs inside Program Files only · this copy is installed elsewhere; uninstall it first to add it - Select at least one program to install + Select Chronos Desktop, Chronos Uploader or both Also delete %LOCALAPPDATA%\Chronos: database, backups, cache, settings, logs, the uploader queue and sign-in · photos in archives are kept Also delete Chronos’s database, backups, cache, settings and logs in %LOCALAPPDATA%\Chronos · the Uploader’s files and photos in archives are kept Also delete the Uploader’s queue, settings, sign-in and logs in %LOCALAPPDATA%\Chronos · Chronos’s files and photos in archives are kept Run the same step again Add the programs to the Start menu Remove programs, shortcuts and file types · your data is kept unless selected - Replace the installed version in place · your data is kept + No program is selected: remove the whole installation · the next step shows what goes + Update the installed programs in place and apply the changes listed · your data is kept Collapse navigation to icons · Ctrl+B Show navigation names · Ctrl+B Pause the job shown; it continues from its checkpoint when resumed diff --git a/i18n/es/Tooltips.es.resx b/i18n/es/Tooltips.es.resx index ffd22f90..9512da92 100644 --- a/i18n/es/Tooltips.es.resx +++ b/i18n/es/Tooltips.es.resx @@ -963,7 +963,6 @@ Pide a los programas en ejecución que se cierren · cada uno gestiona su trabajo sin guardar Instala este programa La aplicación de escritorio para importar, archivar y renderizar time-lapses - Ejecuta Chronos Server en este equipo para otros dispositivos y nodos de renderizado Envía fotos de carpetas vigiladas a un Chronos Server Añade accesos directos al escritorio Dónde se instalan los programas · tus datos se quedan en su propia carpeta diff --git a/i18n/et/Tooltips.et.resx b/i18n/et/Tooltips.et.resx index 157aa1fd..97bff992 100644 --- a/i18n/et/Tooltips.et.resx +++ b/i18n/et/Tooltips.et.resx @@ -963,7 +963,6 @@ Paluge töötavatel programmidel sulguda · igaüks käsitleb oma salvestamata tööd ise Installib selle programmi Töölauarakendus aegvõtete importimiseks, arhiveerimiseks ja renderdamiseks - Käitab selles arvutis Chronos Serverit teiste seadmete ja renderdussõlmede jaoks Saadab jälgitavatest kaustadest fotod Chronos Serverisse Lisab töölauale otseteed Programmide installikoht · teie andmed jäävad oma kausta diff --git a/i18n/fi/Tooltips.fi.resx b/i18n/fi/Tooltips.fi.resx index df3abb29..ec023907 100644 --- a/i18n/fi/Tooltips.fi.resx +++ b/i18n/fi/Tooltips.fi.resx @@ -963,7 +963,6 @@ Pyydä käynnissä olevia ohjelmia sulkeutumaan · kukin käsittelee tallentamattomat työnsä itse Asenna tämä ohjelma Työpöytäsovellus aikaviivevideoiden tuontiin, arkistointiin ja renderöintiin - Suorittaa Chronos-palvelinta tällä tietokoneella muille laitteille ja renderöintisolmuille Lähettää kuvia valvotuista kansioista Chronos-palvelimelle Lisää pikakuvakkeet työpöydälle Kansio, johon ohjelmat asennetaan · tietosi pysyvät omassa kansiossaan diff --git a/i18n/fr/Tooltips.fr.resx b/i18n/fr/Tooltips.fr.resx index 74427385..cff68fd7 100644 --- a/i18n/fr/Tooltips.fr.resx +++ b/i18n/fr/Tooltips.fr.resx @@ -963,7 +963,6 @@ Demander aux programmes en cours de se fermer · chacun gère son travail non enregistré Installer ce programme L'application de bureau pour importer, archiver et rendre des time-lapses - Exécute Chronos Server sur ce PC pour d'autres appareils et des nœuds de rendu Envoie les photos de dossiers surveillés vers un Chronos Server Ajouter des raccourcis sur le bureau Emplacement d'installation des programmes · vos données restent dans leur propre dossier diff --git a/i18n/he/Tooltips.he.resx b/i18n/he/Tooltips.he.resx index c541b769..b8ec1d0f 100644 --- a/i18n/he/Tooltips.he.resx +++ b/i18n/he/Tooltips.he.resx @@ -984,7 +984,6 @@ בקשה מהתוכניות הפועלות להיסגר · כל אחת מטפלת בעבודה שלא נשמרה בה התקנת התוכנית הזו יישום שולחן העבודה לייבוא, לאחסון בארכיון ולרינדור של טיים-לאפס - מפעיל את שרת Chronos במחשב הזה עבור מכשירים אחרים וצומתי רינדור שולח תמונות מתיקיות במעקב לשרת Chronos הוספת קיצורי דרך לשולחן העבודה המקום שבו התוכניות מותקנות · הנתונים שלך נשארים בתיקייה משלהם diff --git a/i18n/hi/Tooltips.hi.resx b/i18n/hi/Tooltips.hi.resx index b404b790..297f398c 100644 --- a/i18n/hi/Tooltips.hi.resx +++ b/i18n/hi/Tooltips.hi.resx @@ -963,7 +963,6 @@ चल रहे प्रोग्राम को बंद होने के लिए कहें · हर प्रोग्राम अपना बिना सहेजा काम खुद संभालता है यह प्रोग्राम इंस्टॉल करें टाइम-लैप्स आयात, संग्रहीत और रेंडर करने के लिए डेस्कटॉप ऐप - अन्य डिवाइस और रेंडर नोड के लिए इस PC पर Chronos Server चलाता है निगरानी वाले फ़ोल्डरों से फ़ोटो किसी Chronos Server को भेजता है डेस्कटॉप पर शॉर्टकट जोड़ें प्रोग्राम कहाँ इंस्टॉल होते हैं · आपका डेटा अपने अलग फ़ोल्डर में रहता है diff --git a/i18n/hr/Tooltips.hr.resx b/i18n/hr/Tooltips.hr.resx index bf36cb0b..2404c84b 100644 --- a/i18n/hr/Tooltips.hr.resx +++ b/i18n/hr/Tooltips.hr.resx @@ -984,7 +984,6 @@ Traži od pokrenutih programa da se zatvore · svaki sam rješava nespremljeni rad Instalira ovaj program Aplikacija za stolna računala za uvoz, arhiviranje i renderiranje time-lapse snimaka - Pokreće Chronos Server na ovom računalu za druge uređaje i čvorove za renderiranje Šalje fotografije iz nadziranih mapa na Chronos Server Dodaje prečace na radnu površinu Mjesto na koje se instaliraju programi · vaši podaci ostaju u vlastitoj mapi diff --git a/i18n/hu/Tooltips.hu.resx b/i18n/hu/Tooltips.hu.resx index ba08ac3b..26ac4769 100644 --- a/i18n/hu/Tooltips.hu.resx +++ b/i18n/hu/Tooltips.hu.resx @@ -963,7 +963,6 @@ Bezárásra kéri a futó programokat · mindegyik maga kezeli a mentetlen munkáját Ennek a programnak a telepítése Az asztali alkalmazás time-lapse felvételek importálásához, archiválásához és rendereléséhez - A Chronos Server futtatása ezen a számítógépen más eszközök és renderelő csomópontok számára Fotókat küld a figyelt mappákból egy Chronos Serverre Parancsikonokat helyez az asztalra A programok telepítési helye · az adatai a saját mappájukban maradnak diff --git a/i18n/id/Tooltips.id.resx b/i18n/id/Tooltips.id.resx index 1b1b34ba..d16336b3 100644 --- a/i18n/id/Tooltips.id.resx +++ b/i18n/id/Tooltips.id.resx @@ -963,7 +963,6 @@ Minta program yang sedang berjalan untuk menutup · masing-masing menangani pekerjaannya yang belum disimpan Instal program ini Aplikasi desktop untuk mengimpor, mengarsipkan, dan merender time-lapse - Menjalankan Chronos Server di PC ini untuk perangkat lain dan node render Mengirim foto dari folder pantauan ke Chronos Server Tambahkan pintasan ke desktop Tempat program diinstal · data Anda tetap di foldernya sendiri diff --git a/i18n/it/Setup.it.resx b/i18n/it/Setup.it.resx index 241563a5..13cc60b9 100644 --- a/i18n/it/Setup.it.resx +++ b/i18n/it/Setup.it.resx @@ -12,10 +12,19 @@ Riprova Disinstalla Aggiorna - Server per Windows - Chronos - Uploader + Aggiunge {0} + {0} resta + Rimuove {0} + Sostituisce {0} {1} + Chronos Server + Chronos Desktop + Installato · {0} + Non più offerto + Chronos Uploader + {0} {1} {0} è installato. + {0:N0} file modificato tenuto + {0:N0} file modificati tenuti {0} è stato rimosso. Windows ha negato l'accesso alla cartella.long La riga di comando non è valida.long @@ -26,6 +35,7 @@ Il programma di installazione è danneggiato; scaricalo di nuovo.long {0} non si è chiuso.long Alcuni file non sono stati rimossi.long + Modifiche Componenti Cartella Lingua diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 4a6a5ca8..6ff3601b 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -959,13 +959,20 @@ Torna alle opzioni senza modificare nulla Scegli la cartella di installazione Chiudi l'installazione senza modificare nulla + Installa questo programma nella stessa cartella + La copia separata in {0} è installata per tutti gli utenti, quindi resta · rimuovila da Impostazioni › App + Rimuove i suoi file e collegamenti · un file modificato dopo l'installazione resta · i tuoi dati restano + Rimuove {0} e il servizio Windows che lo esegue · i suoi dati in %ProgramData%\Chronos Server restano + Sposta qui la copia separata in {0} con la voce di avvio e i collegamenti, poi la rimuove · i tuoi dati restano Chiudi l'installazione Chiedi ai programmi aperti di chiudersi · ognuno gestisce il lavoro non salvato Installa questo programma L'app desktop per importare, archiviare e renderizzare time-lapse - Esegue Chronos Server su questo PC per altri dispositivi e nodi di rendering + {0} · la versione {1} è installata · togli la spunta per rimuoverlo + Installato {0} · non più aggiornato: Chronos Server ora è un'immagine Docker · togli la spunta per rimuoverlo con il suo servizio Windows Invia le foto dalle cartelle monitorate a un Chronos Server Aggiungi collegamenti al desktop + I file modificati dopo l'installazione non vengono mai eliminati · restano nella cartella di installazione Dove vengono installati i programmi · i tuoi dati restano nella loro cartella Inserisci il percorso completo di una cartella che non sia la radice di un'unità o una cartella di sistema {0} è un servizio di Windows, quindi scegli una cartella dentro Programmi @@ -979,14 +986,15 @@ Già installato qui · disinstallalo prima per cambiare cartella o ambito È un servizio di Windows, quindi si installa solo per tutti gli utenti · questa copia è installata solo per te; disinstallala prima per aggiungerlo È un servizio di Windows, quindi si installa solo dentro Programmi · questa copia è installata altrove; disinstallala prima per aggiungerlo - Seleziona almeno un programma da installare + Seleziona Chronos Desktop, Chronos Uploader o entrambi Elimina anche %LOCALAPPDATA%\Chronos: database, backup, cache, impostazioni, log, coda e accesso dell'uploader · le foto negli archivi restano Elimina anche database, backup, cache, impostazioni e log di Chronos in %LOCALAPPDATA%\Chronos · i file dell'uploader e le foto negli archivi restano Elimina anche coda, impostazioni, accesso e log dell'uploader in %LOCALAPPDATA%\Chronos · i file di Chronos e le foto negli archivi restano Esegui di nuovo lo stesso passaggio Aggiungi i programmi al menu Start Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta - Sostituisci la versione installata · i tuoi dati restano + Nessun programma selezionato: rimuovi l'intera installazione · il passo successivo mostra cosa viene rimosso + Aggiorna sul posto i programmi installati e applica le modifiche elencate · i tuoi dati restano Riduci la navigazione alle icone · Ctrl+B Mostra i nomi della navigazione · Ctrl+B Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa diff --git a/i18n/ja/Tooltips.ja.resx b/i18n/ja/Tooltips.ja.resx index c6493183..d6f454a5 100644 --- a/i18n/ja/Tooltips.ja.resx +++ b/i18n/ja/Tooltips.ja.resx @@ -963,7 +963,6 @@ 実行中のプログラムに終了を要求します · 未保存の作業は各プログラムが処理します このプログラムをインストールします。 タイムラプスをインポート、アーカイブ、レンダリングするデスクトップアプリです。 - 他のデバイスとレンダリングノードのために、この PC で Chronos Server を実行します。 監視フォルダーの写真を Chronos Server に送信します。 デスクトップにショートカットを追加します。 プログラムのインストール先です · データは専用のフォルダーに保存されます diff --git a/i18n/ko/Tooltips.ko.resx b/i18n/ko/Tooltips.ko.resx index b33be542..985631f9 100644 --- a/i18n/ko/Tooltips.ko.resx +++ b/i18n/ko/Tooltips.ko.resx @@ -963,7 +963,6 @@ 실행 중인 프로그램에 종료를 요청합니다 · 저장하지 않은 작업은 각 프로그램이 처리 이 프로그램을 설치합니다. 타임랩스를 가져오고, 보관하고, 렌더링하는 데스크톱 앱 - 다른 장치와 렌더링 노드를 위해 이 PC에서 Chronos Server를 실행합니다. 감시 폴더의 사진을 Chronos Server로 보냅니다. 바탕 화면에 바로 가기를 추가합니다. 프로그램이 설치되는 위치 · 데이터는 별도 폴더에 보관됨 diff --git a/i18n/lt/Tooltips.lt.resx b/i18n/lt/Tooltips.lt.resx index b8b82653..e51edf0d 100644 --- a/i18n/lt/Tooltips.lt.resx +++ b/i18n/lt/Tooltips.lt.resx @@ -984,7 +984,6 @@ Paprašyti veikiančių programų užsidaryti · kiekviena pati tvarko neįrašytus duomenis Įdiegti šią programą Darbalaukio programa time-lapse įrašams importuoti, archyvuoti ir atvaizduoti - Paleidžia Chronos serverį šiame kompiuteryje kitiems įrenginiams ir atvaizdavimo mazgams Siunčia nuotraukas iš stebimų aplankų į Chronos serverį Pridėti nuorodas darbalaukyje Kur įdiegiamos programos · jūsų duomenys lieka savo aplanke diff --git a/i18n/lv/Tooltips.lv.resx b/i18n/lv/Tooltips.lv.resx index ae7647c6..bf3d16b8 100644 --- a/i18n/lv/Tooltips.lv.resx +++ b/i18n/lv/Tooltips.lv.resx @@ -984,7 +984,6 @@ Lūgt aktīvajām programmām aizvērties · katra pati apstrādā savu nesaglabāto darbu Instalēt šo programmu Darbvirsmas lietotne timelapse importēšanai, arhivēšanai un renderēšanai - Palaiž Chronos Server šajā datorā citām ierīcēm un renderēšanas mezgliem Sūta fotoattēlus no uzraudzītām mapēm uz Chronos Server Pievienot saīsnes darbvirsmai Kur tiek instalētas programmas · jūsu dati paliek savā mapē diff --git a/i18n/ms/Tooltips.ms.resx b/i18n/ms/Tooltips.ms.resx index d74f80fc..06532afd 100644 --- a/i18n/ms/Tooltips.ms.resx +++ b/i18n/ms/Tooltips.ms.resx @@ -963,7 +963,6 @@ Minta program yang sedang berjalan ditutup · setiap program mengendalikan kerjanya yang belum disimpan Pasang program ini Aplikasi desktop untuk mengimport, mengarkib dan merender time-lapse - Menjalankan Chronos Server pada PC ini untuk peranti lain dan nod render Menghantar foto daripada folder pantauan ke Chronos Server Tambah pintasan pada desktop Lokasi program dipasang · data anda kekal dalam foldernya sendiri diff --git a/i18n/nb/Tooltips.nb.resx b/i18n/nb/Tooltips.nb.resx index 6b508441..133faacf 100644 --- a/i18n/nb/Tooltips.nb.resx +++ b/i18n/nb/Tooltips.nb.resx @@ -963,7 +963,6 @@ Be programmene som kjører, om å lukkes · hvert program håndterer sitt eget ulagrede arbeid Installer dette programmet Skrivebordsappen for å importere, arkivere og rendre timelapser - Kjører Chronos Server på denne PC-en for andre enheter og renderingsnoder Sender bilder fra overvåkede mapper til en Chronos Server Legg til snarveier på skrivebordet Hvor programmene installeres · dataene dine blir i sin egen mappe diff --git a/i18n/nl/Tooltips.nl.resx b/i18n/nl/Tooltips.nl.resx index 29bfbc1d..63bdeea8 100644 --- a/i18n/nl/Tooltips.nl.resx +++ b/i18n/nl/Tooltips.nl.resx @@ -963,7 +963,6 @@ Vraag de geopende programma's om af te sluiten · elk programma handelt zijn niet-opgeslagen werk zelf af Installeer dit programma De desktop-app om time-lapses te importeren, archiveren en renderen - Voert Chronos Server uit op deze pc voor andere apparaten en renderknooppunten Stuurt foto's uit bewaakte mappen naar een Chronos Server Voeg snelkoppelingen toe aan het bureaublad Waar de programma's worden geïnstalleerd · je gegevens blijven in hun eigen map diff --git a/i18n/pl/Tooltips.pl.resx b/i18n/pl/Tooltips.pl.resx index 5ddf3c3b..197c1e1b 100644 --- a/i18n/pl/Tooltips.pl.resx +++ b/i18n/pl/Tooltips.pl.resx @@ -1005,7 +1005,6 @@ Poproś uruchomione programy o zamknięcie · każdy sam zadba o niezapisaną pracę Zainstaluj ten program Aplikacja komputerowa do importowania, archiwizowania i renderowania timelapsów - Uruchamia Chronos Server na tym komputerze dla innych urządzeń i węzłów renderowania Wysyła zdjęcia z obserwowanych folderów do Chronos Server Dodaj skróty na pulpicie Miejsce instalacji programów · Twoje dane pozostają we własnym folderze diff --git a/i18n/pt-BR/Tooltips.pt-BR.resx b/i18n/pt-BR/Tooltips.pt-BR.resx index b7e0f5eb..dd674c11 100644 --- a/i18n/pt-BR/Tooltips.pt-BR.resx +++ b/i18n/pt-BR/Tooltips.pt-BR.resx @@ -963,7 +963,6 @@ Pede aos programas em execução que fechem · cada um cuida do próprio trabalho não salvo Instala este programa O aplicativo da área de trabalho para importar, arquivar e renderizar time-lapses - Executa o Chronos Server neste PC para outros dispositivos e nós de renderização Envia fotos de pastas monitoradas para um Chronos Server Adiciona atalhos à área de trabalho Onde os programas são instalados · seus dados ficam na própria pasta diff --git a/i18n/pt-PT/Tooltips.pt-PT.resx b/i18n/pt-PT/Tooltips.pt-PT.resx index 55bef06a..31be47f6 100644 --- a/i18n/pt-PT/Tooltips.pt-PT.resx +++ b/i18n/pt-PT/Tooltips.pt-PT.resx @@ -963,7 +963,6 @@ Pedir aos programas em execução que fechem · cada um trata do seu trabalho não guardado Instalar este programa A aplicação de ambiente de trabalho para importar, arquivar e renderizar time-lapses - Executa o Chronos Server neste PC para outros dispositivos e nós de renderização Envia fotografias de pastas monitorizadas para um Chronos Server Adicionar atalhos ao ambiente de trabalho Onde os programas são instalados · os seus dados ficam na respetiva pasta diff --git a/i18n/ro/Tooltips.ro.resx b/i18n/ro/Tooltips.ro.resx index 346a599b..d228579e 100644 --- a/i18n/ro/Tooltips.ro.resx +++ b/i18n/ro/Tooltips.ro.resx @@ -984,7 +984,6 @@ Cereți programelor deschise să se închidă · fiecare își gestionează lucrul nesalvat Instalați acest program Aplicația desktop pentru importul, arhivarea și randarea time-lapse-urilor - Rulează Chronos Server pe acest PC pentru alte dispozitive și noduri de randare Trimite fotografii din folderele monitorizate către un Chronos Server Adăugați comenzi rapide pe desktop Locul în care sunt instalate programele · datele dumneavoastră rămân în folderul lor diff --git a/i18n/ru/Tooltips.ru.resx b/i18n/ru/Tooltips.ru.resx index a197b502..85935a75 100644 --- a/i18n/ru/Tooltips.ru.resx +++ b/i18n/ru/Tooltips.ru.resx @@ -1005,7 +1005,6 @@ Попросить запущенные программы закрыться · каждая сама позаботится о несохранённых данных Установить эту программу Настольное приложение для импорта, архивирования и рендеринга таймлапсов - Запускает Chronos Server на этом ПК для других устройств и узлов рендеринга Отправляет фото из отслеживаемых папок на Chronos Server Добавить ярлыки на рабочий стол Куда устанавливаются программы · ваши данные хранятся в отдельной папке diff --git a/i18n/sk/Tooltips.sk.resx b/i18n/sk/Tooltips.sk.resx index 37f05af9..10f97efb 100644 --- a/i18n/sk/Tooltips.sk.resx +++ b/i18n/sk/Tooltips.sk.resx @@ -984,7 +984,6 @@ Požiada spustené programy o zatvorenie · každý sa sám postará o svoju neuloženú prácu Nainštaluje tento program Desktopová aplikácia na import, archiváciu a renderovanie časozberných videí - Spúšťa Chronos Server na tomto počítači pre ďalšie zariadenia a renderovacie uzly Odosiela fotografie zo sledovaných priečinkov na Chronos Server Pridá odkazy na pracovnú plochu Kam sa nainštalujú programy · vaše údaje zostanú vo vlastnom priečinku diff --git a/i18n/sl/Tooltips.sl.resx b/i18n/sl/Tooltips.sl.resx index 656e84af..e6eb2c75 100644 --- a/i18n/sl/Tooltips.sl.resx +++ b/i18n/sl/Tooltips.sl.resx @@ -984,7 +984,6 @@ Prosi programe, ki se izvajajo, naj se zaprejo · vsak sam poskrbi za neshranjeno delo Namesti ta program Namizni program za uvoz, arhiviranje in upodabljanje posnetkov s časovnim zamikom - Izvaja Chronos Server v tem računalniku za druge naprave in vozlišča za upodabljanje Pošilja fotografije iz nadzorovanih map na Chronos Server Dodaj bližnjice na namizje Kam se namestijo programi · vaši podatki ostanejo v svoji mapi diff --git a/i18n/sv/Tooltips.sv.resx b/i18n/sv/Tooltips.sv.resx index 10883e96..b577b215 100644 --- a/i18n/sv/Tooltips.sv.resx +++ b/i18n/sv/Tooltips.sv.resx @@ -963,7 +963,6 @@ Be de program som körs att stänga · vart och ett hanterar sitt osparade arbete Installera det här programmet Skrivbordsappen för att importera, arkivera och rendera timelapser - Kör Chronos Server på den här datorn för andra enheter och renderingsnoder Skickar foton från bevakade mappar till en Chronos Server Lägg till genvägar på skrivbordet Var programmen installeras · dina data stannar i sin egen mapp diff --git a/i18n/th/Tooltips.th.resx b/i18n/th/Tooltips.th.resx index 9da451e3..307034c2 100644 --- a/i18n/th/Tooltips.th.resx +++ b/i18n/th/Tooltips.th.resx @@ -963,7 +963,6 @@ ขอให้โปรแกรมที่กำลังทำงานปิดลง · แต่ละโปรแกรมจะจัดการงานที่ยังไม่ได้บันทึกเอง ติดตั้งโปรแกรมนี้ แอปเดสก์ท็อปสำหรับนำเข้า จัดเก็บในคลัง และเรนเดอร์ไทม์แลปส์ - เรียกใช้ Chronos Server บนพีซีเครื่องนี้สำหรับอุปกรณ์อื่นและโหนดเรนเดอร์ ส่งภาพจากโฟลเดอร์ที่เฝ้าดูไปยัง Chronos Server เพิ่มทางลัดบนเดสก์ท็อป ตำแหน่งที่ติดตั้งโปรแกรม · ข้อมูลของคุณอยู่ในโฟลเดอร์ของตัวเอง diff --git a/i18n/tr/Tooltips.tr.resx b/i18n/tr/Tooltips.tr.resx index e5e971dc..fb9d8113 100644 --- a/i18n/tr/Tooltips.tr.resx +++ b/i18n/tr/Tooltips.tr.resx @@ -963,7 +963,6 @@ Çalışan programlardan kapanmalarını ister · her biri kaydedilmemiş işini kendisi yönetir Bu programı kurar Time-lapse'leri içe aktarmak, arşivlemek ve işlemek için masaüstü uygulaması - Diğer cihazlar ve işleme düğümleri için Chronos Server'ı bu bilgisayarda çalıştırır İzlenen klasörlerdeki fotoğrafları bir Chronos Server'a gönderir Masaüstüne kısayollar ekler Programların kurulacağı yer · verileriniz kendi klasöründe kalır diff --git a/i18n/uk/Tooltips.uk.resx b/i18n/uk/Tooltips.uk.resx index 95607401..aa62273a 100644 --- a/i18n/uk/Tooltips.uk.resx +++ b/i18n/uk/Tooltips.uk.resx @@ -1005,7 +1005,6 @@ Попросити запущені програми закритися · кожна сама подбає про незбережену роботу Інсталювати цю програму Настільний застосунок для імпорту, архівування й рендерингу таймлапсів - Запускає Chronos Server на цьому ПК для інших пристроїв і вузлів рендерингу Надсилає фото з відстежуваних папок на Chronos Server Додати ярлики на робочий стіл Куди інсталюються програми · ваші дані зберігаються в окремій папці diff --git a/i18n/vi/Tooltips.vi.resx b/i18n/vi/Tooltips.vi.resx index 15aa71f6..a944d25c 100644 --- a/i18n/vi/Tooltips.vi.resx +++ b/i18n/vi/Tooltips.vi.resx @@ -963,7 +963,6 @@ Yêu cầu các chương trình đang chạy đóng lại · mỗi chương trình tự xử lý công việc chưa lưu Cài đặt chương trình này Ứng dụng máy tính để nhập, lưu trữ và kết xuất time-lapse - Chạy Chronos Server trên máy tính này cho các thiết bị khác và nút kết xuất Gửi ảnh từ các thư mục được theo dõi đến một Chronos Server Thêm lối tắt vào màn hình nền Nơi cài đặt các chương trình · dữ liệu của bạn vẫn nằm trong thư mục riêng diff --git a/i18n/zh-Hans/Tooltips.zh-Hans.resx b/i18n/zh-Hans/Tooltips.zh-Hans.resx index 0106c407..0976c2ea 100644 --- a/i18n/zh-Hans/Tooltips.zh-Hans.resx +++ b/i18n/zh-Hans/Tooltips.zh-Hans.resx @@ -963,7 +963,6 @@ 请求正在运行的程序关闭 · 各程序会自行处理未保存的工作 安装此程序 用于导入、归档和渲染延时摄影的桌面应用 - 在此电脑上运行 Chronos 服务器,供其他设备和渲染节点使用 将受监视文件夹中的照片发送到 Chronos 服务器 在桌面上添加快捷方式 程序的安装位置 · 你的数据保存在其自己的文件夹中 diff --git a/i18n/zh-Hant/Tooltips.zh-Hant.resx b/i18n/zh-Hant/Tooltips.zh-Hant.resx index 3f5d58d3..b77eaaef 100644 --- a/i18n/zh-Hant/Tooltips.zh-Hant.resx +++ b/i18n/zh-Hant/Tooltips.zh-Hant.resx @@ -963,7 +963,6 @@ 要求執行中的程式關閉 · 各程式會自行處理未儲存的工作 安裝此程式 用於匯入、典藏與算圖縮時攝影的桌面應用程式 - 在此電腦上執行 Chronos Server,供其他裝置與算圖節點使用 將監看資料夾中的相片傳送到 Chronos Server 在桌面新增捷徑 程式的安裝位置 · 您的資料會保留在其專屬資料夾中 diff --git a/src/Chronos.Setup/Cli/SetupArguments.cs b/src/Chronos.Setup/Cli/SetupArguments.cs index 7e52d53b..a8104acb 100644 --- a/src/Chronos.Setup/Cli/SetupArguments.cs +++ b/src/Chronos.Setup/Cli/SetupArguments.cs @@ -5,8 +5,9 @@ namespace Chronos.Setup.Cli; /// /// Command-line switches, case-insensitive, with / or -: -/// /S silent · /DIR=path · /COMPONENTS=Chronos,Uploader · /ALLUSERS · /NODESKTOP · -/// /NOSTARTMENU · /LAUNCH · /LANG=it · /uninstall. +/// /S silent · /DIR=path · /COMPONENTS=Desktop,Uploader (Desktop is the component +/// Chronos; the list is exact, so a retained component it leaves out, such as a 1.0 Server, is removed) · +/// /ALLUSERS · /NODESKTOP · /NOSTARTMENU · /LAUNCH · /LANG=it · /uninstall. /// Internal: /ELEVATED (relaunched for administrator rights), /CLEANUP=path /WAITPID=n (removes the /// uninstaller after the uninstall process exits), /SERVICES=stop,prune,start,remove /NAMES=a,b /DIR=path (the /// elevated step that stops, starts or deletes the named Windows services of an installation). diff --git a/src/Chronos.Setup/Engine/InstallEngine.cs b/src/Chronos.Setup/Engine/InstallEngine.cs index 3192df5c..7c5efe20 100644 --- a/src/Chronos.Setup/Engine/InstallEngine.cs +++ b/src/Chronos.Setup/Engine/InstallEngine.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.IO; using System.Reflection; +using System.Security.Cryptography; using Chronos.Core.Diagnostics; using Chronos.Core.IO; using Chronos.Core.Localization; @@ -11,15 +12,24 @@ using Chronos.Setup.Interop; namespace Chronos.Setup.Engine; /// What to install, where and with which shortcuts. -internal sealed record InstallRequest(string Directory, InstallScope Scope, IReadOnlyList Components, bool DesktopShortcuts, bool StartMenuShortcuts); +internal sealed record InstallRequest(string Directory, InstallScope Scope, IReadOnlyList Components, bool DesktopShortcuts, bool StartMenuShortcuts) +{ + /// Retained components of the previous installation to keep as they are (). + public IReadOnlyList Keep { get; init; } = []; +} + +/// The log written, and how many files of the previous version were kept because they changed since. +internal sealed record InstallResult(InstallLog Log, int KeptFiles); /// Overall progress (0–1) and the file being written. internal readonly record struct SetupProgress(double Fraction, string CurrentFile); /// /// Installs or upgrades in place from the payload: verified extraction into staging, an all-or-nothing move into -/// the folder, removal of files the previous version shipped and this one does not, then shortcuts, file types and -/// the Add/Remove Programs entry. The user data folder is never touched. +/// the folder, removal of files the previous version shipped and this one does not (or of a component the user +/// removed), then shortcuts, file types and the Add/Remove Programs entry. A removed file whose SHA-256 the log +/// recorded is deleted only while it still matches; a retained component's files, shortcuts and service stay as they +/// are. The user data folder is never touched. /// internal sealed class InstallEngine(PayloadReader payload) { @@ -41,7 +51,7 @@ internal sealed class InstallEngine(PayloadReader payload) return Manifest.Shortcuts.FirstOrDefault(s => selected.Contains(s.Component))?.Target; } - public InstallLog Install(InstallRequest request, IProgress? progress, CancellationToken cancellationToken) + public InstallResult Install(InstallRequest request, IProgress? progress, CancellationToken cancellationToken) { var directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(request.Directory)); var product = Manifest.Product; @@ -65,21 +75,13 @@ internal sealed class InstallEngine(PayloadReader payload) var shortcuts = PlanShortcuts(request, directory); var fileTypes = PlanFileTypes(request); - var log = new InstallLog - { - Product = product, - Version = Manifest.Version, - Scope = request.Scope, - Components = [.. request.Components], - Files = [.. files.Select(f => f.Path)], - Shortcuts = [.. shortcuts.Select(s => s.Link)], - Associations = [.. fileTypes.Select(a => new InstalledAssociation(a.Extension, a.ProgId))], - }; - if (previous is not null) RemoveLeftovers(directory, previous, log); + var log = NewLog(request, files, shortcuts.Select(s => (s.Component, s.Link))); + log.Associations = [.. fileTypes.Select(a => new InstalledAssociation(a.Extension, a.ProgId))]; + var kept = previous is null ? 0 : RemoveLeftovers(directory, previous, log); // Saved before registration so that an uninstall can always undo whatever follows. log.Save(directory); - foreach (var (link, target, name, _) in shortcuts.Where(s => s.Create)) 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, FileTypeName(a), PayloadPath.Resolve(directory, a.Target)); if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged(); @@ -89,7 +91,44 @@ internal sealed class InstallEngine(PayloadReader payload) SetupRegistry.WriteUninstallEntry(request.Scope, SetupPaths.ProductKey(product), new UninstallEntry( product, Manifest.Version, Publisher, directory, uninstallerPath, icon, RequiredBytes(request.Components), AboutUrl)); progress?.Report(new SetupProgress(1, string.Empty)); - Log.Info("setup", $"Installed {files.Count} files"); + Log.Info("setup", $"Installed {files.Count} files" + (kept > 0 ? $"; {kept} changed file(s) of the previous version kept" : string.Empty)); + return new InstallResult(log, kept); + } + + /// + /// The format 2 log of : the payload files and shortcuts of its components with their + /// hashes, plus the retained components it keeps, as the previous log recorded them. + /// + internal InstallLog NewLog(InstallRequest request, IReadOnlyList files, IEnumerable<(string Component, string Link)> shortcuts) + { + var links = shortcuts.ToList(); + var log = new InstallLog + { + FormatVersion = InstallLog.CurrentFormat, + Product = Manifest.Product, + Version = Manifest.Version, + Scope = request.Scope, + Components = [.. request.Components], + Files = [.. files.Select(f => f.Path)], + Shortcuts = [.. links.Select(s => s.Link)], + }; + foreach (var id in request.Components) + { + log.ComponentFiles[id] = [.. Manifest.Files.Where(f => f.Component.Equals(id, StringComparison.OrdinalIgnoreCase)).Select(f => f.Path)]; + log.ComponentShortcuts[id] = [.. links.Where(s => s.Component.Equals(id, StringComparison.OrdinalIgnoreCase)).Select(s => s.Link)]; + log.ComponentVersions[id] = Manifest.Version; + } + foreach (var f in files) log.Hashes[f.Path] = f.Sha256; + foreach (var r in request.Keep) + { + log.Components.Add(r.Id); + log.Files.AddRange(r.Files.Where(f => !log.Files.Contains(f, PayloadPath.Comparer))); + log.Shortcuts.AddRange(r.Shortcuts.Where(l => !log.Shortcuts.Contains(l, StringComparer.OrdinalIgnoreCase))); + log.ComponentFiles[r.Id] = [.. r.Files]; + log.ComponentShortcuts[r.Id] = [.. r.Shortcuts]; + log.ComponentVersions[r.Id] = r.Version; + foreach (var (path, hash) in r.Hashes) log.Hashes.TryAdd(path, hash); + } return log; } @@ -116,19 +155,19 @@ internal sealed class InstallEngine(PayloadReader payload) /// neither install retargets or removes the other's, and when the other product is uninstalled it hands the /// shortcut over to this copy (). /// - private List<(string Link, string Target, string Name, bool Create)> PlanShortcuts(InstallRequest request, string directory) + private List<(string Component, string Link, string Target, string Name, bool Create)> PlanShortcuts(InstallRequest request, string directory) { var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase); - var result = new List<(string, string, string, bool)>(); + var result = new List<(string, 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) 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); + if (s.StartMenu && request.StartMenuShortcuts) Add(s.Component, Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name); + if (s.Desktop && request.DesktopShortcuts) Add(s.Component, Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name); } return result; - void Add(string link, string target, string name) + void Add(string component, string link, string target, string name) { var create = true; if (ShellLink.TargetOf(link) is { } current && !CommandProgram.IsPathInside(current, directory) && File.Exists(current)) @@ -136,7 +175,7 @@ internal sealed class InstallEngine(PayloadReader payload) Log.Info("setup", $"Shortcut '{link}' starts '{current}'; left as it is"); create = false; } - result.Add((link, target, name, create)); + result.Add((component, link, target, name, create)); } } @@ -167,10 +206,15 @@ internal sealed class InstallEngine(PayloadReader payload) /// /// Removes what the previous version installed and this one no longer does (files, shortcuts, file types). The /// sign-in entries of the removed programs move to the program that replaces them, or go with a dropped component. + /// A file whose SHA-256 the previous log recorded and that changed since is kept (and left out of the new log); + /// returns how many were. /// - private void RemoveLeftovers(string directory, InstallLog previous, InstallLog current) + private int RemoveLeftovers(string directory, InstallLog previous, InstallLog current) { var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList(); + var changed = Changed(directory, previous, obsolete); + foreach (var path in changed) Log.Info("setup", $"'{path}' changed since setup installed it; kept"); + obsolete = [.. obsolete.Except(changed, PayloadPath.Comparer)]; if (obsolete.Count > 0) { InstalledFiles.Remove(directory, obsolete); @@ -196,6 +240,34 @@ internal sealed class InstallEngine(PayloadReader payload) { if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId); } + return changed.Count; + } + + /// + /// The files among that exist and whose SHA-256 differs from the one + /// recorded: removing them would delete what someone changed since. A file the log has no hash for (a format 1 log) + /// is never among them; one that cannot be read is, as it cannot be shown to be unchanged. + /// + internal static IReadOnlyList Changed(string directory, InstallLog log, IEnumerable paths) + { + var changed = new List(); + foreach (var path in paths) + { + if (log.HashOf(path) is not { } expected) continue; + var full = PayloadPath.Resolve(directory, path); + try + { + if (!File.Exists(full)) continue; + using var stream = new FileStream(full, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1 << 16); + if (!Convert.ToHexStringLower(SHA256.HashData(stream)).Equals(expected, StringComparison.OrdinalIgnoreCase)) changed.Add(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"'{full}' not read", ex); + changed.Add(path); + } + } + return changed; } private static void EnsureFreeSpace(string directory, long required) diff --git a/src/Chronos.Setup/Engine/InstallLog.cs b/src/Chronos.Setup/Engine/InstallLog.cs index c9f7022c..4f286d7d 100644 --- a/src/Chronos.Setup/Engine/InstallLog.cs +++ b/src/Chronos.Setup/Engine/InstallLog.cs @@ -2,18 +2,25 @@ using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using Chronos.Core.IO; +using Chronos.Core.Packaging; namespace Chronos.Setup.Engine; /// /// Record of one installation, kept as install-log.json in the install folder. The uninstaller carries no /// payload, so everything it removes comes from here: payload files, shortcuts and file types. User data is never -/// listed. +/// listed. Format 2 adds which component installed which file and shortcut, the version of each component and the +/// SHA-256 of each file, so that one component can be removed alone and a file changed since is never deleted; a +/// format 1 log (Chronos 1.0) is still read, and a 1.0 setup reads a format 2 log as format 1 (it ignores the rest). /// internal sealed class InstallLog { public const string FileName = "install-log.json"; + /// The format this setup writes. + public const int CurrentFormat = 2; + + /// 1 unless set: a log that does not say otherwise records no components' files (setup writes ). public int FormatVersion { get; set; } = 1; public required string Product { get; set; } public required string Version { get; set; } @@ -30,12 +37,44 @@ internal sealed class InstallLog public List Shortcuts { get; set; } = []; public List Associations { get; set; } = []; + /// Format 2: the payload paths of each component (a path two components ship is listed under both). + public Dictionary> ComponentFiles { get; set; } = []; + + /// Format 2: the shortcuts of each component. + public Dictionary> ComponentShortcuts { get; set; } = []; + + /// Format 2: the version of each component, which differs from for one this setup no longer ships. + public Dictionary ComponentVersions { get; set; } = []; + + /// Format 2: lower-case hex SHA-256 of each file as setup wrote it. + public Dictionary Hashes { get; set; } = []; + [JsonIgnore] public string ProductKey => SetupPaths.ProductKey(Product); [JsonIgnore] public string UninstallerName => SetupPaths.UninstallerName(Product); + /// True when the log records each component's files (format 2). + [JsonIgnore] + public bool HasComponentFiles => FormatVersion >= 2; + + /// The files installed; null for a format 1 log, which does not record them. + public IReadOnlyList? FilesOf(string component) => + !HasComponentFiles ? null : Find(ComponentFiles, component) ?? []; + + /// The shortcuts installed; null for a format 1 log. + public IReadOnlyList? ShortcutsOf(string component) => + !HasComponentFiles ? null : Find(ComponentShortcuts, component) ?? []; + + /// The version of : its own when recorded, else the installation's. + public string VersionOf(string component) => + ComponentVersions.FirstOrDefault(p => p.Key.Equals(component, StringComparison.OrdinalIgnoreCase)).Value is { Length: > 0 } version ? version : Version; + + /// The SHA-256 recorded for ; null when the log has none. + public string? HashOf(string path) => + Hashes.TryGetValue(path, out var hash) ? hash : Hashes.FirstOrDefault(p => PayloadPath.Comparer.Equals(p.Key, path)).Value; + /// The log in , or null when there is none or it is unreadable. public static InstallLog? TryLoad(string directory) { @@ -52,7 +91,14 @@ internal sealed class InstallLog } public void Save(string directory) => - AtomicFile.WriteAllBytes(Path.Combine(directory, FileName), JsonSerializer.SerializeToUtf8Bytes(this, InstallLogJson.Default.InstallLog)); + AtomicFile.WriteAllBytes(Path.Combine(directory, FileName), ToJson()); + + public byte[] ToJson() => JsonSerializer.SerializeToUtf8Bytes(this, InstallLogJson.Default.InstallLog); + + public static InstallLog? FromJson(ReadOnlySpan json) => JsonSerializer.Deserialize(json, InstallLogJson.Default.InstallLog); + + private static List? Find(Dictionary> map, string component) => + map.FirstOrDefault(p => p.Key.Equals(component, StringComparison.OrdinalIgnoreCase)).Value; } /// A file type registered by setup. diff --git a/src/Chronos.Setup/Engine/InstallPlan.cs b/src/Chronos.Setup/Engine/InstallPlan.cs index 28dc34d8..071422d3 100644 --- a/src/Chronos.Setup/Engine/InstallPlan.cs +++ b/src/Chronos.Setup/Engine/InstallPlan.cs @@ -7,53 +7,105 @@ namespace Chronos.Setup.Engine; /// /// 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. A -/// component that installs for all users only (, 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. +/// component of the previous installation that this payload no longer ships is retained (, kept +/// unless the switches leave it out or the user unticks it); a separate 1.0 Uploader product () +/// fixes the scope of a new installation and preselects the Uploader, which replaces it. A component that installs +/// for all users only () makes a new installation an all-users one, in a +/// folder inside Program Files; an installation upgraded in place elsewhere cannot take it. /// internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList Components, ExistingInstall? Existing) { + /// The log of the installation upgraded in place. + public InstallLog? Previous { get; init; } + + /// The components of the previous installation this payload no longer ships. + public IReadOnlyList Retained { get; init; } = []; + + /// The retained components to keep: all of them, unless explicit switches leave some out. + public IReadOnlyList Kept { get; init; } = []; + + /// The separate 1.0 Uploader product installed beside, which the Uploader of this payload replaces. + public LegacyInstall? Legacy { get; init; } + public static InstallPlan Resolve(PayloadManifest manifest, SetupArguments arguments) { var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product)); - var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); + var previous = existing is null ? null : InstallLog.TryLoad(existing.Directory); + return Resolve(manifest, arguments, existing, previous, LegacyProducts.FindUploader(manifest)); + } + + /// from what was found on this PC (no registry access). + public static InstallPlan Resolve(PayloadManifest manifest, SetupArguments arguments, ExistingInstall? existing, InstallLog? previous, LegacyInstall? legacy) + { + // Without an installation of its own, a legacy Uploader fixes the scope: its removal needs the same account. + var scope = existing?.Scope ?? legacy?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); + var retained = existing is null ? [] : LegacyProducts.Retained(manifest, previous); IReadOnlyList components; + IReadOnlyList kept; if (arguments.Components is { } requested) { - var unknown = requested.FirstOrDefault(id => manifest.FindComponent(id) is null); + // Switches are exact: a retained component they leave out is removed. + var ids = requested.Select(LegacyProducts.Canonical).ToList(); + var unknown = ids.FirstOrDefault(id => manifest.FindComponent(id) is null && !retained.Any(r => r.Id.Equals(id, StringComparison.OrdinalIgnoreCase))); if (unknown is not null) throw new SetupException(SetupExitCode.InvalidArguments, $"Unknown component '{unknown}'."); - components = [.. requested.Select(id => manifest.FindComponent(id)!.Id).Distinct()]; + components = [.. ids.Select(manifest.FindComponent).OfType().Select(c => c.Id).Distinct(StringComparer.OrdinalIgnoreCase)]; + kept = [.. retained.Where(r => ids.Contains(r.Id, StringComparer.OrdinalIgnoreCase))]; } else { - var previous = existing is null ? null : InstallLog.TryLoad(existing.Directory)?.Components; - var kept = previous?.Select(manifest.FindComponent).OfType().Select(c => c.Id).ToList(); - components = kept is { Count: > 0 } ? kept : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)]; + var suggested = previous?.Components.Select(manifest.FindComponent).OfType().Select(c => c.Id).ToList() ?? []; + // The legacy Uploader is replaced by this payload's. + if (legacy is not null && manifest.FindComponent(LegacyProducts.UploaderComponent) is { } uploader && !suggested.Contains(uploader.Id, StringComparer.OrdinalIgnoreCase)) + suggested.Add(uploader.Id); + components = suggested.Count > 0 + ? [.. suggested.Distinct(StringComparer.OrdinalIgnoreCase)] + : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)]; + kept = retained; } 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)) + var fixedLocation = existing is not null || legacy is not null; + if (allUsersOnly.Count > 0 && !fixedLocation) scope = InstallScope.AllUsers; + var directory = existing?.Directory ?? (legacy is null ? arguments.Directory : null) ?? SetupPaths.DefaultDirectory(scope, manifest.Product); + if (allUsersOnly.Count > 0 && fixedLocation && !IsServiceSafe(scope, 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}."); + $"{string.Join(", ", allUsersOnly)} installs for all users inside Program Files only; {manifest.Product} is installed in '{directory}' for {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); + return new InstallPlan(scope, directory, components, existing) { Previous = previous, Retained = retained, Kept = kept, Legacy = legacy }; + } + + /// False while the folder and scope are fixed: an installation is upgraded in place, or a legacy Uploader sets the scope. + public bool CanChangeLocation => Existing is null && Legacy is null; + + /// + /// False for a component that installs for all users only when the folder and scope are fixed and are not an + /// all-users folder inside Program Files. + /// + public bool CanInstall(PayloadComponent component) => + !component.AllUsersOnly || CanChangeLocation || (Existing is { } existing ? IsServiceSafe(existing.Scope, existing.Directory) : IsServiceSafe(Scope, Directory)); + + /// The retained components that are not kept: removed, with their service. + public IReadOnlyList Removed(IEnumerable kept) + { + var ids = new HashSet(kept.Select(k => k.Id), StringComparer.OrdinalIgnoreCase); + return [.. Retained.Where(r => !ids.Contains(r.Id))]; } /// - /// 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. + /// The legacy Uploader the installation of replaces: only when the Uploader is among them + /// and allows it; null otherwise. /// - public bool CanInstall(PayloadComponent component) => !component.AllUsersOnly || Existing is null || IsServiceSafe(Existing.Scope, Existing.Directory); + public LegacyInstall? LegacyToReplace(IEnumerable components, InstallScope scope, string directory) => + Legacy is { } legacy && components.Contains(LegacyProducts.UploaderComponent, StringComparer.OrdinalIgnoreCase) && LegacyProducts.CanMerge(legacy, scope, directory) + ? legacy + : null; /// /// True when may be installed in for @@ -67,7 +119,14 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn /// True for an all-users installation inside Program Files: where a program a LocalSystem service starts may live. public static bool IsServiceSafe(InstallScope scope, string directory) => scope == InstallScope.AllUsers && SetupPaths.IsInsideProgramFiles(directory); - /// Executables to look for among running processes: the new payload's and the previous install's. - public static IEnumerable Programs(PayloadManifest manifest, string directory) => - manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []); + /// + /// Executables to look for among running processes, and whose services setup stops: the new payload's and the + /// previous install's, except the files of the retained components it keeps (their service keeps running). + /// + public static IEnumerable Programs(PayloadManifest manifest, string directory, IEnumerable kept) + { + var keep = new HashSet(kept.SelectMany(k => k.Files), PayloadPath.Comparer); + var payload = manifest.Files.Select(f => f.Path).ToList(); + return payload.Concat((InstallLog.TryLoad(directory)?.Files ?? []).Where(f => !keep.Contains(f) || payload.Contains(f, PayloadPath.Comparer))); + } } diff --git a/src/Chronos.Setup/Engine/LegacyProducts.cs b/src/Chronos.Setup/Engine/LegacyProducts.cs new file mode 100644 index 00000000..105fe9e9 --- /dev/null +++ b/src/Chronos.Setup/Engine/LegacyProducts.cs @@ -0,0 +1,134 @@ +using System.IO; +using Chronos.Core.Diagnostics; +using Chronos.Core.Packaging; +using Chronos.Setup.Cli; + +namespace Chronos.Setup.Engine; + +/// +/// A component the previous installation has and this payload no longer ships (Chronos Server 1.0 for Windows): it is +/// kept as it is, its service untouched, until the user unticks it, and it is never updated again. +/// +/// Its payload paths. For a format 1 log, which does not say which component installed what, every file +/// the log lists and this payload does not ship: nothing is removed by guess. +/// Its shortcuts (for a format 1 log, those whose name no shortcut of this payload has). +/// The SHA-256 the log recorded for its files (none for a format 1 log). +internal sealed record RetainedComponent(string Id, string Version, IReadOnlyList Files, IReadOnlyList Shortcuts, + IReadOnlyDictionary Hashes); + +/// The separate Chronos Uploader product of 1.0 (its own folder and Add/Remove Programs entry), found beside this setup's. +internal sealed record LegacyInstall(InstalledProduct Product, InstallScope Scope) +{ + public string Directory => Product.Directory; + public string Version => Product.Log.Version; +} + +/// +/// What became of the 1.0 products in the single setup: the Uploader's own product is merged into Chronos, and a +/// component this setup no longer ships (the Windows Server) is retained. +/// +internal static class LegacyProducts +{ + /// The product the single setup installs. + public const string Product = "Chronos"; + + /// The 1.0 Uploader-only product (key ChronosUploader, folder …\Programs\Chronos Uploader). + public const string UploaderProduct = "Chronos Uploader"; + + public const string DesktopComponent = "Chronos"; + public const string UploaderComponent = "Uploader"; + + /// /COMPONENTS=Desktop names the . + public const string DesktopAlias = "Desktop"; + + /// The component id stands for: is the desktop app. + public static string Canonical(string id) => id.Equals(DesktopAlias, StringComparison.OrdinalIgnoreCase) ? DesktopComponent : id; + + /// The components of that no longer ships, with their files. + public static IReadOnlyList Retained(PayloadManifest manifest, InstallLog? previous) + { + if (previous is null) return []; + var ids = previous.Components.Where(id => manifest.FindComponent(id) is null).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + if (ids.Count == 0) return []; + var result = new List(); + if (previous.HasComponentFiles) + { + foreach (var id in ids) + { + var files = previous.FilesOf(id)!.Where(PayloadPath.IsValid).ToList(); + var hashes = new Dictionary(PayloadPath.Comparer); + foreach (var file in files) + { + if (previous.HashOf(file) is { } hash) hashes[file] = hash; + } + result.Add(new RetainedComponent(id, previous.VersionOf(id), files, [.. previous.ShortcutsOf(id)!], hashes)); + } + return result; + } + + // Format 1: the files and shortcuts this payload does not know go with the retained component, so none is deleted + // by guess. The only cost: a file the previous desktop app had and this one dropped stays until it is unticked. + var payloadFiles = new HashSet(manifest.Files.Select(f => f.Path), PayloadPath.Comparer); + var payloadShortcuts = new HashSet(manifest.Shortcuts.Select(s => s.Name), StringComparer.OrdinalIgnoreCase); + var previousOnly = previous.Files.Where(PayloadPath.IsValid).Where(f => !payloadFiles.Contains(f)).ToList(); + var links = previous.Shortcuts.Where(l => !payloadShortcuts.Contains(Path.GetFileNameWithoutExtension(l))).ToList(); + var empty = new Dictionary(); + result.Add(new RetainedComponent(ids[0], previous.Version, previousOnly, links, empty)); + result.AddRange(ids.Skip(1).Select(id => new RetainedComponent(id, previous.Version, [], [], empty))); + return result; + } + + /// The 1.0 Uploader product beside the Chronos one this payload installs; null when there is none or this is another product. + public static LegacyInstall? FindUploader(PayloadManifest manifest) + { + if (!manifest.Product.Equals(Product, StringComparison.Ordinal) || manifest.FindComponent(UploaderComponent) is null) return null; + if (SetupRegistry.FindInstall(SetupPaths.ProductKey(UploaderProduct)) is not { } found) return null; + if (InstallLog.TryLoad(found.Directory) is not { } log) return null; + return new LegacyInstall(new InstalledProduct(Path.GetFullPath(found.Directory), log), found.Scope); + } + + /// + /// True when the legacy copy can be replaced by an installation for in + /// : not an all-users copy under a per-user installation (that removal would need its own + /// administrator approval: the user removes it in Settings › Apps), and not the same folder. + /// + public static bool CanMerge(LegacyInstall legacy, InstallScope scope, string directory) => + (legacy.Scope == InstallScope.CurrentUser || scope == InstallScope.AllUsers) + && !SetupPaths.IsSameOrInside(directory, legacy.Directory) && !SetupPaths.IsSameOrInside(legacy.Directory, directory); + + /// + /// After the new installation in works: the legacy Uploader's sign-in entry starts the + /// new copy (its Task Manager state kept), then the legacy product is removed from its log (files, entry, uninstaller, + /// folder; its shortcut is handed over to the new copy). User data is shared and never touched. + /// + public static void Merge(LegacyInstall legacy, PayloadManifest manifest, string directory) + { + Log.Info("setup", $"Replacing {legacy.Product.Log.Product} {legacy.Version} in '{legacy.Directory}'"); + try + { + SetupRegistry.MoveStartupEntries(CommandProgram.FullPaths(legacy.Directory, legacy.Product.Log.Files), StartupPrograms(manifest, directory)); + } + catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) + { + Log.Warning("setup", "Sign-in entry of the legacy Uploader not moved", ex); + } + UninstallEngine.Uninstall(legacy.Product, userData: null, progress: null); + } + + /// without failing the installation that already works: a failure is logged. + public static void TryMerge(LegacyInstall legacy, PayloadManifest manifest, string directory) + { + try + { + Merge(legacy, manifest, directory); + } + catch (Exception ex) when (ex is SetupException or IOException or UnauthorizedAccessException or System.Security.SecurityException) + { + Log.Warning("setup", $"The separate {legacy.Product.Log.Product} in '{legacy.Directory}' was not removed", ex); + } + } + + /// The programs the legacy Uploader's sign-in entry moves to: the new copy's, when it is installed. + public static IReadOnlyDictionary StartupPrograms(PayloadManifest manifest, string directory) => + InstallEngine.StartupPrograms(manifest, directory, [UploaderComponent]).Where(p => File.Exists(p.Value)).ToDictionary(StringComparer.Ordinal); +} diff --git a/src/Chronos.Setup/Engine/RunningPrograms.cs b/src/Chronos.Setup/Engine/RunningPrograms.cs index 1df4b3f3..2f668710 100644 --- a/src/Chronos.Setup/Engine/RunningPrograms.cs +++ b/src/Chronos.Setup/Engine/RunningPrograms.cs @@ -11,6 +11,18 @@ namespace Chronos.Setup.Engine; /// internal static class RunningPrograms { + /// + /// Processes of (payload paths) started from inside , + /// except the programs of , which ignore WM_CLOSE; plus the programs of + /// (the legacy Uploader the installation replaces). + /// + public static IReadOnlyList Find(string directory, IEnumerable executables, IReadOnlyCollection? services, InstalledProduct? also) + { + var found = Find(directory, executables, services).ToList(); + if (also is not null) found.AddRange(Find(also.Directory, also.Log.Files, services)); + return found; + } + /// /// Processes of (payload paths) started from inside , /// except the programs of , which ignore WM_CLOSE. diff --git a/src/Chronos.Setup/Engine/SilentSetup.cs b/src/Chronos.Setup/Engine/SilentSetup.cs index 5fef8e0f..f92f9901 100644 --- a/src/Chronos.Setup/Engine/SilentSetup.cs +++ b/src/Chronos.Setup/Engine/SilentSetup.cs @@ -9,8 +9,10 @@ namespace Chronos.Setup.Engine; /// /S: 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 /// 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. +/// upgrade, or when it fails) or deleted with the uninstall or with a retained component the switches leave out, +/// which asks for administrator approval when setup runs without it. A separate 1.0 Uploader is replaced once the +/// installation works (a failure to remove it is logged and does not fail the run). Silent uninstall never removes +/// user data. /// internal static class SilentSetup { @@ -54,24 +56,37 @@ internal static class SilentSetup if (plan.Components.Count == 0) return SetupExitCode.InvalidArguments; var launch = arguments.Launch && engine.LaunchTarget(plan.Components) is { } target ? PayloadPath.Resolve(plan.Directory, target) : null; + var legacy = plan.LegacyToReplace(plan.Components, plan.Scope, plan.Directory); if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated) - return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false); + { + if (arguments.Elevated) return SetupExitCode.ElevationDeclined; + // The components as this account resolved them: the approving account may not see a per-user legacy Uploader. + var exact = arguments with { Components = [.. plan.Components, .. plan.Kept.Select(k => k.Id)] }; + var elevated = await Elevation.RunElevatedAsync(exact, launch).ConfigureAwait(false); + // A per-user legacy Uploader belongs to this account, not to the one that approved the elevation. + if (elevated == SetupExitCode.Success && legacy is { Scope: InstallScope.CurrentUser }) LegacyProducts.TryMerge(legacy, engine.Manifest, plan.Directory); + return elevated; + } // 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 programs = InstallPlan.Programs(engine.Manifest, plan.Directory, plan.Kept).ToList(); var owned = CommandProgram.FullPaths(plan.Directory, programs); - var closed = await CloseProgramsAsync(plan.Directory, programs, owned).ConfigureAwait(false); + var closed = await CloseProgramsAsync(plan.Directory, programs, owned, legacy?.Product).ConfigureAwait(false); if (closed.Code != SetupExitCode.Success) return closed.Code; - var stopped = closed.Services; + // The services of a retained component left out (the 1.0 Server) are deleted; the others are stopped for the upgrade. + var removed = plan.Removed(plan.Kept); + var removing = InstalledServices.Find(CommandProgram.FullPaths(plan.Directory, removed.SelectMany(r => r.Files))); + var stopped = closed.Services.ExceptBy(removing.Select(s => s.Name), s => s.Name, StringComparer.OrdinalIgnoreCase).ToList(); try { var code = await InstalledServices.ApplyAsync(plan.Directory, stopped, ServiceActions.Stop, IntPtr.Zero).ConfigureAwait(false); + if (code == SetupExitCode.Success) code = await InstalledServices.ApplyAsync(plan.Directory, removing, ServiceActions.Remove, 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); + var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu) { Keep = plan.Kept }; engine.Install(request, null, CancellationToken.None); } catch @@ -82,6 +97,9 @@ internal static class SilentSetup // 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); + // Running setup is the explicit action: the legacy Uploader goes once this installation works. A per-user one is + // left to the unelevated parent when this is its elevated copy. + if (legacy is not null && !(arguments.Elevated && legacy.Scope == InstallScope.CurrentUser)) LegacyProducts.TryMerge(legacy, engine.Manifest, plan.Directory); if (services != SetupExitCode.Success) return services; if (launch is null) return SetupExitCode.Success; @@ -130,10 +148,11 @@ internal static class SilentSetup /// , which the caller stops or deletes: a program that does not close stops setup before /// any service is touched. /// - private static async Task<(SetupExitCode Code, IReadOnlyList Services)> CloseProgramsAsync(string directory, IEnumerable programs, IReadOnlySet owned) + private static async Task<(SetupExitCode Code, IReadOnlyList Services)> CloseProgramsAsync(string directory, IEnumerable programs, + IReadOnlySet owned, InstalledProduct? alsoClose = null) { var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList(); - var running = RunningPrograms.Find(directory, programs, services); + var running = RunningPrograms.Find(directory, programs, services, alsoClose); try { if (running.Count == 0) return (SetupExitCode.Success, services); diff --git a/src/Chronos.Setup/Views/ComponentOption.cs b/src/Chronos.Setup/Views/ComponentOption.cs index 38f1456c..2f36e7d6 100644 --- a/src/Chronos.Setup/Views/ComponentOption.cs +++ b/src/Chronos.Setup/Views/ComponentOption.cs @@ -1,43 +1,90 @@ using Chronos.Core.Localization; using Chronos.Core.Packaging; +using Chronos.Setup.Engine; using Chronos.Ui.Mvvm; namespace Chronos.Setup.Views; /// -/// 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. +/// A component checkbox: localized name and tooltip (falling back to the manifest), its state (size, "Installed · +/// size", or "No longer offered" for a retained one) and selection. Unticking an installed component removes it; +/// unticking a retained one (Chronos Server 1.0 for Windows) removes it with its service. 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. /// -/// The tooltip key saying why it cannot be added here; null when it can. -internal sealed class ComponentOption(PayloadComponent component, bool selected, string? unavailableToolTip, Action changed) : LocalizedViewModel +internal sealed class ComponentOption : LocalizedViewModel { - private bool _selected = selected; + private readonly PayloadComponent? _component; + private readonly string? _unavailableToolTip; + private readonly Action _changed; + private bool _selected; - public string Id => component.Id; + /// The version installed now; null when it is not installed. + /// The tooltip key saying why it cannot be added here; null when it can. + public ComponentOption(PayloadComponent component, bool selected, string? installedVersion, string? unavailableToolTip, Action changed) + { + _component = component; + _selected = selected; + InstalledVersion = installedVersion; + _unavailableToolTip = unavailableToolTip; + _changed = changed; + Id = component.Id; + } - public string Name => Loc.Get("Setup.Component." + component.Id, Loc.Culture) ?? component.DisplayName; + /// A retained component: ticked keeps it as it is, unticked removes it with its service. + public ComponentOption(RetainedComponent retained, bool selected, Action changed) + { + Retained = retained; + _selected = selected; + InstalledVersion = retained.Version; + _changed = changed; + Id = retained.Id; + } - /// Installs for all users only (the Server runs as a LocalSystem service from Program Files). - public bool AllUsersOnly => component.AllUsersOnly; + public string Id { get; } + + /// The retained component this row keeps or removes; null for a component of the payload. + public RetainedComponent? Retained { get; } + + public bool IsRetained => Retained is not null; + + /// The version installed now; null when it is not installed. + public string? InstalledVersion { get; } + + public bool IsInstalled => InstalledVersion is not null; + + /// The component's name; a retained one carries its version ("Chronos Server 1.0.0"). + public string Name => Retained is { } retained ? Loc.L("Setup.Component.Versioned", BaseName, retained.Version) : BaseName; + + private string BaseName => Loc.Get("Setup.Component." + Id, Loc.Culture) ?? _component?.DisplayName ?? Id; + + /// Installs for all users only (a program a LocalSystem service runs from Program Files). + public bool AllUsersOnly => _component?.AllUsersOnly == true; /// False when it cannot be installed here: it needs all users in Program Files and this installation is not. - public bool IsAvailable => unavailableToolTip is null; + public bool IsAvailable => _unavailableToolTip is null; - public string ToolTip => unavailableToolTip is { } reason ? Loc.L(reason) + public string ToolTip => _unavailableToolTip is { } reason ? Loc.L(reason) + : Retained is { } retained ? Loc.L("Tooltips.Setup.Component.Retained", retained.Version) : AllUsersOnly ? Loc.L("Tooltips.Setup.AllUsersOnly", Description) + : InstalledVersion is { } version ? Loc.L("Tooltips.Setup.Component.InstalledVersion", Description, version) : Description; - private string Description => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component"); + private string Description => Loc.Get("Tooltips.Setup.Component." + Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component"); - public string SizeText => ByteSize.Format(component.EstimatedSize); + /// The right-hand text of the row: the size, "Installed · size", or "No longer offered". + public string StateText => IsRetained ? Loc.L("Setup.Component.NoLongerOffered") + : IsInstalled ? Loc.L("Setup.Component.Installed", SizeText) + : SizeText; + + public string SizeText => ByteSize.Format(_component?.EstimatedSize ?? 0); public bool IsSelected { get => _selected; set { - if (Set(ref _selected, value)) changed(); + if (Set(ref _selected, value)) _changed(); } } } diff --git a/src/Chronos.Setup/Views/SetupCapture.cs b/src/Chronos.Setup/Views/SetupCapture.cs index 7530c2d2..51e90155 100644 --- a/src/Chronos.Setup/Views/SetupCapture.cs +++ b/src/Chronos.Setup/Views/SetupCapture.cs @@ -13,8 +13,9 @@ namespace Chronos.Setup.Views; /// /// Chronos.Setup.exe --capture <dir>: renders the setup window in every stage (install options, programs -/// running, installing, installed, failed, uninstall with its data plan) in the dark and light themes, then in -/// Arabic (right to left, dark), from a small sample installer built in a temporary folder. Nothing is installed, +/// running, installing, installed, failed, uninstall with its data plan), the update of an installed copy that +/// replaces a legacy Uploader, and a retained Chronos Server 1.0 kept and unticked, in the dark and light themes, then +/// in Arabic (right to left, dark), from a small sample installer built in a temporary folder. Nothing is installed, /// removed or registered. /// internal static class SetupCapture @@ -94,16 +95,41 @@ internal static class SetupCapture { Program.ApplyLanguage(language); using var payload = PayloadReader.Open(installer); - using var install = SetupViewModel.ForInstall(new SetupArguments(), payload); + var manifest = payload.Manifest; + // Nothing installed, whatever this machine has, so every capture shows the same screen. + using var install = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), null, null, null)); + // The desktop app 1.0 installed for this user, the separate 1.0 Uploader beside it: Update replaces it. + var perUser = SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product); + var legacy = new LegacyInstall(new InstalledProduct(SetupPaths.DefaultDirectory(InstallScope.CurrentUser, LegacyProducts.UploaderProduct), + new InstallLog { Product = LegacyProducts.UploaderProduct, Version = "1.0.0", Components = ["Uploader"], Files = ["Chronos.Uploader.exe"] }), InstallScope.CurrentUser); + using var update = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), + new ExistingInstall(InstallScope.CurrentUser, perUser, "1.0.0"), new InstallLog { Product = Product, Version = "1.0.0", Components = ["Chronos"], Files = ["Chronos.exe"] }, legacy)); + // Chronos 1.0 for all users with Chronos Server for Windows, which this setup no longer ships: kept, then unticked. + var allUsers = SetupPaths.DefaultDirectory(InstallScope.AllUsers, Product); + var withServer = new InstallLog + { + Product = Product, + Version = "1.0.0", + Scope = InstallScope.AllUsers, + Components = ["Chronos", "Uploader", "Server"], + Files = ["Chronos.exe", "Chronos.Uploader.exe", "Chronos.Server.exe"], + }; + InstallPlan Retained() => InstallPlan.Resolve(manifest, new SetupArguments(), new ExistingInstall(InstallScope.AllUsers, allUsers, "1.0.0"), withServer, null); + using var retained = SetupViewModel.ForInstall(new SetupArguments(), payload, Retained()); + using var removeServer = SetupViewModel.ForInstall(new SetupArguments(), payload, Retained()); + foreach (var c in removeServer.Components.Where(c => c.IsRetained)) c.IsSelected = false; // 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", Components = ["Chronos", "Uploader"] }), + perUser, new InstallLog { Product = Product, Version = "1.0.0", Components = ["Chronos", "Uploader"] }), UserDataOwners.All); foreach (var theme in themes) { ThemeManager.Apply(theme); var name = suffix + "-" + theme.ToString().ToLowerInvariant(); Capture(install, [.. InstallStages.Select(s => ("setup-" + s.Name + name, s.Stage, (UserDataPlan?)null))], directory); + Capture(update, [("setup-update" + name, SetupStage.Options, null)], directory); + Capture(retained, [("setup-retained" + name, SetupStage.Options, null)], directory); + Capture(removeServer, [("setup-retained-remove" + name, SetupStage.Options, null)], directory); Capture(uninstall, [("setup-uninstall" + name, SetupStage.Options, SamplePlan)], directory); } } @@ -134,15 +160,17 @@ internal static class SetupCapture } } - /// Three components of random (incompressible) bytes, with the shortcuts the real installer carries. + /// + /// The two components of the real installer (the desktop app preselected), of random (incompressible) bytes, with + /// its shortcuts. + /// private static string WriteSampleInstaller(string work) { var random = new Random(1); var components = new (string Id, string DisplayName, bool Selected, string Program, int Bytes)[] { ("Chronos", "Chronos", true, "Chronos.exe", 2_400_000), - ("Uploader", "Chronos Uploader", true, "Chronos.Uploader.exe", 900_000), - ("Server", "Chronos Server", false, "Chronos.Server.exe", 1_600_000), + ("Uploader", "Chronos Uploader", false, "Chronos.Uploader.exe", 900_000), }; foreach (var c in components) { @@ -155,9 +183,9 @@ internal static class SetupCapture PayloadWriter.Write(Environment.ProcessPath ?? throw new InvalidOperationException("No process path."), new PayloadSource { Product = Product, - Version = "1.0.0", - 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" })], + Version = "1.1.0", + Components = [.. components.Select(c => new PayloadComponentSource(c.Id, c.DisplayName, c.Selected, Path.Combine(work, c.Id)))], + Shortcuts = [.. components.Select(c => new PayloadShortcut { Component = c.Id, Name = c.DisplayName, Target = c.Program, StartMenu = true, Desktop = true })], }, installer); return installer; } diff --git a/src/Chronos.Setup/Views/SetupViewModel.cs b/src/Chronos.Setup/Views/SetupViewModel.cs index 95db3f48..71c05502 100644 --- a/src/Chronos.Setup/Views/SetupViewModel.cs +++ b/src/Chronos.Setup/Views/SetupViewModel.cs @@ -14,6 +14,10 @@ namespace Chronos.Setup.Views; /// A line of the "Remove my data" dry run: a file or folder name (or "3 more items") and its size. internal sealed record DataPlanRow(string Name, string Size, bool IsFileName); +/// One change of the dry-run plan shown before Update: a program added, removed or replaced. +/// Shown in the warning colour: something installed goes. +internal sealed record ChangeRow(string Text, string ToolTip, bool IsRemoval); + /// What the setup screen currently shows. internal enum SetupStage { @@ -26,7 +30,10 @@ internal enum SetupStage /// /// The single setup screen for install and uninstall: options, a prompt when installed programs must close, -/// progress, success and failure. Work runs on the thread pool and reports through . +/// progress, success and failure. One setup installs, updates, adds and removes programs: the component rows show +/// what is installed, the Changes line is the dry-run plan of what Update adds, removes or replaces, and with every +/// component unticked the primary action becomes Uninstall, which opens the uninstall options of the same window. +/// Work runs on the thread pool and reports through . /// internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo { @@ -39,10 +46,11 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private readonly PayloadReader? _payload; private readonly InstallEngine? _engine; private readonly InstallPlan? _plan; - private readonly InstalledProduct? _installed; private readonly string _product; private readonly string? _version; - private readonly IReadOnlySet _dataOwners; + private InstalledProduct? _installed; + private IReadOnlySet _dataOwners; + private int _keptFiles; private SetupStage _stage; private string _directory = string.Empty; private bool _allUsers; @@ -66,7 +74,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private IReadOnlyList _stopped = []; private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed, - IReadOnlySet? dataOwners = null) + IReadOnlySet? dataOwners = null, InstallPlan? plan = null) { _arguments = arguments; _product = product; @@ -79,7 +87,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo if (payload is not null) { _engine = new InstallEngine(payload); - _plan = InstallPlan.Resolve(_engine.Manifest, arguments); + _plan = plan ?? InstallPlan.Resolve(_engine.Manifest, arguments); _directory = _plan.Directory; _allUsers = _plan.Scope == InstallScope.AllUsers; } @@ -88,11 +96,20 @@ 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), UnavailableReason(c), - OnComponentsChanged))]; + : + [ + .. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), + InstalledVersionOf(c.Id), UnavailableReason(c), OnComponentsChanged)), + .. _plan!.Retained.Select(r => new ComponentOption(r, _plan.Kept.Any(k => k.Id.Equals(r.Id, StringComparison.OrdinalIgnoreCase)), OnComponentsChanged)), + ]; Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))]; - PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart); + PrimaryCommand = new RelayCommand(() => + { + if (IsUninstall) Start(UninstallAsync); + else if (IsUninstallAll) SwitchToUninstall(); + else Start(InstallAsync); + }, () => CanStart); BrowseCommand = new RelayCommand(Browse, () => IsOptions && CanChangeLocation); CloseProgramsCommand = new RelayCommand(() => { @@ -105,8 +122,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo RetryCommand = new RelayCommand(() => Start(_operation!), () => CanRetry && _operation is not null); } - public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) => - new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null); + /// What was found on this PC; null resolves it from the registry (tests and captures pass their own). + public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload, InstallPlan? plan = null) => + new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null, plan: plan); /// Whose user data "Remove my data" covers; null works it out from the installed products. public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed, IReadOnlySet? dataOwners = null) => @@ -136,7 +154,8 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo public SetupExitCode ExitCode { get; private set; } = SetupExitCode.Cancelled; - public bool IsInstall => _engine is not null; + /// Installing from the payload; false once Uninstall (every component unticked) opened the uninstall options. + public bool IsInstall => _engine is not null && _installed is null; public bool IsUninstall => _installed is not null; public string WindowTitle => IsUninstall ? Loc.L("Setup.Window.Uninstall", _product) : Loc.L("Setup.Window.Title", _product); @@ -182,12 +201,73 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo public IReadOnlyList Components { get; } - private List SelectedComponents => [.. Components.Where(c => c.IsSelected).Select(c => c.Id)]; + /// The components of the payload that are ticked (retained ones excluded). + private List SelectedComponents => [.. Components.Where(c => c.IsSelected && !c.IsRetained).Select(c => c.Id)]; + + /// The retained components that are ticked: kept as they are. + private List KeptComponents => [.. Components.Where(c => c.IsSelected && c.Retained is not null).Select(c => c.Retained!)]; public string RequiredSpaceText => _engine is null ? string.Empty : Loc.L("Setup.Space.Required", ByteSize.Format(_engine.RequiredBytes(SelectedComponents))); - /// False when upgrading: the existing folder and scope are kept. - public bool CanChangeLocation => _plan?.Existing is null; + /// False when upgrading (the existing folder and scope are kept) or replacing a legacy Uploader (its scope is). + public bool CanChangeLocation => _plan is null || _plan.CanChangeLocation; + + /// An installation of this product exists: Update replaces it in place. + private bool IsUpgrade => _plan?.Existing is not null; + + /// Installed, and every component unticked: the primary action is Uninstall, which opens the uninstall options. + public bool IsUninstallAll => IsInstall && IsUpgrade && !Components.Any(c => c.IsSelected); + + /// The Install or Update button is shown. + public bool IsInstallPrimary => IsInstallOptions && !IsUninstallAll; + + /// The destructive Uninstall button of the install options is shown. + public bool IsUninstallAllPrimary => IsInstallOptions && IsUninstallAll; + + /// Cancel is the default when the primary action removes something. + public bool IsCancelDefault => IsUninstallOptions || IsUninstallAllPrimary; + + /// + /// The dry-run plan of the run, shown before it can start: programs added next to the installed ones, programs and a + /// retained Server removed, a legacy Uploader replaced (or left where it is). Empty for a new installation and for an + /// update in place. + /// + public IReadOnlyList Changes + { + get + { + if (!IsInstall || _plan is null || IsUninstallAll) return []; + var rows = new List(); + var replaces = _plan.Legacy is { } found && LegacyProducts.CanMerge(found, Scope, _directory); + if (IsUpgrade) + { + foreach (var c in Components) + { + if (c.Retained is { } retained && !c.IsSelected) + rows.Add(new ChangeRow(Loc.L("Setup.Changes.Remove", c.Name), Loc.L("Tooltips.Setup.Changes.RemoveRetained", FileList(retained.Files)), true)); + else if (!c.IsRetained && c.IsInstalled && !c.IsSelected) + rows.Add(new ChangeRow(Loc.L("Setup.Changes.Remove", c.Name), Loc.L("Tooltips.Setup.Changes.Remove"), true)); + // An Uploader that replaces the legacy one is said by "Replaces Chronos Uploader 1.0.0" below. + else if (!c.IsRetained && !c.IsInstalled && c.IsSelected && !(replaces && c.Id.Equals(LegacyProducts.UploaderComponent, StringComparison.OrdinalIgnoreCase))) + rows.Add(new ChangeRow(Loc.L("Setup.Changes.Add", c.Name), Loc.L("Tooltips.Setup.Changes.Add"), false)); + } + } + if (_plan.Legacy is { } legacy && Components.FirstOrDefault(c => c.Id.Equals(LegacyProducts.UploaderComponent, StringComparison.OrdinalIgnoreCase)) is { IsSelected: true } uploader) + { + rows.Add(replaces + ? new ChangeRow(Loc.L("Setup.Changes.Replace", uploader.Name, legacy.Version), Loc.L("Tooltips.Setup.Changes.Replace", legacy.Directory), false) + : new ChangeRow(Loc.L("Setup.Changes.KeptSeparate", uploader.Name), Loc.L("Tooltips.Setup.Changes.KeptSeparate", legacy.Directory), false)); + } + return rows; + } + } + + public bool HasChanges => Changes.Count > 0; + + /// The changes in one line ("Adds Chronos Uploader · Removes Chronos Server 1.0.0"). + public string ChangesText => string.Join(" · ", Changes.Select(c => c.Text)); + + private InstallScope Scope => _allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser; public bool IsAllUsers { @@ -270,17 +350,21 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo public bool HasStartMenuOption => SelectedShortcuts().Any(s => s.StartMenu); public bool HasLaunchOption => _engine?.LaunchTarget(SelectedComponents) is not null; - public string InstallText => CanChangeLocation ? Loc.L("Setup.Action.Install") : Loc.L("Setup.Action.Update"); + public string InstallText => IsUpgrade ? Loc.L("Setup.Action.Update") : Loc.L("Setup.Action.Install"); /// What Install does, or why it is disabled: no program selected, or a folder it cannot use. - public string InstallToolTip => !Components.Any(c => c.IsSelected) ? Loc.L("Tooltips.Setup.NoComponent") + public string InstallToolTip => SelectedComponents.Count == 0 ? Loc.L("Tooltips.Setup.NoComponent") : !IsDirectoryValid ? FolderErrorText - : CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update"); + : IsUpgrade ? Loc.L("Tooltips.Setup.Update") : Loc.L("Tooltips.Setup.Install"); - /// Removing user data waits for its plan, so the user has seen what goes before choosing Uninstall. + /// + /// Removing user data waits for its plan, so the user has seen what goes before choosing Uninstall. Installing needs + /// a program of the payload (a retained one alone is not an installation); with nothing ticked on an installed copy + /// the action is Uninstall. + /// private bool CanStart => IsOptions && (IsUninstall ? !_removeUserData || _dataPlan is not null - : IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected)); + : IsInstall && (IsUninstallAll || (IsDirectoryValid && SelectedComponents.Count > 0))); // ---- Uninstall options ---- @@ -360,6 +444,11 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo public string DoneText => IsUninstall ? Loc.L("Setup.Done.Removed", _product) : Loc.L("Setup.Done.Installed", _product); + /// "3 files kept": files of the previous version that changed since setup installed them, left in place. + public string KeptText => _keptFiles > 0 ? Loc.Plural("Setup.Done.Kept", _keptFiles) : string.Empty; + + public bool HasKeptFiles => IsDone && _keptFiles > 0; + public bool CanLaunch => IsDone && _launchProgram is not null; public string ErrorText => _failure switch @@ -439,37 +528,48 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo { var request = new InstallRequest( Path.TrimEndingDirectorySeparator(Path.GetFullPath(_directory)), - _allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, + Scope, SelectedComponents, HasDesktopOption && _desktop, - HasStartMenuOption && _startMenu); + HasStartMenuOption && _startMenu) + { Keep = KeptComponents }; var target = engine.LaunchTarget(request.Components); var program = target is null ? null : PayloadPath.Resolve(request.Directory, target); var launch = _launchAfter ? program : null; + var legacy = _plan!.LegacyToReplace(request.Components, request.Scope, request.Directory); if (request.Scope == InstallScope.AllUsers && !Elevation.IsElevated) { - await InstallElevatedAsync(request, program); + await InstallElevatedAsync(request, program, legacy); 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 programs = InstallPlan.Programs(engine.Manifest, request.Directory, request.Keep).ToList(); var owned = CommandProgram.FullPaths(request.Directory, programs); - if (await CloseProgramsAsync(request.Directory, programs, owned) is not { } running) return; + if (await CloseProgramsAsync(request.Directory, programs, owned, legacy?.Product) is not { } running) return; BeginWork(indeterminate: false); - if (running.Count > 0) + // The services of a retained component the user unticked (the 1.0 Server) are deleted; the others are + // stopped for the upgrade and run again after it. + var removing = InstalledServices.Find(CommandProgram.FullPaths(request.Directory, _plan.Removed(request.Keep).SelectMany(r => r.Files))); + var stopping = running.ExceptBy(removing.Select(s => s.Name), s => s.Name, StringComparer.OrdinalIgnoreCase).ToList(); + if (stopping.Count > 0) { - _stopped = running; - await ApplyToServicesAsync(request.Directory, running, ServiceActions.Stop); + _stopped = stopping; + await ApplyToServicesAsync(request.Directory, stopping, ServiceActions.Stop); } + await ApplyToServicesAsync(request.Directory, removing, ServiceActions.Remove); var progress = new Progress(ReportProgress); - await Task.Run(() => engine.Install(request, progress, CancellationToken.None)); + var result = await Task.Run(() => engine.Install(request, progress, CancellationToken.None)); + _keptFiles = result.KeptFiles; // 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); + // The legacy Uploader goes once this installation works; a per-user one is the unelevated parent's to remove. + if (legacy is not null && !(_arguments.Elevated && legacy.Scope == InstallScope.CurrentUser)) + await Task.Run(() => LegacyProducts.TryMerge(legacy, engine.Manifest, request.Directory)); _launchProgram = program; Complete(); if (launch is not null) Launch(); @@ -483,15 +583,16 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo /// /// All users without administrator rights: an elevated copy installs with the chosen options. This process - /// stays behind, hidden, to start unelevated if the copy asks for it. + /// stays behind, hidden, to start unelevated if the copy asks for it, and to remove a + /// per-user Uploader afterwards: it belongs to this account, not to the approving one. /// - private async Task InstallElevatedAsync(InstallRequest request, string? program) + private async Task InstallElevatedAsync(InstallRequest request, string? program, LegacyInstall? legacy) { if (_arguments.Elevated) throw new SetupException(SetupExitCode.ElevationDeclined, "Still not elevated after relaunch."); var switches = new SetupArguments { Directory = request.Directory, - Components = request.Components, + Components = [.. request.Components, .. request.Keep.Select(k => k.Id)], AllUsers = true, NoDesktopShortcut = !request.DesktopShortcuts, NoStartMenu = !request.StartMenuShortcuts, @@ -500,7 +601,27 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo }; var child = Elevation.Start(switches, WindowHandle) ?? throw new SetupException(SetupExitCode.ElevationDeclined, "Administrator approval declined."); VisibilityRequested?.Invoke(this, false); - Finish(await Elevation.WaitAsync(child, program)); + var code = await Elevation.WaitAsync(child, program); + if (code == SetupExitCode.Success && legacy is { Scope: InstallScope.CurrentUser }) + await Task.Run(() => LegacyProducts.TryMerge(legacy, _engine!.Manifest, request.Directory)); + Finish(code); + } + + /// + /// Every component unticked on an installed copy: the uninstall options of that copy (folder, Remove my data and + /// its plan), in the same window. + /// + private void SwitchToUninstall() + { + if (UninstallEngine.Locate(_plan!.Directory, null) is not { } installed) + { + Fail(new SetupException(SetupExitCode.NotInstalled, $"No installation log in '{_plan.Directory}'.")); + return; + } + _installed = installed; + _dataOwners = UserDataOwners.RemovableBeside(installed.Log.Components, SetupRegistry.OtherInstalls(installed.Directory, InstallEngine.Publisher)); + _directory = installed.Directory; + Stage = SetupStage.Options; } private async Task UninstallAsync() @@ -510,6 +631,13 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo { var owned = CommandProgram.FullPaths(installed.Directory, installed.Log.Files); if (await CloseProgramsAsync(installed.Directory, installed.Log.Files, owned) is not { } running) return; + if (installed.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + { + // Reached from the install options (every component unticked): an elevated copy removes the programs and + // their services; the data of this account, when chosen, is removed here afterwards. + await UninstallElevatedAsync(installed); + 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. @@ -528,19 +656,32 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo } } + private async Task UninstallElevatedAsync(InstalledProduct installed) + { + if (_arguments.Elevated) throw new SetupException(SetupExitCode.ElevationDeclined, "Still not elevated after relaunch."); + var switches = new SetupArguments { Uninstall = true, Silent = true, Directory = installed.Directory, Language = Loc.Culture.Name }; + var child = Elevation.Start(switches, WindowHandle) ?? throw new SetupException(SetupExitCode.ElevationDeclined, "Administrator approval declined."); + BeginWork(indeterminate: true); + var code = await Elevation.WaitAsync(child, null); + if (code != SetupExitCode.Success) throw new SetupException(code, $"The elevated uninstall exited with {code}."); + if (_removeUserData && _dataPlan is { Entries.Count: > 0 } plan) await Task.Run(plan.Remove); + Complete(); + } + /// /// Null when the user must first confirm (Confirm stage) that the programs and services running from - /// may close. Otherwise the running programs have closed, and the result lists the + /// (and from , the legacy Uploader being replaced) may close. Otherwise the running programs have closed, and the result lists the /// running services of , which the caller stops or deletes: a program that does not close /// stops setup before any service is touched. /// - private async Task?> CloseProgramsAsync(string directory, IEnumerable programs, IReadOnlySet owned) + private async Task?> CloseProgramsAsync(string directory, IEnumerable programs, IReadOnlySet owned, + InstalledProduct? alsoClose = null) { // A confirmation answers one prompt only; a later attempt asks again. var confirmed = _closeConfirmed; _closeConfirmed = false; var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList(); - var running = RunningPrograms.Find(directory, programs, services); + var running = RunningPrograms.Find(directory, programs, services, alsoClose); try { if (running.Count == 0 && services.Count == 0) return services; @@ -688,9 +829,26 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo OnPropertyChanged(nameof(HasDesktopOption)); OnPropertyChanged(nameof(HasStartMenuOption)); OnPropertyChanged(nameof(HasLaunchOption)); + OnPropertyChanged(nameof(Changes)); + OnPropertyChanged(nameof(HasChanges)); + OnPropertyChanged(nameof(ChangesText)); + OnPropertyChanged(nameof(IsUninstallAll)); + OnPropertyChanged(nameof(IsInstallPrimary)); + OnPropertyChanged(nameof(IsUninstallAllPrimary)); + OnPropertyChanged(nameof(IsCancelDefault)); OnDirectoryRuleChanged(); } + /// The installed version of when the installation upgraded here has it; null otherwise. + private string? InstalledVersionOf(string component) => + _plan is { Existing: not null, Previous: { } previous } && previous.Components.Contains(component, StringComparer.OrdinalIgnoreCase) + ? previous.VersionOf(component) + : null; + + /// The files a removal plan names: the first few, then "…". + private static string FileList(IReadOnlyList files) => + files.Count <= 3 ? string.Join(", ", files) : string.Join(", ", files.Take(3)) + ", …"; + /// The folder, the scope or the components changed: whether the folder is valid, and why not, may have too. private void OnDirectoryRuleChanged() { diff --git a/src/Chronos.Setup/Views/SetupWindow.xaml b/src/Chronos.Setup/Views/SetupWindow.xaml index c9aa718b..b8e9f31b 100644 --- a/src/Chronos.Setup/Views/SetupWindow.xaml +++ b/src/Chronos.Setup/Views/SetupWindow.xaml @@ -32,18 +32,20 @@ + + - + @@ -51,8 +53,30 @@ - - + + + + + + + + + + + + + + + + + + + + + + - - + + @@ -72,8 +96,8 @@ ToolTipService.ShowOnDisabled="True" ToolTip="{Binding BrowseToolTip}" /> - - + + - + + + + + @@ -174,9 +203,12 @@ Visibility="{Binding IsInstallOptions, Converter={StaticResource BoolToVisibility}}" />