From 7a54f1a460acbb62ef88a6746f115821bea301bc Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 18 Nov 2026 13:57:25 +0100 Subject: [PATCH] Programma di installazione per Windows scritto in casa, senza NSIS (C6, 2/4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decisione di Alberto del 18 novembre 2026: niente componenti esterni. Il programma di installazione è ora src/Febe.Installer, solo .NET: pubblicato per win-x64 autosufficiente, in un file solo, ridotto e compresso (circa 11 MB); lo stesso progetto, compilato per il sistema che costruisce, gli appende Febe.exe compresso con Brotli, la versione e un piè di pagina con SHA-256 (--impacchetta), lo ricontrolla (--verifica) e scrive lo zip portabile (--zip). Fa ciò che faceva lo script NSIS: installazione per utente in %LOCALAPPDATA%\Programs\Febe senza permessi di amministratore, collegamenti nel menu Start e (a scelta) sul desktop con ShellLink, voce in App installate sotto HKCU, controllo di WebView2, rifiuto con Febe aperto, aggiornamento che lascia i dati, «Disinstalla Febe.exe» che toglie solo il programma, i collegamenti, l'avvio con il computer e le librerie estratte, mai dati né libreria. Pagine con la finestra di dialogo di Windows; /S, /D= e /PROVA= per le prove. Tolti installer/febe.nsi, NSIS e zip dalla CI e dai documenti: costruisci.sh vuole solo il .NET SDK. Prove: pacchetto, riga di comando, installazione, aggiornamento e disinstallazione su un Windows finto (anche su Linux); su Windows il programma pubblicato davvero, installato e disinstallato senza domande in una cartella di prova, e la prima pagina aperta e annullata. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 2 - .gitea/scripts/ambiente-prove.sh | 4 +- .gitea/scripts/riepilogo-prove.sh | 4 +- .gitea/workflows/rilascio.yml | 10 +- .gitea/workflows/verifica.yml | 13 +- CLAUDE.md | 2 +- Febe.slnx | 1 + docs/decisioni.md | 2 + docs/guida/Installazione-Windows.md | 11 +- docs/guida/Sviluppo.md | 2 +- docs/processo.md | 2 +- docs/windows.md | 33 +- installer/costruisci.sh | 59 +- installer/febe.nsi | 232 ------ src/Febe.Desktop.Core/BrandIcon.cs | 2 +- src/Febe.Desktop/LEGGIMI.md | 3 +- src/Febe.Installer/CommandLine.cs | 143 ++++ src/Febe.Installer/Febe.Installer.csproj | 42 + src/Febe.Installer/ISystemAccess.cs | 48 ++ src/Febe.Installer/Locations.cs | 86 ++ src/Febe.Installer/Package.cs | 405 +++++++++ src/Febe.Installer/Product.cs | 46 ++ src/Febe.Installer/Program.cs | 187 +++++ src/Febe.Installer/SetupActions.cs | 242 ++++++ src/Febe.Installer/SetupFlow.cs | 228 +++++ src/Febe.Installer/Texts.cs | 99 +++ src/Febe.Installer/Windows/DialogInterface.cs | 97 +++ src/Febe.Installer/Windows/ShellLinks.cs | 129 +++ src/Febe.Installer/Windows/TaskDialog.cs | 253 ++++++ src/Febe.Installer/Windows/WindowsSystem.cs | 95 +++ src/Febe.Installer/app.manifest | 32 + .../Febe.Tests.Windows.csproj | 1 + tests/Febe.Tests.Windows/InstallerTests.cs | 338 ++++++++ tests/Febe.Tests/Desktop/InstallerTests.cs | 782 ++++++++++++++++-- .../Febe.Tests/Desktop/Support/Repository.cs | 2 +- tests/Febe.Tests/Febe.Tests.csproj | 1 + tests/Febe.Tests/Packaging/PipelineTests.cs | 15 +- 37 files changed, 3275 insertions(+), 378 deletions(-) delete mode 100644 installer/febe.nsi create mode 100644 src/Febe.Installer/CommandLine.cs create mode 100644 src/Febe.Installer/Febe.Installer.csproj create mode 100644 src/Febe.Installer/ISystemAccess.cs create mode 100644 src/Febe.Installer/Locations.cs create mode 100644 src/Febe.Installer/Package.cs create mode 100644 src/Febe.Installer/Product.cs create mode 100644 src/Febe.Installer/Program.cs create mode 100644 src/Febe.Installer/SetupActions.cs create mode 100644 src/Febe.Installer/SetupFlow.cs create mode 100644 src/Febe.Installer/Texts.cs create mode 100644 src/Febe.Installer/Windows/DialogInterface.cs create mode 100644 src/Febe.Installer/Windows/ShellLinks.cs create mode 100644 src/Febe.Installer/Windows/TaskDialog.cs create mode 100644 src/Febe.Installer/Windows/WindowsSystem.cs create mode 100644 src/Febe.Installer/app.manifest create mode 100644 tests/Febe.Tests.Windows/InstallerTests.cs diff --git a/.gitattributes b/.gitattributes index c760a48..e4d9d12 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,4 @@ # Gli script di shell restano con le righe Unix anche su un Windows con core.autocrlf: bash non regge il CR. *.sh text eol=lf -# Il programma di installazione si costruisce anche da Linux con makensis. -*.nsi text eol=lf # Binari: mai conversioni. *.ico binary diff --git a/.gitea/scripts/ambiente-prove.sh b/.gitea/scripts/ambiente-prove.sh index ece19fc..799a7da 100755 --- a/.gitea/scripts/ambiente-prove.sh +++ b/.gitea/scripts/ambiente-prove.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché # nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno snap, che nei contenitori non va) con le -# sue lingue, Xvfb, ffmpeg e ffprobe, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi +# sue lingue, Xvfb, ffmpeg e ffprobe, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi # caratteri dell'immagine di Febe. Node c'è già (prova della pagina di accesso); setpriv, getent e l'utente nobody # (65534) vengono con Debian (prove dell'avvio del contenitore). # @@ -17,7 +17,6 @@ $sudo apt-get install -y -qq --no-install-recommends \ chromium chromium-l10n \ xvfb \ ffmpeg \ - nsis zip \ locales tzdata libicu76 ca-certificates \ fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ util-linux procps > /dev/null @@ -29,7 +28,6 @@ chromium --version command -v Xvfb ffmpeg -version | head -n 1 || true ffprobe -version | head -n 1 || true -echo "makensis $(makensis -VERSION)" echo "node $(node --version)" locale -a | grep -i '^it_IT\.utf8$' for strumento in setpriv getent stat chown sh; do command -v "$strumento" > /dev/null || { echo "Manca $strumento." >&2; exit 1; }; done diff --git a/.gitea/scripts/riepilogo-prove.sh b/.gitea/scripts/riepilogo-prove.sh index a5ab3bd..1ca1d9d 100755 --- a/.gitea/scripts/riepilogo-prove.sh +++ b/.gitea/scripts/riepilogo-prove.sh @@ -6,7 +6,7 @@ # .gitea/scripts/riepilogo-prove.sh [saltate ammesse] # # Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono -# Chromium, Xvfb, ffmpeg, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. +# Chromium, Xvfb, ffmpeg e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. set -euo pipefail cartella="${1:?Indica la cartella con i file .trx.}" @@ -96,7 +96,7 @@ if (( fallite_totali > 0 )); then esito=1 fi if (( saltate_totali > ammesse )); then - echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, ffmpeg, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 + echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, ffmpeg e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 esito=1 fi diff --git a/.gitea/workflows/rilascio.yml b/.gitea/workflows/rilascio.yml index 017551d..93d14a8 100644 --- a/.gitea/workflows/rilascio.yml +++ b/.gitea/workflows/rilascio.yml @@ -1,8 +1,8 @@ # Rilascio a ogni tag vX.Y.Z (anche vX.Y.Z-qualcosa per un'anteprima): # 1. prove: il tag coincide con di Directory.Build.props, la soluzione si compila con gli avvisi come errori # e tutte le prove passano. Senza prove verdi non si costruisce né si rilascia nulla; -# 2. windows: Febe.exe in un file solo, il programma di installazione NSIS e lo zip portabile (installer/costruisci.sh, -# gira su Linux); +# 2. windows: Febe.exe in un file solo, il programma di installazione nostro (src/Febe.Installer) e lo zip portabile +# (installer/costruisci.sh, gira su Linux con il solo .NET SDK); # 3. immagine: dopo l'installatore, l'immagine Docker (le prove girano anche dentro la build), provata senza rete e # scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro # dei container di Gitea come //febe:X.Y.Z e :latest (solo per le versioni senza @@ -75,12 +75,6 @@ jobs: with: dotnet-version: "10.0.x" - - name: NSIS e zip - run: | - SUDO=""; [ "$(id -u)" = 0 ] || SUDO=sudo - $SUDO apt-get update -qq - $SUDO apt-get install -y -qq nsis zip > /dev/null - - name: Febe.exe, programma di installazione e zip portabile run: bash installer/costruisci.sh "$VERSION" diff --git a/.gitea/workflows/verifica.yml b/.gitea/workflows/verifica.yml index 23cd7d6..578538e 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -4,10 +4,11 @@ # soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate); # prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests # (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con -# Chromium, Xvfb, ffmpeg, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi. +# Chromium, Xvfb, ffmpeg e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi. # Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di # questa esecuzione, scritto nel registro per rifare un errore; -# installatore Febe-Setup--ci..exe e lo zip portabile, artefatti per 14 giorni; +# installatore Febe-Setup--ci..exe (il programma di installazione nostro, src/Febe.Installer) e +# lo zip portabile, artefatti per 14 giorni; serve solo il .NET SDK; # immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute, # Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push # su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre, @@ -108,7 +109,7 @@ jobs: echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)." echo "Per rifarla: FEBE_SEME_PROVA=$seme dotnet test tests/Febe.Tests --filter \"TestCategory=SitoDiProva\"" - - name: Chromium, Xvfb, ffmpeg, NSIS e lingua italiana + - name: Chromium, Xvfb, ffmpeg e lingua italiana run: bash .gitea/scripts/ambiente-prove.sh - uses: actions/setup-dotnet@v4 @@ -157,12 +158,6 @@ jobs: with: dotnet-version: "10.0.x" - - name: NSIS e zip - run: | - SUDO=""; [ "$(id -u)" = 0 ] || SUDO=sudo - $SUDO apt-get update -qq - $SUDO apt-get install -y -qq nsis zip > /dev/null - - name: Febe.exe, programma di installazione e zip portabile (versione di prova) run: | V=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1) diff --git a/CLAUDE.md b/CLAUDE.md index 0658d50..2084d06 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,7 +41,7 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande - Repository: Gitea di casa, https://gitea.encke-hake.ts.net/Alby96/Febe (ramo main). Non è GitHub: niente strumenti GitHub. - Processo (rami `/`, commit piccoli, una richiesta di unione per ramo, verifica verde per unire in main, commit di unione, rilasci, correzioni urgenti): docs/processo.md. - CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`: - - `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb, ffmpeg e NSIS veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-` (con il segreto `REGISTRY_TOKEN`; senza, un avviso). + - `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb e ffmpeg veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore (nostro, `src/Febe.Installer`, solo .NET SDK) e zip `-ci.`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-` (con il segreto `REGISTRY_TOKEN`; senza, un avviso). - `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release. - `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore. - Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera. diff --git a/Febe.slnx b/Febe.slnx index 38a7235..e587a79 100644 --- a/Febe.slnx +++ b/Febe.slnx @@ -8,6 +8,7 @@ + diff --git a/docs/decisioni.md b/docs/decisioni.md index 281748c..dd42aed 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -422,3 +422,5 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» | | 2026-11-18 | Il carattere è quello del sistema (token `--carattere`: `system-ui`, "Segoe UI", Roboto, Cantarell, "Noto Sans", "Liberation Sans", `sans-serif`); tolti i file di Archivo, la sua licenza e il precaricamento; `font-src 'none'` nella CSP e `/caratteri/` non è più fra i percorsi pubblici | Decisione di Alberto del 18 novembre 2026: niente componenti esterni, nemmeno caratteri o icone di terzi. Le larghezze di `font-stretch` restano: valgono dove il sistema ha una variante più stretta o più larga, altrimenti non cambiano nulla | | 2026-11-18 | Le 70 icone sono disegnate per Febe: un SVG per icona in `wwwroot/icone`, griglia di 24, solo tratti (linee, cerchi, rettangoli, poligoni, archi semplici), spessore 1,75 dal foglio di stile; stessi nomi e stesso significato di prima, così `icon('nome')` non cambia; tolte le icone Lucide e la loro licenza | Stessa decisione; i nomi restano identificativi interni. Una prova fallisce se nei file del programma ricompare un riferimento al carattere o alle icone di prima | +| 2026-11-18 | Il programma di installazione per Windows è nostro: `src/Febe.Installer`, un programma .NET pubblicato per win-x64 autosufficiente, in un file solo, ridotto con il trimming e compresso, a cui lo stesso progetto (compilato per il sistema che costruisce: `--impacchetta`, `--verifica`, `--zip`) appende `Febe.exe` compresso con Brotli (qualità 5, finestra di 16 MB), la versione e un piè di pagina di 80 byte con lunghezze e SHA-256. Fa ciò che faceva lo script di prima: per utente in `%LOCALAPPDATA%\Programs\Febe`, collegamenti con l'oggetto ShellLink di Windows (interop COM generata da .NET), voce in App installate sotto HKCU, controllo di WebView2, rifiuto con Febe aperto, disinstallazione che non tocca dati né libreria; pagine con la finestra di dialogo delle attività di Windows (TaskDialog); `/S`, `/D=` e, per le prove, `/PROVA=`. Tolti `installer/febe.nsi`, NSIS e `zip` dalla CI e dai documenti; lo zip portabile lo scrive `ZipArchive` | Decisione di Alberto del 18 novembre 2026: niente componenti esterni. Il trimming e il pacchetto del runtime vengono dallo SDK di .NET (come i runtime per win-x64 che `Febe.exe` già usa), non sono codice di terzi; senza trimming il programma con il suo runtime supererebbe con `Febe.exe` i 100 MB degli allegati di Gitea (oggi 91,4 MB in tutto). Brotli 5 invece di 11: 80,8 MB invece di 79,7, in 3 secondi invece di 6 minuti | +| 2026-11-18 | La disinstallazione si copia in `%TEMP%` (`Febe-disinstalla-.exe`), avvia la copia con la cartella del programma e il proprio numero di processo e finisce; la copia aspetta che finisca, fa il lavoro e resta in `%TEMP%` finché un avvio successivo dell'installazione o della disinstallazione non la toglie | Un eseguibile in esecuzione non può cancellare il proprio file; senza permessi di amministratore Windows non cancella un file al riavvio. `/S` della disinstallazione esce quindi subito con 0 | diff --git a/docs/guida/Installazione-Windows.md b/docs/guida/Installazione-Windows.md index 18f8b76..2ede7f2 100644 --- a/docs/guida/Installazione-Windows.md +++ b/docs/guida/Installazione-Windows.md @@ -46,10 +46,17 @@ , e aprilo. 2. Windows può avvisare che il programma non è firmato (SmartScreen): «Ulteriori informazioni» ▸ «Esegui comunque». 3. Il programma di installazione mette `Febe.exe` in `%LOCALAPPDATA%\Programs\Febe`, crea il collegamento nel menu - Start e, se lasci la scelta «Collegamento sul desktop», uno sul desktop. Febe compare in Impostazioni di Windows ▸ - App installate. + Start e, se lasci la scelta «Crea un collegamento a Febe sul desktop», uno sul desktop. Febe compare in + Impostazioni di Windows ▸ App installate. 4. Alla fine, «Apri Febe adesso» lo avvia. +**Aggiornare.** Esci da Febe (menu dell'icona ▸ Esci) e apri il programma di installazione della versione nuova: la +prima pagina dice «Aggiornamento di Febe alla versione …», sostituisce il programma e lascia dove sono i dati, la +libreria e le impostazioni. Con Febe aperto si ferma e chiede di chiuderlo. + +**Senza domande.** `Febe-Setup-.exe /S` installa (o aggiorna) senza finestre, con il collegamento sul +desktop e senza avviare Febe; `/D=`, ultima opzione, sceglie un'altra cartella. + Non serve installare .NET: `Febe.exe` (circa 86 MB) contiene il runtime, l'interfaccia e le librerie native. Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale. diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 9dd2176..c1015e5 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -198,7 +198,7 @@ richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correz - `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in tutta la storia (gitleaks); - `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in - un contenitore Debian con Chromium, Xvfb, ffmpeg, NSIS e Node veri: nessuna prova si salta; + un contenitore Debian con Chromium, Xvfb, ffmpeg e Node veri: nessuna prova si salta; - `installatore`: `Febe-Setup--ci..exe` e lo zip portabile, fra gli artefatti per 14 giorni; - `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-`. Alla fine si toglie diff --git a/docs/processo.md b/docs/processo.md index 5a42f53..4f6e8bc 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -87,7 +87,7 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget | Lavoro | Quando | Che cosa garantisce | |---|---|---| | `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) | -| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie`) con Chromium della distribuzione, Xvfb, ffmpeg, NSIS, Node e la lingua italiana: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) | +| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie`) con Chromium della distribuzione, Xvfb, ffmpeg, Node e la lingua italiana: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) | | `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup--ci..exe` e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni | | `immagine` | dopo `installatore` (così `:main` e `:sha-` escono solo da un commit con tutta la verifica verde) | l'immagine si costruisce con buildx (dentro girano compilazione e prove), il contenitore parte **senza rete** come dice la guida e diventa «healthy», Chromium e la lingua italiana ci sono, si ferma entro 30 secondi; Trivy 0.75.0 non trova vulnerabilità CRITICAL con correzione disponibile. Solo dopo un push su `main`: pubblicazione `:main` e `:sha-` | diff --git a/docs/windows.md b/docs/windows.md index 086373c..0720b64 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -216,7 +216,7 @@ servono più, cancellale tu — la cartella dei dati contiene la sessione di Ins ## Costruire il programma di installazione -Da Linux (CI, rilascio) o da Windows con bash, con il .NET SDK 10 e NSIS 3 (`apt-get install nsis`): +Da Linux (CI, rilascio) o da Windows con bash, con il solo .NET SDK 10: nessun altro programma. ```sh installer/costruisci.sh # versione di Directory.Build.props @@ -224,9 +224,33 @@ installer/costruisci.sh 0.2.0 # oppure una versione esplicita ``` Il risultato è in `out/`: `Febe-Setup-.exe` e `Febe--portabile.zip`, ognuno sotto i 100 MB -(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB). Lo script -controlla che la pubblicazione abbia prodotto un solo file e che nulla superi il limite. Lo script NSIS è -`installer/febe.nsi` (Unicode, testi in italiano, versione passata con `/DVERSION=…`). +(limite degli allegati di Gitea; con la versione 0.1.2: Febe.exe 86,5 MB, installazione 91,4 MB, zip 80,8 MB). Lo +script controlla che le pubblicazioni abbiano prodotto un solo file ciascuna e che nulla superi il limite. + +Il programma di installazione è nostro, dal 18 novembre 2026: `src/Febe.Installer`, solo la libreria di base di .NET. + +- **Com'è fatto.** `Febe.Installer.exe` è pubblicato per win-x64 autosufficiente, in un file solo, ridotto con il + trimming e compresso (circa 11 MB). Lo stesso progetto, compilato per il sistema che costruisce, è lo strumento del + pacchetto: `--impacchetta` gli appende `Febe.exe` compresso con Brotli, la versione e un piè di pagina di 80 byte con + la lunghezza e lo SHA-256 di `Febe.exe`; `--verifica` lo rilegge come farà l'installazione e confronta il risultato + con `Febe.exe` byte per byte; `--zip` scrive lo zip portabile. Il programma di un file solo trova le sue parti da un + indirizzo scritto dentro di sé, non dalla fine del file: ciò che segue non lo disturba. +- **Che cosa fa** (come prima): installazione per l'utente, senza permessi di amministratore (il manifesto dice + `asInvoker`: Windows non chiede di elevare un programma con «Setup» nel nome), in `%LOCALAPPDATA%\Programs\Febe`; + `Febe.exe` scritto accanto e poi rinominato, e controllato con lo SHA-256 (un pacchetto rovinato non installa nulla); + «Disinstalla Febe.exe» (lo stesso programma, senza `Febe.exe`); collegamento nel menu Start e, se scelto, sul + desktop, scritti con l'oggetto ShellLink di Windows; la voce in App installate sotto `HKEY_CURRENT_USER`; il + controllo di WebView2; un'installazione sopra un'altra sostituisce il programma e lascia tutto il resto. Con Febe + aperto si ferma e chiede di chiuderlo. Le pagine sono le finestre di dialogo di Windows (TaskDialog). +- **Disinstallazione.** «Disinstalla Febe.exe» si copia in `%TEMP%` (un programma non può cancellare il proprio file), + avvia la copia e finisce; la copia toglie il programma, i collegamenti, la voce, l'avvio con il computer e le + librerie estratte in `%TEMP%\.net\Febe`, **mai** la cartella dei dati né la libreria, e dice dove sono. La copia + resta in `%TEMP%` fino al prossimo avvio dell'installazione o della disinstallazione, che la toglie. +- **Senza domande**: `Febe-Setup-.exe /S` (collegamento sul desktop sì, Febe non si avvia, con Febe aperto + esce con il codice 2), `/D=` per un'altra cartella (ultima opzione, anche con spazi); + `"Disinstalla Febe.exe" /S` (esce subito con 0: il lavoro lo fa la sua copia in `%TEMP%`). Codici d'uscita: 0 fatto, 1 annullato, 2 non riuscito (con `/S` il motivo va + sull'errore standard). `/PROVA=` serve alle prove: menu Start, desktop, `%TEMP%` e chiavi del registro + (sotto `HKEY_CURRENT_USER\Software\FebeProve\`) stanno tutti lì dentro. L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è disegnata dal marchio dell'appendice C con SkiaSharp e scritta a mano: per rigenerarla dopo un cambio del marchio, @@ -256,6 +280,7 @@ farlo ripartire. Tutte insieme durano due o tre minuti, quasi tutti della sessio | `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; «Scollega» mentre il primo avvio aspetta di riprovare (un solo browser nella finestra, il «Scollega» dopo riesce subito); «Esci» mentre l'avvio non si completa (non lo aspetta); ripartenza dopo l'arresto del processo; «composizione» di S2 | | `WebView2CdpTests` | S1: i comandi dell'elenco su WebView2 contro il sito di prova, con la finestra fuori vista, e i comandi vietati rifiutati | | `WebView2CollectionTests` | Una sessione vera della composizione (`FebeApp` con `DesktopPlatform`) su WebView2: i file arrivano nella libreria | +| `InstallerTests` | Il programma di installazione pubblicato come nella CI (un file solo, ridotto) e impacchettato con un finto `Febe.exe`: manifesto e risorsa di versione; installazione senza domande in una cartella della prova (`/PROVA=`), collegamenti riletti con ShellLink, voce in App installate; seconda installazione sopra la prima con i dati intatti; rifiuto con Febe aperto; disinstallazione con la `QuietUninstallString`, che toglie solo ciò che è suo. La prima pagina si apre e «Annulla» non installa nulla. Non avvia mai Febe | | `WebView2ConnectionTests` | Il collegamento dal servizio vero della composizione: «Accedi a Instagram» porta in primo piano la finestra con la pagina di accesso (del sito di prova), «Ho finito» trova la sessione e la rimette fuori vista, «Scollega» cancella il profilo e il motore riparte | Quello che di `WebView2CdpSession` non chiede Windows (per esempio: un errore di chi ascolta la ripartenza non disfa diff --git a/installer/costruisci.sh b/installer/costruisci.sh index 673014b..f83faa9 100755 --- a/installer/costruisci.sh +++ b/installer/costruisci.sh @@ -3,8 +3,10 @@ # # installer/costruisci.sh [versione] # -# Gira su Linux (CI e rilascio) come su Windows con bash: servono il .NET SDK 10 e makensis (NSIS 3, «apt-get install -# nsis»). La versione, se non la si passa, è quella di Directory.Build.props (il tag deve coincidere). +# Gira su Linux (CI e rilascio) come su Windows con bash: serve solo il .NET SDK 10. Nessun altro programma: il +# programma di installazione è nostro (src/Febe.Installer) e lo stesso progetto, compilato per il sistema che lo +# costruisce, fa il pacchetto, lo controlla e scrive lo zip. La versione, se non la si passa, è quella di +# Directory.Build.props (il tag deve coincidere). # Risultato in out/: # Febe-Setup-.exe installazione per l'utente, senza permessi di amministratore # Febe--portabile.zip Febe.exe e LEGGIMI.txt, da copiare dove si vuole @@ -20,16 +22,13 @@ if [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then exit 2 fi -# La versione dei file di Windows vuole quattro numeri. -numeri="${versione%%[-+]*}" -versione_file="${numeri}.0" - command -v dotnet >/dev/null || { echo "Manca il .NET SDK (dotnet)." >&2; exit 2; } -command -v makensis >/dev/null || { echo "Manca makensis: installa NSIS (apt-get install nsis)." >&2; exit 2; } uscita="$radice/out" pubblicazione="$uscita/pubblicazione" -rm -rf "$pubblicazione" +installatore="$uscita/installatore" +strumento="$uscita/strumento-installatore" +rm -rf "$pubblicazione" "$installatore" "$strumento" mkdir -p "$pubblicazione" echo "== Pubblicazione di Febe.exe $versione (win-x64, un file solo)" @@ -38,19 +37,31 @@ dotnet publish src/Febe.Desktop/Febe.Desktop.csproj -c Release -r win-x64 --self -p:Version="$versione" -nologo -o "$pubblicazione" # Un file solo: niente accanto all'eseguibile. -altri="$(find "$pubblicazione" -mindepth 1 ! -name Febe.exe)" -if [[ -n "$altri" ]]; then - echo "La pubblicazione ha prodotto altri file oltre a Febe.exe:" >&2 - echo "$altri" >&2 - exit 1 -fi +solo_un_file() { + local cartella="$1" nome="$2" altri + altri="$(find "$cartella" -mindepth 1 ! -name "$nome")" + if [[ -n "$altri" ]]; then + echo "La pubblicazione ha prodotto altri file oltre a $nome:" >&2 + echo "$altri" >&2 + exit 1 + fi +} +solo_un_file "$pubblicazione" Febe.exe + +echo "== Programma di installazione (win-x64, un file solo, ridotto)" +# Le proprietà della pubblicazione (autosufficiente, un file solo, trimming, compressione) sono nel progetto. +dotnet publish src/Febe.Installer/Febe.Installer.csproj -c Release -r win-x64 \ + -p:Version="$versione" -nologo -o "$installatore" +solo_un_file "$installatore" Febe.Installer.exe + +echo "== Strumento del pacchetto (per questo sistema)" +dotnet build src/Febe.Installer/Febe.Installer.csproj -c Release -p:Version="$versione" -nologo -o "$strumento" +pacchetto() { dotnet "$strumento/Febe.Installer.dll" "$@"; } -echo "== Programma di installazione" setup="$uscita/Febe-Setup-$versione.exe" rm -f "$setup" -(cd installer && makensis -V2 -INPUTCHARSET UTF8 \ - -DVERSION="$versione" -DVERSIONE_FILE="$versione_file" \ - -DSORGENTE="$pubblicazione" -DUSCITA="$setup" febe.nsi) +pacchetto --impacchetta "$installatore/Febe.Installer.exe" "$pubblicazione/Febe.exe" "$versione" "$setup" +pacchetto --verifica "$setup" "$pubblicazione/Febe.exe" echo "== Zip portabile" zip_portabile="$uscita/Febe-$versione-portabile.zip" @@ -73,17 +84,7 @@ Non usare insieme Febe per Windows e il contenitore Docker con lo stesso account Guida: https://gitea.encke-hake.ts.net/Alby96/Febe/wiki TESTO sed -i 's/$/\r/' "$leggimi" -if command -v zip >/dev/null; then - (cd "$pubblicazione" && zip -q -9 "$zip_portabile" Febe.exe LEGGIMI.txt) -else - python3 - "$zip_portabile" "$pubblicazione" <<'PY' -import os, sys, zipfile -target, folder = sys.argv[1], sys.argv[2] -with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as archive: - for name in ("Febe.exe", "LEGGIMI.txt"): - archive.write(os.path.join(folder, name), name) -PY -fi +pacchetto --zip "$zip_portabile" "$pubblicazione/Febe.exe" "$leggimi" rm -f "$leggimi" limite=$((100 * 1024 * 1024)) diff --git a/installer/febe.nsi b/installer/febe.nsi deleted file mode 100644 index b9e0d2a..0000000 --- a/installer/febe.nsi +++ /dev/null @@ -1,232 +0,0 @@ -; Febe — programma di installazione per Windows (specifica §12, domanda 6 di §16). -; -; makensis -INPUTCHARSET UTF8 -DVERSION=0.1.0 -DVERSIONE_FILE=0.1.0.0 \ -; -DSORGENTE=out/pubblicazione -DUSCITA=out/Febe-Setup-0.1.0.exe installer/febe.nsi -; -; Di solito lo lancia installer/costruisci.sh, che prima pubblica Febe.exe in un file solo. -; -; - Installazione per l'utente, senza permessi di amministratore, in %LOCALAPPDATA%\Programs\Febe. -; - Collegamento nel menu Start; collegamento sul desktop facoltativo. -; - Disinstallazione registrata in HKCU (Programmi e funzionalità / App installate). -; - La disinstallazione non tocca MAI la cartella dei dati né la libreria e non chiede nulla su di loro: dice dove sono. -; - Controllo del runtime WebView2 di Microsoft, con il collegamento alla pagina ufficiale se manca. - -Unicode true -ManifestDPIAware true -RequestExecutionLevel user -SetCompressor /SOLID lzma - -!ifndef VERSION - !error "Manca la versione: passala con /DVERSION=x.y.z (installer/costruisci.sh la legge da Directory.Build.props)." -!endif -!ifndef SORGENTE - !define SORGENTE "../out/pubblicazione" -!endif -!ifndef USCITA - !define USCITA "../out/Febe-Setup-${VERSION}.exe" -!endif - -!define NOME "Febe" -!define EDITORE "Alberto Balbo" -!define ESEGUIBILE "Febe.exe" -!define DISINSTALLA "Disinstalla Febe.exe" -!define CHIAVE_DISINSTALLA "Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe" -!define CHIAVE_FEBE "Software\Febe" -!define CHIAVE_AVVIO "Software\Microsoft\Windows\CurrentVersion\Run" -!define WEBVIEW2_GUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" -!define WEBVIEW2_PAGINA "https://developer.microsoft.com/microsoft-edge/webview2/" -!define SITO "https://gitea.encke-hake.ts.net/Alby96/Febe" - -Name "${NOME}" -OutFile "${USCITA}" -InstallDir "$LOCALAPPDATA\Programs\Febe" -BrandingText "${NOME} ${VERSION}" -ShowInstDetails show -ShowUninstDetails show - -!ifdef VERSIONE_FILE - VIProductVersion "${VERSIONE_FILE}" - VIAddVersionKey /LANG=1040 "ProductName" "${NOME}" - VIAddVersionKey /LANG=1040 "ProductVersion" "${VERSION}" - VIAddVersionKey /LANG=1040 "CompanyName" "${EDITORE}" - VIAddVersionKey /LANG=1040 "LegalCopyright" "${EDITORE}" - VIAddVersionKey /LANG=1040 "FileDescription" "Installazione di ${NOME}" - VIAddVersionKey /LANG=1040 "FileVersion" "${VERSION}" -!endif - -!include "MUI2.nsh" -!include "LogicLib.nsh" -!include "FileFunc.nsh" - -!define MUI_ICON "../src/Febe.Desktop/Febe.ico" -!define MUI_UNICON "../src/Febe.Desktop/Febe.ico" -!define MUI_ABORTWARNING - -; ------------------------------------------------------------------------------------------------ pagine -!define MUI_WELCOMEPAGE_TITLE "Installazione di Febe ${VERSION}" -!define MUI_WELCOMEPAGE_TEXT "Febe è l'archivio personale di foto, video e storie da Instagram.$\r$\n$\r$\nVerrà installato solo per te, in $LOCALAPPDATA\Programs\Febe: non servono permessi di amministratore.$\r$\n$\r$\nI dati di Febe (database e sessione del browser) andranno in $LOCALAPPDATA\Febe, le foto e i video nella cartella Immagini\Febe; le cartelle si possono cambiare dalle Impostazioni." -!insertmacro MUI_PAGE_WELCOME -!insertmacro MUI_PAGE_COMPONENTS -!insertmacro MUI_PAGE_INSTFILES -!define MUI_FINISHPAGE_TITLE "Febe è installato" -!define MUI_FINISHPAGE_TEXT "Febe si apre in una sua finestra e resta attivo nell'area di notifica, accanto all'orologio.$\r$\n$\r$\nPer collegarlo a Instagram: Impostazioni ▸ Collegamento. Non usare insieme Febe per Windows e il contenitore Docker con lo stesso account." -!define MUI_FINISHPAGE_RUN "$INSTDIR\${ESEGUIBILE}" -!define MUI_FINISHPAGE_RUN_TEXT "Apri Febe adesso" -!insertmacro MUI_PAGE_FINISH - -!define MUI_UNCONFIRMPAGE_TEXT_TOP "Il programma Febe verrà tolto da questo computer. I tuoi dati restano dove sono: la disinstallazione non cancella né la cartella dei dati né la libreria con le foto e i video." -!insertmacro MUI_UNPAGE_CONFIRM -!insertmacro MUI_UNPAGE_INSTFILES -!define MUI_FINISHPAGE_TITLE "Febe è stato disinstallato" -!define MUI_FINISHPAGE_TEXT "I dati di Febe non sono stati toccati:$\r$\n$\r$\n- cartella dei dati: $R8$\r$\n- libreria: $R9, o la cartella scelta nelle Impostazioni.$\r$\n$\r$\nLa cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu." -!insertmacro MUI_UNPAGE_FINISH - -!insertmacro MUI_LANGUAGE "Italian" - -LangString DESC_Programma ${LANG_ITALIAN} "Febe.exe, il menu Start e la voce in App installate." -LangString DESC_Desktop ${LANG_ITALIAN} "Un collegamento a Febe sul desktop." - -; ------------------------------------------------------------------------------------------------ funzioni -; Febe in esecuzione tiene aperto Febe.exe: non si può sovrascrivere né cancellare. -!macro FebeChiuso UN -Function ${UN}FebeChiuso - IfFileExists "$INSTDIR\${ESEGUIBILE}" 0 fatto - riprova: - ClearErrors - FileOpen $0 "$INSTDIR\${ESEGUIBILE}" a - ${If} ${Errors} - MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Febe è aperto. Chiudilo dall'area di notifica (clic destro sull'icona ▸ Esci), poi premi Riprova." /SD IDCANCEL IDRETRY riprova - Abort - ${EndIf} - FileClose $0 - fatto: -FunctionEnd -!macroend -!insertmacro FebeChiuso "" -!insertmacro FebeChiuso "un." - -; Il runtime WebView2 (Evergreen) è installato per tutto il computer o solo per l'utente: «pv» è la sua versione. -Function WebView2Presente - StrCpy $1 "" - ReadRegStr $1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" - ${If} $1 == "" - ${OrIf} $1 == "0.0.0.0" - ReadRegStr $1 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" - ${EndIf} - ${If} $1 == "" - ${OrIf} $1 == "0.0.0.0" - ReadRegStr $1 HKCU "Software\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" - ${EndIf} - ${If} $1 == "0.0.0.0" - StrCpy $1 "" - ${EndIf} - Push $1 -FunctionEnd - -; ------------------------------------------------------------------------------------------------ installazione -Section "Febe" SEC_PROGRAMMA - SectionIn RO - Call FebeChiuso - SetOutPath "$INSTDIR" - File "${SORGENTE}/${ESEGUIBILE}" - WriteUninstaller "$INSTDIR\${DISINSTALLA}" - - ; Menu Start (dell'utente). - SetShellVarContext current - CreateShortCut "$SMPROGRAMS\Febe.lnk" "$INSTDIR\${ESEGUIBILE}" "" "$INSTDIR\${ESEGUIBILE}" 0 SW_SHOWNORMAL "" "Archivio personale di foto, video e storie da Instagram" - - ; App installate (Programmi e funzionalità), per l'utente. - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayName" "${NOME}" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayVersion" "${VERSION}" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "Publisher" "${EDITORE}" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayIcon" "$INSTDIR\${ESEGUIBILE},0" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "InstallLocation" "$INSTDIR" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "UninstallString" '"$INSTDIR\${DISINSTALLA}"' - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "QuietUninstallString" '"$INSTDIR\${DISINSTALLA}" /S' - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "URLInfoAbout" "${SITO}" - WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "NoModify" 1 - WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "NoRepair" 1 - ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2 - WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "EstimatedSize" "$0" - - ; WebView2: senza, Febe non può mostrare nulla. Lo dice anche Febe al primo avvio. - Call WebView2Presente - Pop $1 - ${If} $1 == "" - DetailPrint "Runtime WebView2 di Microsoft: non trovato." - MessageBox MB_YESNO|MB_ICONINFORMATION "Febe ha bisogno del runtime WebView2 di Microsoft, che su questo computer non c'è (Windows 11 e quasi tutti i Windows 10 lo hanno già).$\r$\n$\r$\nSi installa gratis dalla pagina ufficiale di Microsoft, senza permessi di amministratore. Vuoi aprirla adesso?" /SD IDNO IDNO fine_webview2 - ExecShell "open" "${WEBVIEW2_PAGINA}" - fine_webview2: - ${Else} - DetailPrint "Runtime WebView2 di Microsoft: $1." - ${EndIf} -SectionEnd - -Section "Collegamento sul desktop" SEC_DESKTOP - SetShellVarContext current - CreateShortCut "$DESKTOP\Febe.lnk" "$INSTDIR\${ESEGUIBILE}" "" "$INSTDIR\${ESEGUIBILE}" 0 SW_SHOWNORMAL "" "Archivio personale di foto, video e storie da Instagram" -SectionEnd - -!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN - !insertmacro MUI_DESCRIPTION_TEXT ${SEC_PROGRAMMA} $(DESC_Programma) - !insertmacro MUI_DESCRIPTION_TEXT ${SEC_DESKTOP} $(DESC_Desktop) -!insertmacro MUI_FUNCTION_DESCRIPTION_END - -; ------------------------------------------------------------------------------------------------ disinstallazione -Function un.onInit - ; Dove sono i dati, per dirlo alla fine: la cartella scelta nelle Impostazioni o quella predefinita. - ReadRegStr $R8 HKCU "${CHIAVE_FEBE}" "CartellaDati" - ${If} $R8 == "" - StrCpy $R8 "$LOCALAPPDATA\Febe" - ${EndIf} - StrCpy $R9 "$PICTURES\Febe" -FunctionEnd - -; «Avvia con il computer» dei Febe avviati con --dati (un secondo account): valori «Febe-…» che avviano questo Febe.exe. -Function un.TogliAvviiConDati - StrCpy $3 '"$INSTDIR\${ESEGUIBILE}"' - StrLen $4 $3 - StrCpy $0 0 - ciclo: - ClearErrors - EnumRegValue $1 HKCU "${CHIAVE_AVVIO}" $0 - IfErrors fine - StrCmp $1 "" fine - StrCpy $2 $1 5 - ${If} $2 == "Febe-" - ReadRegStr $5 HKCU "${CHIAVE_AVVIO}" $1 - StrCpy $6 $5 $4 - ${If} $6 == $3 - DeleteRegValue HKCU "${CHIAVE_AVVIO}" $1 - ; Il valore successivo prende il posto di quello tolto: stesso indice. - Goto ciclo - ${EndIf} - ${EndIf} - IntOp $0 $0 + 1 - Goto ciclo - fine: -FunctionEnd - -Section "Uninstall" - Call un.FebeChiuso - SetShellVarContext current - - ; Solo i file del programma. MAI la cartella dei dati, MAI la libreria: non si chiede nulla su di loro. - Delete "$INSTDIR\${ESEGUIBILE}" - Delete "$INSTDIR\${DISINSTALLA}" - RMDir "$INSTDIR" - Delete "$SMPROGRAMS\Febe.lnk" - Delete "$DESKTOP\Febe.lnk" - - ; «Avvia Febe all'accensione del computer» punterebbe a un programma che non c'è più: il valore «Febe» e quelli - ; «Febe-…» dei Febe avviati con --dati. - DeleteRegValue HKCU "${CHIAVE_AVVIO}" "Febe" - Call un.TogliAvviiConDati - DeleteRegKey HKCU "${CHIAVE_DISINSTALLA}" - - ; Le librerie native che Febe.exe estrae da sé al primo avvio (non sono dati). - RMDir /r "$TEMP\.net\Febe" - - DetailPrint "I dati restano: cartella dei dati $R8; libreria $R9 (o quella scelta nelle Impostazioni)." - DetailPrint "La cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu." -SectionEnd diff --git a/src/Febe.Desktop.Core/BrandIcon.cs b/src/Febe.Desktop.Core/BrandIcon.cs index 88c3e38..4e26a52 100644 --- a/src/Febe.Desktop.Core/BrandIcon.cs +++ b/src/Febe.Desktop.Core/BrandIcon.cs @@ -74,7 +74,7 @@ public static class BrandMark /// /// Writes Windows .ico files by hand (no package for it, spec §3): the 256-pixel image as PNG, the smaller ones as /// 32-bit DIBs (BGRA with alpha, bottom-up, plus the 1-bit AND mask), which every part of Windows reads — window icons, -/// the notification area, Explorer, NSIS. +/// the notification area, Explorer, the installer. /// public static class IcoWriter { diff --git a/src/Febe.Desktop/LEGGIMI.md b/src/Febe.Desktop/LEGGIMI.md index 7868c2f..062927d 100644 --- a/src/Febe.Desktop/LEGGIMI.md +++ b/src/Febe.Desktop/LEGGIMI.md @@ -44,4 +44,5 @@ Regole che valgono anche qui: ## Pubblicazione `installer/costruisci.sh` pubblica un solo `Febe.exe` (autosufficiente, compresso, librerie native incluse) e ne fa -`out/Febe-Setup-.exe` (NSIS, `installer/febe.nsi`) e `out/Febe--portabile.zip`. +`out/Febe-Setup-.exe` (il programma di installazione nostro, `src/Febe.Installer`) e +`out/Febe--portabile.zip`. diff --git a/src/Febe.Installer/CommandLine.cs b/src/Febe.Installer/CommandLine.cs new file mode 100644 index 0000000..7ab3073 --- /dev/null +++ b/src/Febe.Installer/CommandLine.cs @@ -0,0 +1,143 @@ +namespace Febe.Installer; + +/// What the build asks of the tool (never on Windows of Alberto: in the CI and in installer/costruisci.sh). +internal enum ToolCommand +{ + None, + + /// --impacchetta <installer> <Febe.exe> <version> <output> + Pack, + + /// --verifica <package> <Febe.exe> + Verify, + + /// --zip <output> <file>... + Zip, +} + +/// +/// The command line of the installer and of the uninstaller, the same options as the installer before 18 November 2026: +/// +/// /S: silent, no dialog; the desktop shortcut is created, Febe is not started, an open Febe is an error. +/// /D=<folder>: the program folder (only the installer); last, it takes the rest of the line even +/// with spaces, as before. +/// /PROVA=<folder>: for the tests, every folder and key under that one (). +/// +/// Internal to the uninstaller, which starts a copy of itself from %TEMP% so it can delete its own file: +/// /_?=<program folder> and /ATTENDI=<process>. +/// +internal sealed record CommandLine +{ + public bool Silent { get; init; } + + public string? InstallFolder { get; init; } + + public string? TestRoot { get; init; } + + public string? UninstallFolder { get; init; } + + public int? WaitFor { get; init; } + + public ToolCommand Tool { get; init; } + + public IReadOnlyList ToolArguments { get; init; } = []; + + /// The options again, for the copy of the uninstaller (all but the internal ones). + public IReadOnlyList PassOn() + { + var arguments = new List(); + if (Silent) + { + arguments.Add("/S"); + } + + if (TestRoot is not null) + { + arguments.Add("/PROVA=" + TestRoot); + } + + return arguments; + } + + /// Reads ; an unknown option is an error with its text. + /// An option that does not exist or lacks its value. + public static CommandLine Parse(IReadOnlyList arguments) + { + if (arguments.Count > 0 && arguments[0].StartsWith("--", StringComparison.Ordinal)) + { + var tool = arguments[0] switch + { + "--impacchetta" => ToolCommand.Pack, + "--verifica" => ToolCommand.Verify, + "--zip" => ToolCommand.Zip, + _ => throw new ArgumentException($"Opzione sconosciuta: «{arguments[0]}»."), + }; + var rest = arguments.Skip(1).ToArray(); + var valid = tool switch + { + ToolCommand.Pack => rest.Length == 4, + ToolCommand.Verify => rest.Length == 2, + _ => rest.Length >= 2, + }; + if (!valid) + { + throw new ArgumentException(tool switch + { + ToolCommand.Pack => "Uso: --impacchetta ", + ToolCommand.Verify => "Uso: --verifica ", + _ => "Uso: --zip ...", + }); + } + + return new CommandLine { Tool = tool, ToolArguments = rest }; + } + + var line = new CommandLine(); + for (var i = 0; i < arguments.Count; i++) + { + var argument = arguments[i]; + if (string.Equals(argument, "/S", StringComparison.OrdinalIgnoreCase)) + { + line = line with { Silent = true }; + } + else if (argument.StartsWith("/D=", StringComparison.OrdinalIgnoreCase)) + { + // The last option: the rest of the line is the folder even when unquoted. + var folder = string.Join(' ', [argument[3..], .. arguments.Skip(i + 1)]); + line = line with { InstallFolder = Folder(folder, "/D=") }; + break; + } + else if (argument.StartsWith("/PROVA=", StringComparison.OrdinalIgnoreCase)) + { + line = line with { TestRoot = Folder(argument[7..], "/PROVA=") }; + } + else if (argument.StartsWith("/_?=", StringComparison.Ordinal)) + { + line = line with { UninstallFolder = Folder(argument[4..], "/_?=") }; + } + else if (argument.StartsWith("/ATTENDI=", StringComparison.OrdinalIgnoreCase) + && int.TryParse(argument.AsSpan(9), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var process) + && process > 0) + { + line = line with { WaitFor = process }; + } + else + { + throw new ArgumentException($"Opzione sconosciuta: «{argument}». Le opzioni sono /S e /D=."); + } + } + + return line; + } + + private static string Folder(string value, string option) + { + var folder = value.Trim().Trim('"'); + if (folder.Length == 0 || !Path.IsPathFullyQualified(folder)) + { + throw new ArgumentException($"{option} vuole un percorso completo, per esempio {option}D:\\Programmi\\Febe."); + } + + return Path.TrimEndingDirectorySeparator(folder); + } +} diff --git a/src/Febe.Installer/Febe.Installer.csproj b/src/Febe.Installer/Febe.Installer.csproj new file mode 100644 index 0000000..87e8a17 --- /dev/null +++ b/src/Febe.Installer/Febe.Installer.csproj @@ -0,0 +1,42 @@ + + + + WinExe + Febe.Installer + Febe.Installer + Installazione di Febe + Installazione di Febe + ..\Febe.Desktop\Febe.ico + app.manifest + true + true + true + true + + + + true + true + true + true + none + false + false + false + false + + + + + + diff --git a/src/Febe.Installer/ISystemAccess.cs b/src/Febe.Installer/ISystemAccess.cs new file mode 100644 index 0000000..476ccd6 --- /dev/null +++ b/src/Febe.Installer/ISystemAccess.cs @@ -0,0 +1,48 @@ +namespace Febe.Installer; + +/// A shortcut (.lnk) to write. +internal sealed record Shortcut(string Path, string Target, string WorkingDirectory, string Description, string IconPath, int IconIndex); + +/// +/// What the installation asks of Windows besides files: the registry of the current user (and only reading that of +/// the machine), shortcuts, opening an address, starting a process. The real one is WindowsSystem; the tests use +/// a fake, so the logic of and runs on Linux too. Writing for every +/// user is not even possible through this interface: nothing of the installation needs administrator rights. +/// +internal interface ISystemAccess +{ + /// A string value under HKEY_CURRENT_USER; null when the key or the value is missing or not a string. + string? ReadUserString(string key, string name); + + /// A DWORD value under HKEY_CURRENT_USER; null when missing. + int? ReadUserDword(string key, string name); + + void WriteUserString(string key, string name, string value); + + void WriteUserDword(string key, string name, int value); + + /// The names of the values of a key of HKEY_CURRENT_USER, empty when the key is missing. + IReadOnlyList UserValueNames(string key); + + void DeleteUserValue(string key, string name); + + /// Deletes a key of HKEY_CURRENT_USER with everything under it; nothing when it is missing. + void DeleteUserKeyTree(string key); + + /// A string value under HKEY_LOCAL_MACHINE (64-bit view), only read. + string? ReadMachineString(string key, string name); + + void CreateShortcut(Shortcut shortcut); + + /// Opens an address in the default browser. + void OpenAddress(string address); + + /// Starts a program and does not wait for it. + void Start(string executable, IReadOnlyList arguments, string workingDirectory); + + /// Waits until the process has ended, at most . + void WaitForExit(int processId, TimeSpan timeout); + + /// Waits a little before trying again (a file still held by a process that is ending). + void Pause(TimeSpan delay); +} diff --git a/src/Febe.Installer/Locations.cs b/src/Febe.Installer/Locations.cs new file mode 100644 index 0000000..0a5e5bc --- /dev/null +++ b/src/Febe.Installer/Locations.cs @@ -0,0 +1,86 @@ +namespace Febe.Installer; + +/// +/// Where the installation writes: the folders of the user and the root of the registry keys of Febe. For the user +/// these are the folders of Windows (); for the tests everything moves under one folder and one +/// registry key of its own (, option /PROVA=), so a test never touches the real Start menu, +/// the real desktop or the real entries of an installed Febe. +/// +internal sealed record Locations +{ + /// %LOCALAPPDATA%: the default program folder is under it, and the default Data folder. + public required string LocalAppData { get; init; } + + /// The Programs folder of the user's Start menu. + public required string StartMenuPrograms { get; init; } + + public required string Desktop { get; init; } + + public required string Pictures { get; init; } + + public required string Temp { get; init; } + + /// Empty for the user; for a test, the key under which every key of Febe is written. + public string RegistryRoot { get; init; } = string.Empty; + + /// The folder given with /PROVA=, null for the user. + public string? TestRoot { get; init; } + + public string DefaultInstallFolder => Path.Combine(LocalAppData, "Programs", Product.Name); + + public string StartMenuShortcut => Path.Combine(StartMenuPrograms, Product.ShortcutName); + + public string DesktopShortcut => Path.Combine(Desktop, Product.ShortcutName); + + public string DefaultDataFolder => Path.Combine(LocalAppData, Product.Name); + + public string Library => Path.Combine(Pictures, Product.Name); + + /// Where Febe.exe, a single file, extracts its native libraries on the first start (not data). + public string ExtractionFolder => Path.Combine(Temp, ".net", Product.Name); + + public string UninstallKey => RegistryRoot + Product.UninstallKey; + + public string FebeKey => RegistryRoot + Product.FebeKey; + + public string RunKey => RegistryRoot + Product.RunKey; + + /// The folders of Windows for the current user. + public static Locations ForUser() => new() + { + LocalAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + StartMenuPrograms = Environment.GetFolderPath(Environment.SpecialFolder.Programs), + Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), + Pictures = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), + Temp = Path.TrimEndingDirectorySeparator(Path.GetTempPath()), + }; + + /// + /// Everything under : AppData, Menu, Desktop, Immagini and Temp inside it, and the keys under + /// HKCU\Software\FebeProve\<name of the folder>. + /// + public static Locations ForTest(string root) + { + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + var name = Path.GetFileName(full); + if (name.Length == 0 || name.Contains('\\', StringComparison.Ordinal)) + { + throw new ArgumentException("Cartella di prova non valida.", nameof(root)); + } + + return new() + { + LocalAppData = Path.Combine(full, "AppData"), + StartMenuPrograms = Path.Combine(full, "Menu"), + Desktop = Path.Combine(full, "Desktop"), + Pictures = Path.Combine(full, "Immagini"), + Temp = Path.Combine(full, "Temp"), + RegistryRoot = TestRegistryRoot(full), + TestRoot = full, + }; + } + + /// The registry key under which a test installation in writes. + public static string TestRegistryRoot(string root) => + @"Software\FebeProve\" + Path.GetFileName(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root))) + @"\"; +} diff --git a/src/Febe.Installer/Package.cs b/src/Febe.Installer/Package.cs new file mode 100644 index 0000000..d92bd61 --- /dev/null +++ b/src/Febe.Installer/Package.cs @@ -0,0 +1,405 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; + +namespace Febe.Installer; + +/// What a package is: the installer with Febe.exe inside, or the uninstaller left in the program folder. +internal enum PackageKind +{ + Installer = 1, + Uninstaller = 2, +} + +/// The footer of a package, read back. +internal sealed record PackageInfo( + PackageKind Kind, + long ProgramStart, + long DataLength, + long ProgramLength, + byte[] ProgramHash, + string Version) +{ + /// The length of the program itself (the published installer), before the data: where the data start. + public long StubLength => ProgramStart; +} + +/// +/// The package: the published installer (a .NET single file) followed by Febe.exe compressed with Brotli, the version +/// and a fixed footer of bytes at the very end. The host of a single file finds its bundle +/// through an offset written inside the executable, not from the end of the file, so what follows does not disturb it. +/// The uninstaller is the same program with a footer of its own and no data. +/// +/// [installer][Febe.exe, Brotli][version, UTF-8][footer] +/// footer, little-endian: «FEBE-PKG» · format 1 (int32) · kind (int32) · length of the installer (int64) +/// · length of the data (int64) · length of Febe.exe (int64) · length of the version (int32) +/// · SHA-256 of Febe.exe (32 bytes) · 0 (int32) +/// +/// +internal static partial class Package +{ + public const int FooterLength = 80; + + private const int FormatVersion = 1; + + private const int MaxVersionLength = 64; + + /// Brotli: quality 5 and a 16 MB window, a few seconds for Febe.exe and within 1% of the best. + private const int Quality = 5; + + private const int Window = 24; + + private const int BufferSize = 1 << 20; + + private static ReadOnlySpan Magic => "FEBE-PKG"u8; + + /// The footer of ; null when the file is not a package (no footer at the end). + /// The footer is there but does not describe the file. + public static PackageInfo? Read(string path) + { + using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + return Read(file); + } + + /// + public static PackageInfo? Read(FileStream file) + { + var length = file.Length; + if (length < FooterLength) + { + return null; + } + + Span footer = stackalloc byte[FooterLength]; + file.Position = length - FooterLength; + file.ReadExactly(footer); + if (!footer[..8].SequenceEqual(Magic)) + { + return null; + } + + var format = BinaryPrimitives.ReadInt32LittleEndian(footer[8..]); + var kind = (PackageKind)BinaryPrimitives.ReadInt32LittleEndian(footer[12..]); + var programStart = BinaryPrimitives.ReadInt64LittleEndian(footer[16..]); + var dataLength = BinaryPrimitives.ReadInt64LittleEndian(footer[24..]); + var programLength = BinaryPrimitives.ReadInt64LittleEndian(footer[32..]); + var versionLength = BinaryPrimitives.ReadInt32LittleEndian(footer[40..]); + var hash = footer.Slice(44, 32).ToArray(); + if (format != FormatVersion + || kind is not (PackageKind.Installer or PackageKind.Uninstaller) + || programStart <= 0 || dataLength < 0 || programLength < 0 + || versionLength <= 0 || versionLength > MaxVersionLength + || programStart + dataLength + versionLength + FooterLength != length + || (kind == PackageKind.Uninstaller && (dataLength != 0 || programLength != 0)) + || (kind == PackageKind.Installer && (dataLength == 0 || programLength == 0))) + { + throw new InvalidDataException(Texts.Damaged); + } + + Span versionBytes = stackalloc byte[versionLength]; + file.Position = programStart + dataLength; + file.ReadExactly(versionBytes); + var version = Encoding.UTF8.GetString(versionBytes); + if (!IsVersion(version)) + { + throw new InvalidDataException(Texts.Damaged); + } + + return new PackageInfo(kind, programStart, dataLength, programLength, hash, version); + } + + /// A version as the build writes it: x.y.z, optionally followed by -something or +something. + public static bool IsVersion(string? version) => + version is { Length: > 0 and <= MaxVersionLength } && VersionPattern().IsMatch(version); + + /// + /// Writes the package : the published installer , then + /// (Febe.exe) compressed, the version and the footer. Written beside and renamed at the + /// end, so a failure never leaves half a package. + /// + public static PackageInfo Write(string installer, string program, string version, string output) + { + if (!IsVersion(version)) + { + throw new ArgumentException($"Versione non valida: «{version}» (serve x.y.z).", nameof(version)); + } + + if (Read(installer) is not null) + { + throw new ArgumentException("Il programma di installazione contiene già un pacchetto: serve quello appena pubblicato.", nameof(installer)); + } + + var partial = output + ".part"; + try + { + PackageInfo info; + using (var target = new FileStream(partial, FileMode.Create, FileAccess.Write, FileShare.None)) + { + using (var source = File.OpenRead(installer)) + { + source.CopyTo(target, BufferSize); + } + + var programStart = target.Position; + if (programStart == 0) + { + throw new ArgumentException("Il programma di installazione è vuoto.", nameof(installer)); + } + + byte[] hash; + long programLength; + using (var source = File.OpenRead(program)) + { + (programLength, hash) = Compress(source, target); + } + + if (programLength == 0) + { + throw new ArgumentException("Il programma da installare è vuoto.", nameof(program)); + } + + var dataLength = target.Position - programStart; + info = new PackageInfo(PackageKind.Installer, programStart, dataLength, programLength, hash, version); + WriteTail(target, info); + target.Flush(flushToDisk: true); + } + + File.Move(partial, output, overwrite: true); + return info; + } + catch + { + TryDelete(partial); + throw; + } + } + + /// + /// Decompresses Febe.exe from the package into , checking + /// its length and SHA-256; gets the share written, from 0 to 1. + /// + /// The data are not the program the footer describes. + public static void ExtractProgram(string package, PackageInfo info, string destination, Action? progress = null) + { + if (info.Kind != PackageKind.Installer) + { + throw new InvalidOperationException("Il pacchetto non contiene Febe."); + } + + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + using var file = new FileStream(package, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1, FileOptions.SequentialScan); + using var slice = new SliceStream(file, info.ProgramStart, info.DataLength); + using var brotli = new BrotliStream(slice, CompressionMode.Decompress); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using var target = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None, 1, FileOptions.SequentialScan); + target.SetLength(info.ProgramLength); + long written = 0; + while (true) + { + int read; + try + { + read = brotli.Read(buffer, 0, BufferSize); + } + catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or EndOfStreamException) + { + // Brotli refuses the data, or they end before the footer says. + throw new InvalidDataException(Texts.Damaged, ex); + } + + if (read == 0) + { + break; + } + + written += read; + if (written > info.ProgramLength) + { + throw new InvalidDataException(Texts.Damaged); + } + + hash.AppendData(buffer, 0, read); + target.Write(buffer, 0, read); + progress?.Invoke((double)written / info.ProgramLength); + } + + Span actual = stackalloc byte[32]; + hash.GetHashAndReset(actual); + if (written != info.ProgramLength || !actual.SequenceEqual(info.ProgramHash)) + { + throw new InvalidDataException(Texts.Damaged); + } + + target.Flush(flushToDisk: true); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// + /// Writes the uninstaller into : the program of without + /// Febe.exe, with a footer of kind and the same version. + /// + public static void WriteUninstaller(string package, PackageInfo info, string destination) + { + using var source = new FileStream(package, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + using var target = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None); + using (var program = new SliceStream(source, 0, info.StubLength)) + { + program.CopyTo(target, BufferSize); + } + + WriteTail(target, new PackageInfo(PackageKind.Uninstaller, info.StubLength, 0, 0, new byte[32], info.Version)); + target.Flush(flushToDisk: true); + } + + private static (long Length, byte[] Hash) Compress(Stream source, Stream target) + { + var input = ArrayPool.Shared.Rent(BufferSize); + var output = ArrayPool.Shared.Rent(BufferSize); + try + { + using var encoder = new BrotliEncoder(Quality, Window); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + long length = 0; + while (true) + { + var read = source.Read(input, 0, BufferSize); + var final = read == 0; + length += read; + hash.AppendData(input, 0, read); + var pending = input.AsSpan(0, read); + while (true) + { + var status = encoder.Compress(pending, output, out var consumed, out var produced, final); + target.Write(output, 0, produced); + pending = pending[consumed..]; + if (status is OperationStatus.Done or OperationStatus.NeedMoreData) + { + break; + } + + if (status == OperationStatus.InvalidData) + { + throw new InvalidDataException("Compressione non riuscita."); + } + } + + if (final) + { + return (length, hash.GetHashAndReset()); + } + } + } + finally + { + ArrayPool.Shared.Return(input); + ArrayPool.Shared.Return(output); + } + } + + private static void WriteTail(Stream target, PackageInfo info) + { + var version = Encoding.UTF8.GetBytes(info.Version); + target.Write(version); + Span footer = stackalloc byte[FooterLength]; + footer.Clear(); + Magic.CopyTo(footer); + BinaryPrimitives.WriteInt32LittleEndian(footer[8..], FormatVersion); + BinaryPrimitives.WriteInt32LittleEndian(footer[12..], (int)info.Kind); + BinaryPrimitives.WriteInt64LittleEndian(footer[16..], info.ProgramStart); + BinaryPrimitives.WriteInt64LittleEndian(footer[24..], info.DataLength); + BinaryPrimitives.WriteInt64LittleEndian(footer[32..], info.ProgramLength); + BinaryPrimitives.WriteInt32LittleEndian(footer[40..], version.Length); + info.ProgramHash.CopyTo(footer[44..]); + target.Write(footer); + } + + internal static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Our own temporary file: left behind, it is overwritten next time. + } + } + + [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$", RegexOptions.CultureInvariant)] + private static partial Regex VersionPattern(); +} + +/// A read-only window on a part of a stream, which it never closes. +internal sealed class SliceStream : Stream +{ + private readonly Stream _inner; + private readonly long _start; + private readonly long _length; + private long _position; + + public SliceStream(Stream inner, long start, long length) + { + _inner = inner; + _start = start; + _length = length; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => _length; + + public override long Position + { + get => _position; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var left = _length - _position; + if (left <= 0 || buffer.IsEmpty) + { + return 0; + } + + if (buffer.Length > left) + { + buffer = buffer[..(int)left]; + } + + _inner.Position = _start + _position; + var read = _inner.Read(buffer); + if (read == 0) + { + throw new EndOfStreamException(); + } + + _position += read; + return read; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/src/Febe.Installer/Product.cs b/src/Febe.Installer/Product.cs new file mode 100644 index 0000000..7c9aa3f --- /dev/null +++ b/src/Febe.Installer/Product.cs @@ -0,0 +1,46 @@ +namespace Febe.Installer; + +/// +/// The fixed facts of the installation (spec §12, question 6 of §16): names, registry keys and addresses. The keys +/// , and the values under them are those Febe for Windows writes itself +/// (RegistryLocationStore and Autostart in the desktop projects); a test checks they agree. +/// +internal static class Product +{ + public const string Name = "Febe"; + + public const string Publisher = "Alberto Balbo"; + + public const string Executable = "Febe.exe"; + + public const string Uninstaller = "Disinstalla Febe.exe"; + + public const string ShortcutName = "Febe.lnk"; + + public const string ShortcutDescription = "Archivio personale di foto, video e storie da Instagram"; + + /// Apps installed (Programs and Features), per user, under HKEY_CURRENT_USER. + public const string UninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe"; + + /// Febe's own key: «CartellaDati» says where the data are after a move (spec §12). + public const string FebeKey = @"Software\Febe"; + + public const string DataFolderValue = "CartellaDati"; + + /// «Start Febe with the computer»: the value «Febe» and, for a Febe started with --dati, «Febe-…». + public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + + public const string AutostartValue = "Febe"; + + public const string AutostartPrefix = "Febe-"; + + /// The Evergreen runtime of WebView2: «pv» under this client of EdgeUpdate is its version. + public const string EdgeUpdateClient = @"Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"; + + public const string WebView2Page = "https://developer.microsoft.com/microsoft-edge/webview2/"; + + public const string Site = "https://gitea.encke-hake.ts.net/Alby96/Febe"; + + /// The prefix of the copies of the uninstaller that run from the temporary folder. + public const string UninstallerCopyPrefix = "Febe-disinstalla-"; +} diff --git a/src/Febe.Installer/Program.cs b/src/Febe.Installer/Program.cs new file mode 100644 index 0000000..dedfc5f --- /dev/null +++ b/src/Febe.Installer/Program.cs @@ -0,0 +1,187 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using Febe.Installer.Windows; + +namespace Febe.Installer; + +/// +/// The entry point. With a package footer at the end of its own file it is the installer (Febe.exe inside) or the +/// uninstaller; with --impacchetta, --verifica or --zip it is the build tool, on any system. +/// +internal static class Program +{ + [STAThread] + public static int Main(string[] args) + { + CommandLine line; + try + { + line = CommandLine.Parse(args); + } + catch (ArgumentException ex) + { + return Report(ex.Message, args); + } + + if (line.Tool != ToolCommand.None) + { + return RunTool(line); + } + + if (!OperatingSystem.IsWindows()) + { + Console.Error.WriteLine(Texts.WindowsOnly); + return ExitCodes.Failed; + } + + return RunOnWindows(line); + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static int RunOnWindows(CommandLine line) + { + var self = Environment.ProcessPath; + var locations = line.TestRoot is { } root ? Locations.ForTest(root) : Locations.ForUser(); + // With /S the reason of a failure goes to the standard error, in UTF-8 whatever the code page of the console. + ISetupInterface ui = line.Silent + ? new SilentInterface(new StreamWriter(Console.OpenStandardError(), new System.Text.UTF8Encoding(false)) { AutoFlush = true }) + : new DialogInterface(locations); + PackageInfo? package; + try + { + package = self is null ? null : Package.Read(self); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + ui.Failed(uninstalling: false, Texts.Failure(ex)); + return ExitCodes.Failed; + } + + if (package is null || self is null) + { + ui.Failed(uninstalling: false, Texts.NoPackage); + return ExitCodes.Failed; + } + + SetupFlow.RemoveOldUninstallerCopies(locations, self); + var flow = new SetupFlow(new WindowsSystem(), locations, ui); + try + { + return package.Kind == PackageKind.Installer ? flow.Install(self, package, line) : flow.Uninstall(self, line); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or System.ComponentModel.Win32Exception or System.Runtime.InteropServices.COMException) + { + ui.Failed(package.Kind == PackageKind.Uninstaller, Texts.Failure(ex)); + return ExitCodes.Failed; + } + } + + /// A wrong command line: said in a dialog, or on the standard error with /S or for the build tool. + private static int Report(string message, string[] args) + { + var silent = args.Any(a => string.Equals(a, "/S", StringComparison.OrdinalIgnoreCase)); + if (OperatingSystem.IsWindows() && !silent && !(args.Length > 0 && args[0].StartsWith("--", StringComparison.Ordinal))) + { + new DialogInterface(Locations.ForUser()).Failed(uninstalling: false, message); + } + else + { + Console.Error.WriteLine(message); + } + + return ExitCodes.Failed; + } + + private static int RunTool(CommandLine line) + { + var a = line.ToolArguments; + try + { + switch (line.Tool) + { + case ToolCommand.Pack: + { + var info = Package.Write(a[0], a[1], a[2], a[3]); + Console.WriteLine($"Pacchetto {Path.GetFileName(a[3])}: programma {info.StubLength / 1048576.0:F1} MB, Febe.exe {info.ProgramLength / 1048576.0:F1} MB compresso in {info.DataLength / 1048576.0:F1} MB, versione {info.Version}."); + return ExitCodes.Done; + } + + case ToolCommand.Verify: + return Verify(a[0], a[1]); + + default: + Zip(a[0], a.Skip(1).ToArray()); + Console.WriteLine($"Zip {Path.GetFileName(a[0])}: {a.Count - 1} file."); + return ExitCodes.Done; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException) + { + Console.Error.WriteLine(ex.Message); + return ExitCodes.Failed; + } + } + + /// + /// Checks a package as the installer will read it: a footer of an installer, and inside exactly + /// , decompressed to a file beside and compared byte for byte (then deleted). + /// + private static int Verify(string packagePath, string program) + { + var info = Package.Read(packagePath); + if (info is not { Kind: PackageKind.Installer }) + { + Console.Error.WriteLine($"{packagePath} non è un programma di installazione di Febe."); + return ExitCodes.Failed; + } + + var extracted = packagePath + ".verifica"; + try + { + Package.ExtractProgram(packagePath, info, extracted); + if (!SameContent(extracted, program)) + { + Console.Error.WriteLine($"Il Febe.exe dentro {Path.GetFileName(packagePath)} non è {program}."); + return ExitCodes.Failed; + } + } + finally + { + Package.TryDelete(extracted); + } + + Console.WriteLine($"{Path.GetFileName(packagePath)}: Febe {info.Version}, Febe.exe integro ({info.ProgramLength} byte)."); + return ExitCodes.Done; + } + + private static bool SameContent(string a, string b) + { + using var first = File.OpenRead(a); + using var second = File.OpenRead(b); + return first.Length == second.Length && SHA256.HashData(first).AsSpan().SequenceEqual(SHA256.HashData(second)); + } + + /// The portable zip: each file at the top, by its name, at the strongest compression of Deflate. + internal static void Zip(string output, IReadOnlyList files) + { + var partial = output + ".part"; + try + { + using (var stream = new FileStream(partial, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var archive = new ZipArchive(stream, ZipArchiveMode.Create)) + { + foreach (var file in files) + { + archive.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.SmallestSize); + } + } + + File.Move(partial, output, overwrite: true); + } + catch + { + Package.TryDelete(partial); + throw; + } + } +} diff --git a/src/Febe.Installer/SetupActions.cs b/src/Febe.Installer/SetupActions.cs new file mode 100644 index 0000000..2436d9c --- /dev/null +++ b/src/Febe.Installer/SetupActions.cs @@ -0,0 +1,242 @@ +namespace Febe.Installer; + +/// What an installation asks for: from which package, into which folder, with or without the desktop shortcut. +internal sealed record InstallRequest(string PackagePath, PackageInfo Package, string InstallFolder, bool DesktopShortcut); + +/// +/// The work of the installer and of the uninstaller, without dialogs (spec §12, question 6 of §16): exactly what the +/// installer built with a third-party tool did until 18 November 2026. +/// +/// Per user, without administrator rights, by default in %LOCALAPPDATA%\Programs\Febe. +/// Febe.exe and «Disinstalla Febe.exe»; the shortcut in the Start menu, the one on the desktop if chosen. +/// The uninstall entry under HKCU (Apps installed). +/// An installation over an existing one replaces the program and keeps everything else. +/// The uninstallation removes only the program, its shortcuts, its registry entries and the libraries Febe.exe +/// extracts by itself: NEVER the Data folder or the library, and it asks nothing about them. +/// +/// +internal sealed class SetupActions(ISystemAccess system, Locations locations) +{ + private const string NewSuffix = ".nuovo"; + + public Locations Locations => locations; + + /// + /// True when Febe.exe in is running: a running program cannot be opened for + /// writing, so it could be neither replaced nor deleted. + /// + public static bool IsFebeOpen(string installFolder) + { + var executable = Path.Combine(installFolder, Product.Executable); + if (!File.Exists(executable)) + { + return false; + } + + try + { + using var stream = new FileStream(executable, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete); + return false; + } + catch (IOException) + { + return true; + } + catch (UnauthorizedAccessException) + { + return true; + } + } + + /// The version recorded by an earlier installation, null for none. + public string? InstalledVersion() => system.ReadUserString(locations.UninstallKey, "DisplayVersion"); + + /// + /// The version of the WebView2 runtime of Microsoft, null when it is missing. The Evergreen runtime is installed for + /// the whole computer (32-bit node of the registry on 64-bit Windows) or for the user only; «0.0.0.0» means removed. + /// + public string? WebView2Version() + { + foreach (var value in new[] + { + system.ReadMachineString(@"SOFTWARE\WOW6432Node\" + Product.EdgeUpdateClient, "pv"), + system.ReadMachineString(@"SOFTWARE\" + Product.EdgeUpdateClient, "pv"), + system.ReadUserString(@"Software\" + Product.EdgeUpdateClient, "pv"), + }) + { + if (!string.IsNullOrWhiteSpace(value) && value != "0.0.0.0") + { + return value; + } + } + + return null; + } + + /// Where the data are: the folder chosen in Impostazioni (recorded by Febe) or the default one. + public string DataFolder() => + system.ReadUserString(locations.FebeKey, Product.DataFolderValue) is { Length: > 0 } folder ? folder : locations.DefaultDataFolder; + + /// The command line of the uninstaller, as the uninstall entry records it. + public string UninstallCommand(string installFolder, bool silent) + { + var command = $"\"{Path.Combine(installFolder, Product.Uninstaller)}\""; + if (silent) + { + command += " /S"; + } + + if (locations.TestRoot is { } root) + { + command += $" \"/PROVA={root}\""; + } + + return command; + } + + /// + /// Installs: Febe.exe (written beside and renamed, so an interrupted copy never leaves half a program), the + /// uninstaller, the shortcuts and the uninstall entry. gets the share done, 0 to 1. + /// + public void Install(InstallRequest request, Action? progress = null) + { + var folder = request.InstallFolder; + Directory.CreateDirectory(folder); + var executable = Path.Combine(folder, Product.Executable); + Replace(executable, partial => Package.ExtractProgram(request.PackagePath, request.Package, partial, share => progress?.Invoke(share * 0.95))); + Replace(Path.Combine(folder, Product.Uninstaller), partial => Package.WriteUninstaller(request.PackagePath, request.Package, partial)); + progress?.Invoke(0.97); + + system.CreateShortcut(ShortcutTo(locations.StartMenuShortcut, folder)); + + var key = locations.UninstallKey; + system.WriteUserString(key, "DisplayName", Product.Name); + system.WriteUserString(key, "DisplayVersion", request.Package.Version); + system.WriteUserString(key, "Publisher", Product.Publisher); + system.WriteUserString(key, "DisplayIcon", executable + ",0"); + system.WriteUserString(key, "InstallLocation", folder); + system.WriteUserString(key, "UninstallString", UninstallCommand(folder, silent: false)); + system.WriteUserString(key, "QuietUninstallString", UninstallCommand(folder, silent: true)); + system.WriteUserString(key, "URLInfoAbout", Product.Site); + system.WriteUserDword(key, "NoModify", 1); + system.WriteUserDword(key, "NoRepair", 1); + system.WriteUserDword(key, "EstimatedSize", EstimatedSizeInKb(folder)); + + if (request.DesktopShortcut) + { + system.CreateShortcut(ShortcutTo(locations.DesktopShortcut, folder)); + } + + progress?.Invoke(1); + } + + /// + /// Uninstalls the Febe of : the program files (the folder itself only if nothing + /// else is left in it), the two shortcuts, «Start with the computer» («Febe» and the «Febe-…» values that start + /// this Febe.exe), the uninstall entry and the libraries extracted under %TEMP%. Nothing else. + /// + public void Uninstall(string installFolder) + { + var executable = Path.Combine(installFolder, Product.Executable); + DeleteFile(executable); + DeleteFile(executable + NewSuffix); + DeleteUninstaller(Path.Combine(installFolder, Product.Uninstaller)); + DeleteFile(Path.Combine(installFolder, Product.Uninstaller) + NewSuffix); + try + { + // Only when empty: whatever else is there is not ours to delete. + Directory.Delete(installFolder, recursive: false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + + DeleteFile(locations.StartMenuShortcut); + DeleteFile(locations.DesktopShortcut); + + // «Start Febe with the computer» would point to a program that is no longer there. + system.DeleteUserValue(locations.RunKey, Product.AutostartValue); + var command = $"\"{executable}\""; + foreach (var name in system.UserValueNames(locations.RunKey)) + { + if (name.StartsWith(Product.AutostartPrefix, StringComparison.OrdinalIgnoreCase) + && system.ReadUserString(locations.RunKey, name) is { } value + && value.StartsWith(command, StringComparison.OrdinalIgnoreCase)) + { + system.DeleteUserValue(locations.RunKey, name); + } + } + + system.DeleteUserKeyTree(locations.UninstallKey); + + // The native libraries Febe.exe extracts by itself on the first start: not data. + try + { + if (Directory.Exists(locations.ExtractionFolder)) + { + Directory.Delete(locations.ExtractionFolder, recursive: true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A portable Febe still running holds them: they stay, Windows cleans %TEMP%. + } + } + + private static Shortcut ShortcutTo(string path, string installFolder) + { + var executable = Path.Combine(installFolder, Product.Executable); + return new Shortcut(path, executable, installFolder, Product.ShortcutDescription, executable, 0); + } + + private static void Replace(string path, Action write) + { + var partial = path + NewSuffix; + try + { + write(partial); + File.Move(partial, path, overwrite: true); + } + catch + { + Package.TryDelete(partial); + throw; + } + } + + private static void DeleteFile(string path) + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + + /// The uninstaller that started this one may take a moment to end and release its file. + private void DeleteUninstaller(string path) + { + for (var attempt = 0; ; attempt++) + { + try + { + DeleteFile(path); + return; + } + catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 20) + { + system.Pause(TimeSpan.FromMilliseconds(250)); + } + } + } + + private static int EstimatedSizeInKb(string folder) + { + long bytes = 0; + foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories)) + { + bytes += file.Length; + } + + return (int)Math.Min(int.MaxValue, bytes / 1024); + } +} diff --git a/src/Febe.Installer/SetupFlow.cs b/src/Febe.Installer/SetupFlow.cs new file mode 100644 index 0000000..1688a2e --- /dev/null +++ b/src/Febe.Installer/SetupFlow.cs @@ -0,0 +1,228 @@ +namespace Febe.Installer; + +/// The exit codes of the installer and of the uninstaller. +internal static class ExitCodes +{ + public const int Done = 0; + + /// Alberto said no: «Annulla». + public const int Cancelled = 1; + + /// Something went wrong, or Febe is open in silent mode: nothing was changed, or only the part said. + public const int Failed = 2; +} + +/// +/// The dialogs of the installation: the windows of Windows (DialogInterface) or, with /S, none +/// (). The tests use a fake that answers as told. +/// +internal interface ISetupInterface +{ + /// The first page; null for «Annulla», otherwise whether the desktop shortcut is wanted. + bool? Welcome(string version, string? installedVersion, string installFolder); + + /// Febe is open: true to try again (after closing it), false to give up. + bool RetryWhenFebeIsOpen(bool uninstalling); + + /// Runs showing its progress (0 to 1); its exception comes out of here. + void RunWithProgress(string version, string installFolder, Action> work); + + /// WebView2 is missing: true to open the page of Microsoft. + bool OfferWebView2Page(); + + /// The last page of the installation: true to start Febe now. + bool Installed(); + + bool ConfirmUninstall(); + + void Uninstalled(string dataFolder, string library); + + void Failed(bool uninstalling, string message); +} + +/// +/// /S: no dialog, the answers of the silent mode before: the desktop shortcut yes, Febe open means stop, the page +/// of WebView2 no, Febe not started. A failure goes to the standard error, for whoever started the installer. +/// +internal sealed class SilentInterface(TextWriter errors) : ISetupInterface +{ + public bool? Welcome(string version, string? installedVersion, string installFolder) => true; + + public bool RetryWhenFebeIsOpen(bool uninstalling) => false; + + public void RunWithProgress(string version, string installFolder, Action> work) => work(_ => { }); + + public bool OfferWebView2Page() => false; + + public bool Installed() => false; + + public bool ConfirmUninstall() => true; + + public void Uninstalled(string dataFolder, string library) + { + } + + public void Failed(bool uninstalling, string message) + { + try + { + errors.WriteLine((uninstalling ? Texts.UninstallFailed : Texts.InstallFailed) + ": " + message); + errors.Flush(); + } + catch (IOException) + { + // No one is reading: the exit code says it. + } + } +} + +/// +/// The steps of the installer and of the uninstaller, in the order they always had: first page, Febe closed, copy, +/// WebView2, last page; for the uninstaller: a copy of itself in %TEMP% (an executable cannot delete itself), +/// confirmation, Febe closed, removal, where the data stayed. +/// +internal sealed class SetupFlow(ISystemAccess system, Locations locations, ISetupInterface ui) +{ + private readonly SetupActions _actions = new(system, locations); + + /// The installer: is this program, with Febe.exe inside. + public int Install(string packagePath, PackageInfo package, CommandLine line) + { + var folder = line.InstallFolder ?? locations.DefaultInstallFolder; + var desktop = ui.Welcome(package.Version, _actions.InstalledVersion(), folder); + if (desktop is null) + { + return ExitCodes.Cancelled; + } + + if (!WaitUntilFebeIsClosed(folder, uninstalling: false, line.Silent)) + { + return line.Silent ? ExitCodes.Failed : ExitCodes.Cancelled; + } + + try + { + ui.RunWithProgress(package.Version, folder, progress => + _actions.Install(new InstallRequest(packagePath, package, folder, desktop.Value), progress)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) + { + ui.Failed(uninstalling: false, Texts.Failure(ex)); + return ExitCodes.Failed; + } + + // WebView2: without it Febe cannot show anything. Febe says it too on its first start. + if (_actions.WebView2Version() is null && ui.OfferWebView2Page()) + { + system.OpenAddress(Product.WebView2Page); + } + + if (ui.Installed()) + { + try + { + system.Start(Path.Combine(folder, Product.Executable), [], folder); + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) + { + // Febe is installed all the same; it opens from the Start menu. + } + } + + return ExitCodes.Done; + } + + /// + /// The uninstaller. Started from the program folder ( is «Disinstalla Febe.exe» there), it + /// copies itself into %TEMP%, starts the copy and ends; the copy waits for it, then does the work and can delete + /// the original. + /// + public int Uninstall(string selfPath, CommandLine line) + { + if (line.UninstallFolder is null) + { + var installFolder = Path.GetDirectoryName(Path.GetFullPath(selfPath))!; + Directory.CreateDirectory(locations.Temp); + var copy = Path.Combine(locations.Temp, $"{Product.UninstallerCopyPrefix}{Environment.ProcessId}.exe"); + File.Copy(selfPath, copy, overwrite: true); + system.Start(copy, [.. line.PassOn(), "/_?=" + installFolder, $"/ATTENDI={Environment.ProcessId}"], locations.Temp); + return ExitCodes.Done; + } + + if (line.WaitFor is { } parent) + { + system.WaitForExit(parent, TimeSpan.FromSeconds(30)); + } + + var folder = line.UninstallFolder; + if (!ui.ConfirmUninstall()) + { + return ExitCodes.Cancelled; + } + + if (!WaitUntilFebeIsClosed(folder, uninstalling: true, line.Silent)) + { + return line.Silent ? ExitCodes.Failed : ExitCodes.Cancelled; + } + + // Read before anything is removed, to say at the end where the data stayed. + var dataFolder = _actions.DataFolder(); + try + { + _actions.Uninstall(folder); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + ui.Failed(uninstalling: true, Texts.Failure(ex)); + return ExitCodes.Failed; + } + + ui.Uninstalled(dataFolder, locations.Library); + return ExitCodes.Done; + } + + /// + /// Copies of the uninstaller left in %TEMP% by earlier uninstallations (a running program cannot delete itself): + /// removed when they are no longer running. Never anything else. + /// + public static void RemoveOldUninstallerCopies(Locations locations, string? selfPath) + { + try + { + if (!Directory.Exists(locations.Temp)) + { + return; + } + + foreach (var copy in Directory.EnumerateFiles(locations.Temp, Product.UninstallerCopyPrefix + "*.exe")) + { + if (selfPath is null || !string.Equals(Path.GetFullPath(copy), Path.GetFullPath(selfPath), StringComparison.OrdinalIgnoreCase)) + { + Package.TryDelete(copy); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + private bool WaitUntilFebeIsClosed(string folder, bool uninstalling, bool silent) + { + while (SetupActions.IsFebeOpen(folder)) + { + if (silent) + { + ui.Failed(uninstalling, Texts.FebeOpenSilent); + return false; + } + + if (!ui.RetryWhenFebeIsOpen(uninstalling)) + { + return false; + } + } + + return true; + } +} diff --git a/src/Febe.Installer/Texts.cs b/src/Febe.Installer/Texts.cs new file mode 100644 index 0000000..9347804 --- /dev/null +++ b/src/Febe.Installer/Texts.cs @@ -0,0 +1,99 @@ +namespace Febe.Installer; + +/// What the installer and the uninstaller say, in Italian (glossary: appendix D of the spec). +internal static class Texts +{ + public const string InstallTitle = "Installazione di Febe"; + + public const string UninstallTitle = "Disinstallazione di Febe"; + + public const string Damaged = "Il programma di installazione è rovinato o incompleto: scaricalo di nuovo."; + + public const string NoPackage = "Questo programma non contiene Febe: usa Febe-Setup-.exe dalla pagina delle release."; + + public const string WindowsOnly = "Il programma di installazione di Febe gira solo su Windows."; + + public const string Install = "Installa"; + + public const string Cancel = "Annulla"; + + public const string Retry = "Riprova"; + + public const string Finish = "Fine"; + + public const string Wait = "Attendi"; + + public const string Uninstall = "Disinstalla"; + + public const string OpenPage = "Apri la pagina"; + + public const string NotNow = "Non ora"; + + public const string DesktopShortcut = "Crea un collegamento a Febe sul desktop"; + + public const string RunFebe = "Apri Febe adesso"; + + public static string Welcome(string version, string? installedVersion) => + installedVersion is null ? $"Installazione di Febe {version}" : $"Aggiornamento di Febe alla versione {version}"; + + public static string WelcomeText(Locations locations, string installFolder, string? installedVersion) + { + var text = + "Febe è l'archivio personale di foto, video e storie da Instagram.\n\n" + + $"Verrà installato solo per te, in {installFolder}: non servono permessi di amministratore.\n\n" + + $"I dati di Febe (database e sessione del browser) andranno in {locations.DefaultDataFolder}, le foto e i video " + + "nella cartella Immagini\\Febe; le cartelle si possono cambiare dalle Impostazioni."; + return installedVersion is null + ? text + : $"Febe {installedVersion} è già installato: il programma si sostituisce, i dati, la libreria e le impostazioni restano dove sono.\n\n" + text; + } + + public const string FebeOpen = "Febe è aperto"; + + public const string FebeOpenText = "Chiudilo dall'area di notifica (clic destro sull'icona ▸ Esci), poi premi Riprova."; + + public const string FebeOpenSilent = "Febe è aperto: chiudilo dall'area di notifica (clic destro sull'icona ▸ Esci) e riprova."; + + public static string Installing(string version) => $"Installazione di Febe {version} in corso"; + + public static string InstallingText(string installFolder) => $"Copia di Febe.exe in {installFolder}…"; + + public const string WebView2Missing = "Manca il runtime WebView2 di Microsoft"; + + public const string WebView2MissingText = + "Febe ha bisogno del runtime WebView2 di Microsoft, che su questo computer non c'è (Windows 11 e quasi tutti i " + + "Windows 10 lo hanno già).\n\nSi installa gratis dalla pagina ufficiale di Microsoft, senza permessi di " + + "amministratore. Vuoi aprirla adesso?"; + + public const string Installed = "Febe è installato"; + + public const string InstalledText = + "Febe si apre in una sua finestra e resta attivo nell'area di notifica, accanto all'orologio.\n\n" + + "Per collegarlo a Instagram: Impostazioni ▸ Collegamento. Non usare insieme Febe per Windows e il contenitore " + + "Docker con lo stesso account."; + + public const string InstallFailed = "L'installazione non è riuscita"; + + public const string ConfirmUninstall = "Disinstallare Febe?"; + + public const string ConfirmUninstallText = + "Il programma Febe verrà tolto da questo computer. I tuoi dati restano dove sono: la disinstallazione non " + + "cancella né la cartella dei dati né la libreria con le foto e i video."; + + public const string Uninstalled = "Febe è stato disinstallato"; + + public static string UninstalledText(string dataFolder, string library) => + "I dati di Febe non sono stati toccati:\n\n" + + $"- cartella dei dati: {dataFolder}\n" + + $"- libreria: {library}, o la cartella scelta nelle Impostazioni.\n\n" + + "La cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu."; + + public const string UninstallFailed = "La disinstallazione non è riuscita"; + + public static string Failure(Exception ex) => ex switch + { + InvalidDataException => ex.Message, + UnauthorizedAccessException => $"Windows non permette di scrivere qui: {ex.Message}", + _ => ex.Message, + }; +} diff --git a/src/Febe.Installer/Windows/DialogInterface.cs b/src/Febe.Installer/Windows/DialogInterface.cs new file mode 100644 index 0000000..d6e7c60 --- /dev/null +++ b/src/Febe.Installer/Windows/DialogInterface.cs @@ -0,0 +1,97 @@ +using System.Runtime.Versioning; + +namespace Febe.Installer.Windows; + +/// The pages of the installer and of the uninstaller, as dialogs of Windows (texts: ). +[SupportedOSPlatform("windows")] +internal sealed class DialogInterface(Locations locations) : ISetupInterface +{ + private const int Yes = 100; + + private const int Cancel = TaskDialog.CancelId; + + public bool? Welcome(string version, string? installedVersion, string installFolder) + { + var (button, desktop) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( + Texts.Welcome(version, installedVersion), + Texts.WelcomeText(locations, installFolder, installedVersion), + [(Yes, Texts.Install), (Cancel, Texts.Cancel)]) + { + Verification = Texts.DesktopShortcut, + VerificationChecked = true, + }); + return button == Yes ? desktop : null; + } + + public bool RetryWhenFebeIsOpen(bool uninstalling) + { + var (button, _) = TaskDialog.Show(Title(uninstalling), new DialogPage( + Texts.FebeOpen, + Texts.FebeOpenText, + [(Yes, Texts.Retry), (Cancel, Texts.Cancel)]) + { + Icon = DialogIcon.Warning, + }); + return button == Yes; + } + + public void RunWithProgress(string version, string installFolder, Action> work) => + TaskDialog.ShowProgress(Texts.InstallTitle, new DialogPage( + Texts.Installing(version), + Texts.InstallingText(installFolder), + [(Yes, Texts.Wait)]), work); + + public bool OfferWebView2Page() + { + var (button, _) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( + Texts.WebView2Missing, + Texts.WebView2MissingText, + [(Yes, Texts.OpenPage), (Cancel, Texts.NotNow)]) + { + Icon = DialogIcon.Information, + }); + return button == Yes; + } + + public bool Installed() + { + var (_, run) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( + Texts.Installed, + Texts.InstalledText, + [(Yes, Texts.Finish)]) + { + Verification = Texts.RunFebe, + VerificationChecked = true, + }); + return run; + } + + public bool ConfirmUninstall() + { + var (button, _) = TaskDialog.Show(Texts.UninstallTitle, new DialogPage( + Texts.ConfirmUninstall, + Texts.ConfirmUninstallText, + [(Yes, Texts.Uninstall), (Cancel, Texts.Cancel)])); + return button == Yes; + } + + public void Uninstalled(string dataFolder, string library) => + TaskDialog.Show(Texts.UninstallTitle, new DialogPage( + Texts.Uninstalled, + Texts.UninstalledText(dataFolder, library), + [(Yes, Texts.Finish)]) + { + Icon = DialogIcon.Information, + }); + + public void Failed(bool uninstalling, string message) => + TaskDialog.Show(Title(uninstalling), new DialogPage( + uninstalling ? Texts.UninstallFailed : Texts.InstallFailed, + message, + [(Yes, Texts.Finish)]) + { + Icon = DialogIcon.Error, + }); + + private static string Title(bool uninstalling) => uninstalling ? Texts.UninstallTitle : Texts.InstallTitle; +} diff --git a/src/Febe.Installer/Windows/ShellLinks.cs b/src/Febe.Installer/Windows/ShellLinks.cs new file mode 100644 index 0000000..215f765 --- /dev/null +++ b/src/Febe.Installer/Windows/ShellLinks.cs @@ -0,0 +1,129 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; +using System.Runtime.Versioning; + +namespace Febe.Installer.Windows; + +/// +/// Shortcuts (.lnk) through the ShellLink object of Windows (IShellLinkW and IPersistFile), with the +/// COM interop that .NET generates at compile time: it survives trimming and needs no package. +/// +[SupportedOSPlatform("windows")] +internal static unsafe partial class ShellLinks +{ + private const uint ClassContextInprocServer = 1; + + private const int ShowNormal = 1; + + private const uint ReadMode = 0; + + private const uint RawPath = 4; + + private static readonly Guid ShellLinkClass = new(0x00021401, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46); + + private static readonly Guid ShellLinkInterface = new(0x000214F9, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46); + + private static readonly StrategyBasedComWrappers Wrappers = new(); + + /// Writes , replacing a shortcut already there. + public static void Create(Shortcut shortcut) + { + var link = New(); + link.SetPath(shortcut.Target); + link.SetWorkingDirectory(shortcut.WorkingDirectory); + link.SetDescription(shortcut.Description); + link.SetIconLocation(shortcut.IconPath, shortcut.IconIndex); + link.SetShowCmd(ShowNormal); + Directory.CreateDirectory(Path.GetDirectoryName(shortcut.Path)!); + ((IPersistFile)link).Save(shortcut.Path, true); + } + + /// Reads back a shortcut: target, working folder and description (for the tests). + public static (string Target, string WorkingDirectory, string Description) Read(string path) + { + var link = New(); + ((IPersistFile)link).Load(path, ReadMode); + var buffer = stackalloc char[1024]; + link.GetPath(buffer, 1024, 0, RawPath); + var target = new string(buffer); + link.GetWorkingDirectory(buffer, 1024); + var folder = new string(buffer); + link.GetDescription(buffer, 1024); + return (target, folder, new string(buffer)); + } + + private static IShellLinkW New() + { + Marshal.ThrowExceptionForHR(CoCreateInstance(in ShellLinkClass, 0, ClassContextInprocServer, in ShellLinkInterface, out var pointer)); + try + { + return (IShellLinkW)Wrappers.GetOrCreateObjectForComInstance(pointer, CreateObjectFlags.None); + } + finally + { + Marshal.Release(pointer); + } + } + + [LibraryImport("ole32.dll")] + private static partial int CoCreateInstance(in Guid classId, nint outer, uint context, in Guid interfaceId, out nint instance); +} + +[GeneratedComInterface(StringMarshalling = StringMarshalling.Utf16)] +[Guid("000214F9-0000-0000-C000-000000000046")] +internal unsafe partial interface IShellLinkW +{ + void GetPath(char* file, int length, nint findData, uint flags); + + void GetIDList(out nint list); + + void SetIDList(nint list); + + void GetDescription(char* name, int length); + + void SetDescription(string name); + + void GetWorkingDirectory(char* directory, int length); + + void SetWorkingDirectory(string directory); + + void GetArguments(char* arguments, int length); + + void SetArguments(string arguments); + + void GetHotkey(out ushort hotkey); + + void SetHotkey(ushort hotkey); + + void GetShowCmd(out int show); + + void SetShowCmd(int show); + + void GetIconLocation(char* iconPath, int length, out int icon); + + void SetIconLocation(string iconPath, int icon); + + void SetRelativePath(string relativePath, uint reserved); + + void Resolve(nint window, uint flags); + + void SetPath(string file); +} + +[GeneratedComInterface(StringMarshalling = StringMarshalling.Utf16)] +[Guid("0000010b-0000-0000-C000-000000000046")] +internal partial interface IPersistFile +{ + void GetClassID(out Guid classId); + + [PreserveSig] + int IsDirty(); + + void Load(string fileName, uint mode); + + void Save(string? fileName, [MarshalAs(UnmanagedType.Bool)] bool remember); + + void SaveCompleted(string fileName); + + void GetCurFile(out nint fileName); +} diff --git a/src/Febe.Installer/Windows/TaskDialog.cs b/src/Febe.Installer/Windows/TaskDialog.cs new file mode 100644 index 0000000..db68570 --- /dev/null +++ b/src/Febe.Installer/Windows/TaskDialog.cs @@ -0,0 +1,253 @@ +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace Febe.Installer.Windows; + +/// The standard icons of the dialog of Windows. +internal enum DialogIcon +{ + None = 0, + Warning = 0xFFFF, + Error = 0xFFFE, + Information = 0xFFFD, +} + +/// One page of a dialog: texts, buttons (the first is the default) and the check box at the bottom. +internal sealed record DialogPage(string Instruction, string Content, IReadOnlyList<(int Id, string Text)> Buttons) +{ + public DialogIcon Icon { get; init; } + + /// The text of the check box at the bottom, null for none. + public string? Verification { get; init; } + + public bool VerificationChecked { get; init; } + + /// Esc and the close button answer . + public bool AllowCancel { get; init; } = true; +} + +/// +/// The dialog of Windows (TaskDialogIndirect of the common controls, version 6 through the manifest): the +/// pages of the installer without a window framework, so the installer can be trimmed and stays small. +/// +[SupportedOSPlatform("windows")] +internal static unsafe partial class TaskDialog +{ + public const int CancelId = 2; + + private const int AllowDialogCancellation = 0x0008; + private const int VerificationFlagChecked = 0x0100; + private const int ShowProgressBar = 0x0200; + private const int CallbackTimer = 0x0800; + private const int SizeToContent = 0x01000000; + + private const uint Created = 0; + private const uint ButtonClicked = 2; + private const uint Timer = 4; + + private const uint UserMessage = 0x0400; + private const uint ClickButton = UserMessage + 102; + private const uint SetProgressBarPosition = UserMessage + 106; + private const uint EnableButton = UserMessage + 111; + + private const int Ok = 0; + private const int False = 1; + + /// Shows and waits: the button pressed and the state of the check box. + public static (int Button, bool Checked) Show(string title, DialogPage page) => Run(title, page, 0, 0); + + /// + /// Shows with a progress bar while runs on another thread; its + /// only button stays disabled and the dialog closes by itself at the end. The exception of the work comes out of here. + /// + public static void ShowProgress(string title, DialogPage page, Action> work) + { + var state = new ProgressState(work, page.Buttons[0].Id); + var handle = GCHandle.Alloc(state); + try + { + Run(title, page with { AllowCancel = false }, ShowProgressBar | CallbackTimer, GCHandle.ToIntPtr(handle)); + } + finally + { + handle.Free(); + } + + state.Error?.Throw(); + } + + private static (int Button, bool Checked) Run(string title, DialogPage page, int extraFlags, nint callbackData) + { + var strings = new List(); + nint Text(string? value) + { + if (value is null) + { + return 0; + } + + var pointer = Marshal.StringToHGlobalUni(value); + strings.Add(pointer); + return pointer; + } + + var buttons = (Button*)NativeMemory.Alloc((nuint)page.Buttons.Count, (nuint)sizeof(Button)); + try + { + for (var i = 0; i < page.Buttons.Count; i++) + { + buttons[i] = new Button { Id = page.Buttons[i].Id, Text = (char*)Text(page.Buttons[i].Text) }; + } + + var flags = SizeToContent | extraFlags; + if (page.AllowCancel) + { + flags |= AllowDialogCancellation; + } + + if (page.VerificationChecked) + { + flags |= VerificationFlagChecked; + } + + var config = new Config + { + Size = (uint)sizeof(Config), + Flags = flags, + WindowTitle = (char*)Text(title), + MainIcon = (nint)page.Icon, + MainInstruction = (char*)Text(page.Instruction), + Content = (char*)Text(page.Content), + ButtonCount = (uint)page.Buttons.Count, + Buttons = buttons, + DefaultButton = page.Buttons[0].Id, + VerificationText = (char*)Text(page.Verification), + Callback = callbackData == 0 ? null : &ProgressCallback, + CallbackData = callbackData, + }; + int pressed; + int verified; + Marshal.ThrowExceptionForHR(TaskDialogIndirect(&config, &pressed, null, &verified)); + return (pressed, verified != 0); + } + finally + { + NativeMemory.Free(buttons); + foreach (var pointer in strings) + { + Marshal.FreeHGlobal(pointer); + } + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static int ProgressCallback(nint window, uint message, nint wParam, nint lParam, nint data) + { + try + { + var state = (ProgressState)GCHandle.FromIntPtr(data).Target!; + switch (message) + { + case Created: + SendMessageW(window, EnableButton, state.ButtonId, 0); + state.Start(); + break; + case Timer: + SendMessageW(window, SetProgressBarPosition, state.Percent, 0); + if (state.Finished && !state.Closing) + { + state.Closing = true; + SendMessageW(window, EnableButton, state.ButtonId, 1); + SendMessageW(window, ClickButton, state.ButtonId, 0); + } + + break; + case ButtonClicked: + return state.Finished ? Ok : False; + } + } + catch (Exception) + { + // Nothing may escape into Windows; the work keeps its own error. + } + + return Ok; + } + + private sealed class ProgressState(Action> work, int buttonId) + { + private volatile bool _finished; + private volatile int _percent; + + public int ButtonId => buttonId; + + public int Percent => _percent; + + public bool Finished => _finished; + + public bool Closing { get; set; } + + public ExceptionDispatchInfo? Error { get; private set; } + + public void Start() => _ = Task.Run(() => + { + try + { + work(share => _percent = (int)Math.Clamp(share * 100, 0, 100)); + } + catch (Exception ex) + { + Error = ExceptionDispatchInfo.Capture(ex); + } + finally + { + _finished = true; + } + }); + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private struct Button + { + public int Id; + public char* Text; + } + + /// TASKDIALOGCONFIG of commctrl.h, packed to 1 byte as there. + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private struct Config + { + public uint Size; + public nint Parent; + public nint Instance; + public int Flags; + public int CommonButtons; + public char* WindowTitle; + public nint MainIcon; + public char* MainInstruction; + public char* Content; + public uint ButtonCount; + public Button* Buttons; + public int DefaultButton; + public uint RadioButtonCount; + public Button* RadioButtons; + public int DefaultRadioButton; + public char* VerificationText; + public char* ExpandedInformation; + public char* ExpandedControlText; + public char* CollapsedControlText; + public nint FooterIcon; + public char* Footer; + public delegate* unmanaged[Stdcall] Callback; + public nint CallbackData; + public uint Width; + } + + [LibraryImport("comctl32.dll")] + private static partial int TaskDialogIndirect(Config* config, int* button, int* radioButton, int* verificationChecked); + + [LibraryImport("user32.dll")] + private static partial nint SendMessageW(nint window, uint message, nint wParam, nint lParam); +} diff --git a/src/Febe.Installer/Windows/WindowsSystem.cs b/src/Febe.Installer/Windows/WindowsSystem.cs new file mode 100644 index 0000000..1d9396e --- /dev/null +++ b/src/Febe.Installer/Windows/WindowsSystem.cs @@ -0,0 +1,95 @@ +using System.Diagnostics; +using System.Runtime.Versioning; +using Microsoft.Win32; + +namespace Febe.Installer.Windows; + +/// +/// on Windows: the registry of .NET (HKEY_CURRENT_USER for writing, HKEY_LOCAL_MACHINE only +/// read), the Shell for the shortcuts, for the rest. +/// +[SupportedOSPlatform("windows")] +internal sealed class WindowsSystem : ISystemAccess +{ + public string? ReadUserString(string key, string name) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: false); + return opened?.GetValue(name) as string; + } + + public int? ReadUserDword(string key, string name) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: false); + return opened?.GetValue(name) is int value ? value : null; + } + + public void WriteUserString(string key, string name, string value) + { + using var opened = Registry.CurrentUser.CreateSubKey(key, writable: true); + opened.SetValue(name, value, RegistryValueKind.String); + } + + public void WriteUserDword(string key, string name, int value) + { + using var opened = Registry.CurrentUser.CreateSubKey(key, writable: true); + opened.SetValue(name, value, RegistryValueKind.DWord); + } + + public IReadOnlyList UserValueNames(string key) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: false); + return opened?.GetValueNames() ?? []; + } + + public void DeleteUserValue(string key, string name) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: true); + opened?.DeleteValue(name, throwOnMissingValue: false); + } + + public void DeleteUserKeyTree(string key) => Registry.CurrentUser.DeleteSubKeyTree(key, throwOnMissingSubKey: false); + + public string? ReadMachineString(string key, string name) + { + using var machine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); + using var opened = machine.OpenSubKey(key, writable: false); + return opened?.GetValue(name) as string; + } + + public void CreateShortcut(Shortcut shortcut) => ShellLinks.Create(shortcut); + + public void OpenAddress(string address) + { + using var process = Process.Start(new ProcessStartInfo(address) { UseShellExecute = true }); + } + + public void Start(string executable, IReadOnlyList arguments, string workingDirectory) + { + var start = new ProcessStartInfo(executable) { WorkingDirectory = workingDirectory, UseShellExecute = false }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start); + } + + public void WaitForExit(int processId, TimeSpan timeout) + { + try + { + using var process = Process.GetProcessById(processId); + process.WaitForExit(timeout); + } + catch (ArgumentException) + { + // Already ended. + } + catch (InvalidOperationException) + { + // Ended while looking at it. + } + } + + public void Pause(TimeSpan delay) => Thread.Sleep(delay); +} diff --git a/src/Febe.Installer/app.manifest b/src/Febe.Installer/app.manifest new file mode 100644 index 0000000..849d344 --- /dev/null +++ b/src/Febe.Installer/app.manifest @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2 + true + + + + + + + + diff --git a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj index 404c8cf..c29d1cb 100644 --- a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj +++ b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj @@ -26,6 +26,7 @@ + diff --git a/tests/Febe.Tests.Windows/InstallerTests.cs b/tests/Febe.Tests.Windows/InstallerTests.cs new file mode 100644 index 0000000..bb791b7 --- /dev/null +++ b/tests/Febe.Tests.Windows/InstallerTests.cs @@ -0,0 +1,338 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using Febe.Installer; +using Febe.Installer.Windows; +using Febe.Tests.Windows.Support; +using Microsoft.Win32; + +namespace Febe.Tests.Windows; + +/// +/// The installer on a real Windows: published for win-x64 as installer/costruisci.sh does it (self-contained, single +/// file, trimmed), packed with a stand-in Febe.exe, then installed in silent mode into a folder of the test +/// (/PROVA=: Start menu, desktop, %TEMP% and registry keys of the test, never those of an installed Febe), +/// installed again over itself, refused while Febe is open, and uninstalled with the command recorded in Apps +/// installed. The first page of the dialogs opens and «Annulla» closes it. Nothing here starts Febe. +/// +[TestClass] +public sealed class InstallerTests +{ + private static string? s_publishedInstaller; + private static TestFolder? s_build; + + public TestContext TestContext { get; set; } = null!; + + [ClassInitialize] + public static void PublishTheInstaller(TestContext context) + { + var project = Path.Combine(RepositoryRoot(), "src", "Febe.Installer", "Febe.Installer.csproj"); + s_build = new TestFolder("installatore-pubblicato"); + var output = s_build.Combine("uscita"); + var start = new ProcessStartInfo("dotnet") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in new[] { "publish", project, "-c", "Release", "-r", "win-x64", "-p:Version=0.0.1", "-nologo", "-o", output, "--artifacts-path", s_build.Combine("artefatti") }) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var stdout = process.StandardOutput.ReadToEndAsync(context.CancellationToken); + var stderr = process.StandardError.ReadToEndAsync(context.CancellationToken); + process.WaitForExit(); + Assert.AreEqual(0, process.ExitCode, $"dotnet publish:\n{stdout.Result}\n{stderr.Result}"); + CollectionAssert.AreEqual(new[] { "Febe.Installer.exe" }, Directory.GetFiles(output).Select(Path.GetFileName).ToArray(), "a single file"); + s_publishedInstaller = Path.Combine(output, "Febe.Installer.exe"); + } + + [ClassCleanup] + public static void RemoveTheBuild() => s_build?.Dispose(); + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task InstalledSilentlyIntoATestFolderUpdatedRefusedWhileOpenAndUninstalled() + { + using var folder = new TestFolder("installazione"); + var root = folder.Combine("utente"); + Directory.CreateDirectory(root); + var locations = Locations.ForTest(root); + var registryRoot = Locations.TestRegistryRoot(root).TrimEnd('\\'); + try + { + // The program and its version resource: not elevated (it would not even start here), version and names. + var first = Pack(folder, "0.0.1", seed: 1); + Assert.IsGreaterThan(1_000_000L, new FileInfo(s_publishedInstaller!).Length); + Assert.IsLessThan(20_000_000L, new FileInfo(s_publishedInstaller!).Length, "trimmed: a few MB beside Febe.exe"); + var version = FileVersionInfo.GetVersionInfo(first.Setup); + Assert.AreEqual("Febe", version.ProductName); + Assert.AreEqual("Installazione di Febe", version.FileDescription); + Assert.AreEqual("Alberto Balbo", version.CompanyName); + StringAssert.StartsWith(version.ProductVersion, "0.0.1"); + var bytes = await File.ReadAllBytesAsync(s_publishedInstaller!, TestContext.CancellationToken); + Assert.IsTrue(Contains(bytes, "asInvoker"u8), "the manifest is inside: no administrator rights"); + Assert.IsTrue(Contains(bytes, "Microsoft.Windows.Common-Controls"u8), "the manifest asks for the common controls 6"); + + // Installation, silent, default folder of the test user. + Assert.AreEqual(0, await Run(first.Setup, ["/S", "/PROVA=" + root])); + var program = locations.DefaultInstallFolder; + CollectionAssert.AreEqual(first.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken)); + Assert.AreEqual(PackageKind.Uninstaller, Package.Read(Path.Combine(program, "Disinstalla Febe.exe"))!.Kind); + foreach (var shortcut in new[] { locations.StartMenuShortcut, locations.DesktopShortcut }) + { + var (target, workingDirectory, description) = ShellLinks.Read(shortcut); + Assert.AreEqual(Path.Combine(program, "Febe.exe"), target, shortcut); + Assert.AreEqual(program, workingDirectory); + Assert.AreEqual("Archivio personale di foto, video e storie da Instagram", description); + } + + using (var key = Registry.CurrentUser.OpenSubKey(locations.UninstallKey)!) + { + Assert.AreEqual("Febe", key.GetValue("DisplayName")); + Assert.AreEqual("0.0.1", key.GetValue("DisplayVersion")); + Assert.AreEqual("Alberto Balbo", key.GetValue("Publisher")); + Assert.AreEqual(program, key.GetValue("InstallLocation")); + Assert.AreEqual(1, key.GetValue("NoModify")); + Assert.AreEqual(RegistryValueKind.DWord, key.GetValueKind("EstimatedSize")); + } + + // The data of Febe and «Start with the computer». + var data = Path.Combine(locations.DefaultDataFolder, "febe.sqlite"); + Directory.CreateDirectory(locations.DefaultDataFolder); + await File.WriteAllTextAsync(data, "dati", TestContext.CancellationToken); + using (var run = Registry.CurrentUser.CreateSubKey(locations.RunKey)) + { + run.SetValue("Febe", $"\"{Path.Combine(program, "Febe.exe")}\" --nascosto"); + run.SetValue("Febe-Altro", "\"C:\\Altrove\\Febe.exe\" --nascosto --dati \"D:\\Altro\""); + } + + // Again, a newer version over it: the program changes, the data stay. + var second = Pack(folder, "0.0.2", seed: 2); + Assert.AreEqual(0, await Run(second.Setup, ["/S", "/PROVA=" + root])); + CollectionAssert.AreEqual(second.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken)); + Assert.AreEqual("0.0.2", Registry.GetValue(@"HKEY_CURRENT_USER\" + locations.UninstallKey, "DisplayVersion", null)); + Assert.AreEqual("dati", await File.ReadAllTextAsync(data, TestContext.CancellationToken)); + + // Febe open: the installer stops (exit 2), says why on the standard error, changes nothing. + using (new FileStream(Path.Combine(program, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.Read)) + { + var errors = new StringBuilder(); + Assert.AreEqual(2, await Run(first.Setup, ["/S", "/PROVA=" + root], errors)); + StringAssert.Contains(errors.ToString(), "Febe è aperto"); + } + + CollectionAssert.AreEqual(second.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken)); + + // Uninstallation with the command Apps installed would use in silent mode: it hands over to a copy of + // itself in %TEMP% and ends; the copy does the work. + var quiet = (string)Registry.GetValue(@"HKEY_CURRENT_USER\" + locations.UninstallKey, "QuietUninstallString", null)!; + var (uninstaller, arguments) = Split(quiet); + Assert.AreEqual(Path.Combine(program, "Disinstalla Febe.exe"), uninstaller); + Assert.AreEqual(0, await Run(uninstaller, arguments)); + await WaitUntil(() => !Directory.Exists(program) && Registry.CurrentUser.OpenSubKey(locations.UninstallKey) is null, TimeSpan.FromSeconds(60)); + + Assert.IsFalse(File.Exists(locations.StartMenuShortcut)); + Assert.IsFalse(File.Exists(locations.DesktopShortcut)); + Assert.AreEqual("dati", await File.ReadAllTextAsync(data, TestContext.CancellationToken), "never the Data folder"); + using (var run = Registry.CurrentUser.OpenSubKey(locations.RunKey)!) + { + CollectionAssert.AreEqual(new[] { "Febe-Altro" }, run.GetValueNames(), "only the value of another Febe stays"); + } + + // The copy that did the work ends by itself; the next run of the installer removes it. + await WaitUntil(() => !Process.GetProcesses().Any(p => p.ProcessName.StartsWith("Febe-disinstalla-", StringComparison.Ordinal) && SafePath(p)?.StartsWith(root, StringComparison.OrdinalIgnoreCase) == true), TimeSpan.FromSeconds(30)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(registryRoot, throwOnMissingSubKey: false); + DeleteEmptyTestKey(); + } + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheFirstPageOpensAsADialogOfWindowsAndAnnullaInstallsNothing() + { + using var folder = new TestFolder("dialogo"); + var root = folder.Combine("utente"); + Directory.CreateDirectory(root); + var locations = Locations.ForTest(root); + try + { + var package = Pack(folder, "0.0.1", seed: 3); + using var process = Process.Start(new ProcessStartInfo(package.Setup, ["/PROVA=" + root]))!; + var window = IntPtr.Zero; + await WaitUntil(() => (window = VisibleWindowOf(process.Id)) != IntPtr.Zero, TimeSpan.FromSeconds(30)); + Assert.AreEqual("Installazione di Febe", WindowTitle(window)); + + // Close: with «Annulla» allowed, it answers as «Annulla». + PostMessage(window, 0x0010, IntPtr.Zero, IntPtr.Zero); + Assert.IsTrue(process.WaitForExit(30_000)); + Assert.AreEqual(1, process.ExitCode, "cancelled"); + Assert.IsFalse(Directory.Exists(locations.DefaultInstallFolder)); + Assert.IsNull(Registry.CurrentUser.OpenSubKey(locations.UninstallKey)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(Locations.TestRegistryRoot(root).TrimEnd('\\'), throwOnMissingSubKey: false); + DeleteEmptyTestKey(); + } + } + + private static (string Setup, byte[] Program) Pack(TestFolder folder, string version, int seed) + { + // Not an executable: if anything tried to start it, Windows would refuse it at once. + var program = new byte[300_000 + seed]; + new Random(seed).NextBytes(program); + program[0] = (byte)'F'; + program[1] = (byte)'B'; + var source = folder.Combine($"Febe-{seed}.exe"); + File.WriteAllBytes(source, program); + var setup = folder.Combine($"Febe-Setup-{version}-{seed}.exe"); + Package.Write(s_publishedInstaller!, source, version, setup); + return (setup, program); + } + + private async Task Run(string executable, IReadOnlyList arguments, StringBuilder? errors = null) + { + var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardError = true, StandardErrorEncoding = Encoding.UTF8 }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var text = await process.StandardError.ReadToEndAsync(TestContext.CancellationToken); + await process.WaitForExitAsync(TestContext.CancellationToken); + errors?.Append(text); + return process.ExitCode; + } + + private async Task WaitUntil(Func condition, TimeSpan timeout) + { + var deadline = Stopwatch.StartNew(); + while (!condition()) + { + Assert.IsLessThan(timeout, deadline.Elapsed, "timed out"); + await Task.Delay(200, TestContext.CancellationToken); + } + } + + /// The program and the arguments of a command line as Windows reads it (quotes group). + private static (string Program, string[] Arguments) Split(string commandLine) + { + var words = new List(); + var word = new StringBuilder(); + var quoted = false; + foreach (var c in commandLine) + { + if (c == '"') + { + quoted = !quoted; + } + else if (c == ' ' && !quoted) + { + if (word.Length > 0) + { + words.Add(word.ToString()); + word.Clear(); + } + } + else + { + word.Append(c); + } + } + + if (word.Length > 0) + { + words.Add(word.ToString()); + } + + return (words[0], words.Skip(1).ToArray()); + } + + private static string? SafePath(Process process) + { + try + { + return process.MainModule?.FileName; + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) + { + return null; + } + } + + private static bool Contains(byte[] haystack, ReadOnlySpan needle) => haystack.AsSpan().IndexOf(needle) >= 0; + + private static void DeleteEmptyTestKey() + { + using var tests = Registry.CurrentUser.OpenSubKey(@"Software\FebeProve"); + if (tests is not null && tests.SubKeyCount == 0 && tests.ValueCount == 0) + { + Registry.CurrentUser.DeleteSubKey(@"Software\FebeProve", throwOnMissingSubKey: false); + } + } + + private static string RepositoryRoot() + { + for (var folder = new DirectoryInfo(AppContext.BaseDirectory); folder is not null; folder = folder.Parent) + { + if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx"))) + { + return folder.FullName; + } + } + + Assert.Inconclusive("Il repository non è accanto alle prove."); + return string.Empty; + } + + /// The first visible top-level window of the process, zero for none. + private static IntPtr VisibleWindowOf(int processId) + { + var found = IntPtr.Zero; + EnumWindows((window, data) => + { + GetWindowThreadProcessId(window, out var owner); + if (owner == (uint)processId && IsWindowVisible(window)) + { + found = window; + return false; + } + + return true; + }, IntPtr.Zero); + return found; + } + + private static string WindowTitle(IntPtr window) + { + var buffer = new char[256]; + var length = GetWindowText(window, buffer, buffer.Length); + return new string(buffer, 0, Math.Max(length, 0)); + } + + private delegate bool WindowVisitor(IntPtr window, IntPtr data); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool EnumWindows(WindowVisitor visitor, IntPtr data); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool IsWindowVisible(IntPtr window); + + [DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)] + private static extern int GetWindowText(IntPtr window, [Out] char[] text, int maxCount); + + [DllImport("user32.dll", EntryPoint = "PostMessageW")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool PostMessage(IntPtr window, uint message, IntPtr wParam, IntPtr lParam); +} diff --git a/tests/Febe.Tests/Desktop/InstallerTests.cs b/tests/Febe.Tests/Desktop/InstallerTests.cs index f884dea..d405910 100644 --- a/tests/Febe.Tests/Desktop/InstallerTests.cs +++ b/tests/Febe.Tests/Desktop/InstallerTests.cs @@ -1,14 +1,21 @@ using System.Diagnostics; +using System.IO.Compression; +using System.Text; using System.Text.RegularExpressions; +using Febe.Desktop.Core; +using Febe.Installer; using Febe.Tests.Desktop.Support; using Febe.Tests.Support; namespace Febe.Tests.Desktop; /// -/// The installer of Windows (spec §12, question 6 of §16): installer/febe.nsi compiles with makensis (a dry -/// compile with a stand-in Febe.exe; skipped where NSIS is not installed), installs per user without administrator -/// rights, registers its uninstaller in HKCU, and its uninstaller never deletes the Data folder or the library. +/// The installer of Windows (spec §12, question 6 of §16), written in house in src/Febe.Installer since 18 November +/// 2026 instead of NSIS: the package (Febe.exe compressed after the program, with its SHA-256), the command line, and +/// the installation and uninstallation against a fake Windows (registry and shortcuts) and real files in a temporary +/// folder, on any system. Per user without administrator rights; an installation over another replaces the program +/// and keeps the data; the uninstaller never touches the Data folder or the library. The real Windows, with the +/// published installer, is in tests/Febe.Tests.Windows (InstallerTests). /// [TestClass] public sealed partial class InstallerTests @@ -16,101 +23,433 @@ public sealed partial class InstallerTests public TestContext TestContext { get; set; } = null!; [TestMethod] - [Timeout(120_000, CooperativeCancellation = true)] - public async Task TheScriptCompilesWithMakensisWithoutWarnings() + public void ThePackageCarriesFebeAfterTheProgramAndGivesItBackIdentical() { - var makensis = FindOnPath("makensis"); - if (makensis is null) - { - Assert.Inconclusive("makensis non è installato (apt-get install nsis): la prova del programma di installazione si salta."); - } + using var temp = new TempFolder("pacchetto"); + var stub = WriteBytes(temp.Combine("Febe.Installer.exe"), Bytes(200_000, seed: 1, compressible: false)); + var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(3_000_000, seed: 2, compressible: true)); + var setup = temp.Combine("Febe-Setup-1.2.3-ci.4.exe"); - var script = Repository.PathOf("installer", "febe.nsi"); - using var temp = new TempFolder("nsis"); - await File.WriteAllTextAsync(temp.Combine("Febe.exe"), "MZ finto per la prova", TestContext.CancellationToken); - var output = temp.Combine("Febe-Setup-0.0.1.exe"); - var start = new ProcessStartInfo(makensis) - { - WorkingDirectory = Path.GetDirectoryName(script)!, - RedirectStandardOutput = true, - RedirectStandardError = true, - }; - foreach (var argument in new[] { "-V2", "-WX", "-INPUTCHARSET", "UTF8", "-DVERSION=0.0.1", "-DVERSIONE_FILE=0.0.1.0", $"-DSORGENTE={temp.Path}", $"-DUSCITA={output}", "febe.nsi" }) - { - start.ArgumentList.Add(argument); - } + var written = Package.Write(stub, program, "1.2.3-ci.4", setup); + var info = Package.Read(setup); - using var process = Process.Start(start)!; - var stdout = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); - var stderr = process.StandardError.ReadToEndAsync(TestContext.CancellationToken); - await process.WaitForExitAsync(TestContext.CancellationToken); - Assert.AreEqual(0, process.ExitCode, $"makensis (avvisi = errori):\n{await stdout}\n{await stderr}"); - Assert.IsTrue(File.Exists(output)); - Assert.IsGreaterThan(100_000L, new FileInfo(output).Length); + Assert.IsNotNull(info); + Assert.AreEqual(PackageKind.Installer, info.Kind); + Assert.AreEqual("1.2.3-ci.4", info.Version); + Assert.AreEqual(200_000L, info.StubLength); + Assert.AreEqual(3_000_000L, info.ProgramLength); + Assert.AreEqual(written.DataLength, info.DataLength); + Assert.IsLessThan(3_000_000L, info.DataLength, "compressed"); + CollectionAssert.AreEqual(File.ReadAllBytes(stub), File.ReadAllBytes(setup)[..200_000], "the program comes first, untouched: its single-file bundle still works"); + Assert.IsFalse(File.Exists(setup + ".part")); - // Without the version the script refuses to compile: it always comes from the build. - using var noVersion = Process.Start(new ProcessStartInfo(makensis, ["-V1", $"-DSORGENTE={temp.Path}", $"-DUSCITA={temp.Combine("x.exe")}", "febe.nsi"]) - { - WorkingDirectory = Path.GetDirectoryName(script)!, - RedirectStandardOutput = true, - RedirectStandardError = true, - })!; - await noVersion.WaitForExitAsync(TestContext.CancellationToken); - Assert.AreNotEqual(0, noVersion.ExitCode); + var shares = new List(); + Package.ExtractProgram(setup, info, temp.Combine("estratto.exe"), shares.Add); + CollectionAssert.AreEqual(File.ReadAllBytes(program), File.ReadAllBytes(temp.Combine("estratto.exe"))); + Assert.AreEqual(1.0, shares[^1], 1e-9); + + // The uninstaller: the same program, no Febe.exe, a footer of its own. + Package.WriteUninstaller(setup, info, temp.Combine("Disinstalla Febe.exe")); + var uninstaller = Package.Read(temp.Combine("Disinstalla Febe.exe")); + Assert.IsNotNull(uninstaller); + Assert.AreEqual(PackageKind.Uninstaller, uninstaller.Kind); + Assert.AreEqual("1.2.3-ci.4", uninstaller.Version); + Assert.AreEqual(200_000L + "1.2.3-ci.4".Length + Package.FooterLength, new FileInfo(temp.Combine("Disinstalla Febe.exe")).Length); + CollectionAssert.AreEqual(File.ReadAllBytes(stub), File.ReadAllBytes(temp.Combine("Disinstalla Febe.exe"))[..200_000]); } [TestMethod] - public void TheScriptInstallsPerUserAndItsUninstallerNeverTouchesTheData() + public void ADamagedPackageIsRefusedAndNeverInstalled() { - var text = File.ReadAllText(Repository.PathOf("installer", "febe.nsi")); - StringAssert.Contains(text, "Unicode true"); - StringAssert.Contains(text, "RequestExecutionLevel user"); - StringAssert.Contains(text, "InstallDir \"$LOCALAPPDATA\\Programs\\Febe\""); - StringAssert.Contains(text, "MUI_LANGUAGE \"Italian\""); - StringAssert.Contains(text, "$SMPROGRAMS\\Febe.lnk"); - StringAssert.Contains(text, "Section \"Collegamento sul desktop\""); - foreach (var value in new[] { "DisplayName", "DisplayVersion", "Publisher", "DisplayIcon", "UninstallString" }) - { - StringAssert.Contains(text, $"WriteRegStr HKCU \"${{CHIAVE_DISINSTALLA}}\" \"{value}\""); - } + using var temp = new TempFolder("pacchetto"); + var stub = WriteBytes(temp.Combine("Febe.Installer.exe"), Bytes(50_000, seed: 3, compressible: false)); + var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(500_000, seed: 4, compressible: true)); + var setup = temp.Combine("Febe-Setup.exe"); + var info = Package.Write(stub, program, "0.0.1", setup); - StringAssert.Contains(text, "\"DisplayVersion\" \"${VERSION}\""); - StringAssert.Contains(text, "\"Publisher\" \"${EDITORE}\""); - StringAssert.Contains(text, "!define EDITORE \"Alberto Balbo\""); - StringAssert.Contains(text, "EdgeUpdate\\Clients\\${WEBVIEW2_GUID}"); - StringAssert.Contains(text, "https://developer.microsoft.com/microsoft-edge/webview2/"); - Assert.DoesNotContain("HKLM\" \"${CHIAVE", text, "nothing written for every user"); - Assert.IsFalse(Regex.IsMatch(text, @"Write\w*\s+HKLM"), "no machine-wide registry"); + // Not a package at all: the bare program, or anything with bytes after the footer. + Assert.IsNull(Package.Read(stub)); + var longer = WriteBytes(temp.Combine("piu-lungo.exe"), [.. File.ReadAllBytes(setup), 0]); + Assert.IsNull(Package.Read(longer)); - // The uninstall section deletes only the program, its shortcuts and its registry entries. - var uninstall = text[text.IndexOf("Section \"Uninstall\"", StringComparison.Ordinal)..]; - uninstall = uninstall[..uninstall.IndexOf("SectionEnd", StringComparison.Ordinal)]; - foreach (Match removal in Removals().Matches(uninstall)) - { - var target = removal.Groups["target"].Value; - Assert.IsTrue( - target.StartsWith("$INSTDIR\\", StringComparison.Ordinal) || target == "$INSTDIR" - || target is "$SMPROGRAMS\\Febe.lnk" or "$DESKTOP\\Febe.lnk" or "$TEMP\\.net\\Febe", - $"the uninstaller removes «{target}»: only the program may go"); - } + // A byte of Febe.exe changed: the SHA-256 (or Brotli itself) says no. + var bytes = File.ReadAllBytes(setup); + bytes[info.ProgramStart + (info.DataLength / 2)] ^= 0x5A; + var damaged = WriteBytes(temp.Combine("rovinato.exe"), bytes); + var damagedInfo = Package.Read(damaged)!; + var error = Assert.ThrowsExactly(() => Package.ExtractProgram(damaged, damagedInfo, temp.Combine("x.exe"))); + Assert.AreEqual(Texts.Damaged, error.Message); - Assert.DoesNotContain("$LOCALAPPDATA\\Febe", uninstall.Replace("StrCpy $R8 \"$LOCALAPPDATA\\Febe\"", string.Empty, StringComparison.Ordinal), "never the Data folder"); - Assert.DoesNotContain("$PICTURES", uninstall, "never the library"); - Assert.DoesNotContain("MB_YESNO", uninstall, "it asks nothing about the data"); - StringAssert.Contains(uninstall, "DeleteRegValue HKCU \"${CHIAVE_AVVIO}\" \"Febe\"", "the start with the computer goes with the program"); + // A footer that does not describe the file: an error, not a guess. + bytes = File.ReadAllBytes(setup); + bytes[bytes.Length - Package.FooterLength + 16] ^= 1; + Assert.ThrowsExactly(() => Package.Read(WriteBytes(temp.Combine("piede.exe"), bytes))); + + // The tool never packs a package again, nor without a version of the build. + Assert.ThrowsExactly(() => Package.Write(setup, program, "0.0.1", temp.Combine("doppio.exe"))); + Assert.ThrowsExactly(() => Package.Write(stub, program, "1.0", temp.Combine("v.exe"))); + Assert.IsFalse(File.Exists(temp.Combine("doppio.exe")) || File.Exists(temp.Combine("doppio.exe.part"))); } [TestMethod] - public void TheBuildScriptIsValidBashAndProducesTheTwoFilesUnder100Mb() + public void TheCommandLineHasTheOptionsOfNsis() + { + var root = Root("Prove"); + Assert.AreEqual(new CommandLine(), CommandLine.Parse([])); + Assert.IsTrue(CommandLine.Parse(["/S"]).Silent); + Assert.IsTrue(CommandLine.Parse(["/s"]).Silent); + + // /D= is the last and takes the rest of the line, spaces included, as with NSIS. + var folder = Path.Combine(root, "Programmi personali", "Febe"); + var line = CommandLine.Parse(["/S", "/D=" + Path.Combine(root, "Programmi"), "personali" + Path.DirectorySeparatorChar + "Febe"]); + Assert.IsTrue(line.Silent); + Assert.AreEqual(folder, line.InstallFolder); + + line = CommandLine.Parse(["/PROVA=" + root, $"/_?={folder}", "/ATTENDI=4242"]); + Assert.AreEqual(root, line.TestRoot); + Assert.AreEqual(folder, line.UninstallFolder); + Assert.AreEqual(4242, line.WaitFor); + CollectionAssert.AreEqual(new[] { "/PROVA=" + root }, line.PassOn().ToArray(), "the internal options are not passed on"); + CollectionAssert.AreEqual(new[] { "/S" }, CommandLine.Parse(["/S"]).PassOn().ToArray()); + + Assert.ThrowsExactly(() => CommandLine.Parse(["/X"])); + Assert.ThrowsExactly(() => CommandLine.Parse(["/D=relativa"])); + Assert.ThrowsExactly(() => CommandLine.Parse(["/D="])); + + // The build tool. + Assert.AreEqual(ToolCommand.Pack, CommandLine.Parse(["--impacchetta", "a", "b", "1.0.0", "c"]).Tool); + Assert.AreEqual(ToolCommand.Verify, CommandLine.Parse(["--verifica", "a", "b"]).Tool); + Assert.AreEqual(ToolCommand.Zip, CommandLine.Parse(["--zip", "a.zip", "b"]).Tool); + Assert.ThrowsExactly(() => CommandLine.Parse(["--impacchetta", "a"])); + Assert.ThrowsExactly(() => CommandLine.Parse(["--altro"])); + } + + [TestMethod] + public void AnInstallationIsPerUserWithTheShortcutsAndTheEntryInAppsInstalled() + { + using var bed = new SetupBed("installa"); + var setup = bed.Package("0.1.2", seed: 5); + var ui = new ScriptedInterface { DesktopShortcut = true, StartFebe = true }; + + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(setup, Package.Read(setup)!, new CommandLine())); + + var folder = bed.Locations.DefaultInstallFolder; + Assert.AreEqual(Path.Combine(bed.Root, "AppData", "Programs", "Febe"), folder, "%LOCALAPPDATA%\\Programs\\Febe"); + CollectionAssert.AreEqual(bed.Program(5), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); + Assert.AreEqual(PackageKind.Uninstaller, Package.Read(Path.Combine(folder, "Disinstalla Febe.exe"))!.Kind); + CollectionAssert.AreEquivalent(new[] { "Febe.exe", "Disinstalla Febe.exe" }, Directory.GetFiles(folder).Select(Path.GetFileName).ToArray(), "nothing else, no .nuovo left"); + + // The shortcuts: Start menu always, desktop as chosen; both to Febe.exe, from its folder, with its icon. + Assert.HasCount(2, bed.System.Shortcuts); + foreach (var (shortcut, path) in bed.System.Shortcuts.Zip([bed.Locations.StartMenuShortcut, bed.Locations.DesktopShortcut])) + { + Assert.AreEqual(path, shortcut.Path); + Assert.AreEqual(Path.Combine(folder, "Febe.exe"), shortcut.Target); + Assert.AreEqual(folder, shortcut.WorkingDirectory); + Assert.AreEqual(Path.Combine(folder, "Febe.exe"), shortcut.IconPath); + Assert.AreEqual(0, shortcut.IconIndex); + Assert.AreEqual("Archivio personale di foto, video e storie da Instagram", shortcut.Description); + } + + // Apps installed: under HKEY_CURRENT_USER only (the fake has nothing else to write to). + var key = bed.Locations.UninstallKey; + Assert.AreEqual(Locations.TestRegistryRoot(bed.Root) + @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe", key); + Assert.AreEqual("Febe", bed.System.String(key, "DisplayName")); + Assert.AreEqual("0.1.2", bed.System.String(key, "DisplayVersion")); + Assert.AreEqual("Alberto Balbo", bed.System.String(key, "Publisher")); + Assert.AreEqual(Path.Combine(folder, "Febe.exe") + ",0", bed.System.String(key, "DisplayIcon")); + Assert.AreEqual(folder, bed.System.String(key, "InstallLocation")); + var uninstaller = $"\"{Path.Combine(folder, "Disinstalla Febe.exe")}\""; + Assert.AreEqual($"{uninstaller} \"/PROVA={bed.Root}\"", bed.System.String(key, "UninstallString")); + Assert.AreEqual($"{uninstaller} /S \"/PROVA={bed.Root}\"", bed.System.String(key, "QuietUninstallString")); + Assert.AreEqual("https://gitea.encke-hake.ts.net/Alby96/Febe", bed.System.String(key, "URLInfoAbout")); + Assert.AreEqual(1, bed.System.ReadUserDword(key, "NoModify")); + Assert.AreEqual(1, bed.System.ReadUserDword(key, "NoRepair")); + var size = new DirectoryInfo(folder).EnumerateFiles().Sum(f => f.Length) / 1024; + Assert.AreEqual((int)size, bed.System.ReadUserDword(key, "EstimatedSize")); + + // WebView2 is there (in the fake): no question. Febe starts, from its folder. + CollectionAssert.DoesNotContain(ui.Calls, "webview2"); + Assert.HasCount(1, bed.System.Started); + Assert.AreEqual(Path.Combine(folder, "Febe.exe"), bed.System.Started[0].Executable); + Assert.AreEqual(folder, bed.System.Started[0].WorkingDirectory); + CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "installato" }, ui.Calls); + Assert.IsNull(ui.Version, "a fresh installation: nothing installed before"); + } + + [TestMethod] + public void WithoutTheDesktopShortcutAndInAnotherFolderOnlyTheStartMenuHasFebe() + { + using var bed = new SetupBed("cartella"); + var setup = bed.Package("0.1.2", seed: 6); + var folder = Path.Combine(bed.Root, "Altrove", "Febe"); + var ui = new ScriptedInterface { DesktopShortcut = false }; + + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/D=" + folder]))); + + Assert.IsTrue(File.Exists(Path.Combine(folder, "Febe.exe"))); + Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder)); + Assert.AreEqual(bed.Locations.StartMenuShortcut, bed.System.Shortcuts.Single().Path); + Assert.AreEqual(folder, ui.Folder); + Assert.IsEmpty(bed.System.Started, "«Apri Febe adesso» unchecked"); + } + + [TestMethod] + public void AnInstallationOverAnotherReplacesTheProgramAndKeepsTheData() + { + using var bed = new SetupBed("aggiorna"); + var first = bed.Package("0.1.1", seed: 7); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); + + // Febe has been used: data, a library, a Data folder moved elsewhere, start with the computer. + var data = bed.FillData(); + var folder = bed.Locations.DefaultInstallFolder; + + var second = bed.Package("0.2.0", seed: 8); + var ui = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); + + Assert.AreEqual("0.1.1", ui.Version, "the first page says it is an update"); + CollectionAssert.AreEqual(bed.Program(8), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); + Assert.AreEqual("0.2.0", Package.Read(Path.Combine(folder, "Disinstalla Febe.exe"))!.Version); + Assert.AreEqual("0.2.0", bed.System.String(bed.Locations.UninstallKey, "DisplayVersion")); + CollectionAssert.AreEquivalent(new[] { "Febe.exe", "Disinstalla Febe.exe" }, Directory.GetFiles(folder).Select(Path.GetFileName).ToArray()); + data.AssertUntouched(); + } + + [TestMethod] + public void AnOpenFebeStopsTheInstallationUntilItIsClosed() + { + using var bed = new SetupBed("aperto"); + var first = bed.Package("0.1.1", seed: 9); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); + var executable = Path.Combine(bed.Locations.DefaultInstallFolder, "Febe.exe"); + var second = bed.Package("0.2.0", seed: 10); + + using (new FileStream(executable, FileMode.Open, FileAccess.Read, FileShare.None)) + { + Assert.IsTrue(SetupActions.IsFebeOpen(bed.Locations.DefaultInstallFolder)); + + // Silent: an error on the standard error, nothing replaced. + var errors = new StringWriter(); + Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Install(second, Package.Read(second)!, CommandLine.Parse(["/S"]))); + StringAssert.Contains(errors.ToString(), "Febe è aperto"); + + // With dialogs: «Annulla» gives up. + var ui = new ScriptedInterface { Retries = new Queue([false]) }; + Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); + CollectionAssert.AreEqual(new[] { "benvenuto", "aperto" }, ui.Calls); + } + + CollectionAssert.AreEqual(bed.Program(9), File.ReadAllBytes(executable)); + Assert.AreEqual("0.1.1", bed.System.String(bed.Locations.UninstallKey, "DisplayVersion")); + + // Closed now: «Riprova» goes on. + Assert.IsFalse(SetupActions.IsFebeOpen(bed.Locations.DefaultInstallFolder)); + var retry = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(retry).Install(second, Package.Read(second)!, new CommandLine())); + CollectionAssert.AreEqual(bed.Program(10), File.ReadAllBytes(executable)); + } + + [TestMethod] + public void TheUninstallerRemovesOnlyTheProgramItsShortcutsAndItsEntriesAndSaysWhereTheDataAre() + { + using var bed = new SetupBed("disinstalla"); + var setup = bed.Package("0.1.2", seed: 11); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); + var folder = bed.Locations.DefaultInstallFolder; + var data = bed.FillData(); + + // Something of Alberto's in the program folder, and the libraries Febe.exe extracted by itself. + File.WriteAllText(Path.Combine(folder, "appunti.txt"), "miei"); + Directory.CreateDirectory(Path.Combine(bed.Locations.ExtractionFolder, "abc")); + File.WriteAllText(Path.Combine(bed.Locations.ExtractionFolder, "abc", "e_sqlite3.dll"), "x"); + + // Start with the computer: this Febe, this Febe with --dati, a portable Febe with --dati, something else. + var run = bed.Locations.RunKey; + var executable = Path.Combine(folder, "Febe.exe"); + bed.System.WriteUserString(run, "Febe", Autostart.Command(executable)); + bed.System.WriteUserString(run, "Febe-AbC", Autostart.Command(executable.ToUpperInvariant(), Path.Combine(bed.Root, "Secondo"))); + bed.System.WriteUserString(run, "Febe-Portabile", Autostart.Command(Path.Combine(bed.Root, "Portabile", "Febe.exe"), Path.Combine(bed.Root, "Terzo"))); + bed.System.WriteUserString(run, "Altro", Autostart.Command(executable)); + + var ui = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); + + Assert.IsFalse(File.Exists(executable)); + Assert.IsFalse(File.Exists(Path.Combine(folder, "Disinstalla Febe.exe"))); + Assert.IsTrue(File.Exists(Path.Combine(folder, "appunti.txt")), "not ours: it stays, and so does the folder"); + Assert.IsFalse(File.Exists(bed.Locations.StartMenuShortcut)); + Assert.IsFalse(File.Exists(bed.Locations.DesktopShortcut)); + Assert.IsFalse(Directory.Exists(bed.Locations.ExtractionFolder)); + Assert.IsFalse(bed.System.HasKey(bed.Locations.UninstallKey)); + CollectionAssert.AreEquivalent(new[] { "Febe-Portabile", "Altro" }, bed.System.UserValueNames(run).ToArray()); + data.AssertUntouched(); + + // It asked nothing about the data and said where they are: the folder chosen in Impostazioni. + CollectionAssert.AreEqual(new[] { "conferma", "disinstallato" }, ui.Calls); + Assert.AreEqual((data.MovedDataFolder, bed.Locations.Library), ui.UninstalledWith); + + // A second time, with the program folder now empty: the folder goes too. + File.Delete(Path.Combine(folder, "appunti.txt")); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); + Assert.IsFalse(Directory.Exists(folder)); + } + + [TestMethod] + public void TheUninstallerAsksAndAnOpenFebeOrANoStopsItBeforeAnything() + { + using var bed = new SetupBed("rifiuto"); + var setup = bed.Package("0.1.2", seed: 12); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); + var folder = bed.Locations.DefaultInstallFolder; + var line = CommandLine.Parse(["/_?=" + folder]); + + var no = new ScriptedInterface { Confirm = false }; + Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(no).Uninstall("copia.exe", line)); + using (new FileStream(Path.Combine(folder, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.None)) + { + Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(new ScriptedInterface { Retries = new Queue([false]) }).Uninstall("copia.exe", line)); + var errors = new StringWriter(); + Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Uninstall("copia.exe", CommandLine.Parse(["/S", "/_?=" + folder]))); + StringAssert.Contains(errors.ToString(), "La disinstallazione non è riuscita: Febe è aperto"); + } + + Assert.IsTrue(File.Exists(Path.Combine(folder, "Febe.exe"))); + Assert.IsTrue(File.Exists(bed.Locations.StartMenuShortcut)); + Assert.IsTrue(bed.System.HasKey(bed.Locations.UninstallKey)); + } + + [TestMethod] + public void StartedFromTheProgramFolderTheUninstallerRunsACopyOfItselfFromTemp() + { + using var bed = new SetupBed("copia"); + var setup = bed.Package("0.1.2", seed: 13); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); + var folder = bed.Locations.DefaultInstallFolder; + var uninstaller = Path.Combine(folder, "Disinstalla Febe.exe"); + + // An old copy left by an earlier uninstallation goes; nothing else in %TEMP% does. + Directory.CreateDirectory(bed.Locations.Temp); + File.WriteAllText(Path.Combine(bed.Locations.Temp, "Febe-disinstalla-1.exe"), "vecchia"); + File.WriteAllText(Path.Combine(bed.Locations.Temp, "altro.exe"), "non nostro"); + SetupFlow.RemoveOldUninstallerCopies(bed.Locations, selfPath: uninstaller); + Assert.IsFalse(File.Exists(Path.Combine(bed.Locations.Temp, "Febe-disinstalla-1.exe"))); + Assert.IsTrue(File.Exists(Path.Combine(bed.Locations.Temp, "altro.exe"))); + + var ui = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Uninstall(uninstaller, CommandLine.Parse(["/S", "/PROVA=" + bed.Root]))); + + Assert.IsEmpty(ui.Calls, "the copy asks, not this one"); + Assert.IsTrue(File.Exists(uninstaller), "nothing removed yet"); + var (copy, arguments, workingDirectory) = bed.System.Started.Single(); + Assert.AreEqual(Path.Combine(bed.Locations.Temp, $"Febe-disinstalla-{Environment.ProcessId}.exe"), copy); + CollectionAssert.AreEqual(File.ReadAllBytes(uninstaller), File.ReadAllBytes(copy)); + CollectionAssert.AreEqual(new[] { "/S", "/PROVA=" + bed.Root, "/_?=" + folder, $"/ATTENDI={Environment.ProcessId}" }, arguments.ToArray()); + Assert.AreEqual(bed.Locations.Temp, workingDirectory); + + // The copy waits for the first one to end, then does the work. + var copyLine = CommandLine.Parse(arguments.ToArray()); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Uninstall(copy, copyLine)); + Assert.AreEqual(Environment.ProcessId, bed.System.WaitedFor.Single()); + Assert.IsFalse(Directory.Exists(folder)); + } + + [TestMethod] + public void WebView2IsLookedForWhereMicrosoftPutsItAndItsPageOfferedWhenMissing() + { + using var bed = new SetupBed("webview2"); + var actions = new SetupActions(bed.System, bed.Locations); + const string Client = @"Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"; + bed.System.Machine.Clear(); + Assert.IsNull(actions.WebView2Version()); + + bed.System.Machine[(@"SOFTWARE\WOW6432Node\" + Client, "pv")] = "0.0.0.0"; + Assert.IsNull(actions.WebView2Version(), "0.0.0.0: removed"); + bed.System.Machine[(@"SOFTWARE\" + Client, "pv")] = "131.0.2903.70"; + Assert.AreEqual("131.0.2903.70", actions.WebView2Version()); + bed.System.Machine.Clear(); + bed.System.WriteUserString(@"Software\" + Client, "pv", "130.0.1.2"); + Assert.AreEqual("130.0.1.2", actions.WebView2Version(), "installed for the user only; never under the test key"); + bed.System.DeleteUserKeyTree(@"Software\" + Client); + + // Missing: the question, and the page of Microsoft only on «Apri la pagina»; never in silent mode. + var setup = bed.Package("0.1.2", seed: 14); + var yes = new ScriptedInterface { OpenWebView2Page = true }; + Assert.AreEqual(ExitCodes.Done, bed.Flow(yes).Install(setup, Package.Read(setup)!, new CommandLine())); + CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "webview2", "installato" }, yes.Calls); + CollectionAssert.AreEqual(new[] { "https://developer.microsoft.com/microsoft-edge/webview2/" }, bed.System.Opened); + + Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/S"]))); + Assert.HasCount(1, bed.System.Opened); + Assert.IsEmpty(bed.System.Started, "silent: Febe is not started"); + Assert.IsTrue(File.Exists(bed.Locations.DesktopShortcut), "silent: the desktop shortcut, as the NSIS sections chosen by default"); + } + + [TestMethod] + public void TheKeysAreThoseFebeForWindowsWritesItself() + { + string[] desktop = [Autostart.RunKey, Autostart.ValueName]; + string[] installer = [Product.RunKey, Product.AutostartValue]; + CollectionAssert.AreEqual(desktop, installer); + StringAssert.StartsWith(Autostart.ValueNameFor(Path.Combine(Root("x"), "Secondo")), Product.AutostartPrefix); + StringAssert.StartsWith(Autostart.Command(@"C:\Febe\Febe.exe", @"D:\Dati"), "\"C:\\Febe\\Febe.exe\"", "the uninstaller recognizes the values by the quoted program"); + + var shell = File.ReadAllText(Repository.PathOf("src", "Febe.Desktop", "WindowsShell.cs")); + StringAssert.Contains(shell, $"public const string Key = @\"{Product.FebeKey}\";"); + StringAssert.Contains(shell, $"Read(\"{Product.DataFolderValue}\")"); + } + + [TestMethod] + public void TheToolWritesThePortableZipWithEachFileAtTheTop() + { + using var temp = new TempFolder("zip"); + var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(300_000, seed: 15, compressible: true)); + File.WriteAllText(temp.Combine("LEGGIMI.txt"), "Febe portabile\r\n"); + var zip = temp.Combine("Febe-0.1.2-portabile.zip"); + + Febe.Installer.Program.Zip(zip, [program, temp.Combine("LEGGIMI.txt")]); + + using var archive = ZipFile.OpenRead(zip); + CollectionAssert.AreEqual(new[] { "Febe.exe", "LEGGIMI.txt" }, archive.Entries.Select(e => e.FullName).ToArray()); + using var entry = archive.GetEntry("Febe.exe")!.Open(); + using var copy = new MemoryStream(); + entry.CopyTo(copy); + CollectionAssert.AreEqual(File.ReadAllBytes(program), copy.ToArray()); + Assert.IsFalse(File.Exists(zip + ".part")); + } + + [TestMethod] + public void TheBuildScriptIsValidBashUsesOnlyDotnetAndProducesTheTwoFilesUnder100Mb() { var script = Repository.PathOf("installer", "costruisci.sh"); var text = File.ReadAllText(script); StringAssert.Contains(text, "set -euo pipefail"); StringAssert.Contains(text, "-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true"); + StringAssert.Contains(text, "dotnet publish src/Febe.Installer/Febe.Installer.csproj -c Release -r win-x64"); + StringAssert.Contains(text, "pacchetto --impacchetta \"$installatore/Febe.Installer.exe\" \"$pubblicazione/Febe.exe\" \"$versione\" \"$setup\""); + StringAssert.Contains(text, "pacchetto --verifica \"$setup\" \"$pubblicazione/Febe.exe\""); + StringAssert.Contains(text, "pacchetto --zip \"$zip_portabile\""); StringAssert.Contains(text, "Febe-Setup-$versione.exe"); StringAssert.Contains(text, "Febe-$versione-portabile.zip"); StringAssert.Contains(text, "100 * 1024 * 1024"); Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR"); + foreach (var program in new[] { "makensis", "python3", "command -v zip", "zip -q" }) + { + Assert.DoesNotContain(program, text, "only the .NET SDK"); + } + + // The publication of the installer: self-contained, single file, trimmed, compressed; no package of others. + var project = File.ReadAllText(Repository.PathOf("src", "Febe.Installer", "Febe.Installer.csproj")); + foreach (var property in new[] { "true", "true", "true", "true", "app.manifest" }) + { + StringAssert.Contains(project, property); + } + + Assert.DoesNotContain("PackageReference", project); + var manifest = File.ReadAllText(Repository.PathOf("src", "Febe.Installer", "app.manifest")); + StringAssert.Contains(manifest, "", "never administrator rights, even with «Setup» in the name"); + StringAssert.Contains(manifest, "name=\"Microsoft.Windows.Common-Controls\" version=\"6.0.0.0\"", "the dialogs of Windows need the common controls 6"); var bash = FindBash(); if (bash is null) @@ -124,7 +463,69 @@ public sealed partial class InstallerTests Assert.AreEqual(0, process.ExitCode, errors); } - private static string? FindOnPath(string name) => OnPath(name).FirstOrDefault(); + [TestMethod] + public void NsisIsGoneFromTheProgramTheBuildAndTheGuide() + { + var root = Repository.Root(); + if (root is null) + { + Assert.Inconclusive("Il repository non è accanto alle prove."); + } + + Assert.IsFalse(File.Exists(Path.Combine(root, "installer", "febe.nsi"))); + var offending = new List(); + var files = new[] { "src", "tools", "installer", "docker", ".gitea", Path.Combine("docs", "guida") } + .Select(folder => Path.Combine(root, folder)) + .Where(Directory.Exists) + .SelectMany(folder => Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)) + .Concat(new[] { "CLAUDE.md", ".gitattributes", Path.Combine("docs", "windows.md"), Path.Combine("docs", "processo.md") }.Select(file => Path.Combine(root, file))) + .Where(file => File.Exists(file) && !IsBuildOutput(root, file) && IsText(file)); + foreach (var file in files) + { + var text = File.ReadAllText(file); + if (NsisWord().IsMatch(text)) + { + offending.Add(Path.GetRelativePath(root, file)); + } + } + + Assert.IsEmpty(offending, "NSIS is still named in: " + string.Join(", ", offending)); + } + + private static bool IsBuildOutput(string root, string file) + { + var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); + return relative.Contains("/bin/", StringComparison.Ordinal) || relative.Contains("/obj/", StringComparison.Ordinal) || relative.Contains("/node_modules/", StringComparison.Ordinal); + } + + private static bool IsText(string file) => + Path.GetExtension(file).ToLowerInvariant() is ".cs" or ".csproj" or ".md" or ".sh" or ".yml" or ".yaml" or ".json" or ".xml" or ".js" or ".css" or ".html" or ".txt" or ".props" or ".manifest" or "" or ".gitattributes" or ".nsi"; + + private static string Root(string name) => + Path.Combine(Path.GetTempPath(), name); + + private static byte[] Bytes(int length, int seed, bool compressible) + { + var random = new Random(seed); + var bytes = new byte[length]; + random.NextBytes(bytes); + if (compressible) + { + // Long runs, as in an executable: Brotli has something to do. + for (var i = 0; i < length; i += 4096) + { + bytes.AsSpan(i, Math.Min(2048, length - i)).Fill((byte)(i / 4096)); + } + } + + return bytes; + } + + private static string WriteBytes(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + return path; + } /// /// A bash that checks the script on this system. Elsewhere than Windows, the first on PATH. On Windows Git Bash @@ -136,11 +537,11 @@ public sealed partial class InstallerTests { if (!OperatingSystem.IsWindows()) { - return FindOnPath("bash"); + return OnPath("bash").FirstOrDefault(); } var roots = new List(); - if (FindOnPath("git") is { } git) + if (OnPath("git").FirstOrDefault() is { } git) { // git.exe sits in \cmd, \bin or \mingw64\bin. for (var folder = Path.GetDirectoryName(git); folder is not null && roots.Count < 3; folder = Path.GetDirectoryName(folder)) @@ -189,6 +590,227 @@ public sealed partial class InstallerTests } } - [GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?[^""]+)""", RegexOptions.Multiline)] - private static partial Regex Removals(); + [GeneratedRegex(@"\b(?:nsis|makensis)\b|\.nsi\b", RegexOptions.IgnoreCase)] + private static partial Regex NsisWord(); + + /// A test installation: a folder of its own (Locations.ForTest), a fake Windows, packages made on the spot. + private sealed class SetupBed : IDisposable + { + private readonly TempFolder _temp; + private readonly Dictionary _programs = []; + + public SetupBed(string name) + { + _temp = new TempFolder("installatore-" + name); + Root = _temp.Path; + Locations = Locations.ForTest(Root); + System.Machine[(@"SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}", "pv")] = "131.0.2903.70"; + } + + public string Root { get; } + + public Locations Locations { get; } + + public FakeSystem System { get; } = new(); + + public SetupFlow Flow(ISetupInterface ui) => new(System, Locations, ui); + + public byte[] Program(int seed) => _programs[seed]; + + /// A package of version with a Febe.exe of its own (by ). + public string Package(string version, int seed) + { + var folder = Directory.CreateDirectory(Path.Combine(Root, "pacchetti", seed.ToString(global::System.Globalization.CultureInfo.InvariantCulture))).FullName; + var stub = WriteBytes(Path.Combine(folder, "Febe.Installer.exe"), Bytes(20_000, seed: 1000 + seed, compressible: false)); + _programs[seed] = Bytes(400_000 + seed, seed, compressible: true); + var program = WriteBytes(Path.Combine(folder, "Febe.exe"), _programs[seed]); + var setup = Path.Combine(folder, $"Febe-Setup-{version}.exe"); + Febe.Installer.Package.Write(stub, program, version, setup); + return setup; + } + + /// Febe used for a while: a Data folder (moved by Impostazioni), the default one, a library. + public UsedData FillData() + { + var moved = Path.Combine(Root, "DatiSpostati"); + System.WriteUserString(Locations.FebeKey, "CartellaDati", moved); + var files = new[] + { + Path.Combine(moved, "febe.sqlite"), + Path.Combine(moved, "sessione", "sessione.json"), + Path.Combine(Locations.DefaultDataFolder, "febe.sqlite"), + Path.Combine(Locations.DefaultDataFolder, "browser", "Default", "Cookies"), + Path.Combine(Locations.Library, "alberto", "2026-11-18_post.jpg"), + }; + foreach (var file in files) + { + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + File.WriteAllText(file, file); + } + + return new UsedData(this, moved, files); + } + + public void Dispose() => _temp.Dispose(); + } + + private sealed record UsedData(SetupBed Bed, string MovedDataFolder, string[] Files) + { + public void AssertUntouched() + { + foreach (var file in Files) + { + Assert.IsTrue(File.Exists(file), file); + Assert.AreEqual(file, File.ReadAllText(file)); + } + + Assert.AreEqual(MovedDataFolder, Bed.System.String(Bed.Locations.FebeKey, "CartellaDati"), "Febe's key is not the installer's"); + } + } + + /// Windows for the tests: a registry of HKEY_CURRENT_USER in memory, HKLM read from a table, shortcuts as small files. + private sealed class FakeSystem : ISystemAccess + { + private readonly Dictionary> _user = new(StringComparer.OrdinalIgnoreCase); + + public Dictionary<(string Key, string Name), string> Machine { get; } = []; + + public List Shortcuts { get; } = []; + + public List Opened { get; } = []; + + public List<(string Executable, IReadOnlyList Arguments, string WorkingDirectory)> Started { get; } = []; + + public List WaitedFor { get; } = []; + + public string? String(string key, string name) => ReadUserString(key, name); + + public bool HasKey(string key) => _user.Keys.Any(k => k.Equals(key, StringComparison.OrdinalIgnoreCase) || k.StartsWith(key + "\\", StringComparison.OrdinalIgnoreCase)); + + public string? ReadUserString(string key, string name) => + _user.TryGetValue(key, out var values) && values.TryGetValue(name, out var value) ? value as string : null; + + public int? ReadUserDword(string key, string name) => + _user.TryGetValue(key, out var values) && values.TryGetValue(name, out var value) && value is int number ? number : null; + + public void WriteUserString(string key, string name, string value) => Values(key)[name] = value; + + public void WriteUserDword(string key, string name, int value) => Values(key)[name] = value; + + public IReadOnlyList UserValueNames(string key) => _user.TryGetValue(key, out var values) ? [.. values.Keys] : []; + + public void DeleteUserValue(string key, string name) + { + if (_user.TryGetValue(key, out var values)) + { + values.Remove(name); + } + } + + public void DeleteUserKeyTree(string key) + { + foreach (var existing in _user.Keys.Where(k => k.Equals(key, StringComparison.OrdinalIgnoreCase) || k.StartsWith(key + "\\", StringComparison.OrdinalIgnoreCase)).ToList()) + { + _user.Remove(existing); + } + } + + public string? ReadMachineString(string key, string name) => Machine.GetValueOrDefault((key, name)); + + public void CreateShortcut(Shortcut shortcut) + { + Shortcuts.Add(shortcut); + Directory.CreateDirectory(Path.GetDirectoryName(shortcut.Path)!); + File.WriteAllText(shortcut.Path, shortcut.Target, Encoding.UTF8); + } + + public void OpenAddress(string address) => Opened.Add(address); + + public void Start(string executable, IReadOnlyList arguments, string workingDirectory) => Started.Add((executable, arguments, workingDirectory)); + + public void WaitForExit(int processId, TimeSpan timeout) => WaitedFor.Add(processId); + + public void Pause(TimeSpan delay) + { + } + + private Dictionary Values(string key) + { + if (!_user.TryGetValue(key, out var values)) + { + values = new Dictionary(StringComparer.OrdinalIgnoreCase); + _user[key] = values; + } + + return values; + } + } + + /// The pages, answered as told; each records its name in . + private sealed class ScriptedInterface : ISetupInterface + { + public bool DesktopShortcut { get; init; } = true; + + public bool StartFebe { get; init; } + + public bool OpenWebView2Page { get; init; } + + public bool Confirm { get; init; } = true; + + public Queue Retries { get; init; } = new([true]); + + public List Calls { get; } = []; + + public string? Version { get; private set; } + + public string? Folder { get; private set; } + + public (string DataFolder, string Library)? UninstalledWith { get; private set; } + + public bool? Welcome(string version, string? installedVersion, string installFolder) + { + Calls.Add("benvenuto"); + Version = installedVersion; + Folder = installFolder; + return DesktopShortcut; + } + + public bool RetryWhenFebeIsOpen(bool uninstalling) + { + Calls.Add("aperto"); + return Retries.Count > 0 && Retries.Dequeue(); + } + + public void RunWithProgress(string version, string installFolder, Action> work) + { + Calls.Add("avanzamento"); + work(_ => { }); + } + + public bool OfferWebView2Page() + { + Calls.Add("webview2"); + return OpenWebView2Page; + } + + public bool Installed() + { + Calls.Add("installato"); + return StartFebe; + } + + public bool ConfirmUninstall() + { + Calls.Add("conferma"); + return Confirm; + } + + public void Uninstalled(string dataFolder, string library) + { + Calls.Add("disinstallato"); + UninstalledWith = (dataFolder, library); + } + + public void Failed(bool uninstalling, string message) => Calls.Add("errore: " + message); + } } diff --git a/tests/Febe.Tests/Desktop/Support/Repository.cs b/tests/Febe.Tests/Desktop/Support/Repository.cs index 069f95c..269723d 100644 --- a/tests/Febe.Tests/Desktop/Support/Repository.cs +++ b/tests/Febe.Tests/Desktop/Support/Repository.cs @@ -1,6 +1,6 @@ namespace Febe.Tests.Desktop.Support; -/// Files of the repository the desktop tests look at (the committed icon, the NSIS script). +/// Files of the repository the desktop tests look at (the committed icon, the build script of the installer). internal static class Repository { /// The folder with Febe.slnx, found from the test binaries upward; null outside a checkout. diff --git a/tests/Febe.Tests/Febe.Tests.csproj b/tests/Febe.Tests/Febe.Tests.csproj index cfa37cb..807ef63 100644 --- a/tests/Febe.Tests/Febe.Tests.csproj +++ b/tests/Febe.Tests/Febe.Tests.csproj @@ -14,6 +14,7 @@ + diff --git a/tests/Febe.Tests/Packaging/PipelineTests.cs b/tests/Febe.Tests/Packaging/PipelineTests.cs index e4e4b87..905e349 100644 --- a/tests/Febe.Tests/Packaging/PipelineTests.cs +++ b/tests/Febe.Tests/Packaging/PipelineTests.cs @@ -69,11 +69,24 @@ public sealed partial class PipelineTests StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\""); var environment = Script("ambiente-prove.sh"); - foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" }) + foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "locales" }) { StringAssert.Contains(environment, package); } + // The installer is ours (src/Febe.Installer): no installer tool, no zip, nothing to install for it. + foreach (var gone in new[] { "nsis", "zip" }) + { + Assert.IsFalse(Regex.IsMatch(Code(environment), $@"\b{gone}\b"), $"ambiente-prove.sh: «{gone}»"); + } + + foreach (var (name, job) in new[] { ("verifica.yml", "installatore"), ("rilascio.yml", "windows") }) + { + var steps = Job(Workflow(name), job); + StringAssert.Contains(steps, "bash installer/costruisci.sh", $"{name}: {job}"); + Assert.DoesNotContain("apt-get", steps, $"{name}: {job} needs only the .NET SDK"); + } + // tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project. foreach (var name in new[] { "verifica.yml", "rilascio.yml" }) {