diff --git a/.gitattributes b/.gitattributes index a54dd85..d1cf138 100644 --- a/.gitattributes +++ b/.gitattributes @@ -16,3 +16,9 @@ *.dmg binary *.msi binary *.deb binary + +# Windows batch files need CRLF (cmd.exe has LF edge cases, e.g. around +# labels); BMPs are binary. Used by packaging/windows/ installer scripts +# and img/installer_*.bmp — see the installer polish design (issue #183). +*.bat text eol=crlf +*.bmp binary diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 8c68271..7c623d6 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -6,6 +6,7 @@ on: - "pyproject.toml" - "src/**" - "img/**" + - "packaging/windows/**" - ".github/workflows/build-windows.yml" workflow_dispatch: diff --git a/CHANGELOG.md b/CHANGELOG.md index c1470f6..de5848e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Windows installer polish**: the MSI now creates a desktop shortcut, asks + per-user vs per-machine at install time, and shows a proper finish page + ("Launch ProFiles" checkbox plus Documentation / What's new links). +- **"Add ProFiles to PATH" install option** (checked by default, both + scopes): `profiles --headless` works from any new terminal after a + default install; the entry is removed on uninstall. Silent installs keep + working (`/qn`) and opt out via `msiexec /i ProFiles-.msi /qn + OPTION_ADD_TO_PATH=0`. +- **Branded installer**: the welcome dialog and page banners now use the + ProFiles brand art (indigo-violet gradient) instead of the stock WiX look. + ### Changed - **Loopback-only by default**: the web server now binds `127.0.0.1` on launch diff --git a/docs/installation-guide.en.md b/docs/installation-guide.en.md index ca3a49d..fe4babd 100644 --- a/docs/installation-guide.en.md +++ b/docs/installation-guide.en.md @@ -35,6 +35,35 @@ Download the installer for your platform from the Launch ProFiles from your Start Menu (Windows), `/Applications` (macOS), or your application launcher (Linux). No Python installation is needed. +### Windows installer options + +The MSI wizard walks through: **license → install scope → install folder → +install options → install**. + +- **Install scope** — the wizard asks whether to install *per-user* (no + admin rights, just for you) or *per-machine* (all users, requires local + Administrator privileges). +- **Add ProFiles to PATH** — checked by default. Lets you run + `profiles --headless` (and the other CLI modes) from any *new* terminal + window, out of the box. Uncheck it if you prefer not to modify PATH. + A Start Menu entry **and a desktop shortcut** are always created. +- **Finish page** — a checked *Launch ProFiles* box plus links to the + [documentation](../README.md) and the [what's new](../CHANGELOG.md) page. + +Silent installs keep working and add ProFiles to PATH by default: + +```bat +:: quiet install (PATH included by default) +msiexec /i ProFiles-.msi /qn + +:: quiet install without the PATH modification +msiexec /i ProFiles-.msi /qn OPTION_ADD_TO_PATH=0 +``` + +Uninstalling (from *Settings → Apps* or `msiexec /x`) removes the PATH +entry the installer added and both shortcuts — your `.profiles` +configurations and logs are left untouched. + ## Method 2: One-Line Install (Developers) Requires Python 3.11+ on the machine. diff --git a/docs/installation-guide.fr.md b/docs/installation-guide.fr.md index f2fb7ae..19a5007 100644 --- a/docs/installation-guide.fr.md +++ b/docs/installation-guide.fr.md @@ -32,6 +32,38 @@ Téléchargez l'installateur de votre plateforme depuis la page Aucune installation de Python n'est requise. +### Options de l'installateur Windows + +L'assistant MSI se parcourt ainsi : **licence → périmètre d'installation → +dossier → options d'installation → installation**. + +- **Périmètre d'installation** — l'assistant demande une installation + *par utilisateur* (aucun droit admin, que pour vous) ou *par machine* + (tous les utilisateurs, nécessite les privilèges Administrateur locaux). +- **Ajouter ProFiles au PATH** — cochée par défaut. Permet de lancer + `profiles --headless` (et les autres modes CLI) depuis n'importe quel + *nouveau* terminal, sans configuration. Décochez-la si vous préférez ne + pas modifier le PATH. Une entrée dans le menu Démarrer **et un + raccourci bureau** sont toujours créés. +- **Page de fin** — une case *Launch ProFiles* cochée par défaut, plus des + liens vers la [documentation](../README.md) et les + [nouveautés](../CHANGELOG.md). + +Les installations silencieuses continuent de fonctionner et ajoutent +ProFiles au PATH par défaut : + +```bat +:: installation silencieuse (PATH inclus par défaut) +msiexec /i ProFiles-.msi /qn + +:: installation silencieuse sans modification du PATH +msiexec /i ProFiles-.msi /qn OPTION_ADD_TO_PATH=0 +``` + +La désinstallation (via *Paramètres → Applications* ou `msiexec /x`) retire +l'entrée de PATH ajoutée par l'installateur ainsi que les deux raccourcis — +vos configurations `.profiles` et vos journaux restent intacts. + ## Méthode 2 : Installation en une ligne (Développeurs) Nécessite Python 3.11+. diff --git a/docs/superpowers/plans/2026-11-18-installer-art-native-frame.md b/docs/superpowers/plans/2026-11-18-installer-art-native-frame.md new file mode 100644 index 0000000..3fc8186 --- /dev/null +++ b/docs/superpowers/plans/2026-11-18-installer-art-native-frame.md @@ -0,0 +1,197 @@ +# Installer Art Native-Frame Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Rework the two MSI BMPs so WiX's black text never lands on artwork, while keeping the ProFiles brand visible. + +**Architecture:** Adopt the stock WiX art layout. The 493×312 background becomes a 164 px brand panel on the left plus a white text zone; the 493×58 banner becomes white for the title zone (x=0–428) plus a brand block on the right (x=429–492). Both are generated at 4× and LANCZOS-downsampled by the existing Pillow script, then committed. + +**Tech Stack:** Pillow (generator, dev-side only), pytest (layout regression tests), Briefcase 0.4.7 / WiX UI (consumer). + +**Spec:** `docs/superpowers/specs/2026-11-18-installer-art-native-frame-design.md` + +## Global Constraints + +- No changes under `src/profiles/**`. +- BMPs are committed assets at exactly 493×312 / 493×58, 24-bit RGB; never generated at build time. +- Generator stays stdlib + Pillow and **font-free** (no text rendering). +- No WiX/Briefcase template changes; art-only fix. +- Commits use explicit paths; the working tree carries unrelated `.zcode/` and `src/profiles/web/dist/` churn that must NOT be committed. +- English-only docs; `tests/AGENTS.md` needs no change (no new test file). + +## Review Focus + +1. **Banner title contrast** — the black page title is drawn at x≈20; the banner must be white left of x=429. Pinned by `test_banner_keeps_title_zone_clear`. +2. **Dialog text/link/checkbox contrast** — body text starts at x≈173; the background must be white right of x=169. Pinned by `test_background_keeps_text_zone_clear`. +3. **DPI crispness** — the banner is downscaled to 370×44; 4× supersampling prevents ragged logo edges. Verified visually and by the unchanged dimension tests. +4. **Half-applied fix** — banner reworked but background not (or vice versa). The two tests cover one asset each, so both must pass. +5. **Docs drift** — the 2026-11-17 spec still describes full-bleed art. Task 2 replaces that section and the plan's Task 2 text. + +--- + +### Task 1: Rework the BMP generator and regenerate both assets + +**Files:** +- Modify: `packaging/windows/generate_bmps.py` +- Modify: `img/installer_background.bmp`, `img/installer_banner.bmp` (regenerated) +- Test: `tests/packaging/test_windows_installer_assets.py` + +**Interfaces:** +- Produces: `generate_background() -> Image.Image`, `generate_banner() -> Image.Image` (same public names the `main()` entry point already calls). +- Produces: module constants `SCALE = 4`, `PANEL_WIDTH = 164`, `BANNER_BRAND_X = 429`, `BANNER_BRAND_WIDTH = 64`. +- Produces: `_mark(size, radius, bar_width, bar_height, gap, pad, third_width) -> Image.Image` returning an RGBA mark at `SCALE`× resolution. + +- [ ] **Step 1: Add the failing layout tests** + +Append to `tests/packaging/test_windows_installer_assets.py`: + +```python +def test_banner_keeps_title_zone_clear() -> None: + """WiX draws the black banner title at x≈20; keep x<429 white.""" + path = REPO_ROOT / "img" / "installer_banner.bmp" + with Image.open(path) as img: + rgb = img.convert("RGB") + darkest = min(band[0] for band in rgb.crop((0, 0, 429, 58)).getextrema()) + edge = rgb.getpixel((428, 6)) + brand = rgb.getpixel((430, 6)) + assert darkest >= 250 # no art under the title + assert min(edge) >= 250 # title zone reaches the brand block + assert brand[2] > brand[0] # indigo/violet block on the right + + +def test_background_keeps_text_zone_clear() -> None: + """WiX draws body text from x≈173; keep x>169 white.""" + path = REPO_ROOT / "img" / "installer_background.bmp" + with Image.open(path) as img: + rgb = img.convert("RGB") + darkest = min(band[0] for band in rgb.crop((170, 0, 493, 312)).getextrema()) + panel = rgb.getpixel((10, 156)) + boundary = rgb.getpixel((164, 156)) + assert darkest >= 250 # no art under the text, links or checkbox + assert panel[2] > panel[0] # brand panel on the left + assert min(boundary) >= 250 # panel ends at x=163 +``` + +- [ ] **Step 2: Run the tests to verify they fail on the current art** + +Run: `uv run --no-sync pytest tests/packaging/test_windows_installer_assets.py -q` +Expected: the two new tests FAIL (`assert darkest >= 250`), all existing tests pass. + +- [ ] **Step 3: Rewrite the generator** + +In `packaging/windows/generate_bmps.py`: + +- Set `SCALE = 4`, `WHITE = (255, 255, 255)`, `PANEL_WIDTH = 164`, + `BANNER_BRAND_X = 429`, `BANNER_BRAND_WIDTH = 64`. +- Keep `GRADIENT_LEFT`, `GRADIENT_RIGHT`, `BACKGROUND_SIZE`, `BANNER_SIZE`, `_lerp`. +- Remove `SOURCE`, `MARK_BOX`, `MARK_BARS`, `PILLS` and the cover-crop logic. +- Add `_h_gradient(size)` and `_v_gradient(size)` helpers that draw one line per + column/row with `_lerp` (same technique as the old banner). +- Add `_mark(...)` drawing a white rounded square with three `GRADIENT_LEFT` + bars on an RGBA layer, all dimensions multiplied by `SCALE` internally. +- `generate_background()`: `493×312` canvas filled white; paste a + `164×312` vertical gradient at `(0, 0)`; paste a 56 px mark at + `(54, 128)` with radius 14, bars 30×6, gap 4, pad 13, third bar 19; + resize to `(493, 312)` with `Image.LANCZOS`. +- `generate_banner()`: `493×58` canvas filled white; paste a `64×58` + horizontal gradient at `(429, 0)`; paste a 34 px mark at `(444, 12)` + with radius 9, bars 18×4, gap 2, pad 8, third bar 11; resize to + `(493, 58)` with `Image.LANCZOS`. +- Update the module docstring (native-frame zones, no source PNG) and make + `--check` use only the script itself as the input timestamp. + +- [ ] **Step 4: Regenerate and verify** + +Run: `uv run --no-sync python packaging/windows/generate_bmps.py` +Run: `uv run --no-sync pytest tests/packaging/test_windows_installer_assets.py -q` +Expected: all tests PASS. + +- [ ] **Step 5: Eyeball the assets** + +Convert both BMPs to PNG (Pillow) and inspect them: banner left of x=429 +pure white with the mark in the right block; background left panel purple +with the mark, right side pure white. Compare against the approved mock-up. + +- [ ] **Step 6: Commit** + +```bash +git add packaging/windows/generate_bmps.py img/installer_background.bmp img/installer_banner.bmp tests/packaging/test_windows_installer_assets.py +git commit -m "fix(installer): keep WiX text zones clear in branded art" && git show --stat +``` + +--- + +### Task 2: Sync the design docs and packaging README + +**Files:** +- Modify: `docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md` (§6.2) +- Modify: `docs/superpowers/plans/2026-11-18-windows-installer-polish.md` (Task 2 art description) +- Modify: `packaging/windows/README.md` (art section) +- Commit: `docs/superpowers/specs/2026-11-18-installer-art-native-frame-design.md` (already in tree) + +**Interfaces:** +- Consumes: the layout values from Task 1. +- Produces: no code; keeps the committed spec truthful. + +- [ ] **Step 1: Update the 2026-11-17 spec §6.2** + +Replace the two-row table content with a short native-frame description +(164 px panel / white text zone; white title zone x=0–428 / brand block +x=429–492) and mark the "Open visual checkpoint" resolved: WiX renders +black text, mitigated by the text-safe zones. Link +`2026-11-18-installer-art-native-frame-design.md` as the superseding doc. + +- [ ] **Step 2: Update the 2026-11-18 implementation plan Task 2** + +Replace the "Art (spec §6.2, direction A)" paragraph and the Step 3 sketch +with the native-frame layout and a reference to the new spec. Keep the +rest of the task unchanged. + +- [ ] **Step 3: Update the packaging README** + +In "Regenerating the installer art", add that the layout follows WiX's +text-safe zones (banner title zone white, background text zone white) and +link the new spec alongside the original one. + +- [ ] **Step 4: Commit** + +```bash +git add docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md docs/superpowers/plans/2026-11-18-windows-installer-polish.md packaging/windows/README.md docs/superpowers/specs/2026-11-18-installer-art-native-frame-design.md +git commit -m "docs: record native-frame installer art layout" && git show --stat +``` + +--- + +### Task 3: Quality gates and PR artifact + +**Files:** none (verification only). + +- [ ] **Step 1: Format and lint the touched Python files** + +Run: `uv run --no-sync ruff format packaging/windows/generate_bmps.py tests/packaging/test_windows_installer_assets.py` +Run: `uv run --no-sync ruff check packaging/windows/generate_bmps.py tests/packaging/test_windows_installer_assets.py` +Expected: clean. Commit any formatting fallout under `style: ruff format`. + +- [ ] **Step 2: Full test suite** + +Run: `uv run --no-sync pytest -q` +Expected: all tests pass (the packaging module included). + +- [ ] **Step 3: Push and let CI rebuild the MSI** + +Run: `git push` +Expected: `build-windows.yml` starts; the `ProFiles-windows-msi` artifact is +the final visual check on the work machine. + +- [ ] **Step 4: Report** + +Tell the owner the new artifact is ready and which screens to check +(progress/banner pages, welcome, finish). The PR description's visual +checkpoint can be updated once the artifact is confirmed. + +## Self-Review Notes + +- Spec coverage: background zones → Task 1; banner zones → Task 1; superseding docs → Task 2; verification → Task 3. +- Types/names consistent: `generate_background`, `generate_banner`, `_mark`, `SCALE`, `PANEL_WIDTH`, `BANNER_BRAND_X` used as defined. +- Review Focus lines 1–4 are pinned by Task 1 tests; line 5 by Task 2. +- No new files mean `tests/AGENTS.md` and `AGENTS.md` trees stay accurate. diff --git a/docs/superpowers/plans/2026-11-18-windows-installer-polish.md b/docs/superpowers/plans/2026-11-18-windows-installer-polish.md new file mode 100644 index 0000000..b730256 --- /dev/null +++ b/docs/superpowers/plans/2026-11-18-windows-installer-polish.md @@ -0,0 +1,362 @@ +# Windows Installer Polish Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make the Windows MSI match its documentation: desktop shortcut, real finish page (Launch + links), PATH convenience option, and branded installer art — as declarative Briefcase 0.4.7 config plus two small bundled `.bat` scripts, in one PR closing #183. + +**Architecture:** Everything lives in `[tool.briefcase.app.profiles.windows]` config, committed BMP assets, and `packaging/windows/` scripts. PATH is the only custom behaviour: the WiX template's native PATH feature is console-app-only, so `install_option add_to_path` (singular key!) drives a checkbox whose state is passed to a bundled `post_install.bat` (PowerShell registry edit, `REG_EXPAND_SZ`-safe, `WM_SETTINGCHANGE` broadcast); `pre_uninstall.bat` removes the exact entry from both hives. + +**Tech Stack:** Briefcase 0.4.7 + WiX v5 template (no vendoring), PowerShell 5.1 via `.bat`, Pillow (asset generation, dev-side only), pytest + tomllib (coherence tests). + +**Spec:** `docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md` (§ numbers below refer to it) + +## Global Constraints + +- One PR, branch `feat/installer-polish-183`, `Closes #183` (spec §3). +- **No changes under `src/profiles/**`** (spec §3). +- English-only installer surface (spec §4). +- BMPs are committed assets, 493×312 / 493×58, 24-bit RGB (spec §6.2); never generated at build time; generator script committed for provenance. +- `.bat` scripts always end `exit /b 0`; recoverable failures log and continue (`Return="check"` would fail the install — spec §6.3.4). +- PATH edits: `DoNotExpandEnvironmentNames` read + `ExpandString` write, exact-match add/remove, no `setx` (spec §4, §6.3). +- Config key is **singular** `install_option`, array of tables, each entry requires `name` (spec §6.1 notes; reviewer-verified against the briefcase 0.4.7 wheel). +- Commits use explicit paths — the working tree carries unrelated `src/profiles/web/dist/` churn that must NOT be committed. Verify `git show --stat` after every commit. +- `tests/AGENTS.md` mirrors the tests tree — update it in the commit that adds the test file. + +## Review Focus + +1. **Install paths with spaces** (`C:\Program Files\ProFiles`) through cmd→PowerShell quoting — expect the PATH entry to be correct, not truncated/split. Pinned by Task 3 test (quoting markers in `.bat`) and the Task 8 manual checklist (install to a spaced path). +2. **`REG_EXPAND_SZ` destruction** (`%SystemRoot%` refs expanded to literals) — expect preserved. Pinned by Task 3/4 test markers (`DoNotExpandEnvironmentNames`, `ExpandString`) and checklist. +3. **Silent install `/qn` regression** — expect PATH added by default, no hang, opt-out via `OPTION_ADD_TO_PATH=0`. Pinned by Task 4 test (`default = true`) and checklist. +4. **Uninstall collateral damage** — expect exact-match removal only; `.profiles` configs/logs untouched. Pinned by Task 3 test (exact-match marker) and checklist. +5. **Plural-key silent feature loss** (`install_options` instead of `install_option`) — expect the Install Options page to exist. Pinned by Task 4 test (singular key present AND plural absent). + +--- + +### Task 1: Branch + `.gitattributes` rules + +**Files:** +- Modify: `.gitattributes` (append after the existing binary block) +- Branch: `feat/installer-polish-183` off current `main` + +**Interfaces:** +- Produces: attribute rules that must exist **before** any `.bat`/`.bmp` is `git add`-ed (Task 2, Task 3). + +- [ ] **Step 1: Sync and branch** + +```bash +git fetch origin && git status --short # expect only the known dist/ churn +git checkout -b feat/installer-polish-183 origin/main +``` + +- [ ] **Step 2: Append rules** + +```gitattributes +# Windows batch files need CRLF (cmd.exe LF edge cases); BMPs are binary. +*.bat text eol=crlf +*.bmp binary +``` + +- [ ] **Step 3: Commit** + +```bash +git add .gitattributes +git commit -m "chore: enforce CRLF for .bat and binary handling for .bmp" && git show --stat +``` + +### Task 2: Branded BMP assets + generator + first coherence tests + +**Files:** +- Create: `packaging/windows/generate_bmps.py` +- Create: `img/installer_background.bmp` (493×312), `img/installer_banner.bmp` (493×58) +- Test: `tests/packaging/test_windows_installer_assets.py` (create) +- Modify: `tests/AGENTS.md` (tree entry for the new test file) + +**Interfaces:** +- Produces: `img/installer_background.bmp`, `img/installer_banner.bmp` at the exact paths Task 4's pyproject references; test module that Tasks 3–4 extend. + +Art (spec §6.2, superseded by `2026-11-18-installer-art-native-frame-design.md`): native-frame layout. Background = 164 px brand panel on the left (gradient + white mark), plain white from x=164 for WiX dialog text; banner = white x=0–428 for the black page title, brand block with the white mark at x=429–492. Render at 4× and LANCZOS-downsample; font-free. + +- [ ] **Step 1: Write the failing tests** + +```python +"""Coherence checks for the Windows MSI installer assets and config. + +The Windows packaging (pyproject briefcase config + bundled scripts + BMP +art) is exercised only by CI's build-windows job; these tests catch the +breakages that would otherwise surface only there. See +docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md. +""" + +from pathlib import Path + +from PIL import Image + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def test_background_bmp_dimensions() -> None: + """Welcome-dialog art is a 493x312 24-bit BMP (WiX WixUIDialogBmp).""" + path = REPO_ROOT / "img" / "installer_background.bmp" + assert path.is_file() + with Image.open(path) as img: + assert img.format == "BMP" + assert img.size == (493, 312) + assert img.mode == "RGB" + + +def test_banner_bmp_dimensions() -> None: + """Banner art is a 493x58 24-bit BMP (WiX WixUIBannerBmp).""" + path = REPO_ROOT / "img" / "installer_banner.bmp" + assert path.is_file() + with Image.open(path) as img: + assert img.format == "BMP" + assert img.size == (493, 58) + assert img.mode == "RGB" +``` + +- [ ] **Step 2: Run to verify failure** + +Run: `uv run pytest tests/packaging/test_windows_installer_assets.py -v` +Expected: FAIL (`assert path.is_file()` — BMPs missing) + +- [ ] **Step 3: Write `packaging/windows/generate_bmps.py`** + +Deterministic Pillow script, stdlib+Pillow only, no font rendering (font-free keeps it reproducible across dev machines). Body sketch: draw both assets at 4× and `Image.LANCZOS`-downsample. Background = 493×312: 164 px vertical gradient panel (`#635BCC`→`#825ED9`) at the left, 56 px white mark at (54, 128) with three indigo bars, rest white. Banner = 493×58: white, 64 px horizontal gradient block at x=429, 34 px mark at (444, 12). Save BMP RGB. `--check` flag exits 1 if outputs missing/stale (used by the next step, not by CI). + +- [ ] **Step 4: Generate and verify** + +Run: `uv run python packaging/windows/generate_bmps.py && uv run pytest tests/packaging/test_windows_installer_assets.py -v` +Expected: PASS (2 tests). Eyeball both BMPs via Read (image preview) against the approved native-frame mock-up. + +- [ ] **Step 5: Update `tests/AGENTS.md`** tree entry for `tests/packaging/test_windows_installer_assets.py` (read the file first; mirror its existing entry style). + +- [ ] **Step 6: Commit** + +```bash +git add packaging/windows/generate_bmps.py img/installer_background.bmp img/installer_banner.bmp tests/packaging/test_windows_installer_assets.py tests/AGENTS.md +git commit -m "feat(installer): add branded MSI background/banner assets" && git show --stat +``` + +### Task 3: PATH scripts (`.bat` ×2) + provenance README + +**Files:** +- Create: `packaging/windows/post_install.bat`, `packaging/windows/pre_uninstall.bat` (CRLF) +- Create: `packaging/windows/README.md` +- Test: extend `tests/packaging/test_windows_installer_assets.py` + +**Interfaces:** +- Consumes (runtime, from the Briefcase wrapper env): `ALLUSERS`, `INSTALLER_PATH`, `INSTALLER_UNATTENDED`, `OPTION_ADD_TO_PATH`; `%~dp0` = `\_installer\` (spec §2.3). +- Produces: script paths referenced by Task 4's pyproject. + +- [ ] **Step 1: Write the failing tests** (append to the module) + +```python +SCRIPTS = ("post_install.bat", "pre_uninstall.bat") + + +def test_bat_scripts_exist_and_exit_clean() -> None: + """Both scripts exist and always terminate 0 (WiX Return="check").""" + for name in SCRIPTS: + body = (REPO_ROOT / "packaging" / "windows" / name).read_bytes() + assert b"exit /b 0" in body + assert body.rstrip().endswith(b"exit /b 0") + assert b"\r\n" in body # committed via *.bat eol=crlf + + +def test_post_install_preserves_expand_sz_and_broadcasts() -> None: + """PATH edit must not expand REG_EXPAND_SZ and must notify shells.""" + body = (REPO_ROOT / "packaging" / "windows" / "post_install.bat").read_text(encoding="utf-8") + assert "DoNotExpandEnvironmentNames" in body + assert "ExpandString" in body + assert "setx" not in body.lower() + # WM_SETTINGCHANGE broadcast (0x1a) to running Explorer/shells. + assert "SendMessageTimeout" in body and "0x1a" in body + # Quoting survives "C:\Program Files\..." paths. + assert "OPTION_ADD_TO_PATH" in body and "ALLUSERS" in body + + +def test_pre_uninstall_removes_exactly_its_own_entry() -> None: + """Cleanup matches the literal install dir in BOTH hives, nothing else.""" + body = (REPO_ROOT / "packaging" / "windows" / "pre_uninstall.bat").read_text(encoding="utf-8") + assert body.count("DoNotExpandEnvironmentNames") >= 2 # HKCU and HKLM + assert "ExpandString" in body and "setx" not in body.lower() + assert "SendMessageTimeout" in body +``` + +- [ ] **Step 2: Run to verify failure** — `uv run pytest tests/packaging/test_windows_installer_assets.py -v` → new tests FAIL (files missing) + +- [ ] **Step 3: Write the two `.bat` files** + +`post_install.bat` behavioural skeleton (cmd layer only; the PowerShell one-liner does the registry work in a single `-Command`, single-quoted PS strings throughout, `\"` escapes only inside the C# `MemberDefinition`): + +```bat +@echo off +setlocal +REM ProFiles post-install: add the install dir to PATH when the user asked +REM for it on the Install Options page. Wrapper exports ALLUSERS (0/1), +REM INSTALLER_PATH, INSTALLER_UNATTENDED, OPTION_ADD_TO_PATH; %~dp0 is the +REM _installer folder inside the install dir. Spec: docs/superpowers/specs/ +REM 2026-11-17-windows-installer-polish-design.md section 6.3. +set "LOG=%~dp0path_setup.log" +> "%LOG%" echo [%DATE% %TIME%] ProFiles post-install start +>>"%LOG%" echo OPTION_ADD_TO_PATH=%OPTION_ADD_TO_PATH% ALLUSERS=%ALLUSERS% UNATTENDED=%INSTALLER_UNATTENDED% + +if not "%OPTION_ADD_TO_PATH%"=="1" ( + >>"%LOG%" echo Skipping PATH modification: option not selected. + exit /b 0 +) + +REM Install dir = parent of this script's _installer folder (%~fI resolves +REM the trailing ".." to an absolute path, no trailing backslash). +for %%I in ("%~dp0..") do set "INSTALL_DIR=%%~fI" +>>"%LOG%" echo Install dir: %INSTALL_DIR% + +set "SCOPE=User" +if "%ALLUSERS%"=="1" set "SCOPE=Machine" + +REM ; append output +REM to the log; on any failure log a WARNING and CONTINUE (never fail the +REM install for a PATH convenience). +>>"%LOG%" 2>&1 powershell -NoProfile -ExecutionPolicy Bypass -Command "" +if errorlevel 1 >>"%LOG%" echo WARNING: PATH update failed; install continues. + +exit /b 0 +``` + +`pre_uninstall.bat`: same shape; no option gate; **loop over both hives** (`User` then `Machine`) removing the literal install-dir entry, ignoring per-hive access errors (per-user uninstall cannot write HKLM — that is success, not failure); same dedupe/normalisation (`-ireplace`-free: plain split/filter/join), same broadcast, same log, same exit-0 policy. `%~dp0` is still valid: the action runs `After="InstallInitialize"`, before `RemoveFiles`. + +One-liner contract (what the PS string must do, either inline in each `.bat` or factored into an identical `-Command` string): `$dir`/`$scope` params; pick `CurrentUser`/`LocalMachine` + subkey `Environment` / `SYSTEM\CurrentControlSet\Control\Session Manager\Environment`; `GetValue('Path','', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)`; split `;`, drop empties, filter exact match (case-insensitive, `TrimEnd('\')` on both sides) — add `$dir` first for post-install / drop `$dir` for pre-uninstall; re-join; `SetValue('Path', $new, [Microsoft.Win32.RegistryValueKind]::ExpandString)`; broadcast via `Add-Type -MemberDefinition` P/Invoke `SendMessageTimeout` (HWND_BROADCAST=0xffff, 0x1a, 'Environment', 2, 5000); `exit 0`. + +- [ ] **Step 4: `packaging/windows/README.md`** — provenance note: what the scripts do, env-var contract, why no `setx`, how BMPs are regenerated (`uv run python packaging/windows/generate_bmps.py`), pointer to the spec. + +- [ ] **Step 5: Run tests to verify pass** — `uv run pytest tests/packaging/test_windows_installer_assets.py -v` → all PASS + +- [ ] **Step 6: Commit** + +```bash +git add packaging/windows/post_install.bat packaging/windows/pre_uninstall.bat packaging/windows/README.md tests/packaging/test_windows_installer_assets.py +git commit -m "feat(installer): add PATH post-install/pre-uninstall scripts" && git show --stat +``` + +### Task 4: `pyproject.toml` windows section + config tests + +**Files:** +- Modify: `pyproject.toml` (new `[tool.briefcase.app.profiles.windows]` table + `[[tool.briefcase.app.profiles.windows.install_option]]` array, placed after the `permission` table, **before** `[tool.pylint.MASTER]`) +- Test: extend `tests/packaging/test_windows_installer_assets.py` + +**Interfaces:** +- Consumes: `img/installer_background{.bmp}`, `img/installer_banner{.bmp}` (Task 2), `packaging/windows/{post_install,pre_uninstall}.bat` (Task 3). +- Produces: the exact TOML the CI MSI build consumes. + +- [ ] **Step 1: Write the failing tests** (append; `import tomllib`) + +```python +def test_windows_installer_config() -> None: + """The briefcase windows section matches the approved design.""" + with open(REPO_ROOT / "pyproject.toml", "rb") as fh: + cfg = tomllib.load(fh)["tool"]["briefcase"]["app"]["profiles"]["windows"] + + # Scope dialog stays the wizard default (perUserOrMachine). + assert "system_installer" not in cfg + assert cfg["create_desktop_shortcut"] is True + assert cfg["installer_background"] == "img/installer_background" + assert cfg["installer_banner"] == "img/installer_banner" + assert cfg["installer_completion_launch_app"] is True + assert cfg["post_install_script"] == "packaging/windows/post_install.bat" + assert cfg["pre_uninstall_script"] == "packaging/windows/pre_uninstall.bat" + + urls = cfg["installer_completion_urls"] + assert [u["title"] for u in urls] == ["Documentation", "What's new"] + assert all(u["url"].startswith("https://github.com/falbany/ProFiles") for u in urls) + + # Singular key, array-of-tables, required `name`. The plural + # `install_options` key is silently swallowed by DraftAppConfig. + assert "install_options" not in cfg # the plural trap + options = cfg["install_option"] + assert len(options) == 1 + opt = options[0] + assert opt["name"] == "add_to_path" + assert opt["default"] is True + assert opt["title"] == "Add ProFiles to PATH" + + +def test_referenced_installer_files_exist(tmp_path: Path) -> None: + """Every file the windows section references must resolve on disk.""" + with open(REPO_ROOT / "pyproject.toml", "rb") as fh: + cfg = tomllib.load(fh)["tool"]["briefcase"]["app"]["profiles"]["windows"] + + for key in ("installer_background", "installer_banner"): + # Briefcase resolves with_suffix(".bmp") against the project root. + assert (REPO_ROOT / f"{cfg[key]}.bmp").is_file() + for key in ("post_install_script", "pre_uninstall_script"): + assert (REPO_ROOT / cfg[key]).is_file() +``` + +- [ ] **Step 2: Run to verify failure** — `uv run pytest tests/packaging/test_windows_installer_assets.py -v` → config tests FAIL (no windows section) + +- [ ] **Step 3: Add the TOML** — exactly as spec §6.1 (corrected block: singular `[[tool.briefcase.app.profiles.windows.install_option]]` with `name`/`title`/`description`/`default = true`), with the explanatory comments from the spec (why `system_installer` is unset; the singular-key warning referencing the existing `document_type` comment; `.bmp` suffix-resolution note). + +- [ ] **Step 4: Run tests to verify pass** — `uv run pytest tests/packaging/test_windows_installer_assets.py -v` → all PASS + +- [ ] **Step 5: Commit** + +```bash +git add pyproject.toml tests/packaging/test_windows_installer_assets.py +git commit -m "feat(installer): enable Windows MSI installer options" && git show --stat +``` + +### Task 5: Docs, CHANGELOG, spec/plan docs + +**Files:** +- Modify: `docs/installation-guide.en.md`, `docs/installation-guide.fr.md`, `CHANGELOG.md` +- Commit (already in tree): spec + this plan document + +- [ ] **Step 1: Update the EN guide** — read the current MSI bullet (the "A Start Menu entry and desktop shortcut are created" sentence); correct it and add a short **Installer options** sub-block under Method 1: scope dialog (per-user vs per-machine), Install Options page ("Add ProFiles to PATH", checked by default), finish page (Launch + Documentation / What's new links); `msiexec /qn` keeps working with PATH included, `OPTION_ADD_TO_PATH=0` opts out; `profiles --headless` works from any **new** terminal after install. + +- [ ] **Step 2: Mirror in the FR guide** — translate the same changes; keep the FR doc's existing voice. + +- [ ] **Step 3: CHANGELOG** — under `[Unreleased]`, add an `### Added` section (before the existing `### Changed`): desktop shortcut, scope dialog, finish page (Launch + links), "Add ProFiles to PATH" install option, branded installer art; note silent-install opt-out property. + +- [ ] **Step 4: Verify link targets** — the two finish-page URLs (`https://github.com/falbany/ProFiles#readme`, `.../blob/main/CHANGELOG.md`) resolve; guide anchors/paths valid. + +- [ ] **Step 5: Commit** + +```bash +git add docs/installation-guide.en.md docs/installation-guide.fr.md CHANGELOG.md docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md docs/superpowers/plans/2026-11-18-windows-installer-polish.md +git commit -m "docs: document MSI installer options and PATH convenience" && git show --stat +``` + +### Task 6: CI trigger addition + +**Files:** +- Modify: `.github/workflows/build-windows.yml` (`paths:` list) + +- [ ] **Step 1: Add `packaging/windows/**`** to the `on.pull_request.paths` list (spec §6.8; effective within this PR — GitHub uses the PR branch's workflow for `pull_request` events). + +- [ ] **Step 2: Commit** + +```bash +git add .github/workflows/build-windows.yml +git commit -m "ci: rebuild MSI when packaging scripts change" && git show --stat +``` + +### Task 7: Quality gates + +- [ ] **Step 1:** `uv run ruff format .` (expect: only packaging/tests files touched, if any) and `uv run ruff check --fix .` +- [ ] **Step 2:** `uv run pytest` — full suite green (new module included) +- [ ] **Step 3:** `uv run pylint src/profiles` — score ≥ 8.0 (src untouched; guard against import-time regressions) +- [ ] **Step 4:** Commit any formatting fallout (`style: ruff format`), else proceed. + +### Task 8: Push, PR, MSI artifact + +- [ ] **Step 1:** `git push -u origin feat/installer-polish-183` +- [ ] **Step 2:** `gh pr create` — title `feat(installer): Windows MSI polish (shortcuts, finish page, PATH option, branding)`; body: summary, `Closes #183`, the reviewer calls made (workflow one-liner, spec self-correction), and the **work-machine test checklist** from spec §7 (per-user + per-machine install, PATH in new terminal both scopes, uninstall interactive + `/x /qn`, `/qn` install + `OPTION_ADD_TO_PATH=0` opt-out, upgrade-over-current-release, **banner text-contrast checkpoint**). +- [ ] **Step 3:** Watch `build-windows.yml` on the PR (`gh run watch`), then report the artifact (`ProFiles-windows-msi`) to the owner for the work-machine pass. CI green (quality + windows build) is the completion signal for this session; the checklist execution stays with the owner. + +## Self-Review Notes + +- Spec coverage: §6.1→T4, §6.2→T2, §6.3/6.4→T3, §6.5→T5, §6.6→T2–T4, §6.7→T1, §6.8→T6, §7→T8, §2/§4/§8 are rationale (no build artefact). macOS explicitly out (§3). +- The PowerShell one-liner body is deliberately specified as a *contract* (Step 3 list) not a transcript — its exact quoting is validated on Windows in T8; content markers are pinned by T3 tests. +- Types/names consistent: `install_option` (singular) everywhere; file paths match across T2/T3/T4. diff --git a/docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md b/docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md new file mode 100644 index 0000000..d7261ad --- /dev/null +++ b/docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md @@ -0,0 +1,353 @@ +# Windows Installer Polish Design (MSI options, PATH convenience, branding) + +- **Date:** 2026-11-17 (finalised 2026-11-18) +- **Status:** Approved design — awaiting implementation +- **Author:** ProFiles team +- **Implements:** [Issue #183](https://github.com/falbany/ProFiles/issues/183) (Windows MSI scope only) + +--- + +## 1. Problem Statement + +The Windows MSI (`ProFiles-.msi`) is built with Briefcase defaults: + +- **No desktop shortcut** — the installation guide promises "a Start Menu entry + and desktop shortcut are created" (`docs/installation-guide.en.md`), but the + current config produces no desktop shortcut. The docs are ahead of reality. +- **Bare finish page** — no "Launch ProFiles" convenience, no links to docs / + what's new after install. +- **No PATH convenience** — `profiles --headless` automation is a documented + usage mode, but the packaged app is not on PATH, so terminal use requires + typing the full install path. +- **Stock installer branding** — plain WiX look, while the project has brand + assets (indigo-violet gradient, `img/ProFiles_banner.png`, white logo mark). + +## 2. Ground truth — Briefcase 0.4.7 Windows MSI backend + +All of the following was verified directly against the **Briefcase v0.4.7** +source (the version pinned in `uv.lock`) and the **`briefcase-windows-app-template`** +WiX template it uses. The issue's premise that "all installer options are +unused" stands, but its assumption that most features need custom machinery +was based on pre-0.4 docs: **nearly everything is native declarative config**. + +### 2.1 Native config inventory (`[tool.briefcase.app.profiles.windows]`) + +| Config key | Effect | Verified behaviour | +| --- | --- | --- | +| `system_installer` *(unset)* | Wizard asks per-user vs per-machine | `install_scope = "perUserOrMachine"` → WiX `InstallScopeDlg` in the wizard | +| `create_desktop_shortcut = true` | Desktop shortcut, checked by default | `DesktopFolder` component; visible as a feature checkbox in the customize flow | +| `installer_background` | Welcome-dialog art | Path is `with_suffix(".bmp")`-resolved against project root; **file must be a 493×312 BMP** | +| `installer_banner` | Top strip art on every other dialog | Same mechanism; **file must be a 493×58 BMP** | +| `installer_completion_launch_app` | "Launch ProFiles" checkbox on finish page | `COMPLETION_LAUNCH` property preset to `1` (checked by default); launch honoured interactively only | +| `installer_completion_text` | Custom install-finish text | Rendered on `ExitDialog` (install case) | +| `uninstaller_completion_text` | Custom uninstall-finish text | Rendered on `ExitDialog` (uninstall case) | +| `installer_completion_urls` | Up to 5 hyperlinks on the finish page | List of `{title = …, url = …}`; install case only | +| `install_option` *(singular!)* | Real checkboxes on a dedicated **Install Options** wizard page | **Array of tables** `[[…install_option]]`, each with required `name`, `title`, `description`, optional `default`/`system` → becomes `OPTION_` public property; `default = true` ⇒ checked; `system` unset ⇒ visible in both scopes. Same plural-vs-singular trap as `document_type` (see pyproject comment): the plural `install_options` key is silently swallowed by `**kwargs` and overwritten in `DraftAppConfig` — use the singular key. | +| `post_install_script` / `pre_uninstall_script` | Bundled `.bat` hooks | Must be `.bat`, path relative to project root; copied to `/extras/_installer/{post_install,pre_uninstall}.bat` | + +### 2.2 Wizard flow (interactive, with our config) + +``` +Welcome → License → Install Scope (per-user / per-machine) + → Install dir → Install Options ("Add ProFiles to PATH" ✔) + → Ready → Progress → Finish (Launch ✔ + Documentation / What's new links) +``` + +The Install Options page is **first-class** — `CustomInstallDirDlg.Next` → +`InstallOptionsDlg` → `VerifyReadyDlg`. No "Advanced" detour. + +### 2.3 Script mechanics (verified) + +- **Post-install**: scheduled `Before="InstallFinalize"`, deferred, + `Impersonate="no"` (elevated on per-machine installs), condition + `NOT Installed` (runs on fresh install and major-upgrade installs; **not** + on repair). A template wrapper (`run_post_install.bat`) exports: + - `ALLUSERS` = `1` (per-machine) / `0` (per-user) + - `INSTALLER_PATH` = path of the MSI being installed + - `INSTALLER_UNATTENDED` = `1` in quiet mode (`UILevel < 3`), else `0` + - `OPTION_ADD_TO_PATH` = `1`/`0` (from the checkbox / property default) + …then `CALL`s our `post_install.bat`, whose `%~dp0` resolves to + `\_installer\` — **the install dir is `%~dp0\..`**. +- **Pre-uninstall**: scheduled `After="InstallInitialize"` (before + `RemoveFiles`; files and `%~dp0` still valid), condition `REMOVE="ALL"`, + impersonated (user context; elevated when the uninstall is elevated). + Wrapper exports `INSTALLER_UNATTENDED` only — **no scope flag**, so the + cleanup script must inspect both registry hives and remove wherever the + entry matches. +- **Failure semantics**: both actions use `Return="check"` — a non-zero exit + **fails the install/uninstall**. Our scripts must therefore be defensive: + log-and-continue on recoverable errors, and always `exit /b 0` unless the + situation is unrecoverable. +- **Silent installs** (`msiexec /qn`): quiet variants of both actions run; + option properties apply their defaults (`add_to_path` ⇒ `1`), overridable + on the command line via the public property + `msiexec /i ProFiles.msi /qn OPTION_ADD_TO_PATH=0`. +- **PATH via native WiX ``**: exists in the template but is + gated behind `console_app = true` (CLI apps). ProFiles is a GUI app, so the + custom post-install route below is required and by design. + +## 3. Scope + +- **Windows MSI only.** macOS DMG branding (issue items 7–8) is explicitly + **out of scope** (owner decision, 2026-11-18). Note: the DMG volume icon is + already effectively covered by Briefcase's app-icon fallback + (`img/profiles.icns`); only a DMG background PNG would remain — deferred to + a future issue. +- **One PR** (owner decision, 2026-11-18): pyproject config + scripts + + branding BMPs + `.gitattributes` rules + a one-line CI trigger addition + + docs + CHANGELOG + a config-coherence test. The spec file itself is part of + the PR and is amended in the same commit as its §6.1 correction, so the + committed spec stays truthful. +- No changes to `src/profiles/**` — everything is packaging, assets and docs. + +## 4. Goals / Non-goals + +**Goals** + +1. The installation guide's shortcut claim becomes true. +2. Finish page: "Launch ProFiles" (checked) + Documentation / What's new + links + custom completion text. +3. `profiles --headless` works from any terminal after a default install + (install dir on PATH), per-user and per-machine. +4. Uninstall removes exactly the PATH entry it added — nothing else. +5. Branded welcome dialog + banner (direction **A** — brand gradient, + approved in the 2026-11-18 brainstorming session). +6. Silent installs keep working (`msiexec /qn`), PATH included by default. + +**Non-goals / anti-goals** + +- No user-data deletion on uninstall (`.profiles` configs, logs untouched). +- No non-English installer surface (English-first app). +- No vendoring/patching of the Briefcase WiX template — config + bundled + scripts only, staying upstream-aligned. +- No `setx` (1024-char truncation) and no reading PATH via expanded-string + APIs (would destroy `REG_EXPAND_SZ` references like `%SystemRoot%`). + +## 5. Decision Summary + +| Feature | Mechanism | Native / custom | +| --- | --- | --- | +| Scope dialog | `system_installer` unset (wizard default) | Native | +| Desktop shortcut | `create_desktop_shortcut = true` | Native | +| Finish page (launch + text + links) | `installer_completion_*` keys | Native | +| **Add to PATH** | `install_options.add_to_path` + `post_install.bat` (PowerShell registry edit) | **Custom script on native hooks** | +| PATH cleanup on uninstall | `pre_uninstall.bat` (exact-match removal, both hives) | **Custom script on native hook** | +| Installer art | Committed 493×312 / 493×58 BMPs, native-frame layout | Assets | + +## 6. Detailed Design + +### 6.1 `pyproject.toml` + +New section (appended after the existing `permission` table), with comments +explaining the *why* of each key (Briefcase 0.4.7 dropped the MSI reference +docs — these comments are the in-repo documentation): + +```toml +[tool.briefcase.app.profiles.windows] +# system_installer deliberately unset: the wizard asks per-user vs +# per-machine at install time ("perUserOrMachine"). +create_desktop_shortcut = true +installer_background = "img/installer_background" # 493x312 BMP on disk +installer_banner = "img/installer_banner" # 493x58 BMP on disk +installer_completion_launch_app = true +installer_completion_text = """\ +ProFiles has been installed successfully. Launch it now, or find it in \ +your Start Menu.""" +uninstaller_completion_text = """\ +ProFiles has been removed. Your configurations and logs were left \ +untouched.""" +installer_completion_urls = [ + { title = "Documentation", url = "https://github.com/falbany/ProFiles#readme" }, + { title = "What's new", url = "https://github.com/falbany/ProFiles/blob/main/CHANGELOG.md" }, +] + +# NOTE: singular `install_option`, array-of-tables, each entry requires +# `name`. The plural `install_options` key is silently swallowed by +# **kwargs and overwritten in DraftAppConfig — same trap as +# `document_type` (see comment above in this file). +[[tool.briefcase.app.profiles.windows.install_option]] +name = "add_to_path" +title = "Add ProFiles to PATH" +description = "Run 'profiles' (including --headless automation) from any terminal." +default = true + +post_install_script = "packaging/windows/post_install.bat" +pre_uninstall_script = "packaging/windows/pre_uninstall.bat" +``` + +Notes: + +- Briefcase resolves `installer_background`/`installer_banner` with + `with_suffix(".bmp")` — the extension in the config value is irrelevant; + the **committed file must be `.bmp`**. +- `install_option` uses the **singular** key and array-of-tables shape with a + required `name` (verified against the Briefcase 0.4.7 wheel: + `DraftAppConfig.__init__` takes `install_option`; `validate_install_options_config` + expects each element to be a dict carrying `name`/`title`/`description`). + No `system` key ⇒ checkbox shown in both scopes; `default = true` ⇒ checked, + and the default also applies to `/qn` silent installs. +- `OPTION_ADD_TO_PATH` is an uppercase (public) MSI property ⇒ overridable on + the `msiexec` command line. + +### 6.2 Installer branding BMPs (native-frame layout) + +Two committed assets (one-off generation, then versioned like any other +asset — **never regenerated at build time**). The layout follows the WiX UI +text positions: the black banner title starts at x≈20 of 493 and dialog body +text starts at x≈173, so art lives only outside those zones. + +| File | Size | Content | +| --- | --- | --- | +| `img/installer_background.bmp` | 493×312, 24-bit BMP | 164 px brand panel on the left (indigo-violet gradient + white rounded logo mark); plain white from x=164 for dialog text, links and checkboxes. | +| `img/installer_banner.bmp` | 493×58, 24-bit BMP | White from x=0–428 for the black page title; brand-gradient block with the white logo mark at x=429–492. | + +Generation: one-off Python/PIL script (committed under +`packaging/windows/generate_bmps.py` for provenance/reproducibility), run +locally, output committed. The script draws both assets at 4× and +LANCZOS-downsamples them so the mark survives the 370×44 banner display. +A note in `packaging/windows/README.md` records provenance and the +regeneration command. + +**Visual checkpoint — resolved 2026-11-18:** the first CI artifact confirmed +that WiX renders the banner title and dialog body text in black. The original +full-bleed art put the mark/wordmark under that text; the native-frame layout +above keeps the text zones white instead of patching the template. Full +rationale: [2026-11-18 installer art native-frame design](2026-11-18-installer-art-native-frame-design.md) +(supersedes the art direction originally written in this section). + +### 6.3 `packaging/windows/post_install.bat` + +Behavioural contract (implementation is the builder's, within these rules): + +1. Honours the env vars exported by the template wrapper: `OPTION_ADD_TO_PATH`, + `ALLUSERS`, `INSTALLER_UNATTENDED`. Skips silently (exit 0) when + `OPTION_ADD_TO_PATH` ≠ `1`. +2. Install dir = parent of `%~dp0` (the `_installer` folder), trailing + backslash normalised away. +3. PATH edit via one `powershell -NoProfile -ExecutionPolicy Bypass -Command …` + invocation (PowerShell 5.1 is present on all supported Windows): + - **Per-user** (`ALLUSERS=0`): `HKCU\Environment` `Path`. + - **Per-machine** (`ALLUSERS=1`): `HKLM\SYSTEM\CurrentControlSet\Control\ + Session Manager\Environment` `Path`. + - Read with `DoNotExpandEnvironmentNames`; write back as `ExpandString` — + preserves `REG_EXPAND_SZ` and unexpanded `%…%` references (this is why + `setx` is banned). + - Prepend the install dir if not already present (case-insensitive, + backslash-normalised comparison); de-duplicate any existing identical + entry. + - Broadcast `WM_SETTINGCHANGE` (`SendMessageTimeout`, `HWND_BROADCAST`) + so new shells pick up PATH without logoff — `setx`'s other raison + d'être, handled natively. +4. Failure policy: append findings to `\_installer\path_setup.log` + and **exit 0** on recoverable errors (registry permission denied, PowerShell + unavailable). A non-zero exit fails the whole install (`Return="check"`) — + reserved for truly unrecoverable states (in practice: never). +5. `exit /b 0` at the end, always. + +### 6.4 `packaging/windows/pre_uninstall.bat` + +1. No scope flag exists — remove the exact entry from **both** hives, + ignoring access-denied on the one that isn't writable in the current + context (per-user uninstall → HKLM write fails silently = correct). +2. Exact-literal match only (same normalisation as 6.3): removes precisely + the entry added at install time; anything else in PATH is untouched. +3. Never touches `.profiles` configs, logs or any user data (anti-goal). +4. Same PowerShell approach (`DoNotExpandEnvironmentNames` + `ExpandString` + + `WM_SETTINGCHANGE`), same log file, same exit-0 failure policy. + +### 6.5 Docs & CHANGELOG + +- `docs/installation-guide.en.md` (+ `.fr.md` mirror): + - The shortcut claim becomes true — verify wording against reality. + - Document the new wizard flow: scope choice, **Install Options** page with + "Add ProFiles to PATH" (checked by default), finish page. + - Document `msiexec` escape hatches: `/qn` (PATH included by default), + `OPTION_ADD_TO_PATH=0` opt-out. + - Note that `profiles --headless` now works from any terminal after a + default install (new terminal windows pick up PATH; already-open ones + don't). +- `CHANGELOG.md` under `[Unreleased]` → `### Added`: installer polish bullets + (desktop shortcut, finish page, PATH option, branded installer). + +### 6.6 Config-coherence test + +`tests/packaging/test_windows_installer_assets.py` (new module inside the +**existing** `tests/packaging/` package): + +- pyproject parses (tomllib) and the windows section contains the expected keys. +- The PATH option is declared under the **singular** `install_option` key as + an array-of-tables entry with `name = "add_to_path"` and `default = true` + (regression guard for the plural-key trap — the plural key would silently + disable the feature). +- `installer_background`/`installer_banner` resolve to committed files that + are **BMPs of exactly 493×312 / 493×58** (regression guard: someone replacing + a BMP with a PNG otherwise only breaks CI packaging, not tests). +- `post_install_script`/`pre_uninstall_script` files exist and end with + `exit /b 0` (the `Return="check"` guard). +- Pure-Python, no Windows dependency, runs in the existing CI matrix. + +### 6.7 Line endings & binary rules (gotcha) + +The repo enforces `eol=lf` via `.gitattributes`. Batch files with LF-only +line endings hit known `cmd.exe` edge cases. Add to `.gitattributes` in the +same PR: + +```gitattributes +*.bat text eol=crlf +*.bmp binary +``` + +### 6.8 CI trigger addition + +`.github/workflows/build-windows.yml` builds the MSI on PRs via a `paths:` +filter (`pyproject.toml`, `src/**`, `img/**`, itself). The iteration loop of +§7 requires fresh artifacts when only `packaging/windows/*.bat` changes, so +add `packaging/windows/**` to that filter (one-line, additive). + +## 7. Verification Plan + +1. PR ⇒ `build-windows.yml` builds the MSI and uploads it as an artifact — + no local Windows needed for iteration. (The §6.8 `paths:` addition takes + effect within the PR itself: for `pull_request` events GitHub uses the + workflow file from the PR branch, so later pushes that only touch + `packaging/windows/**` still get fresh artifacts.) +2. Owner tests the artifact on the professional Windows machine: + - Per-user install: wizard flow (License → Scope → Dir → **Install Options** + → Ready → Finish); desktop shortcut created; finish page shows Launch + (checked) + both links; **banner/welcome art + text contrast checkpoint**. + - New terminal: `profiles --headless` resolves (per-user scope). + - Per-machine install (admin): same checks; PATH lands in HKLM. + - Uninstall (interactive + `/x /qn`): PATH entry gone from the right + hive(s); Start Menu / desktop shortcut gone; `.profiles` configs & logs + intact. + - `msiexec /i ProFiles.msi /qn`: silent install works; PATH added; + `OPTION_ADD_TO_PATH=0` opt-out respected. + - Upgrade over the currently released version: fresh-install semantics + (`NOT Installed` ⇒ post-install runs once). +3. macOS / Linux release jobs unaffected (no config outside the windows + table except docs/CHANGELOG). + +## 8. Alternatives Considered + +- **Declarative-only** (no scripts): simplest, but loses the PATH convenience + (native WiX PATH feature is console-app-only in 0.4.7). +- **Native WiX `` PATH**: rejected — gated to `console_app = true`; + enabling it for ProFiles would change the stub binary behaviour. +- **`setx` in the post-install script**: rejected — 1024-char truncation and + expanded-string writes destroy `REG_EXPAND_SZ` content. +- **Aggressive uninstall cleanup** (checkbox to delete config/logs): rejected — + uninstall options don't display in the standard Add/Remove Programs flow + (upstream quirk), and user-data deletion is risky. +- **`starter_config` install option**: dropped — an installer cannot know + where the test-programs tree lives; `ProFiles.exe --init` stays available. +- **macOS PKG instead of DMG / DMG branding**: out of scope per §3. +- **Vendoring the WiX template**: rejected — upstream template already + provides every hook we need; staying aligned keeps future Briefcase bumps + cheap. + +## 9. Left to the Builder + +- Exact PowerShell one-liner composition and `.bat` quoting/escaping. +- BMP pixel work (PIL drawing details, anti-aliasing, text zone layout). +- Test file naming details beyond §6.6 and doc phrasing polish. +- Branch/PR naming per repo conventions (single PR, `Closes #183`). diff --git a/docs/superpowers/specs/2026-11-18-installer-art-native-frame-design.md b/docs/superpowers/specs/2026-11-18-installer-art-native-frame-design.md new file mode 100644 index 0000000..8ac815a --- /dev/null +++ b/docs/superpowers/specs/2026-11-18-installer-art-native-frame-design.md @@ -0,0 +1,90 @@ +# Installer Art — Native-Frame Layout (supersedes §6.2 of the 2026-11-17 spec) + +- **Date:** 2026-11-18 +- **Status:** Approved by owner 2026-11-18 (native-frame mock-up accepted) +- **Implements:** follow-up to [issue #183](https://github.com/falbany/ProFiles/issues/183), PR #190 +- **Supersedes:** art direction in `2026-11-17-windows-installer-polish-design.md` §6.2 + +## Why + +The first MSI artifact rendered the branded BMPs under WiX's own text: + +- **Banner pages** draw the page title in black at **x ≈ 20 of 493** (control + `X=15..20`, `W=300..330` dialog units, scaled ×493/370). The logo mark + (x=16–42) and pills (x≥360) sat directly under it. +- **Welcome / Finish pages** draw body text, links and checkboxes in black + from **x ≈ 173 of 493** (control `X=130..135`). The full-bleed background + put the mark, wordmark and tagline in that same zone. + +Text colour is fixed by the WiX UI theme; changing it would require +vendoring/patching the template, which §4 of the original spec rules out. + +## Goal + +Every wizard page is readable while keeping the ProFiles brand visible. + +**Non-goals:** changing installer behaviour, config, scripts, or WiX +template; adding fonts at generation time (generator stays font-free); +touching `src/profiles/**`. + +## Chosen approach — native-frame layout + +Mirror the stock WiX art layout, which is designed around those text +coordinates. + +### `img/installer_background.bmp` — 493×312, 24-bit + +| Zone | Content | +| --- | --- | +| x = 0–163 | Vertical brand gradient (`#635BCC` → `#825ED9`), white rounded logo mark (56×56) centred in the panel | +| x = 164–492 | Plain white (`#FFFFFF`) — all dialog text, links and checkboxes land here | + +Text starts at x≈173 (Welcome) / x≈180 (Finish), leaving a ≥ 9 px white +gutter after the panel. + +### `img/installer_banner.bmp` — 493×58, 24-bit + +The banner is reworked in the same pass — it is not left as-is. WiX +renders it inside a **370×44** control, so the 493×58 source is a 4/3 +supersample: details are drawn at 493×58 but sized to stay crisp after the +downscale (and at 125–150 % DPI). + +| Zone | Content | +| --- | --- | +| x = 0–428 | Plain white (`#FFFFFF`) — the page title (black) can run up to x≈420 | +| x = 429–492 | Brand gradient block with the white rounded logo mark (34×34) | + +No pills or wordmark in the banner: the right block alone carries the brand. +This is the same layout rule as the stock WiX banner (content at the far +right, title zone clear), adapted to the ProFiles colours. + +A full-height purple band on the left — even one matching the background +panel — is rejected: the banner title starts at x≈20, so the black text +would land on it again. + +### Rejected — baked white "content card" + +Keeping the full gradient and painting a white card under the text zones. +More brand colour, but the card edges must be tuned per dialog, can clash +with the native separator lines/buttons, and still constrains long titles. +More fragile for no functional gain. + +## Implementation notes + +- `packaging/windows/generate_bmps.py`: replace the cover-crop background and + the left-mark banner with the zones above; keep the Pillow-only, font-free + drawing and the `--check` flag. Regenerate and commit both BMPs. +- `tests/packaging/test_windows_installer_assets.py`: add layout regression + guards (existing dimension tests stay): + - banner x < 429 is near-white (black title contrast); + - background x > 169 is near-white; + - both files still carry brand colour in their art zone. +- Docs: update §6.2 of the 2026-11-17 spec and Task 2 of the implementation + plan to point at this document, so the committed design stays truthful. +- Verification: regenerate, run the packaging tests, eyeball both BMPs; the + CI MSI artifact is the final visual check on the work machine. + +## Left to the builder + +Exact gradient stops, mark radius/bar proportions, and the pixel thresholds +in the layout tests. diff --git a/img/installer_background.bmp b/img/installer_background.bmp new file mode 100644 index 0000000..e4775e7 Binary files /dev/null and b/img/installer_background.bmp differ diff --git a/img/installer_banner.bmp b/img/installer_banner.bmp new file mode 100644 index 0000000..2f0870e Binary files /dev/null and b/img/installer_banner.bmp differ diff --git a/packaging/windows/README.md b/packaging/windows/README.md new file mode 100644 index 0000000..596b9d2 --- /dev/null +++ b/packaging/windows/README.md @@ -0,0 +1,57 @@ +# Windows packaging resources + +Support files for the Windows MSI built by Briefcase (issue #183). The +installer behaviour itself is configured in `pyproject.toml` +(`[tool.briefcase.app.profiles.windows]`); this directory holds the pieces +that cannot live there. + +| File | Role | +| --- | --- | +| `post_install.bat` | Adds the install dir to PATH when the "Add ProFiles to PATH" checkbox is checked (default). | +| `pre_uninstall.bat` | Removes exactly that PATH entry on uninstall; touches nothing else. | +| `generate_bmps.py` | Regenerates the branded installer BMPs (committed under `img/`). | + +## Script contract + +Briefcase bundles both scripts into the MSI and runs them through its +template wrappers: + +- `post_install.bat` runs **before `InstallFinalize`** on fresh installs + only, elevated for per-machine installs. The wrapper exports + `ALLUSERS` (1/0), `INSTALLER_PATH`, `INSTALLER_UNATTENDED` (1 in + `msiexec /qn` mode) and `OPTION_ADD_TO_PATH` (1/0 from the checkbox). +- `pre_uninstall.bat` runs **after `InstallInitialize`** (before + `RemoveFiles`). The wrapper exports only `INSTALLER_UNATTENDED` — there + is no scope flag, so it clears the entry from **both** hives and treats + an unwritable hive as success. + +Both scripts: registry edits via PowerShell (`DoNotExpandEnvironmentNames` +read / `ExpandString` write, so `REG_EXPAND_SZ` content survives), exact +case-insensitive matching of the install dir only, `WM_SETTINGCHANGE` +broadcast, a `path_setup.log` written next to the script, and **always +exit 0** — WiX runs them with `Return="check"`, so a non-zero exit would +fail the whole install/uninstall for a PATH convenience. + +Why not `setx`: it truncates PATH at 1024 characters and writes the +expanded value, destroying `%…%` references. + +## Regenerating the installer art + +`img/installer_background.bmp` (493×312, welcome dialog) and +`img/installer_banner.bmp` (493×58, page banner) are committed assets — +they are **not** generated at build time. To tweak them: + +```bash +uv run python packaging/windows/generate_bmps.py # regenerate +uv run python packaging/windows/generate_bmps.py --check # staleness check +``` + +The art follows WiX's text-safe zones: the banner stays white left of x=429 +(WiX draws the black page title at x≈20) and the background stays white +right of x=169 (dialog text starts at x≈173). Do not add art back into those +zones. + +Commit any regenerated BMP together with this script (the provenance +record). Design background: +`docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md` +and `docs/superpowers/specs/2026-11-18-installer-art-native-frame-design.md`. diff --git a/packaging/windows/generate_bmps.py b/packaging/windows/generate_bmps.py new file mode 100644 index 0000000..0cbf916 --- /dev/null +++ b/packaging/windows/generate_bmps.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Generate the brand-native WiX installer BMPs. + +Outputs (committed to the repo — this script is provenance, not part of +any build): + +- ``img/installer_background.bmp`` 493x312 — the welcome/finish dialog art + (WiX ``WixUIDialogBmp``). A 164 px brand-gradient panel on the left with + the white logo mark; plain white on the right. WiX draws the dialog text + from x≈173, so everything right of the panel must stay free of art. +- ``img/installer_banner.bmp`` 493x58 — the top-strip art on banner pages + (WiX ``WixUIBannerBmp``). White from x=0 to x=428 because WiX draws the + black page title at x≈20; the brand-gradient block with the logo mark + sits at x=429..492. + +Both assets are drawn at 4x and LANCZOS-downsampled: WiX renders the +493x58 banner in a 370x44 control, so the mark needs clean edges at that +scale (and at 125–150 % DPI). + +WiX requires uncompressed 24-bit BMPs at exactly these sizes; Briefcase +resolves the ``installer_background``/``installer_banner`` config values +with ``with_suffix(".bmp")`` against the project root. + +Usage:: + + uv run python packaging/windows/generate_bmps.py [--check] + +``--check`` exits non-zero when the outputs are missing or older than this +script (dev convenience; CI never regenerates the BMPs). +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from PIL import Image, ImageDraw + +REPO_ROOT = Path(__file__).resolve().parents[2] +BACKGROUND_OUT = REPO_ROOT / "img" / "installer_background.bmp" +BANNER_OUT = REPO_ROOT / "img" / "installer_banner.bmp" + +# Brand gradient endpoints, sampled from the source banner art. +GRADIENT_LEFT = (99, 91, 204) # #635BCC +GRADIENT_RIGHT = (130, 93, 217) # #825ED9 +WHITE = (255, 255, 255) + +BACKGROUND_SIZE = (493, 312) # WiX WixUIDialogBmp +BANNER_SIZE = (493, 58) # WiX WixUIBannerBmp + +# Native-frame zones: WiX draws the page title at x≈20 of 493 on banner +# pages, and body text from x≈173 on the welcome/finish dialogs. +PANEL_WIDTH = 164 # background brand panel; text zone starts at x≈173 +BANNER_BRAND_X = 429 # banner brand block start; title box ends at x≈420 +BANNER_BRAND_WIDTH = 64 + +# Render at 4x then downsample with LANCZOS for clean rounded edges. +SCALE = 4 + + +def _lerp(start: int, end: int, t: float) -> int: + """Linear interpolation between two channel values.""" + return round(start + (end - start) * t) + + +def _gradient(size: tuple[int, int], *, horizontal: bool) -> Image.Image: + """Draw the brand gradient, one line per column (or row).""" + width, height = size + gradient = Image.new("RGB", size) + draw = ImageDraw.Draw(gradient) + span = max((width if horizontal else height) - 1, 1) + for step in range(span + 1): + color = tuple( + _lerp(a, b, step / span) for a, b in zip(GRADIENT_LEFT, GRADIENT_RIGHT, strict=False) + ) + if horizontal: + draw.line([(step, 0), (step, height)], fill=color) + else: + draw.line([(0, step), (width, step)], fill=color) + return gradient + + +def _mark( + size: int, + radius: int, + bar_width: int, + bar_height: int, + gap: int, + pad: int, + third_width: int, +) -> Image.Image: + """White rounded square with three brand bars, at SCALE× size.""" + side = size * SCALE + mark = Image.new("RGBA", (side, side), (0, 0, 0, 0)) + draw = ImageDraw.Draw(mark) + draw.rounded_rectangle( + (0, 0, side - 1, side - 1), + radius=radius * SCALE, + fill=(*WHITE, 255), + ) + y = pad * SCALE + for width in (bar_width, bar_width, third_width): + draw.rectangle( + (pad * SCALE, y, (pad + width) * SCALE - 1, y + bar_height * SCALE - 1), + fill=(*GRADIENT_LEFT, 255), + ) + y += (bar_height + gap) * SCALE + return mark + + +def generate_background() -> Image.Image: + """Draw the 493x312 art: left brand panel, white dialog-text zone.""" + width, height = BACKGROUND_SIZE + canvas = Image.new("RGB", (width * SCALE, height * SCALE), WHITE) + panel = _gradient((PANEL_WIDTH * SCALE, height * SCALE), horizontal=False) + canvas.paste(panel, (0, 0)) + + mark = _mark( + size=56, + radius=14, + bar_width=30, + bar_height=6, + gap=4, + pad=13, + third_width=19, + ) + canvas.paste(mark, (54 * SCALE, 128 * SCALE), mark) + return canvas.resize(BACKGROUND_SIZE, Image.LANCZOS) + + +def generate_banner() -> Image.Image: + """Draw the 493x58 banner: white title zone, brand block on the right.""" + width, height = BANNER_SIZE + canvas = Image.new("RGB", (width * SCALE, height * SCALE), WHITE) + block = _gradient((BANNER_BRAND_WIDTH * SCALE, height * SCALE), horizontal=True) + canvas.paste(block, (BANNER_BRAND_X * SCALE, 0)) + + mark = _mark( + size=34, + radius=9, + bar_width=18, + bar_height=4, + gap=2, + pad=8, + third_width=11, + ) + canvas.paste(mark, (444 * SCALE, 12 * SCALE), mark) + return canvas.resize(BANNER_SIZE, Image.LANCZOS) + + +def main(argv: list[str] | None = None) -> int: + """Write (or verify) the installer BMPs; see module docstring.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--check", + action="store_true", + help="exit 1 when outputs are missing or older than this script", + ) + args = parser.parse_args(argv) + + outputs = (BACKGROUND_OUT, BANNER_OUT) + if args.check: + script_mtime = Path(__file__).stat().st_mtime + for out in outputs: + if not out.is_file() or out.stat().st_mtime < script_mtime: + print(f"stale or missing: {out}", file=sys.stderr) + return 1 + return 0 + + generate_background().save(BACKGROUND_OUT, format="BMP") + generate_banner().save(BANNER_OUT, format="BMP") + for out in outputs: + print(f"wrote {out.relative_to(REPO_ROOT)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/windows/post_install.bat b/packaging/windows/post_install.bat new file mode 100644 index 0000000..e58cc79 --- /dev/null +++ b/packaging/windows/post_install.bat @@ -0,0 +1,45 @@ +@echo off +setlocal +REM ProFiles post-install: add the install dir to PATH when the user asked +REM for it on the Install Options page. Runs before InstallFinalize, +REM elevated for per-machine installs, fresh installs only (NOT Installed). +REM +REM Env vars exported by the Briefcase wrapper (run_post_install.bat): +REM ALLUSERS 1 = per-machine, 0 = per-user +REM INSTALLER_PATH path of the MSI being installed +REM INSTALLER_UNATTENDED 1 = quiet install (msiexec /qn), else 0 +REM OPTION_ADD_TO_PATH 1 = checkbox checked (default), 0 = unchecked +REM %~dp0 is the _installer folder inside the install dir. +REM +REM Design: docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md +REM (section 6.3). Never fails the install for a PATH convenience: the +REM wrapper uses Return="check", so this script always exits 0 and logs. + +set "LOG=%~dp0path_setup.log" +> "%LOG%" echo [%DATE% %TIME%] ProFiles post-install start +>>"%LOG%" echo OPTION_ADD_TO_PATH=%OPTION_ADD_TO_PATH% ALLUSERS=%ALLUSERS% UNATTENDED=%INSTALLER_UNATTENDED% + +if not "%OPTION_ADD_TO_PATH%"=="1" ( + >>"%LOG%" echo Skipping PATH modification: option not selected. + exit /b 0 +) + +REM Install dir = parent of this script's _installer folder; %%~fI resolves +REM the trailing ".." to an absolute path without a trailing backslash. +for %%I in ("%~dp0..") do set "INSTALL_DIR=%%~fI" +>>"%LOG%" echo Install dir: %INSTALL_DIR% + +set "SCOPE=User" +if "%ALLUSERS%"=="1" set "SCOPE=Machine" + +REM One PowerShell 5.1 shot: read PATH with DoNotExpandEnvironmentNames +REM (preserves REG_EXPAND_SZ content - naive tools would expand it), prepend +REM the install dir unless an identical entry (case-insensitive, trailing +REM backslash ignored) already exists, write back as ExpandString, then +REM broadcast WM_SETTINGCHANGE (0x1a) so running shells pick it up without +REM logging off. The ''='% substitution doubles any apostrophes in the +REM install dir so they cannot break the PowerShell single-quoted literal. +>>"%LOG%" 2>&1 powershell -NoProfile -ExecutionPolicy Bypass -Command "$opt=[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames; $k='Environment'; $r=[Microsoft.Win32.Registry]::CurrentUser; if('%SCOPE%' -eq 'Machine'){$k='SYSTEM\CurrentControlSet\Control\Session Manager\Environment'; $r=[Microsoft.Win32.Registry]::LocalMachine}; $key=$r.OpenSubKey($k,$true); $old=[string]$key.GetValue('Path','',$opt); $dir='%INSTALL_DIR:'=''%'.TrimEnd('\'); $rest=@($old -split ';' | Where-Object {$_ -and ($_.TrimEnd('\') -ine $dir)}); $key.SetValue('Path', (@($dir)+$rest) -join ';', [Microsoft.Win32.RegistryValueKind]::ExpandString); $key.Close(); Add-Type -MemberDefinition '[DllImport(\"user32.dll\", SetLastError=true, CharSet=CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);' -Name NativeMethods -Namespace ProFiles.Installer | Out-Null; $res=[UIntPtr]::Zero; [ProFiles.Installer.NativeMethods]::SendMessageTimeout([IntPtr]0xffff, 0x1a, [UIntPtr]::Zero, 'Environment', 2, 2000, [ref]$res) | Out-Null" +if errorlevel 1 >>"%LOG%" echo WARNING: PATH update failed; install continues. + +exit /b 0 diff --git a/packaging/windows/pre_uninstall.bat b/packaging/windows/pre_uninstall.bat new file mode 100644 index 0000000..dda663c --- /dev/null +++ b/packaging/windows/pre_uninstall.bat @@ -0,0 +1,33 @@ +@echo off +setlocal +REM ProFiles pre-uninstall: remove the PATH entry this install added. +REM Runs after InstallInitialize and before RemoveFiles, so %~dp0 is still +REM valid and only the PATH registry value is touched - never .profiles +REM configs, logs or any other user data. +REM +REM Env vars exported by the Briefcase wrapper (run_pre_uninstall.bat): +REM INSTALLER_UNATTENDED 1 = quiet uninstall (msiexec /x /qn), else 0 +REM There is no scope flag: the script clears the entry from BOTH hives, +REM ignoring the one it cannot write in the current context (a per-user +REM uninstall fails to open HKLM - that is success, not an error). +REM %~dp0 is the _installer folder inside the (still present) install dir. +REM +REM Design: docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md +REM (section 6.4). The uninstall must always succeed: this script always +REM exits 0 and logs; exact-match removal only (case-insensitive, trailing +REM backslash ignored) so no unrelated PATH entry is ever touched. + +set "LOG=%~dp0path_setup.log" +>>"%LOG%" echo [%DATE% %TIME%] ProFiles pre-uninstall start (unattended=%INSTALLER_UNATTENDED%) + +for %%I in ("%~dp0..") do set "INSTALL_DIR=%%~fI" +>>"%LOG%" echo Install dir: %INSTALL_DIR% + +REM Same REG_EXPAND_SZ-safe edit as post_install: read with +REM DoNotExpandEnvironmentNames, filter out exactly the install dir entry, +REM write back as ExpandString, broadcast WM_SETTINGCHANGE (0x1a). The +REM '%'='% substitution doubles any apostrophes in the install dir. +>>"%LOG%" 2>&1 powershell -NoProfile -ExecutionPolicy Bypass -Command "$opt=[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames; $dir='%INSTALL_DIR:'=''%'.TrimEnd('\'); foreach($s in 'User','Machine'){ if($s -eq 'Machine'){$k='SYSTEM\CurrentControlSet\Control\Session Manager\Environment'; $r=[Microsoft.Win32.Registry]::LocalMachine}else{$k='Environment'; $r=[Microsoft.Win32.Registry]::CurrentUser}; try{$key=$r.OpenSubKey($k,$true)}catch{$key=$null}; if($key){ $old=[string]$key.GetValue('Path','',$opt); $p=@($old -split ';' | Where-Object {$_ -and ($_.TrimEnd('\') -ine $dir)}); $key.SetValue('Path', ($p -join ';'), [Microsoft.Win32.RegistryValueKind]::ExpandString); $key.Close() } }; Add-Type -MemberDefinition '[DllImport(\"user32.dll\", SetLastError=true, CharSet=CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);' -Name NativeMethods -Namespace ProFiles.Installer | Out-Null; $res=[UIntPtr]::Zero; [ProFiles.Installer.NativeMethods]::SendMessageTimeout([IntPtr]0xffff, 0x1a, [UIntPtr]::Zero, 'Environment', 2, 2000, [ref]$res) | Out-Null" +if errorlevel 1 >>"%LOG%" echo WARNING: PATH cleanup failed; uninstall continues. + +exit /b 0 diff --git a/pyproject.toml b/pyproject.toml index bdb3c0a..ba40788 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -146,6 +146,45 @@ LSHandlerRank = "Owner" [tool.briefcase.app.profiles.permission] camera = "ProFiles uses the camera to scan configuration barcodes and QR codes." +# Windows MSI polish (issue #183). Briefcase 0.4.x dropped the MSI reference +# docs; every option below is verified against the 0.4.7 source and its WiX +# template — see docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md. +# +# system_installer is deliberately UNSET: the wizard then asks per-user vs +# per-machine at install time ("perUserOrMachine" install scope). +[tool.briefcase.app.profiles.windows] +create_desktop_shortcut = true +# Briefcase resolves these with_suffix(".bmp") against the project root — +# the committed files must be BMPs (img/installer_*.bmp), sizes are fixed +# by WiX (493x312 dialog / 493x58 banner) and pinned by tests/packaging. +installer_background = "img/installer_background" +installer_banner = "img/installer_banner" +# Finish page: checked "Launch ProFiles" box + links + completion text. +installer_completion_launch_app = true +installer_completion_text = """\ +ProFiles has been installed successfully. Launch it now, or find it in \ +your Start Menu.""" +uninstaller_completion_text = """\ +ProFiles has been removed. Your configurations and logs were left \ +untouched.""" +installer_completion_urls = [ + { title = "Documentation", url = "https://github.com/falbany/ProFiles#readme" }, + { title = "What's new", url = "https://github.com/falbany/ProFiles/blob/main/CHANGELOG.md" }, +] +# PATH convenience: bundled scripts (packaging/windows/) do the registry +# work — the WiX template's native PATH feature is console-app-only. +post_install_script = "packaging/windows/post_install.bat" +pre_uninstall_script = "packaging/windows/pre_uninstall.bat" + +# NOTE: singular `install_option`, array of tables, each entry REQUIRES +# `name`. The plural `install_options` key is absorbed by **kwargs and +# overwritten in DraftAppConfig — the same trap as `document_type` above. +[[tool.briefcase.app.profiles.windows.install_option]] +name = "add_to_path" +title = "Add ProFiles to PATH" +description = "Run 'profiles' (including --headless automation) from any terminal." +default = true + [tool.pylint.MASTER] init-import = "yes" ignore-paths = ["src/profiles/_version.py"] diff --git a/tests/AGENTS.md b/tests/AGENTS.md index 44e5abe..94ec924 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -85,7 +85,8 @@ tests/ ├── packaging/ # cross-cutting (no single source module) │ ├── test_entry_point.py # profiles/__init__ lazy main + Briefcase stub │ ├── test_packaging.py # pyproject/briefcase dependency rules -│ └── test_shortcut_launch.py # ProFiles.pyw launcher stub behavior +│ ├── test_shortcut_launch.py # ProFiles.pyw launcher stub behavior +│ └── test_windows_installer_assets.py # MSI installer assets/config coherence (issue #183) ├── server/ │ ├── test_app.py # ← server/app.py (FastAPI factory + client telemetry) │ ├── test_barcode_integration.py # cross-cutting server integration (exception) diff --git a/tests/packaging/test_windows_installer_assets.py b/tests/packaging/test_windows_installer_assets.py new file mode 100644 index 0000000..6b8448d --- /dev/null +++ b/tests/packaging/test_windows_installer_assets.py @@ -0,0 +1,168 @@ +"""Coherence checks for the Windows MSI installer assets and config. + +The Windows packaging (pyproject briefcase config + bundled scripts + BMP +art) is exercised only by CI's build-windows job; these tests catch the +breakages that would otherwise surface only there. See +docs/superpowers/specs/2026-11-17-windows-installer-polish-design.md. +""" + +import tomllib +from pathlib import Path + +from PIL import Image + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _windows_config() -> dict: + """Load the [tool.briefcase.app.profiles.windows] section.""" + with open(REPO_ROOT / "pyproject.toml", "rb") as fh: + return tomllib.load(fh)["tool"]["briefcase"]["app"]["profiles"]["windows"] + + +def test_background_bmp_dimensions() -> None: + """Welcome-dialog art is a 493x312 24-bit BMP (WiX WixUIDialogBmp).""" + path = REPO_ROOT / "img" / "installer_background.bmp" + assert path.is_file() + with Image.open(path) as img: + assert img.format == "BMP" + assert img.size == (493, 312) + assert img.mode == "RGB" + + +def test_banner_bmp_dimensions() -> None: + """Banner art is a 493x58 24-bit BMP (WiX WixUIBannerBmp).""" + path = REPO_ROOT / "img" / "installer_banner.bmp" + assert path.is_file() + with Image.open(path) as img: + assert img.format == "BMP" + assert img.size == (493, 58) + assert img.mode == "RGB" + + +SCRIPTS = ("post_install.bat", "pre_uninstall.bat") + + +def test_bat_scripts_exist_and_exit_clean() -> None: + """Both scripts exist and always terminate 0 (WiX Return="check").""" + for name in SCRIPTS: + body = (REPO_ROOT / "packaging" / "windows" / name).read_bytes() + assert body.rstrip().endswith(b"exit /b 0") + assert b"\r\n" in body # committed via *.bat eol=crlf + + +def test_post_install_preserves_expand_sz_and_broadcasts() -> None: + """PATH edit must not expand REG_EXPAND_SZ and must notify shells.""" + body = (REPO_ROOT / "packaging" / "windows" / "post_install.bat").read_text(encoding="utf-8") + assert "DoNotExpandEnvironmentNames" in body + assert "ExpandString" in body + assert "setx" not in body.lower() + # WM_SETTINGCHANGE broadcast (0x1a) so running shells see the new PATH. + assert "SendMessageTimeout" in body and "0x1a" in body + # Driven by the Install Options checkbox and the install scope. + assert "OPTION_ADD_TO_PATH" in body and "ALLUSERS" in body + + +def test_pre_uninstall_removes_exactly_its_own_entry() -> None: + """Cleanup matches the literal install dir in BOTH hives, nothing else.""" + body = (REPO_ROOT / "packaging" / "windows" / "pre_uninstall.bat").read_text(encoding="utf-8") + # One loop over both hives: per-user uninstall cannot write HKLM, and + # that must be treated as success (no scope flag reaches this script). + assert "foreach($s in 'User','Machine')" in body + assert "DoNotExpandEnvironmentNames" in body + assert "ExpandString" in body + assert "setx" not in body.lower() + assert "SendMessageTimeout" in body + + +def test_windows_installer_config() -> None: + """The briefcase windows section matches the approved design.""" + cfg = _windows_config() + + # Scope dialog stays the wizard default (perUserOrMachine). + assert "system_installer" not in cfg + assert cfg["create_desktop_shortcut"] is True + assert cfg["installer_background"] == "img/installer_background" + assert cfg["installer_banner"] == "img/installer_banner" + assert cfg["installer_completion_launch_app"] is True + assert cfg["post_install_script"] == "packaging/windows/post_install.bat" + assert cfg["pre_uninstall_script"] == "packaging/windows/pre_uninstall.bat" + + urls = cfg["installer_completion_urls"] + assert [u["title"] for u in urls] == ["Documentation", "What's new"] + assert all(u["url"].startswith("https://github.com/falbany/ProFiles") for u in urls) + + # Singular key, array-of-tables, required `name`. The plural + # `install_options` key is silently swallowed by DraftAppConfig. + assert "install_options" not in cfg # the plural trap + options = cfg["install_option"] + assert len(options) == 1 + opt = options[0] + assert opt["name"] == "add_to_path" + assert opt["default"] is True + assert opt["title"] == "Add ProFiles to PATH" + + +def test_referenced_installer_files_exist() -> None: + """Every file the windows section references must resolve on disk.""" + cfg = _windows_config() + + for key in ("installer_background", "installer_banner"): + # Briefcase resolves with_suffix(".bmp") against the project root. + assert (REPO_ROOT / f"{cfg[key]}.bmp").is_file() + for key in ("post_install_script", "pre_uninstall_script"): + assert (REPO_ROOT / cfg[key]).is_file() + + +def test_install_dir_apostrophe_quoting_idiom() -> None: + """The cmd→PowerShell substitution must double apostrophes, not strip. + + %INSTALL_DIR:'=''% replaces ' with '' (valid PowerShell literal for + dirs like C:\\Users\\O'Brien\\...). The inverted ''=% form strips + doubled apostrophes and leaves single ones breaking the PS quoting. + """ + for name in SCRIPTS: + body = (REPO_ROOT / "packaging" / "windows" / name).read_text(encoding="utf-8") + # Doubling idiom %INSTALL_DIR:'=''% : cmd replaces ' with ''. + # The inverted ''=% form strips doubled apostrophes and leaves + # single ones breaking the PowerShell quoting. + doubling = "%INSTALL_DIR:" + chr(39) + "=" + chr(39) + chr(39) + "%" + stripping = "%INSTALL_DIR:" + chr(39) + chr(39) + "=" + "%" + assert doubling in body + assert stripping not in body + + +def test_registry_contracts_are_pinned() -> None: + """Content pins for the HKLM key and the unwritable-hive swallow.""" + for name in SCRIPTS: + body = (REPO_ROOT / "packaging" / "windows" / name).read_text(encoding="utf-8") + assert "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment" in body + pre = (REPO_ROOT / "packaging" / "windows" / "pre_uninstall.bat").read_text(encoding="utf-8") + assert "catch{$key=$null}" in pre + + +def test_banner_keeps_title_zone_clear() -> None: + """WiX draws the black banner title at x≈20; keep the title box white.""" + path = REPO_ROOT / "img" / "installer_banner.bmp" + with Image.open(path) as img: + rgb = img.convert("RGB") + # The title control ends near x=420; the brand block starts at + # x=429. Probe 4 px inside each zone so the LANCZOS seam at the + # block edge does not count as art under the title. + darkest = min(band[0] for band in rgb.crop((0, 0, 425, 58)).getextrema()) + brand = rgb.getpixel((434, 6)) + assert darkest >= 250 # no art under the title + assert brand[2] > brand[0] # indigo/violet block on the right + + +def test_background_keeps_text_zone_clear() -> None: + """WiX draws body text from x≈173; keep the text zone white.""" + path = REPO_ROOT / "img" / "installer_background.bmp" + with Image.open(path) as img: + rgb = img.convert("RGB") + darkest = min(band[0] for band in rgb.crop((170, 0, 493, 312)).getextrema()) + panel = rgb.getpixel((160, 156)) + text_zone = rgb.getpixel((170, 156)) + assert darkest >= 250 # no art under the text, links or checkbox + assert panel[2] > panel[0] # brand panel on the left + assert min(text_zone) >= 250 # panel ends before the text zone