From 336a471b6ace0ab88b1504e6274807ed2b168ccf Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Thu, 26 Nov 2026 16:14:46 +0100 Subject: [PATCH 01/32] docs: Adds the Linux port plan. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plans App Studio on Linux as agreed with Serverpod: five PRs (app runs, setup works, preview works, packaging, polish), Tuesday as PRs 1–3 plus an AppImage running on Ubuntu and Arch, and CI, releases and auto-updates owned by Serverpod with build scripts delivered from here. Records what already works through the host seam, where Linux falls through to macOS behaviour, the CEF spike findings and the open questions. --- specs/linux_port.md | 443 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 443 insertions(+) create mode 100644 specs/linux_port.md diff --git a/specs/linux_port.md b/specs/linux_port.md new file mode 100644 index 0000000..e4f66a0 --- /dev/null +++ b/specs/linux_port.md @@ -0,0 +1,443 @@ +# Linux port: plan + +Status: **agreed with Serverpod on 2026-11-25** (scope, the five PRs and the +Tuesday milestone). The details per subsystem below are the working plan. +Date: 2026-11-26. Baseline: `main` @ `6b3686c`, App Studio 0.4.0+24. + +## The plan in short + +Five PRs, each merged into `linux/port` once tested: + +| PR | Name | What | +|---|---|---| +| 1 | **App runs** | The Linux app shell, platform basics, menus | +| 2 | **Setup works** | Flutter and Serverpod CLI install, prerequisites | +| 3 | **Preview works** | The CEF fixes in the `webview_cef` fork | +| 4 | **Packaging** | AppImage, `.deb`, `.rpm`, reusing an existing Flutter Linux packaging setup, including AppImage updates through Gear Lever | +| 5 | **Polish** | "Open in…" editors, notifications, uninstall | + +**CI, the release pipeline and auto-updates run on Serverpod's +infrastructure, so Serverpod owns them.** This port delivers the build +scripts. + +Estimate: 15–25 hours. + +### Tuesday 2026-12-01 + +**PRs 1–3, plus an AppImage that runs on Ubuntu and Arch**, built on the dev +machine: + +- setup installs Flutter and the Serverpod CLI; +- a new project opens; +- the server runs; +- the preview works; +- Hot Restart and the menus work; +- closing App Studio stops the server. + +**Not for Tuesday:** the `.deb` and `.rpm` (the `.deb` if time allows), +Fedora testing, auto-updates, a release pipeline, "Open in…" editors, +uninstall. + +### Decisions + +| # | Decision | +|---|---| +| L1 | **x64 only.** | +| L2 | **Tested on Ubuntu and Arch (Omarchy, Hyprland).** Not on Fedora for now. Omarchy is Wayland and a tiling window manager, so it is the hard case. | +| L3 | **No Flatpak.** Its sandbox gets in the way of everything App Studio does outside itself: installing Flutter into `~/develop`, editing the shell profile, starting the user's tools. | +| L4 | **App Studio never runs `sudo` or `pkexec`.** It installs Flutter and the Serverpod CLI per user, as on macOS and Windows. For system packages (git, curl, unzip, xz), setup checks and gives the distro's own install command with a **Check again** button, the same pattern as `ManualUpdateDialog`. The `.deb` and `.rpm` declare them as dependencies instead. | + +--- + +App Studio runs on macOS and Windows today. This document is the plan for +bringing it to Linux **without changing anything a macOS or Windows user +sees or relies on**. The Windows port already did most of the groundwork: +the host seam, process handling and the in-window menu strip all exist. +Large parts of this plan are therefore "give Linux the branch it is +missing" rather than new design. + +1. Ground rules and branches +2. What we know +3. Inventory: what Linux gets for free, and where it falls through to macOS +4. Approach per subsystem +5. The five PRs in detail +6. Testing +7. Risks +8. Open questions +9. Developer machine setup (Linux) + +--- + +## 1. Ground rules and branches + +The Windows port's rules (section 1 of `windows_port.md`) apply as written, +with Windows read as "macOS and Windows": + +- **Every change either adds a Linux-only branch or file, or is a refactor + that leaves macOS and Windows behaviour identical.** +- **Host decisions go through `HostPlatform`** (`lib/platform/host.dart`), + which already knows `HostOs.linux`. No new `Platform.isLinux` checks + scattered around the code. +- **The existing suite stays green on macOS and Windows at every step.** +- **Native code shared with macOS or Windows** (`packages/webview_cef/common/`) + is changed only behind `OS_LINUX` / `__linux__` guards. +- **The macOS and Windows release tooling is not touched.** + +**Branches.** The work happens on a fork. `linux/port` is the root branch, +with a single PR against `serverpod/appstudio` `main`. Each of the five PRs +is a branch off `linux/port` (`linux/1-app-runs`, `linux/2-setup`, +`linux/3-preview`, `linux/4-packaging`, `linux/5-polish`) and is merged into +`linux/port` after testing, not into `main`. Serverpod reviews only the root +PR, once the Tuesday scope works. The checklist at the end of this document +is what that PR tracks. + +--- + +## 2. What we know + +### CEF spike (2026-11-25, Omarchy / Hyprland, Flutter 3.44.8) + +A throwaway Flutter app with `packages/webview_cef`: + +| Check | Result | +|---|---| +| Rendering on Wayland | **Works natively.** The GPU helper runs with `--ozone-platform=wayland`; no XWayland needed. | +| Input | Clicking, typing, umlauts, and copy and paste in both directions work. The plugin's `xclip` paste workaround fails silently and is not needed. | +| Auto-setup | `target_modifier/modify_target.sh` patches `linux/main.cc` and `linux/my_application.cc`, but current Flutter puts them in `linux/runner/`. Nothing gets patched, and every CEF helper starts a full copy of the app (~30 processes). **The hooks must be wired into the runner by hand**: `initCEFProcesses` in `main`, and the key press and release handlers on the `FlView`. | +| Shortcuts | With the preview focused, app shortcuts (Ctrl+R) never reach Flutter. This is the Linux version of Windows' W4, the other way round. | +| CEF cache folder | No `root_cache_path` on Linux, so CEF uses `~/.config/cef_user_data`. A killed run leaves a `SingletonLock` there that blocks the next start. This is the bug `511902c` fixed on macOS and W3 fixed on Windows. | +| Frame buffer | A memory bug in the plugin's frame buffer handling. Fixed in PR 3. | +| Quit | Closing the window exits cleanly with no CEF helpers left behind. **Not checked:** whether the close runs App Studio's `onExitRequested` teardown (see 4.2). | +| Bundle size | 1.5 GB unstripped. | + +### Checked in the code and on the dev machine (2026-11-26) + +| Check | Result | +|---|---| +| Database | **No Docker on Linux either.** `serverpod_embedded_postgres` 4.1.2 ships `linux-x64` and `linux-arm64` binaries and caches them in `$XDG_CACHE_HOME/serverpod/pg-binaries`. | +| `HostPlatform` | Knows `HostOs.linux`: POSIX paths, `:` separator, plain executable names. | +| Process killing | `ProcessKiller`'s signal path already covers Linux (`host.isMacOS \|\| host.os == HostOs.linux`). | +| Runner socket limit | `runner_discovery.dart` already uses 108 bytes on Linux. The CLI's registry symlink needs no special permission on Linux, so long project paths work as on macOS. | +| AF_UNIX crash | Windows only. `settleAfUnixSockets` is already a no-op off Windows. | +| Analytics | `app_analytics.dart` already reports `Linux`. | +| CEF cache API | `setRootCachePath` in `common/webview_plugin.cc` is compiled for Windows *and* Linux already; only the Linux runner has to call it. | +| `dart install` | Puts executables in `$XDG_STATE_HOME/Dart/install/bin` (default `~/.local/state/Dart/install/bin`, capital D), as symlinks into `…/install/app-bundles//hosted//bundle/bin/`. | +| Dev machine Flutter | Comes through an **asdf shim**, which the probe already handles (`flutter --version --machine` → `flutterRoot`). The dev machine exercises the shim path for free. | + +--- + +## 3. Inventory + +### 3.1 Already works on Linux + +- `HostPlatform`, path handling, `whichOnPath` (POSIX execute bits), + `resolveToolCommand` (no batch files). +- `ProcessKiller`, dev-session cleanup, runner ownership. +- The runner protocol, discovery and client. +- The login-shell `PATH` capture (`login_shell_path.dart`). A program + started from a desktop launcher gets the session's `PATH`, which can miss + lines from `.zshrc`, the same problem as a Finder launch on macOS. +- FVM, Puro, asdf and mise shims in the probe. +- `UpdateController`'s `MissingPluginException` fallback: with no native + side, Check for Updates is greyed out. +- The compact window's fallback: with `supportsCompactWindow` false, a + minimized phone view behaves as desktop-minimized (chrome hidden, window + untouched). + +### 3.2 Falls through to macOS behaviour + +These check `isWindows` and treat everything else as macOS, so Linux gets +macOS paths and commands: + +| # | Area | Where | What Linux gets today | PR | +|---|---|---|---|---| +| F1 | App data folder | `toolchain_paths.dart` `forHome` | `~/Library/Application Support/App Studio` | 1 | +| F2 | `dart install` folder | `toolchain_paths.dart` `dartInstallBinDir` | `~/Library/Application Support/Dart/install/bin` | 2 | +| F3 | CEF cache and preferences folders | `toolchain_paths.dart` `localDataRoot`, `preferencesRoot` | null (macOS has neither) | 1 | +| F4 | Platform key | `platform_key_io.dart` | `unsupported` | 1 | +| F5 | Tool set | `tool_status.dart` `ToolId.requiredOn` | **no tools at all**: Flutter and Serverpod list only macOS and Windows, so setup installs nothing | 2 | +| F6 | Flutter download | `install_plan.dart`, `toolchain_installer.dart` | `releases_macos.json`, a `.zip`. Linux needs `releases_linux.json`, which serves **`.tar.xz`** | 2 | +| F7 | Shell profile | `shell_profile.dart` | macOS's files: `~/.zprofile` for zsh, `~/.bash_profile` for bash. **On Linux both are wrong.** A Linux terminal starts a non-login shell, which reads neither, so a new terminal would not find Flutter. And creating `~/.bash_profile` on Ubuntu (which has only `~/.profile`) makes login bash stop reading `~/.profile`. | 2 | +| F8 | Opening a URL | `open_url_io.dart` | `/usr/bin/open` (does not exist) | 1 | +| F9 | External editors | `external_editors.dart` | looks for `.app` bundles in `/Applications`; finds nothing, so no buttons | 5 | +| F10 | Menus | `main.dart` mounts the menu strip only `if isWindows`; `MacAppMenu` returns early off macOS | **no menus and no shortcuts** | 1 | +| F11 | Shortcut hints | `shortcut_hint.dart` | `⌘R` | 1 | +| F12 | Fonts | `app_theme.dart` | `.AppleSystemUIFont` and `Menlo`, which do not exist | 1 | +| F13 | Notifications | `studio_notifications.dart` | silent (returns off macOS and Windows) | 5 | +| F14 | Uninstall | `uninstaller.dart`, copy | macOS folders; copy about the Trash and NSUserDefaults | 5 | +| F15 | Setup copy | `toolchain_notices.dart`, `install_plan.dart` | "Terminal", "this Mac", "Apple's installer" | 2 | + +### 3.3 Missing outright + +| # | What | PR | +|---|---|---| +| M1 | The `linux/` Flutter runner (`.metadata` lists only `root`, `macos`, `windows`). | 1 | +| M2 | CEF hooks in that runner, wired by hand (section 2). | 1 | +| M3 | Window close → teardown on GTK (to verify, 4.2). | 1 | +| M4 | Packaging: AppImage, `.deb`, `.rpm`, a `.desktop` file, the icon. | 4 | + +--- + +## 4. Approach per subsystem + +### 4.1 Folders (XDG) + +| What | Linux | Follows | +|---|---|---| +| App data (F1) | `$XDG_DATA_HOME/App Studio` (default `~/.local/share/App Studio`) | Q2 | +| CEF cache (F3) | `/CEF`, set by the runner through `setRootCachePath` before CEF starts | — | +| Preferences (F3) | where `shared_preferences` puts them: `$XDG_DATA_HOME//shared_preferences.json`, with `APPLICATION_ID` `dev.serverpod.appstudio` | Q2 | +| Flutter | `~/develop/flutter`, as on macOS | — | +| `dart install` (F2) | `$XDG_STATE_HOME/Dart/install/bin` (section 2) | — | +| Pub cache | `~/.pub-cache` | — | +| `~/.serverpod` | unchanged | — | + +App data and preferences would land in two sibling folders. Picking one +name for both (Q2) makes uninstall one delete. + +### 4.2 The Linux app shell (PR 1) + +- `flutter create --platforms=linux --org dev.serverpod .`, then commit + `linux/`. `APPLICATION_ID` `dev.serverpod.appstudio`, binary + `appstudio`, window title "App Studio", 1280×800, minimum 670×720 (in step + with `kMinAppWindowSize`). +- **CEF hooks by hand**: `initCEFProcesses(argc, argv)` first in `main()`, + so helper processes return before GTK starts; the key press and release + handlers on the `FlView`. Without them the app does not run at all, which + is why they are in PR 1 and the rest of the CEF work is in PR 3. +- **Window close → teardown, to verify first.** On Windows the close + skipped `onExitRequested` because CEF keeps hidden top-level windows. On + GTK, the check is: does clicking close (and Super+Q on Hyprland) run the + teardown that stops the runner? If not, the runner's `delete-event` + handler asks Dart over `dev.serverpod.appstudio/lifecycle`, the channel + Windows already uses (`window_close.dart`). +- **Menus (F10):** mount the Windows shad menu strip (`windows_app_menu.dart`) + on Linux too. Same commands, same Ctrl shortcuts, same enable rules. +- **Shortcut hints (F11):** `shortcutHint()` gives the Ctrl form on Linux. +- **Fonts (F12):** UI in shad's bundled Inter, as on Windows (weight + correction 1). Monospace: the generic `monospace` family, which fontconfig + resolves to the distro's default (DejaVu Sans Mono on Ubuntu). Bundling a + font is the fallback if that looks wrong. +- **`openUrl` (F8):** `xdg-open`. +- Folders (4.1) and the platform key `linux-x64` (F4). +- **Compact window:** off (`supportsCompactWindow` false). Wayland does not + let a program place its own window, and a tiling window manager decides + the size, so the phone-shaped borderless window is unlikely to be worth + it. The desktop-minimized fallback already works. + +### 4.3 Setup (PR 2) + +- **Tool set (F5).** Linux gets **System packages → Flutter → Serverpod**. + `ToolId.systemPackages` is new and Linux only. + - Probe: `git`, `curl`, `unzip` and `xz` via `whichOnPath`. These are the + command-line tools Flutter's own Linux instructions list. + - Install: none (L4). Setup shows the missing ones and the command for + this distro, read from `/etc/os-release` (`ID`, `ID_LIKE`): + `sudo apt install …`, `sudo pacman -S --needed …`, `sudo dnf install …`. + Unknown distro: the list of package names. **Check again** re-probes. +- **Flutter (F6).** `releases_linux.json`, verified against its sha256 as + on macOS, unpacked with `tar -xJf` into a staging folder, then renamed into + `~/develop/flutter`. Same ownership rules as macOS. +- **Serverpod CLI.** `dart install serverpod_cli@`, the same as macOS. +- **`PATH` lines (F7): the files Flutter's own Linux instructions name** + (docs.flutter.dev/install/add-to-path, Linux section). That follows the + existing rule that every tool is installed the way its own instructions + say. The Dart line goes in the same file as Flutter's, as on macOS. + + | Shell | Linux | macOS (unchanged) | + |---|---|---| + | zsh | `~/.zshenv` (read by every zsh, login or not), or `$ZDOTDIR/.zshenv` when the login shell sets `ZDOTDIR` | `~/.zprofile` | + | bash | `~/.bashrc` (read by every interactive bash) | `~/.bash_profile` | + | sh, ksh | `~/.profile` | not supported | + | fish | by hand for now. Flutter's command is `fish_add_path -U -p ~/develop/flutter/bin`, a universal variable rather than a line in a file, so the install record and uninstall need a new kind of entry. | by hand | + | anything else | the lines to add by hand, as today | same | + + Discovery is unaffected: the probe's login-shell fallback runs `-l -i`, + which reads all of these. +- **Copy (F15):** "Terminal" stays, "this Mac" becomes "this computer", + Apple's installer becomes the system packages step. + +### 4.4 The preview (PR 3) + +All in `packages/webview_cef/linux/`, or behind `__linux__` in `common/`: + +- **Auto-setup:** take `modify_target.sh` out of the plugin's CMake. The + hooks live in the runner (PR 1), and the script is what breaks on current + Flutter. +- **Cache folder:** export `setRootCachePath` from the Linux plugin and call + it from the runner with `/CEF` before CEF starts. +- **Shortcuts:** with the preview focused, the page gets the keys, but Ctrl + on any other character key stays App Studio's shortcut, as on Windows. + Ctrl+X/C/V/A/Z go to the page as edit commands. +- **Frame buffer:** the memory bug from the spike. +- **The `xclip` workaround:** remove it (not needed, section 2). +- **End to end:** hard reload and the project-switch clear + (`clearBrowsingData`, `reloadIgnoreCache`) on Linux's multi-threaded CEF + loop; Hot Restart reloads the preview. + +### 4.5 Packaging (PR 4) + +- **AppImage first** (Tuesday), built on the dev machine, from an existing + Flutter Linux AppImage setup with zsync update info, so Gear Lever can + update it. The CEF helpers must resolve their own paths inside the + mounted image; check that early. +- **`.deb`, then `.rpm`:** dependencies on git, curl, unzip and xz, plus + CEF's runtime libraries (libnss3, libgbm1, libasound2 and the rest; to + list from `ldd` on the bundle). +- **Every format:** a `.desktop` file with `StartupWMClass` matching the GTK + application id, so the dock and window match; the icon in hicolor sizes. +- **Size:** strip the bundle (1.5 GB unstripped). The macOS app is 350 MB + with 302 MB of it CEF, which is a fair target. +- **Build scripts in `tool/linux/`**, handed over for Serverpod's CI and + release pipeline. + +### 4.6 Polish (PR 5) + +- **External editors (F9):** + - VS Code and Cursor are found as `code` and `cursor` on `PATH`, or + through their `.desktop` files, and started with the folder. + - Deep links (Codex, OpenCode) go through `xdg-open`, but only when + `xdg-mime query default x-scheme-handler/` names a handler. + - Claude has no official Linux desktop app, so it gets no button. + - Whether Cursor's CLI reaches its Agents Window on Linux is still to + verify, as on Windows. +- **Notifications (F13):** freedesktop notifications over D-Bus + (`notify-send` is not installed everywhere). +- **Uninstall (F14):** remove the XDG folders, the recorded `PATH` lines, + Flutter and the CLI under the existing rules. Never touch system packages. + The app itself goes by deleting the AppImage or through the package + manager; the copy says which. + +--- + +## 5. The five PRs in detail + +Each PR is one branch off `linux/port`, merged into it after testing, with +macOS and Windows CI green. + +### PR 1: App runs (`linux/1-app-runs`) [Tuesday] + +- The app shell (4.2): runner, CEF hooks, window, menus, shortcut hints, + fonts, `xdg-open`, folders, platform key. +- Window close → teardown, checked and fixed if needed. +- Done when: App Studio starts on Omarchy, shows the setup screen with no + runtime errors, the menus work, and closing leaves no processes behind. + +### PR 2: Setup works (`linux/2-setup`) [Tuesday] + +- System packages check, Flutter, Serverpod CLI, `PATH` lines, copy (4.3). +- Widgetbook use cases for the system packages step. +- Done when: on a fresh Ubuntu user account, setup installs Flutter and the + CLI and lands on the start page; on Omarchy it finds the existing asdf + Flutter, reinstalls the too-old `dart install` CLI (4.0.4 on the dev + machine) and nothing else. + +### PR 3: Preview works (`linux/3-preview`) [Tuesday] + +- The CEF fixes (4.4). +- Done when: a new project opens, the server runs, the preview shows the app + and takes typing, copy and paste, Hot Restart works with the preview + focused, and closing App Studio stops the server and its Postgres + (`pgrep -f serverpod`, `pgrep -f postgres` come back empty). + +### PR 4: Packaging (`linux/4-packaging`) + +- The AppImage for Tuesday (4.5); the `.deb` if time allows; the `.rpm` + later. +- Done when (Tuesday): the AppImage runs on Ubuntu and on Omarchy and passes + the smoke checklist (section 6). + +### PR 5: Polish (`linux/5-polish`) + +- Editors, notifications, uninstall (4.6). After Tuesday. + +### Serverpod's side + +- CI (a Linux job, if wanted), the release pipeline, hosting and + auto-updates, using the build scripts from PR 4. + +--- + +## 6. Testing + +- **Unit tests for Linux logic run on every host** through + `HostPlatform.linux`, as Windows logic does: folders, the tool set, the + shell profile choice, the distro install command. +- **Smoke checklist** for Tuesday, run on Ubuntu and Omarchy with the + AppImage: + - start from the launcher; + - first-run setup installs Flutter and the Serverpod CLI; + - create a project; it opens and the server runs; + - the preview works: typing, copy and paste; + - Hot Restart, also with the preview focused; + - the menus and their shortcuts; + - closing App Studio stops the server and leaves nothing running. +- **macOS and Windows:** CI stays the gate. Any PR touching + `packages/webview_cef/common/` also gets a macOS build before it merges + into `linux/port`. +- **For Serverpod's CI, if wanted:** a job on `ubuntu-latest` can run the + whole suite, including the `process` tests (there is no AF_UNIX crash on + Linux), plus `flutter build linux`. Widget tests need no display; the + build needs the GTK headers. + +--- + +## 7. Risks + +| Risk | Impact | Mitigation | +|---|---|---| +| Window close skips the teardown, as it did on Windows | The server and Postgres keep running after App Studio closes | Checked first in PR 1; the `lifecycle` channel already exists | +| Shell profile choice (F7) | macOS's files on Linux: a new terminal does not find Flutter, and a new `~/.bash_profile` silently disables the user's `~/.profile` | Flutter's Linux files (`~/.zshenv`, `~/.bashrc`, `~/.profile`); tests pin each shell on both hosts | +| CEF inside an AppImage | Helpers fail to find their resources or sandbox inside the mounted image | Build a first AppImage as soon as PR 1 runs, not on Monday | +| CEF's Chromium sandbox | Distros that restrict unprivileged user namespaces (Ubuntu 24.04's AppArmor rule) can stop the sandbox | Check on Ubuntu early | +| Bundle size | A 1.5 GB download | Strip; compare with the macOS 350 MB | +| X11 sessions | The spike only covered Wayland | Check Ubuntu on X11 once | +| Shared `common/` CEF edits | macOS or Windows break | `__linux__` guards; a macOS build before merging | +| Tight schedule | 15–25 hours over Friday, Saturday and some of Monday | PR 5 and the `.deb`/`.rpm` are already outside Tuesday | + +--- + +## 8. Open questions + +For Serverpod, since updates and releases are theirs: + +1. **Updates.** The AppImage carries zsync update info, so Gear Lever (and + AppImageUpdate) can update it from wherever Serverpod hosts it. Is that + enough, or should updates go through apt/dnf repositories (which need GPG + signing and hosting)? +2. **Folder name.** One data folder named after the app id + (`dev.serverpod.appstudio`), or "App Studio" as on macOS and Windows? +3. **Ubuntu baseline.** 24.04 LTS? + +--- + +## 9. Developer machine setup (Linux) + +| What | Why | How | +|---|---|---| +| Flutter ≥ 3.44 (stable) | Host SDK for building App Studio | any stable SDK on `PATH`; not in `~/develop/flutter`, which is where App Studio installs its own | +| Flutter's Linux desktop dependencies | `flutter build linux` | Ubuntu: `sudo apt install clang cmake ninja-build pkg-config libgtk-3-dev`; Arch: `sudo pacman -S --needed clang cmake ninja pkgconf gtk3` | +| git, curl, unzip, xz | Flutter itself, and App Studio's own setup check | usually there already | +| ~2 GB free and network on the first build | CEF downloads during the first CMake configure | — | + +Clean-room testing: a second user account on the dev machine gives a fresh +home folder in seconds, which covers setup and `PATH` writing. A spare +laptop with a fresh Ubuntu covers the AppImage on a clean system. + +--- + +## Root PR checklist + +Tuesday: + +- [ ] PR 1: App runs +- [ ] PR 2: Setup works +- [ ] PR 3: Preview works +- [ ] AppImage runs on Ubuntu (smoke checklist) +- [ ] AppImage runs on Omarchy (smoke checklist) + +After Tuesday: + +- [ ] PR 4: `.deb` and `.rpm` +- [ ] PR 5: Polish ("Open in…" editors, notifications, uninstall) +- [ ] Build scripts handed over for Serverpod's CI and release pipeline From effd3d643c90ef9b36c1526ec640099280a5edee Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Thu, 26 Nov 2026 16:42:04 +0100 Subject: [PATCH 02/32] feat: Adds the Linux runner with CEF wired in by hand. The runner calls initCEFProcesses before GTK starts, so CEF's helper processes return instead of booting App Studio again, and hands the view's key events to the preview. The plugin's own script for this patches linux/main.cc, which current Flutter no longer generates. Window title App Studio, 1280x800, minimum 670x600 as on Windows. --- .metadata | 3 + linux/.gitignore | 1 + linux/CMakeLists.txt | 128 ++++++++++++++ linux/flutter/CMakeLists.txt | 88 ++++++++++ linux/flutter/generated_plugin_registrant.cc | 23 +++ linux/flutter/generated_plugin_registrant.h | 15 ++ linux/flutter/generated_plugins.cmake | 27 +++ linux/runner/CMakeLists.txt | 26 +++ linux/runner/main.cc | 18 ++ linux/runner/my_application.cc | 168 +++++++++++++++++++ linux/runner/my_application.h | 21 +++ 11 files changed, 518 insertions(+) create mode 100644 linux/.gitignore create mode 100644 linux/CMakeLists.txt create mode 100644 linux/flutter/CMakeLists.txt create mode 100644 linux/flutter/generated_plugin_registrant.cc create mode 100644 linux/flutter/generated_plugin_registrant.h create mode 100644 linux/flutter/generated_plugins.cmake create mode 100644 linux/runner/CMakeLists.txt create mode 100644 linux/runner/main.cc create mode 100644 linux/runner/my_application.cc create mode 100644 linux/runner/my_application.h diff --git a/.metadata b/.metadata index 4beee9f..a891b62 100644 --- a/.metadata +++ b/.metadata @@ -21,6 +21,9 @@ migration: - platform: windows create_revision: abaf9c523780a608bd46686fd5e53740a07077f8 base_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + - platform: linux + create_revision: 737ba8f885dc774b53b442759999a312c9461e4e + base_revision: 737ba8f885dc774b53b442759999a312c9461e4e # User provided section diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..6295e5a --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "appstudio") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "dev.serverpod.appstudio") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..92b09c2 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); + g_autoptr(FlPluginRegistrar) webview_cef_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "WebviewCefPlugin"); + webview_cef_plugin_register_with_registrar(webview_cef_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..8d2bd5a --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,27 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + url_launcher_linux + webview_cef +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e081001 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,18 @@ +#include + +#include "my_application.h" + +int main(int argc, char** argv) { + // CEF starts its helper processes (renderer, GPU, utility) from this same + // executable. Each of them must run CEF's own entry point and return here, + // before GTK or Flutter start; otherwise every helper boots a full copy of + // App Studio. The plugin's own script that was meant to add this patches + // linux/main.cc, which current Flutter no longer generates. + int exit_code = initCEFProcesses(argc, argv); + if (exit_code >= 0) { + return exit_code; + } + + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..5a47f9e --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,168 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include + +#include "flutter/generated_plugin_registrant.h" + +// kAppWindowSize and kMinAppWindowSize in widgetbook/host.dart. The minimum +// is Windows' (flutter_window.cpp): 600 high fits a 1080p laptop screen at +// 150%, which macOS's 720 does not. A tiling window manager ignores both. +constexpr int kInitialWidth = 1280; +constexpr int kInitialHeight = 800; +constexpr int kMinWidth = 670; +constexpr int kMinHeight = 600; + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "App Studio"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "App Studio"); + } + + gtk_window_set_default_size(window, kInitialWidth, kInitialHeight); + GdkGeometry min_size = {}; + min_size.min_width = kMinWidth; + min_size.min_height = kMinHeight; + gtk_window_set_geometry_hints(window, nullptr, &min_size, GDK_HINT_MIN_SIZE); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + // Keys for the preview: CEF renders off screen, so it only sees the keys + // the view hands it while a page has focus. + g_signal_connect(view, "key_press_event", G_CALLBACK(processKeyEventForCEF), + nullptr); + g_signal_connect(view, "key_release_event", + G_CALLBACK(processKeyEventForCEF), nullptr); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ From 144eefaa4d4818886cb848e43304c8fa48babe14 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Thu, 26 Nov 2026 16:43:43 +0100 Subject: [PATCH 03/32] feat: Gives Linux its data folder, menu strip, fonts and Ctrl shortcuts. App Studio's data goes in $XDG_DATA_HOME/dev.serverpod.appstudio, the folder shared_preferences already uses on Linux. The Windows menu strip is mounted on Linux too, with Quit on Ctrl+Q and no Uninstall until the uninstaller knows Linux. Inter for the UI and fontconfig's monospace, Ctrl in shortcut hints and in the terminal, xdg-open for links, and a linux-x64 platform key. --- lib/main.dart | 9 ++- lib/platform/host_platform.dart | 1 + lib/platform/shortcut_hint.dart | 5 +- lib/platform/windows_app_menu.dart | 28 ++++++-- lib/theme/app_theme.dart | 23 ++++--- lib/toolchain/platform_key_io.dart | 5 +- lib/toolchain/toolchain_paths.dart | 65 ++++++++++++++----- .../terminal/interactive_terminal_view.dart | 3 +- lib/util/open_url_io.dart | 9 ++- specs/linux_port.md | 12 ++-- test/platform/shortcut_hint_test.dart | 23 +++++++ test/platform/windows_app_menu_test.dart | 54 +++++++++++++++ test/toolchain/toolchain_paths_test.dart | 59 +++++++++++++++++ 13 files changed, 248 insertions(+), 48 deletions(-) create mode 100644 test/platform/shortcut_hint_test.dart diff --git a/lib/main.dart b/lib/main.dart index 5327b66..59a6b86 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -252,6 +252,7 @@ class _AppStudioAppState extends State { /// The Windows menu strip, with the same handlers [MacAppMenu] is given. Widget _withWindowsMenu(BuildContext context, Widget? child) => WindowsAppMenuBar( + host: currentHost, session: widget.session, process: widget.process, agent: widget.agent, @@ -531,9 +532,11 @@ class _AppStudioAppState extends State { CompactWindowChannel.supportsTransparency ? Colors.transparent : null, - // Windows has no menu bar to add to: the menus are a strip in the - // window, over every screen. macOS gets `MacAppMenu` instead. - builder: currentHost.isWindows ? _withWindowsMenu : null, + // Windows and Linux have no menu bar to add to: the menus are a + // strip in the window, over every screen. macOS gets `MacAppMenu`. + builder: currentHost.isWindows || currentHost.isLinux + ? _withWindowsMenu + : null, home: switch (_uninstalled) { final result? => UninstalledScreen(result: result), // The teardown stops the server and the agent, which takes a diff --git a/lib/platform/host_platform.dart b/lib/platform/host_platform.dart index 2eca847..6c959ef 100644 --- a/lib/platform/host_platform.dart +++ b/lib/platform/host_platform.dart @@ -42,6 +42,7 @@ class HostPlatform { bool get isWindows => os == HostOs.windows; bool get isMacOS => os == HostOs.macos; + bool get isLinux => os == HostOs.linux; /// Path rules for this host, whatever the machine running the code. On a /// Mac, `HostPlatform.macos.path.join` is `p.join`. diff --git a/lib/platform/shortcut_hint.dart b/lib/platform/shortcut_hint.dart index f900852..9350dba 100644 --- a/lib/platform/shortcut_hint.dart +++ b/lib/platform/shortcut_hint.dart @@ -1,9 +1,10 @@ import 'package:flutter/foundation.dart'; /// A keyboard shortcut as the platform writes it in a tooltip: `⇧⌘R` on a -/// Mac, `Ctrl+Shift+R` on Windows — where the Windows menu strip binds the +/// Mac, `Ctrl+Shift+R` on Windows and Linux — where the menu strip binds the /// same keys with Ctrl (`platform/windows_app_menu.dart`). String shortcutHint(String key, {bool shift = false}) => - defaultTargetPlatform == TargetPlatform.windows + defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.linux ? 'Ctrl+${shift ? 'Shift+' : ''}$key' : '${shift ? '⇧' : ''}⌘$key'; diff --git a/lib/platform/windows_app_menu.dart b/lib/platform/windows_app_menu.dart index 693818e..d0dc45e 100644 --- a/lib/platform/windows_app_menu.dart +++ b/lib/platform/windows_app_menu.dart @@ -14,13 +14,17 @@ import '../ui/server_log/log_view_controller.dart'; import '../ui/server_log/server_log_view.dart'; import '../util/open_url.dart'; import '../util/prompt_generator.dart'; +import 'host_platform.dart'; -/// The Windows counterpart of [MacAppMenu]: the same commands with the same -/// rules for when each is live, as a menu strip across the top of the window -/// with `Ctrl` shortcuts — Windows has no menu bar of its own to add them to. +/// The Windows and Linux counterpart of [MacAppMenu]: the same commands with +/// the same rules for when each is live, as a menu strip across the top of the +/// window with `Ctrl` shortcuts — neither has a menu bar of its own to add +/// them to. /// /// File · View · Server · Logs · Help, the Windows order: Settings and Exit -/// live in File, updates and Uninstall in Help. Every enabled/checked rule +/// live in File, updates and Uninstall in Help. On Linux ([host]) Exit is +/// Quit on Ctrl+Q, as Linux apps name it, and Uninstall is left out until +/// the uninstaller knows Linux's folders (specs/linux_port.md, PR 5). Every enabled/checked rule /// here is the one `macos_app_menu.dart` applies to the same command; the two /// are kept apart so macOS's native menu is untouched. /// @@ -50,8 +54,13 @@ class WindowsAppMenuBar extends StatefulWidget { required this.changes, required this.child, this.stripHidden, + this.host = HostPlatform.windows, }); + /// Windows or Linux: the two differ in how quitting is named and bound, and + /// in whether Uninstall is offered. + final HostPlatform host; + final ProjectSession session; final ServerpodProcessController process; final AgentController agent; @@ -224,6 +233,7 @@ class _WindowsAppMenuBarState extends State { LogicalKeyboardKey.keyR => shift ? _fullRestart : _hotRestart, LogicalKeyboardKey.keyM when !shift => _migrate, LogicalKeyboardKey.keyL when !shift => _toggleLogs, + LogicalKeyboardKey.keyQ when !shift && widget.host.isLinux => _exit, _ => null, }; if (action == null) return false; @@ -357,7 +367,9 @@ class _WindowsAppMenuBarState extends State { onPressed: _settings, ), _divider, - _item('Exit', shortcut: 'Alt+F4', onPressed: _exit), + widget.host.isLinux + ? _item('Quit', shortcut: 'Ctrl+Q', onPressed: _exit) + : _item('Exit', shortcut: 'Alt+F4', onPressed: _exit), ]; } @@ -479,8 +491,10 @@ class _WindowsAppMenuBarState extends State { widget.onSetAutomaticUpdates(!widget.automaticUpdatesEnabled()), ), _divider, - _item('Uninstall App Studio...', onPressed: widget.onUninstall), - _divider, + if (!widget.host.isLinux) ...[ + _item('Uninstall App Studio...', onPressed: widget.onUninstall), + _divider, + ], _item('About App Studio', onPressed: widget.onAbout), ]; } diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart index a058197..5cf2c92 100644 --- a/lib/theme/app_theme.dart +++ b/lib/theme/app_theme.dart @@ -8,18 +8,25 @@ import 'package:shad/shad.dart'; const Color kBrandBlue = Color(0xFF1295F0); bool get _windows => defaultTargetPlatform == TargetPlatform.windows; +bool get _linux => defaultTargetPlatform == TargetPlatform.linux; /// macOS system UI font (SF Pro on modern macOS). const _kMacUiFont = '.AppleSystemUIFont'; -/// The UI font: SF on macOS. On Windows, shad's own bundled Inter (`null` -/// picks it) — the typeface shad's metrics were drawn for, so layouts measure -/// as designed and no weight correction is needed. -String? get _uiFont => _windows ? null : _kMacUiFont; +/// The UI font: SF on macOS. On Windows and Linux, shad's own bundled Inter +/// (`null` picks it) — the typeface shad's metrics were drawn for, so layouts +/// measure as designed and no weight correction is needed. +String? get _uiFont => _windows || _linux ? null : _kMacUiFont; /// Monospace for terminal output and code: Menlo on macOS, Cascadia Mono — -/// shipped with Windows 11 — on Windows. -String get kMonoFont => _windows ? 'Cascadia Mono' : 'Menlo'; +/// shipped with Windows 11 — on Windows. On Linux the generic `monospace` +/// family, which fontconfig resolves to the distro's own (DejaVu Sans Mono on +/// Ubuntu): no single monospace font is on every distro. +String get kMonoFont => _windows + ? 'Cascadia Mono' + : _linux + ? 'monospace' + : 'Menlo'; /// Headline face, bundled at Black (900) and no other weight. /// @@ -39,8 +46,8 @@ const kHeadlineFont = 'Inter'; /// uncorrected `w500` lands where Inter's `w600` would and the whole UI reads /// a step heavy. /// -/// 1 on Windows, where the UI font is Inter itself. -double get _kWeightAxisRatio => _windows ? 1 : 1.65 / 3.17; +/// 1 on Windows and Linux, where the UI font is Inter itself. +double get _kWeightAxisRatio => _windows || _linux ? 1 : 1.65 / 3.17; /// A `wght` variation carrying the appearance [weight] has in shad's font. /// diff --git a/lib/toolchain/platform_key_io.dart b/lib/toolchain/platform_key_io.dart index 53e7667..f0dfe0b 100644 --- a/lib/toolchain/platform_key_io.dart +++ b/lib/toolchain/platform_key_io.dart @@ -1,11 +1,12 @@ import 'dart:io'; -/// `macos-arm64`, `macos-x64`, `windows-arm64`, `windows-x64`, or -/// `unsupported`. +/// `macos-arm64`, `macos-x64`, `windows-arm64`, `windows-x64`, `linux-arm64`, +/// `linux-x64`, or `unsupported`. String currentPlatformKey() { final os = switch (Platform.operatingSystem) { 'macos' => 'macos', 'windows' => 'windows', + 'linux' => 'linux', _ => null, }; if (os == null) return 'unsupported'; diff --git a/lib/toolchain/toolchain_paths.dart b/lib/toolchain/toolchain_paths.dart index 4a5efd7..5355d63 100644 --- a/lib/toolchain/toolchain_paths.dart +++ b/lib/toolchain/toolchain_paths.dart @@ -8,6 +8,12 @@ import '../platform/host.dart'; /// Windows). const kAppSupportDirName = 'App Studio'; +/// Linux: the directory under `$XDG_DATA_HOME`. It is the GTK application id +/// (`linux/CMakeLists.txt`), because `shared_preferences` already keeps the +/// settings in a directory of that name, so App Studio's own data joins them +/// and there is one directory to remove (specs/linux_port.md, L5). +const kLinuxAppDataDirName = 'dev.serverpod.appstudio'; + /// What the directory was called before the product was renamed. Only ever /// deleted now — see [ToolchainPaths.legacyPaths]. const kLegacyAppSupportDirName = 'AppStudio'; @@ -32,30 +38,53 @@ class ToolchainPaths { final home = resolvedHost.homeFrom(Platform.environment) ?? Directory.systemTemp.path; - return ToolchainPaths.forHome(home, host: resolvedHost); + return ToolchainPaths.forHome( + home, + host: resolvedHost, + environment: Platform.environment, + ); } - factory ToolchainPaths.forHome(String home, {HostPlatform? host}) { + /// [environment] is read only on Linux, for the XDG base directories. + factory ToolchainPaths.forHome( + String home, { + HostPlatform? host, + Map environment = const {}, + }) { final resolvedHost = host ?? currentHost; + final path = resolvedHost.path; return ToolchainPaths( home: home, - appSupportRoot: resolvedHost.isWindows - ? resolvedHost.path.join( - home, - 'AppData', - 'Roaming', - kAppSupportDirName, - ) - : resolvedHost.path.join( - home, - 'Library', - 'Application Support', - kAppSupportDirName, - ), + appSupportRoot: switch (resolvedHost.os) { + HostOs.windows => path.join( + home, + 'AppData', + 'Roaming', + kAppSupportDirName, + ), + HostOs.linux => path.join( + _xdgDir(environment['XDG_DATA_HOME'], path) ?? + path.join(home, '.local', 'share'), + kLinuxAppDataDirName, + ), + HostOs.macos => path.join( + home, + 'Library', + 'Application Support', + kAppSupportDirName, + ), + }, host: resolvedHost, ); } + /// An XDG base directory variable, or null when it is unset, empty or + /// relative — the spec says to ignore a relative one and use the default. + static String? _xdgDir(String? value, p.Context path) => + value != null && value.isNotEmpty && path.isAbsolute(value) + ? value + : null; + final String home; /// App Studio's own data. No tools live here any more. @@ -111,14 +140,16 @@ class ToolchainPaths { /// Windows: App Studio's machine-local data — the preview's CEF cache, which /// the runner puts in `%LOCALAPPDATA%\App Studio\CEF` (`windows/runner/ - /// main.cpp`). Null on macOS, where all of it is under [appSupportRoot]. + /// main.cpp`). Null on macOS and Linux, where all of it is under + /// [appSupportRoot]. String? get localDataRoot => host.isWindows ? _path.join(home, 'AppData', 'Local', kAppSupportDirName) : null; /// Windows: where `shared_preferences` keeps its file — /// `%APPDATA%\\` from `windows/runner/Runner.rc`. - /// Null on macOS, where preferences are NSUserDefaults. + /// Null on macOS, where preferences are NSUserDefaults, and on Linux, where + /// the file is in [appSupportRoot] itself. String? get preferencesRoot => host.isWindows ? _path.join(home, 'AppData', 'Roaming', 'Serverpod', kAppSupportDirName) : null; diff --git a/lib/ui/terminal/interactive_terminal_view.dart b/lib/ui/terminal/interactive_terminal_view.dart index 7b2beda..f2b3276 100644 --- a/lib/ui/terminal/interactive_terminal_view.dart +++ b/lib/ui/terminal/interactive_terminal_view.dart @@ -149,7 +149,8 @@ class InteractiveTerminalView extends StatelessWidget { /// does — the host in the app, and whatever a test sets in a test, so the /// Windows mapping can be tested on a Mac and the other way round. static bool get _ctrlIsTerminal => - defaultTargetPlatform == TargetPlatform.windows; + defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.linux; /// Lets ⌘ chords past xterm to the menu bar. See the class comment. static KeyEventResult _routeKey(FocusNode node, KeyEvent event) { diff --git a/lib/util/open_url_io.dart b/lib/util/open_url_io.dart index 93cae71..cc57942 100644 --- a/lib/util/open_url_io.dart +++ b/lib/util/open_url_io.dart @@ -4,13 +4,20 @@ import '../platform/host.dart'; import '../platform/windows/win32_system.dart'; /// `open` hands the URL to LaunchServices, which picks the user's browser. -/// On Windows `ShellExecute` does the same through the registered handler. +/// On Windows `ShellExecute` does the same through the registered handler, and +/// on Linux `xdg-open` through the desktop's default handlers. Future openUrl(Uri url) async { try { if (currentHost.isWindows) { Win32System().shellOpen(url.toString()); return; } + if (currentHost.isLinux) { + // Found on PATH: it is /usr/bin/xdg-open on every desktop distro, but + // an absolute path would be one more thing to be wrong about. + await Process.run('xdg-open', [url.toString()]); + return; + } await Process.run('/usr/bin/open', [url.toString()]); } catch (_) { // Nothing useful to report: the link text is still on screen. diff --git a/specs/linux_port.md b/specs/linux_port.md index e4f66a0..6e3f0c5 100644 --- a/specs/linux_port.md +++ b/specs/linux_port.md @@ -46,6 +46,7 @@ uninstall. | L2 | **Tested on Ubuntu and Arch (Omarchy, Hyprland).** Not on Fedora for now. Omarchy is Wayland and a tiling window manager, so it is the hard case. | | L3 | **No Flatpak.** Its sandbox gets in the way of everything App Studio does outside itself: installing Flutter into `~/develop`, editing the shell profile, starting the user's tools. | | L4 | **App Studio never runs `sudo` or `pkexec`.** It installs Flutter and the Serverpod CLI per user, as on macOS and Windows. For system packages (git, curl, unzip, xz), setup checks and gives the distro's own install command with a **Check again** button, the same pattern as `ManualUpdateDialog`. The `.deb` and `.rpm` declare them as dependencies instead. | +| L5 | **One data folder, named after the app id: `$XDG_DATA_HOME/dev.serverpod.appstudio`** (default `~/.local/share/dev.serverpod.appstudio`). `shared_preferences` already keeps the settings there on Linux, so App Studio's own data joins them: one folder, removed in one go, and the lowercase, space-free name Linux folders usually have. macOS and Windows keep their "App Studio" folders. | --- @@ -184,16 +185,15 @@ macOS paths and commands: | What | Linux | Follows | |---|---|---| -| App data (F1) | `$XDG_DATA_HOME/App Studio` (default `~/.local/share/App Studio`) | Q2 | +| App data (F1) | `$XDG_DATA_HOME/dev.serverpod.appstudio` (default `~/.local/share/dev.serverpod.appstudio`) | L5 | | CEF cache (F3) | `/CEF`, set by the runner through `setRootCachePath` before CEF starts | — | -| Preferences (F3) | where `shared_preferences` puts them: `$XDG_DATA_HOME//shared_preferences.json`, with `APPLICATION_ID` `dev.serverpod.appstudio` | Q2 | +| Preferences (F3) | where `shared_preferences` puts them: `$XDG_DATA_HOME//shared_preferences.json`, with `APPLICATION_ID` `dev.serverpod.appstudio`: the same folder | L5 | | Flutter | `~/develop/flutter`, as on macOS | — | | `dart install` (F2) | `$XDG_STATE_HOME/Dart/install/bin` (section 2) | — | | Pub cache | `~/.pub-cache` | — | | `~/.serverpod` | unchanged | — | -App data and preferences would land in two sibling folders. Picking one -name for both (Q2) makes uninstall one delete. +App data and preferences share one folder (L5), so uninstall is one delete. ### 4.2 The Linux app shell (PR 1) @@ -405,9 +405,7 @@ For Serverpod, since updates and releases are theirs: AppImageUpdate) can update it from wherever Serverpod hosts it. Is that enough, or should updates go through apt/dnf repositories (which need GPG signing and hosting)? -2. **Folder name.** One data folder named after the app id - (`dev.serverpod.appstudio`), or "App Studio" as on macOS and Windows? -3. **Ubuntu baseline.** 24.04 LTS? +2. **Ubuntu baseline.** 24.04 LTS? --- diff --git a/test/platform/shortcut_hint_test.dart b/test/platform/shortcut_hint_test.dart new file mode 100644 index 0000000..78e4020 --- /dev/null +++ b/test/platform/shortcut_hint_test.dart @@ -0,0 +1,23 @@ +import 'package:appstudio/platform/shortcut_hint.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Tooltips name a shortcut the way the platform's menus bind it. +void main() { + tearDown(() => debugDefaultTargetPlatformOverride = null); + + test('macOS writes ⌘ and ⇧', () { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + expect(shortcutHint('R'), '⌘R'); + expect(shortcutHint('R', shift: true), '⇧⌘R'); + }); + + test('Windows and Linux write Ctrl, as their menu strip binds it', () { + for (final platform in [TargetPlatform.windows, TargetPlatform.linux]) { + debugDefaultTargetPlatformOverride = platform; + expect(shortcutHint('R'), 'Ctrl+R', reason: '$platform'); + expect(shortcutHint('R', shift: true), 'Ctrl+Shift+R', + reason: '$platform'); + } + }); +} diff --git a/test/platform/windows_app_menu_test.dart b/test/platform/windows_app_menu_test.dart index 751ddcd..1a5d6f2 100644 --- a/test/platform/windows_app_menu_test.dart +++ b/test/platform/windows_app_menu_test.dart @@ -1,4 +1,5 @@ import 'package:appstudio/agent/agent_controller.dart'; +import 'package:appstudio/platform/host_platform.dart'; import 'package:appstudio/platform/windows_app_menu.dart'; import 'package:appstudio/process/serverpod_process.dart'; import 'package:appstudio/session/project_session.dart'; @@ -50,6 +51,7 @@ void main() { ChangeNotifier? changes, bool Function()? stripHidden, Widget child = const SizedBox.expand(), + HostPlatform host = HostPlatform.windows, }) async { await tester.pumpWidget( ShadApp( @@ -72,6 +74,7 @@ void main() { onCreateRepairMigration: () {}, changes: changes ?? ChangeNotifier(), stripHidden: stripHidden, + host: host, child: child, ), ), @@ -171,6 +174,57 @@ void main() { expect(counter.currentState!.count, 7); }); + Future openMenu(WidgetTester tester, String title) async { + await tester.tap(find.text(title)); + await tester.pumpAndSettle(); + } + + testWidgets('Windows quits with Exit on Alt+F4', (tester) async { + await pumpMenu(tester); + + await openMenu(tester, 'File'); + + expect(find.text('Exit'), findsOneWidget); + expect(find.text('Alt+F4'), findsOneWidget); + expect(find.text('Quit'), findsNothing); + }); + + testWidgets('Linux quits with Quit on Ctrl+Q', (tester) async { + await pumpMenu(tester, host: HostPlatform.linux); + + await openMenu(tester, 'File'); + + expect(find.text('Quit'), findsOneWidget); + expect(find.text('Ctrl+Q'), findsOneWidget); + expect(find.text('Exit'), findsNothing); + }); + + testWidgets('Windows offers Uninstall', (tester) async { + await pumpMenu(tester); + + await openMenu(tester, 'Help'); + + expect(find.text('Uninstall App Studio...'), findsOneWidget); + }); + + testWidgets('Linux offers no Uninstall until it knows Linux\'s folders', + (tester) async { + await pumpMenu(tester, host: HostPlatform.linux); + + await openMenu(tester, 'Help'); + + expect(find.text('About App Studio'), findsOneWidget); + expect(find.text('Uninstall App Studio...'), findsNothing); + }); + + testWidgets('Linux binds the same Ctrl shortcuts', (tester) async { + await pumpMenu(tester, host: HostPlatform.linux); + + await ctrl(tester, LogicalKeyboardKey.keyN); + + expect(newProjects, 1); + }); + testWidgets('the shortcuts go with the menu', (tester) async { await pumpMenu(tester); await tester.pumpWidget(const SizedBox()); diff --git a/test/toolchain/toolchain_paths_test.dart b/test/toolchain/toolchain_paths_test.dart index 6818193..f45e5cf 100644 --- a/test/toolchain/toolchain_paths_test.dart +++ b/test/toolchain/toolchain_paths_test.dart @@ -76,4 +76,63 @@ void main() { expect(windows.legacyShellFiles, isEmpty); }); }); + + group('on Linux', () { + final linux = ToolchainPaths.forHome( + '/home/alex', + host: HostPlatform.linux, + ); + + test('App Studio keeps its data in one folder named after the app id', () { + // The folder shared_preferences already uses on Linux, so settings and + // data are removed together. + expect( + linux.appSupportRoot, + '/home/alex/.local/share/dev.serverpod.appstudio', + ); + expect(linux.localDataRoot, isNull); + expect(linux.preferencesRoot, isNull); + }); + + test('XDG_DATA_HOME moves it', () { + final moved = ToolchainPaths.forHome( + '/home/alex', + host: HostPlatform.linux, + environment: const {'XDG_DATA_HOME': '/data/alex'}, + ); + expect(moved.appSupportRoot, '/data/alex/dev.serverpod.appstudio'); + }); + + test('an empty or relative XDG_DATA_HOME is ignored, as the spec says', + () { + for (final value in ['', 'relative/share']) { + final paths = ToolchainPaths.forHome( + '/home/alex', + host: HostPlatform.linux, + environment: {'XDG_DATA_HOME': value}, + ); + expect( + paths.appSupportRoot, + '/home/alex/.local/share/dev.serverpod.appstudio', + ); + } + }); + + test('XDG_DATA_HOME means nothing off Linux', () { + final mac = ToolchainPaths.forHome( + '/Users/alex', + host: HostPlatform.macos, + environment: const {'XDG_DATA_HOME': '/data/alex'}, + ); + expect( + mac.appSupportRoot, + '/Users/alex/Library/Application Support/App Studio', + ); + }); + + test('no build ever shipped a toolchain there, so nothing is legacy', () { + expect(linux.legacyPaths, isEmpty); + expect(linux.legacyShellFiles, isEmpty); + }); + }); } From 920903074e676bc9442c8454436615fb4dc12260 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Thu, 26 Nov 2026 16:44:16 +0100 Subject: [PATCH 04/32] test: Runs the legacy toolchain tests on macOS only. Only macOS builds ever shipped a private toolchain, so these tests already skipped on Windows; on a Linux host they failed. --- test/toolchain/tool_probe_test.dart | 4 ++-- test/toolchain/toolchain_installer_test.dart | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/toolchain/tool_probe_test.dart b/test/toolchain/tool_probe_test.dart index 5fd7911..c28dde0 100644 --- a/test/toolchain/tool_probe_test.dart +++ b/test/toolchain/tool_probe_test.dart @@ -506,7 +506,7 @@ void main() { test('an earlier build\'s private toolchain is found', () async { await touch(p.join(paths.legacyToolchainRoot, 'flutter', 'marker')); expect((await probe().inventory()).legacyInstallFound, isTrue); - }, skip: Platform.isWindows ? 'no Windows build shipped a toolchain' : false); + }, skip: Platform.isMacOS ? false : 'only macOS builds shipped a toolchain'); test('so is only its PATH block', () async { await touch( @@ -514,7 +514,7 @@ void main() { '# mine\n\n$kLegacyShellBlockStart\n# x\n$kLegacyShellBlockEnd\n', ); expect((await probe().inventory()).legacyInstallFound, isTrue); - }, skip: Platform.isWindows ? 'no Windows build shipped a toolchain' : false); + }, skip: Platform.isMacOS ? false : 'only macOS builds shipped a toolchain'); }); group('parseFlutterRoot', () { diff --git a/test/toolchain/toolchain_installer_test.dart b/test/toolchain/toolchain_installer_test.dart index 849d22c..f4f22e5 100644 --- a/test/toolchain/toolchain_installer_test.dart +++ b/test/toolchain/toolchain_installer_test.dart @@ -288,7 +288,7 @@ void main() { } expect(await scratch.exists(), isTrue); expect(await zshrc.readAsString(), '# mine\n'); - }); + }, skip: Platform.isMacOS ? false : 'only macOS builds shipped a toolchain'); }); test('collectGarbage clears a crashed unpack', () async { From 73b1c898a45fccaf2d2aa82d909c25fa65170293 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Thu, 26 Nov 2026 17:17:47 +0100 Subject: [PATCH 05/32] feat: Checks Linux's system packages and gives the distro's command to install them. Linux's tool set is system packages, Flutter and the Serverpod CLI. git, curl, unzip and xz are probed on PATH; App Studio never runs sudo, so missing ones are a manual step: setup shows the apt, pacman, dnf or zypper command read from /etc/os-release, or the package names for a distro it does not know, with Check again, before anything else is installed. --- assets/toolchain_manifest.json | 5 ++ lib/toolchain/linux_packages.dart | 82 +++++++++++++++++++ lib/toolchain/tool_probe.dart | 63 ++++++++++++++ lib/toolchain/tool_status.dart | 23 ++++-- lib/toolchain/toolchain_controller.dart | 16 +++- lib/ui/toolchain/manage_tools_pane.dart | 13 +-- lib/ui/toolchain/toolchain_notices.dart | 55 +++++++++++-- .../uninstall/uninstall_confirm_dialog.dart | 2 +- .../toolchain_setup_screen_test.dart | 38 +++++++++ widgetbook/fakes/tools.dart | 43 ++++++++++ widgetbook/use_cases/first_run.dart | 22 +++++ 11 files changed, 338 insertions(+), 24 deletions(-) create mode 100644 lib/toolchain/linux_packages.dart diff --git a/assets/toolchain_manifest.json b/assets/toolchain_manifest.json index 2f71e9d..7653bb7 100644 --- a/assets/toolchain_manifest.json +++ b/assets/toolchain_manifest.json @@ -16,6 +16,11 @@ "displayName": "Git for Windows", "description": "The git Flutter runs on." }, + { + "id": "system_packages", + "displayName": "System packages", + "description": "git, curl, unzip and xz from your distribution. Flutter runs on them." + }, { "id": "flutter", "displayName": "Flutter", diff --git a/lib/toolchain/linux_packages.dart b/lib/toolchain/linux_packages.dart new file mode 100644 index 0000000..900ba10 --- /dev/null +++ b/lib/toolchain/linux_packages.dart @@ -0,0 +1,82 @@ +/// Linux's system packages: the command-line tools Flutter's own Linux +/// instructions list, which App Studio checks for and never installs itself. +/// It runs no `sudo` (specs/linux_port.md, L4): setup names what is missing +/// and gives this distro's command to install it. +/// +/// Free of `dart:io` — the probe reads `/etc/os-release` and hands it in. +library; + +/// The commands App Studio needs on `PATH`. Flutter runs on `git`, and its +/// tool downloads and unpacks with `curl`, `unzip` and `xz`; App Studio's own +/// Flutter install unpacks a `.tar.xz` too. +const kLinuxRequiredCommands = ['git', 'curl', 'unzip', 'xz']; + +/// The package managers App Studio can write an install command for. +enum LinuxPackageManager { + apt('sudo apt install'), + pacman('sudo pacman -S --needed'), + dnf('sudo dnf install'), + zypper('sudo zypper install'); + + const LinuxPackageManager(this.installPrefix); + + final String installPrefix; +} + +/// The package manager of the distro `/etc/os-release` describes, from its +/// `ID` and then each `ID_LIKE` entry — Omarchy is `ID=omarchy`, +/// `ID_LIKE=arch`. Null for a distro none of them is known for. +LinuxPackageManager? packageManagerFor(String osRelease) { + final fields = parseOsRelease(osRelease); + final ids = [ + ?fields['ID'], + ...?fields['ID_LIKE']?.split(RegExp(r'\s+')), + ]; + for (final id in ids) { + final manager = switch (id) { + 'debian' || 'ubuntu' => LinuxPackageManager.apt, + 'arch' => LinuxPackageManager.pacman, + 'fedora' || 'rhel' || 'centos' => LinuxPackageManager.dnf, + 'suse' || 'opensuse' || 'sles' => LinuxPackageManager.zypper, + _ when id.startsWith('opensuse') => LinuxPackageManager.zypper, + _ => null, + }; + if (manager != null) return manager; + } + return null; +} + +/// `KEY=value` lines, with the shell quoting os-release allows stripped. +Map parseOsRelease(String contents) { + final fields = {}; + for (final line in contents.split('\n')) { + final trimmed = line.trim(); + if (trimmed.isEmpty || trimmed.startsWith('#')) continue; + final eq = trimmed.indexOf('='); + if (eq <= 0) continue; + var value = trimmed.substring(eq + 1); + if (value.length >= 2 && + (value.startsWith('"') && value.endsWith('"') || + value.startsWith("'") && value.endsWith("'"))) { + value = value.substring(1, value.length - 1); + } + fields[trimmed.substring(0, eq)] = value; + } + return fields; +} + +/// The package that provides [command]. Only Debian and Ubuntu name one +/// differently: `xz` comes in `xz-utils`. +String linuxPackageFor(String command, LinuxPackageManager? manager) => + command == 'xz' && manager == LinuxPackageManager.apt ? 'xz-utils' : command; + +/// The command that installs [missing] with [manager], or null when the +/// distro is not one App Studio knows — the caller then lists the packages. +String? linuxInstallCommand( + List missing, + LinuxPackageManager? manager, +) { + if (manager == null || missing.isEmpty) return null; + final packages = [for (final c in missing) linuxPackageFor(c, manager)]; + return '${manager.installPrefix} ${packages.join(' ')}'; +} diff --git a/lib/toolchain/tool_probe.dart b/lib/toolchain/tool_probe.dart index 78c73f4..87838ab 100644 --- a/lib/toolchain/tool_probe.dart +++ b/lib/toolchain/tool_probe.dart @@ -8,6 +8,7 @@ import '../platform/windows/win32_system.dart'; import '../platform/windows/windows_system.dart'; import '../process/tool_command.dart'; import 'install_record.dart'; +import 'linux_packages.dart'; import 'login_shell_path.dart'; import 'shell_profile.dart'; import 'tool_status.dart'; @@ -251,6 +252,7 @@ class ToolProbe { Map? environment, WindowsSystem? windows, ProbeSandbox? sandbox, + this.osReleasePath = '/etc/os-release', }) : _run = runner ?? sandbox?.runner ?? _defaultRunner, _loginShellPath = loginShellPath ?? sandbox?.loginShellPath ?? captureLoginShellPath, @@ -263,6 +265,10 @@ class ToolProbe { final ToolManifest manifest; final InstallRecord record; + /// Linux: names the distro, and so the command that installs missing system + /// packages. + final String osReleasePath; + HostPlatform get _host => paths.host; p.Context get _path => _host.path; @@ -311,6 +317,7 @@ class ToolProbe { if (manifest[ToolId.commandLineTools] != null) _probeCommandLineTools(), if (manifest[ToolId.developerMode] != null) _probeDeveloperMode(), if (manifest[ToolId.git] != null) _probeGit(), + if (manifest[ToolId.systemPackages] != null) _probeSystemPackages(), _probeServerpod(dartExecutable, deep: deep), ]); for (final status in rest) { @@ -459,6 +466,62 @@ class ToolProbe { ); } + // -- System packages (Linux) ---------------------------------------------- + + /// Every command in [kLinuxRequiredCommands] on `PATH`, or the ones that + /// are not. Missing ones are the user's to install — they need `sudo`, + /// which App Studio never runs — so the action is [ToolAction.manual], with + /// the distro's command in the `installCommand` fact when it is known. + Future _probeSystemPackages() async { + final spec = manifest[ToolId.systemPackages]!; + const id = ToolId.systemPackages; + final missing = [ + for (final command in kLinuxRequiredCommands) + if (await _which(command) == null) command, + ]; + if (missing.isEmpty) { + return ToolStatus( + spec: spec, + candidates: [ + ToolCandidate( + id: id, + source: ToolSource.host, + fitness: ToolFitness.satisfied, + ), + ], + ); + } + String? osRelease; + try { + osRelease = await File(osReleasePath).readAsString(); + } catch (_) { + osRelease = null; + } + final manager = osRelease == null ? null : packageManagerFor(osRelease); + final command = linuxInstallCommand(missing, manager); + return ToolStatus( + spec: spec, + candidates: [ + ToolCandidate( + id: id, + source: ToolSource.host, + // Not notFound: [ToolStatus.bestRejected] skips those, and the + // setup dialog reads what is missing from it. + fitness: ToolFitness.incomplete, + reason: 'missing ${missing.join(', ')}', + facts: { + 'missing': missing.join(' '), + 'packages': [ + for (final c in missing) linuxPackageFor(c, manager), + ].join(' '), + 'installCommand': ?command, + }, + ), + ], + action: ToolAction.manual, + ); + } + // -- Flutter -------------------------------------------------------------- /// Every Flutter SDK, in precedence order: `FLUTTER_ROOT`, then what diff --git a/lib/toolchain/tool_status.dart b/lib/toolchain/tool_status.dart index e89be38..6ccbdd1 100644 --- a/lib/toolchain/tool_status.dart +++ b/lib/toolchain/tool_status.dart @@ -3,10 +3,10 @@ import 'toolchain_manifest.dart'; import 'tool_version.dart'; /// The tools App Studio needs, in install order: the Command Line Tools -/// (macOS) or Git for Windows supply the `git` Flutter runs on, and the -/// Serverpod CLI is installed with Flutter's own `dart`. On Windows, -/// Developer Mode comes first: Flutter and the Serverpod runner need the -/// symbolic links only it allows. +/// (macOS), Git for Windows or Linux's system packages supply the `git` +/// Flutter runs on, and the Serverpod CLI is installed with Flutter's own +/// `dart`. On Windows, Developer Mode comes first: Flutter and the Serverpod +/// runner need the symbolic links only it allows. /// /// Each tool says which hosts need it; a host's tool set is /// [ToolId.requiredOn], in this order. @@ -18,8 +18,16 @@ enum ToolId { ), developerMode('developer_mode', 'Developer Mode', {HostOs.windows}), git('git', 'Git for Windows', {HostOs.windows}), - flutter('flutter', 'Flutter', {HostOs.macos, HostOs.windows}), - serverpodCli('serverpod_cli', 'Serverpod', {HostOs.macos, HostOs.windows}); + + /// Linux: `git`, `curl`, `unzip` and `xz` (`linux_packages.dart`). Never + /// installed by App Studio — the user runs the distro's command. + systemPackages('system_packages', 'System packages', {HostOs.linux}), + flutter('flutter', 'Flutter', {HostOs.macos, HostOs.windows, HostOs.linux}), + serverpodCli( + 'serverpod_cli', + 'Serverpod', + {HostOs.macos, HostOs.windows, HostOs.linux}, + ); const ToolId(this.manifestId, this.displayName, this.hosts); @@ -103,7 +111,8 @@ enum ToolAction { update, /// There is a copy App Studio did not install and must not touch — the user - /// updates it themselves. In practice: their own Flutter is too old. + /// updates it themselves. In practice: their own Flutter is too old, or + /// Linux's system packages are missing, which need `sudo`. manual; /// Whether App Studio can carry this out on its own. diff --git a/lib/toolchain/toolchain_controller.dart b/lib/toolchain/toolchain_controller.dart index b2550d5..c29c20b 100644 --- a/lib/toolchain/toolchain_controller.dart +++ b/lib/toolchain/toolchain_controller.dart @@ -197,6 +197,9 @@ class ToolchainController extends ChangeNotifier implements ToolsView { case ToolId.developerMode: // A setting, not a download. return const PlannedTool(id: ToolId.developerMode); + case ToolId.systemPackages: + // Never planned: the user installs them (ToolAction.manual). + return const PlannedTool(id: ToolId.systemPackages); case ToolId.git: final release = await fetchGitRelease(client, arch: currentArch()); return PlannedTool( @@ -209,7 +212,7 @@ class ToolchainController extends ChangeNotifier implements ToolsView { client, accepts: status.spec.accepts, arch: currentArch(), - windows: paths.host.isWindows, + os: paths.host.os, ); // An update runs `flutter upgrade`, which picks its own release; the // feed only says what that will be. @@ -369,6 +372,12 @@ class ToolchainController extends ChangeNotifier implements ToolsView { await installer.enableDeveloperMode(onProgress: onProgress), ); + case ToolId.systemPackages: + // Never installable: they need sudo, which App Studio never runs. + throw const ToolInstallException( + 'Install the missing system packages from a terminal.', + ); + case ToolId.git: final release = _plan[id]?.gitRelease; if (release == null) { @@ -518,6 +527,8 @@ class ToolchainController extends ChangeNotifier implements ToolsView { ToolId.commandLineTools => await Directory('/Library/Developer/CommandLineTools').exists(), ToolId.developerMode => developerModeEnabled(installer.windows), + // Never recorded: App Studio does not install them. + ToolId.systemPackages => false, ToolId.git => entry.path != null && await File(paths.host.path.join(entry.path!, 'cmd', 'git.exe')) .exists(), @@ -550,6 +561,9 @@ class ToolchainController extends ChangeNotifier implements ToolsView { await installer.uninstallGit(entry); case ToolId.developerMode: await installer.disableDeveloperMode(); + case ToolId.systemPackages: + // Never recorded, so never removed: other software needs them. + return; } await _saveRecord(_record.without(id)); } diff --git a/lib/ui/toolchain/manage_tools_pane.dart b/lib/ui/toolchain/manage_tools_pane.dart index c701cad..0fc7221 100644 --- a/lib/ui/toolchain/manage_tools_pane.dart +++ b/lib/ui/toolchain/manage_tools_pane.dart @@ -113,12 +113,10 @@ class _ManageToolsPaneState extends State { for (final status in manual) ...[ const ShadGap(3), ErrorBanner(message: manualUpdateMessage(status)), - if (status.bestRejected case final candidate? - when candidate.fitness == ToolFitness.wrongVersion) - if (manualUpdateCommand(candidate) case final command?) ...[ - const ShadGap(2), - CommandBlock(command: command), - ], + if (manualCommandFor(status) case final command?) ...[ + const ShadGap(2), + CommandBlock(command: command), + ], ], if (pathLines.isNotEmpty) ...[ const ShadGap(3), @@ -164,6 +162,9 @@ class _ManageToolsPaneState extends State { null => appWarningBadge( theme, child: Text(switch (status.action) { + // Linux's system packages are manual too, but they are not + // there at all rather than out of date. + _ when status.id == ToolId.systemPackages => 'Missing', ToolAction.manual || ToolAction.update => 'Update needed', _ => 'Missing', }), diff --git a/lib/ui/toolchain/toolchain_notices.dart b/lib/ui/toolchain/toolchain_notices.dart index 84f8ada..e900f39 100644 --- a/lib/ui/toolchain/toolchain_notices.dart +++ b/lib/ui/toolchain/toolchain_notices.dart @@ -301,8 +301,40 @@ String? manualUpdateCommand(ToolCandidate candidate) { ].join('\n'); } -/// Explains a copy that App Studio did not install and so will not change. +/// What to run for a tool the user has to fix themselves, or null when there +/// is no one command: Flutter's own update for an old Flutter +/// ([manualUpdateCommand]), the distro's install command for Linux's missing +/// system packages. +String? manualCommandFor(ToolStatus status) { + final candidate = status.bestRejected; + if (candidate == null) return null; + if (status.id == ToolId.systemPackages) { + return candidate.facts['installCommand']; + } + if (candidate.fitness != ToolFitness.wrongVersion) return null; + return manualUpdateCommand(candidate); +} + +/// `a`, `a and b`, `a, b and c`. +String _andList(List items) => items.length <= 1 + ? items.join() + : '${items.sublist(0, items.length - 1).join(', ')} and ${items.last}'; + +/// Explains a copy that App Studio did not install and so will not change — +/// or, on Linux, the system packages it does not install at all. String manualUpdateMessage(ToolStatus status) { + if (status.id == ToolId.systemPackages) { + final facts = status.bestRejected?.facts ?? const {}; + final missing = (facts['missing'] ?? '').split(' ') + ..removeWhere((m) => m.isEmpty); + final how = facts['installCommand'] == null + ? ' Install ${missing.length == 1 ? 'it' : 'them'} with your ' + 'distribution\'s package manager: ' + '${(facts['packages'] ?? '').split(' ').join(', ')}.' + : ''; + return 'Flutter needs ${_andList(missing)}, and ' + '${missing.length == 1 ? 'it is' : 'they are'} not installed.$how'; + } final candidate = status.bestRejected; final where = candidate?.root == null ? '' : ' in ${prettyPath(candidate!.root!)}'; @@ -377,7 +409,9 @@ class _ManualUpdateDialogState extends State { canPop: false, child: ShadDialog.alert( title: Text( - pending.length == 1 + pending.every((s) => s.id == ToolId.systemPackages) + ? 'Install system packages' + : pending.length == 1 ? 'Update ${pending.single.spec.displayName}' : 'Update your tools', ), @@ -411,9 +445,14 @@ class _ManualUpdateDialogState extends State { mainAxisSize: MainAxisSize.min, children: [ if (_stillNeeded) ...[ - const ErrorBanner( - message: 'Still out of date. Check that the command ' - 'finished without errors.', + ErrorBanner( + message: pending.every( + (s) => s.id == ToolId.systemPackages, + ) + ? 'Still missing. Check that the command finished ' + 'without errors.' + : 'Still out of date. Check that the command ' + 'finished without errors.', ), const ShadGap(3), ], @@ -423,10 +462,8 @@ class _ManualUpdateDialogState extends State { style: theme.textTheme.muted, ), const ShadGap(2), - if (status.bestRejected case final candidate? - when candidate.fitness == ToolFitness.wrongVersion) - if (manualUpdateCommand(candidate) case final command?) - CommandBlock(command: command), + if (manualCommandFor(status) case final command?) + CommandBlock(command: command), ], ], ), diff --git a/lib/ui/uninstall/uninstall_confirm_dialog.dart b/lib/ui/uninstall/uninstall_confirm_dialog.dart index cf153c0..56bad9a 100644 --- a/lib/ui/uninstall/uninstall_confirm_dialog.dart +++ b/lib/ui/uninstall/uninstall_confirm_dialog.dart @@ -39,7 +39,7 @@ String? uninstallConsequence(ToolId id) => switch (id) { ToolId.developerMode => 'Other developer tools on this PC may rely on Developer Mode.', ToolId.git => 'Other apps and terminals that use git may be affected.', - ToolId.flutter || ToolId.serverpodCli => null, + ToolId.flutter || ToolId.serverpodCli || ToolId.systemPackages => null, }; Future showUninstallConfirmDialog( diff --git a/test/toolchain/toolchain_setup_screen_test.dart b/test/toolchain/toolchain_setup_screen_test.dart index fbe77ef..f6099ba 100644 --- a/test/toolchain/toolchain_setup_screen_test.dart +++ b/test/toolchain/toolchain_setup_screen_test.dart @@ -230,6 +230,44 @@ void main() { expect(find.byType(ManualUpdateDialog), findsNothing); }, skip: macOSOnlyForNow); // Windows: Phase 3 (flutter.bat update command) + testWidgets('missing Linux system packages block until they are installed', + (tester) async { + final tools = _ScriptedTools(inventory: linuxMissingPackagesInventory); + await pumpScreen(tester, tools); + await settleDialog(tester); + + expect(find.byType(ManualUpdateDialog), findsOneWidget); + expect(find.text('Install system packages'), findsOneWidget); + expect(find.textContaining('Flutter needs curl and xz'), findsOneWidget); + expect(find.text('sudo apt install curl xz-utils'), findsOneWidget); + // Nothing is looked up or installed before them: Flutter runs on them. + expect(tools.preflights, 0); + + await tester.tap(find.text('Check again')); + await settleDialog(tester); + expect(find.textContaining('Still missing'), findsOneWidget); + + tools.inventory = completeInventory; + await tester.tap(find.text('Check again')); + await settleDialog(tester); + await settleDialog(tester); + + expect(find.byType(ManualUpdateDialog), findsNothing); + }); + + testWidgets('an unknown distro gets the package names, not a command', + (tester) async { + final tools = _ScriptedTools(inventory: linuxUnknownDistroInventory); + await pumpScreen(tester, tools); + await settleDialog(tester); + + expect( + find.textContaining("your distribution's package manager: curl, xz."), + findsOneWidget, + ); + expect(find.textContaining('sudo'), findsNothing); + }); + test('the update command switches channel only when it has to', () { const candidate = ToolCandidate( id: ToolId.flutter, diff --git a/widgetbook/fakes/tools.dart b/widgetbook/fakes/tools.dart index 31d272b..3b0a5c6 100644 --- a/widgetbook/fakes/tools.dart +++ b/widgetbook/fakes/tools.dart @@ -228,6 +228,49 @@ final windowsMixedInventory = _inventory( manifest: windowsPreviewManifest, ); +/// The Linux tool set: the system packages instead of Apple's command line +/// tools. +final linuxPreviewManifest = ToolManifest( + tools: { + ToolId.systemPackages: _spec(ToolId.systemPackages, '*'), + ToolId.flutter: _spec(ToolId.flutter, '>=3.47.0'), + ToolId.serverpodCli: _spec(ToolId.serverpodCli, '>=4.0.0 <4.1.0'), + }, +); + +ToolchainInventory _linuxMissing(Map facts) => _inventory( + { + ToolId.systemPackages: ( + [ + ToolCandidate( + id: ToolId.systemPackages, + source: ToolSource.host, + fitness: ToolFitness.incomplete, + reason: 'missing ${facts['missing']}', + facts: facts, + ), + ], + ToolAction.manual, + ), + ToolId.flutter: (const [], ToolAction.install), + ToolId.serverpodCli: (const [], ToolAction.install), + }, + manifest: linuxPreviewManifest, +); + +/// A fresh Ubuntu without curl and xz, which Flutter needs. +final linuxMissingPackagesInventory = _linuxMissing(const { + 'missing': 'curl xz', + 'packages': 'curl xz-utils', + 'installCommand': 'sudo apt install curl xz-utils', +}); + +/// The same on a distro App Studio has no install command for. +final linuxUnknownDistroInventory = _linuxMissing(const { + 'missing': 'curl xz', + 'packages': 'curl xz', +}); + /// What preflight finds for [windowsEmptyInventory]. final windowsPreviewPlan = InstallPlan({ ToolId.developerMode: const PlannedTool(id: ToolId.developerMode), diff --git a/widgetbook/use_cases/first_run.dart b/widgetbook/use_cases/first_run.dart index 82e53ee..a60bd34 100644 --- a/widgetbook/use_cases/first_run.dart +++ b/widgetbook/use_cases/first_run.dart @@ -144,6 +144,28 @@ final firstRunFolder = WidgetbookFolder( ), ], ), + WidgetbookComponent( + name: 'Install system packages (Linux)', + useCases: [ + WidgetbookUseCase( + name: 'Ubuntu', + builder: (_) => _onLanding( + ManualUpdateDialog( + toolchains: + FakeToolsView(inventory: linuxMissingPackagesInventory), + ), + ), + ), + WidgetbookUseCase( + name: 'Unknown distro', + builder: (_) => _onLanding( + ManualUpdateDialog( + toolchains: FakeToolsView(inventory: linuxUnknownDistroInventory), + ), + ), + ), + ], + ), WidgetbookComponent( name: 'Install plan', useCases: [ From 4e9c9458e3747af21109bfc52d8a787b4881e7a9 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Thu, 26 Nov 2026 17:19:17 +0100 Subject: [PATCH 06/32] feat: Installs Flutter and the Serverpod CLI on Linux where their own instructions put them. Flutter comes from releases_linux.json and its .tar.xz is unpacked with tar. dart install puts the CLI in $XDG_STATE_HOME/Dart/install/bin. PATH lines go in the files Flutter's Linux instructions name: ~/.zshenv (or $ZDOTDIR/.zshenv), ~/.bashrc, or ~/.profile for sh and ksh. A Linux terminal starts a non-login shell, which reads neither of the macOS files. --- lib/toolchain/install_plan.dart | 27 ++- lib/toolchain/shell_profile.dart | 44 ++++- lib/toolchain/toolchain_installer.dart | 15 +- lib/toolchain/toolchain_paths.dart | 43 +++-- specs/linux_port.md | 6 +- test/toolchain/linux_toolchain_test.dart | 212 +++++++++++++++++++++++ test/toolchain/shell_profile_test.dart | 54 +++++- 7 files changed, 367 insertions(+), 34 deletions(-) create mode 100644 test/toolchain/linux_toolchain_test.dart diff --git a/lib/toolchain/install_plan.dart b/lib/toolchain/install_plan.dart index b96136a..0c9b8fd 100644 --- a/lib/toolchain/install_plan.dart +++ b/lib/toolchain/install_plan.dart @@ -8,6 +8,7 @@ import 'dart:convert'; import 'package:http/http.dart' as http; +import '../platform/host_platform.dart'; import 'tool_status.dart'; import 'tool_version.dart'; @@ -21,6 +22,18 @@ final kFlutterWindowsReleasesUrl = Uri.parse( 'https://storage.googleapis.com/flutter_infra_release/releases/releases_windows.json', ); +/// The same feed for Linux. Its archives are `.tar.xz`, not `.zip`. +final kFlutterLinuxReleasesUrl = Uri.parse( + 'https://storage.googleapis.com/flutter_infra_release/releases/releases_linux.json', +); + +/// Flutter's release feed for [os]. +Uri flutterReleasesUrlFor(HostOs os) => switch (os) { + HostOs.macos => kFlutterReleasesUrl, + HostOs.windows => kFlutterWindowsReleasesUrl, + HostOs.linux => kFlutterLinuxReleasesUrl, +}; + /// Git for Windows' latest release, from its official GitHub repository. final kGitForWindowsReleaseUrl = Uri.parse( 'https://api.github.com/repos/git-for-windows/git/releases/latest', @@ -250,13 +263,12 @@ Future fetchFlutterRelease( http.Client client, { required VersionRange accepts, required String arch, - bool windows = false, + HostOs os = HostOs.macos, }) async { final String feed; try { - final response = await client - .get(windows ? kFlutterWindowsReleasesUrl : kFlutterReleasesUrl) - .timeout(_timeout); + final response = + await client.get(flutterReleasesUrlFor(os)).timeout(_timeout); if (response.statusCode != 200) throw 'HTTP ${response.statusCode}'; feed = response.body; } catch (_) { @@ -267,7 +279,12 @@ Future fetchFlutterRelease( final release = pickFlutterRelease(feed, accepts: accepts, arch: arch); if (release == null) { throw PlanException( - 'No stable Flutter release for this ${windows ? 'PC' : 'Mac'} matches ' + 'No stable Flutter release for this ' + '${switch (os) { + HostOs.macos => 'Mac', + HostOs.windows => 'PC', + HostOs.linux => 'computer', + }} matches ' '$accepts.', ); } diff --git a/lib/toolchain/shell_profile.dart b/lib/toolchain/shell_profile.dart index d2a88c8..95de1a1 100644 --- a/lib/toolchain/shell_profile.dart +++ b/lib/toolchain/shell_profile.dart @@ -2,7 +2,7 @@ /// /// The lines are exactly the ones the official instructions give — Flutter's /// for its SDK, `dart install`'s for its bin directory — written to the file -/// Flutter's macOS instructions name. Each one is recorded as written, so +/// Flutter's instructions name for this platform. Each one is recorded as written, so /// uninstall removes that exact line and nothing else. library; @@ -20,10 +20,18 @@ const kWindowsUserPathRecord = r'HKCU\Environment\Path'; /// The rc file to add `PATH` lines to, from `$SHELL`. /// -/// zsh gets `~/.zprofile` because that is what Flutter's macOS instructions -/// say. bash gets `~/.bash_profile`, which macOS login shells read. Anything -/// else (fish, nu) has its own syntax, so the lines are shown for the user to -/// add rather than guessed at. +/// macOS: zsh gets `~/.zprofile` because that is what Flutter's macOS +/// instructions say. bash gets `~/.bash_profile`, which macOS login shells +/// read. +/// +/// Linux: the files Flutter's Linux instructions name. A Linux terminal starts +/// a non-login shell, which reads neither of macOS's files — and a new +/// `~/.bash_profile` would stop login bash reading `~/.profile`. zsh gets +/// `~/.zshenv` (or `$ZDOTDIR/.zshenv`), which every zsh reads; bash gets +/// `~/.bashrc`, which every interactive bash reads; sh and ksh `~/.profile`. +/// +/// Anything else (fish, nu) has its own syntax, so the lines are shown for the +/// user to add rather than guessed at. class ShellProfile { const ShellProfile({required this.shell, required this.path}); @@ -37,20 +45,40 @@ class ShellProfile { /// On Windows there is no rc file: `PATH` lives in the registry, under the /// user's own environment, and every program started afterwards reads it /// from there. [kWindowsUserPathRecord] stands in for the file. + /// + /// [environment] supplies `SHELL`, and on Linux `ZDOTDIR`. static ShellProfile resolve({ required String home, String? shellOverride, HostPlatform? host, + Map? environment, }) { - if ((host ?? currentHost).isWindows) { + final resolvedHost = host ?? currentHost; + final env = environment ?? Platform.environment; + if (resolvedHost.isWindows) { return const ShellProfile( shell: 'windows', path: kWindowsUserPathRecord, ); } - final shellPath = - shellOverride ?? Platform.environment['SHELL'] ?? '/bin/zsh'; + final shellPath = shellOverride ?? env['SHELL'] ?? '/bin/zsh'; final shell = p.basename(shellPath); + if (resolvedHost.isLinux) { + final zdotdir = env['ZDOTDIR']; + return switch (shell) { + 'zsh' => ShellProfile( + shell: shell, + path: p.join( + zdotdir != null && p.isAbsolute(zdotdir) ? zdotdir : home, + '.zshenv', + ), + ), + 'bash' => ShellProfile(shell: shell, path: p.join(home, '.bashrc')), + 'sh' || 'ksh' => + ShellProfile(shell: shell, path: p.join(home, '.profile')), + _ => ShellProfile(shell: shell, path: null), + }; + } return switch (shell) { 'zsh' => ShellProfile(shell: shell, path: p.join(home, '.zprofile')), 'bash' => ShellProfile(shell: shell, path: p.join(home, '.bash_profile')), diff --git a/lib/toolchain/toolchain_installer.dart b/lib/toolchain/toolchain_installer.dart index d16aa6d..d02bc00 100644 --- a/lib/toolchain/toolchain_installer.dart +++ b/lib/toolchain/toolchain_installer.dart @@ -574,8 +574,12 @@ class ToolchainInstaller { await _checkDiskSpace(target.parent.path, expected); cancel.throwIfCancelled(); + // `.zip` on macOS and Windows, `.tar.xz` on Linux: kept as the feed names + // it, so the unpack step knows which it has. + final extension = + release.archiveUrl.path.endsWith('.tar.xz') ? '.tar.xz' : '.zip'; final archive = File( - p.join(paths.downloadsDir, 'flutter_${release.version}.zip'), + p.join(paths.downloadsDir, 'flutter_${release.version}$extension'), ); await _download( url: release.archiveUrl, @@ -1085,7 +1089,9 @@ class ToolchainInstaller { /// `unzip`, as Flutter's own instructions use — it keeps the symlinks and /// exec bits the SDK needs. It is a real binary in `/usr/bin`, not one of - /// the Command Line Tools shims. + /// the Command Line Tools shims. Linux's archive is a `.tar.xz`, which + /// Flutter's Linux instructions unpack with `tar`; it needs `xz`, one of + /// the system packages setup checks for first. Future _unzip(File archive, Directory into) async { await into.create(recursive: true); // Windows: the tar.exe Windows ships (bsdtar) reads zip archives. @@ -1095,6 +1101,11 @@ class ToolchainInstaller { _host.path.join(systemRoot, 'System32', 'tar.exe'), ['-xf', archive.path, '-C', into.path], ) + : archive.path.endsWith('.tar.xz') + ? await Process.run( + '/usr/bin/tar', + ['-xJf', archive.path, '-C', into.path], + ) : await Process.run( '/usr/bin/unzip', ['-q', '-o', archive.path, '-d', into.path], diff --git a/lib/toolchain/toolchain_paths.dart b/lib/toolchain/toolchain_paths.dart index 5355d63..a29bddd 100644 --- a/lib/toolchain/toolchain_paths.dart +++ b/lib/toolchain/toolchain_paths.dart @@ -28,6 +28,7 @@ class ToolchainPaths { required this.home, required this.appSupportRoot, this._host, + this._stateHome, }); /// Resolves from the home directory (`HOME`, or `USERPROFILE` on Windows). @@ -75,6 +76,7 @@ class ToolchainPaths { ), }, host: resolvedHost, + stateHome: _xdgDir(environment['XDG_STATE_HOME'], path), ); } @@ -92,6 +94,9 @@ class ToolchainPaths { final HostPlatform? _host; + /// Linux: `XDG_STATE_HOME` when it was set, for [dartInstallBinDir]. + final String? _stateHome; + /// The machine these paths are for. HostPlatform get host => _host ?? currentHost; @@ -103,17 +108,33 @@ class ToolchainPaths { /// indistinguishable from an install done by hand. String get flutterInstallDir => _path.join(home, 'develop', 'flutter'); - /// Where `dart install` puts executables. - String get dartInstallBinDir => host.isWindows - ? _path.join(home, 'AppData', 'Local', 'Dart', 'install', 'bin') - : _path.join( - home, - 'Library', - 'Application Support', - 'Dart', - 'install', - 'bin', - ); + /// Where `dart install` puts executables. On Linux that is under + /// `$XDG_STATE_HOME` (`~/.local/state`), with a capital D, each one a + /// symlink into the package's bundle. + String get dartInstallBinDir => switch (host.os) { + HostOs.windows => _path.join( + home, + 'AppData', + 'Local', + 'Dart', + 'install', + 'bin', + ), + HostOs.linux => _path.join( + _stateHome ?? _path.join(home, '.local', 'state'), + 'Dart', + 'install', + 'bin', + ), + HostOs.macos => _path.join( + home, + 'Library', + 'Application Support', + 'Dart', + 'install', + 'bin', + ), + }; /// The pub cache when `PUB_CACHE` does not say otherwise. String get defaultPubCache => host.isWindows diff --git a/specs/linux_port.md b/specs/linux_port.md index 6e3f0c5..7f5f6ee 100644 --- a/specs/linux_port.md +++ b/specs/linux_port.md @@ -328,9 +328,9 @@ macOS and Windows CI green. - System packages check, Flutter, Serverpod CLI, `PATH` lines, copy (4.3). - Widgetbook use cases for the system packages step. - Done when: on a fresh Ubuntu user account, setup installs Flutter and the - CLI and lands on the start page; on Omarchy it finds the existing asdf - Flutter, reinstalls the too-old `dart install` CLI (4.0.4 on the dev - machine) and nothing else. + CLI and lands on the start page; on Omarchy it finds the system packages, + the existing asdf Flutter (and asks for it to be updated when it is too + old) and the Serverpod CLI already on `PATH`, and installs nothing. ### PR 3: Preview works (`linux/3-preview`) [Tuesday] diff --git a/test/toolchain/linux_toolchain_test.dart b/test/toolchain/linux_toolchain_test.dart new file mode 100644 index 0000000..12f407a --- /dev/null +++ b/test/toolchain/linux_toolchain_test.dart @@ -0,0 +1,212 @@ +import 'dart:io'; + +import 'package:appstudio/platform/host_platform.dart'; +import 'package:appstudio/toolchain/install_plan.dart'; +import 'package:appstudio/toolchain/install_record.dart'; +import 'package:appstudio/toolchain/linux_packages.dart'; +import 'package:appstudio/toolchain/tool_probe.dart'; +import 'package:appstudio/toolchain/tool_status.dart'; +import 'package:appstudio/toolchain/tool_version.dart'; +import 'package:appstudio/toolchain/toolchain_manifest.dart'; +import 'package:appstudio/toolchain/toolchain_paths.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +import '../support/toolchain_support.dart'; + +/// The Linux toolchain: which tools, the system packages App Studio checks for +/// but never installs, and where Flutter and `dart install` put things. +void main() { + const linux = HostPlatform.linux; + + group('the tool set', () { + test('Linux checks the system packages before Flutter', () { + expect(ToolId.requiredOn(linux), [ + ToolId.systemPackages, + ToolId.flutter, + ToolId.serverpodCli, + ]); + }); + + test('the system packages are Linux\'s alone', () async { + final source = await loadTestManifestSource(); + final onLinux = ToolManifest.tryParse(source, host: linux)!; + expect(onLinux.tools.keys, ToolId.requiredOn(linux)); + for (final other in [HostPlatform.macos, HostPlatform.windows]) { + final manifest = ToolManifest.tryParse(source, host: other)!; + expect(manifest[ToolId.systemPackages], isNull, reason: '$other'); + } + }); + }); + + group('the distro\'s install command', () { + const ubuntu = 'NAME="Ubuntu"\nID=ubuntu\nID_LIKE=debian\n'; + const omarchy = 'NAME="Omarchy"\nID=omarchy\nID_LIKE=arch\n'; + const fedora = 'NAME="Fedora Linux"\nID=fedora\n'; + const tumbleweed = + 'NAME="openSUSE Tumbleweed"\nID="opensuse-tumbleweed"\n' + 'ID_LIKE="opensuse suse"\n'; + + test('is found from ID, then ID_LIKE', () { + expect(packageManagerFor(ubuntu), LinuxPackageManager.apt); + expect(packageManagerFor(omarchy), LinuxPackageManager.pacman); + expect(packageManagerFor(fedora), LinuxPackageManager.dnf); + expect(packageManagerFor(tumbleweed), LinuxPackageManager.zypper); + expect(packageManagerFor('ID=nixos\n'), isNull); + }); + + test('names Debian\'s xz package as Debian does', () { + expect( + linuxInstallCommand(['curl', 'xz'], LinuxPackageManager.apt), + 'sudo apt install curl xz-utils', + ); + expect( + linuxInstallCommand(['curl', 'xz'], LinuxPackageManager.pacman), + 'sudo pacman -S --needed curl xz', + ); + }); + + test('is not guessed for a distro App Studio does not know', () { + expect(linuxInstallCommand(['curl'], null), isNull); + }); + + test('os-release quoting is stripped', () { + expect(parseOsRelease(tumbleweed)['ID'], 'opensuse-tumbleweed'); + expect(parseOsRelease("ID='x'\n# c\n\nBAD\n"), {'ID': 'x'}); + }); + }); + + group('probing the system packages', () { + late Directory tmp; + late String bin; + late String osRelease; + + setUp(() async { + tmp = await Directory.systemTemp.createTemp('linux_probe'); + bin = p.join(tmp.path, 'bin'); + await Directory(bin).create(); + osRelease = p.join(tmp.path, 'os-release'); + await File(osRelease).writeAsString('ID=ubuntu\nID_LIKE=debian\n'); + }); + + tearDown(() => tmp.delete(recursive: true)); + + /// An executable named [name] on the probe's PATH: a link to a real one, + /// so it carries the execute bits `whichOnPath` checks for. + Future provide(String name) => + Link(p.join(bin, name)).create(Platform.resolvedExecutable); + + Future probe() async { + final manifest = + ToolManifest.tryParse(await loadTestManifestSource(), host: linux)!; + final inventory = await ToolProbe( + paths: ToolchainPaths.forHome(p.join(tmp.path, 'home'), host: linux), + manifest: manifest, + record: InstallRecord.empty, + osReleasePath: osRelease, + sandbox: ProbeSandbox( + runner: (executable, arguments, {environment}) async => + ProcessResult(0, 1, '', ''), + loginShellPath: () async => null, + environment: {'PATH': bin}, + ), + ).inventory(); + return inventory[ToolId.systemPackages]!; + } + + test('all four on PATH is satisfied', () async { + for (final name in kLinuxRequiredCommands) { + await provide(name); + } + final status = await probe(); + expect(status.isSatisfied, isTrue); + expect(status.action, ToolAction.none); + }); + + test('a missing one is the user\'s to install, with the distro\'s command', + () async { + await provide('git'); + await provide('unzip'); + final status = await probe(); + expect(status.isSatisfied, isFalse); + // Never automatic: it needs sudo, which App Studio never runs. + expect(status.action, ToolAction.manual); + final facts = status.bestRejected!.facts; + expect(facts['missing'], 'curl xz'); + expect(facts['installCommand'], 'sudo apt install curl xz-utils'); + }); + + test('an unknown distro gets the package names, not a guessed command', + () async { + await File(osRelease).writeAsString('ID=nixos\n'); + final status = await probe(); + final facts = status.bestRejected!.facts; + expect(facts['installCommand'], isNull); + expect(facts['packages'], 'git curl unzip xz'); + }); + + test('setup waits on them', () async { + final manifest = + ToolManifest.tryParse(await loadTestManifestSource(), host: linux)!; + final status = await probe(); + final inventory = ToolchainInventory( + manifest: manifest, + tools: {ToolId.systemPackages: status}, + ); + expect(inventory.needsManualUpdate, [status]); + expect(inventory.needsSetup, isTrue); + expect(inventory.installable, isEmpty); + }); + }, skip: Platform.isWindows ? 'needs POSIX executables' : false); + + group('where things go', () { + final paths = ToolchainPaths.forHome('/home/alex', host: linux); + + test('Flutter goes where Flutter\'s Linux instructions extract it', () { + expect(paths.flutterInstallDir, '/home/alex/develop/flutter'); + }); + + test('dart install puts executables in ~/.local/state/Dart', () { + expect( + paths.dartInstallBinDir, + '/home/alex/.local/state/Dart/install/bin', + ); + }); + + test('XDG_STATE_HOME moves them', () { + final moved = ToolchainPaths.forHome( + '/home/alex', + host: linux, + environment: const {'XDG_STATE_HOME': '/state/alex'}, + ); + expect(moved.dartInstallBinDir, '/state/alex/Dart/install/bin'); + }); + + test('Flutter comes from the Linux feed, which serves .tar.xz', () { + expect( + flutterReleasesUrlFor(HostOs.linux).path, + endsWith('/releases_linux.json'), + ); + const feed = ''' +{ + "base_url": "https://storage.googleapis.com/flutter_infra_release/releases", + "releases": [ + { + "channel": "stable", + "version": "3.50.1", + "dart_sdk_arch": "x64", + "archive": "stable/linux/flutter_linux_3.50.1-stable.tar.xz", + "sha256": "AB12" + } + ] +}'''; + final release = pickFlutterRelease( + feed, + accepts: VersionRange.tryParse('>=3.47.0')!, + arch: 'x64', + )!; + expect(release.archiveUrl.path, endsWith('.tar.xz')); + expect(release.sha256, 'ab12'); + }); + }); +} diff --git a/test/toolchain/shell_profile_test.dart b/test/toolchain/shell_profile_test.dart index a4e3eda..c764160 100644 --- a/test/toolchain/shell_profile_test.dart +++ b/test/toolchain/shell_profile_test.dart @@ -4,6 +4,7 @@ library; import 'dart:io'; +import 'package:appstudio/platform/host_platform.dart'; import 'package:appstudio/toolchain/shell_profile.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; @@ -38,26 +39,69 @@ void main() { }); group('ShellProfile', () { + const mac = HostPlatform.macos; + test('zsh uses .zprofile, as Flutter\'s instructions say', () { - final profile = - ShellProfile.resolve(home: '/h', shellOverride: '/bin/zsh'); + final profile = ShellProfile.resolve( + home: '/h', shellOverride: '/bin/zsh', host: mac); expect(profile.path, '/h/.zprofile'); }); test('bash uses .bash_profile', () { expect( - ShellProfile.resolve(home: '/h', shellOverride: '/bin/bash').path, + ShellProfile.resolve(home: '/h', shellOverride: '/bin/bash', host: mac) + .path, '/h/.bash_profile', ); }); test('anything else is shown, not guessed at', () { - final fish = - ShellProfile.resolve(home: '/h', shellOverride: '/opt/homebrew/bin/fish'); + final fish = ShellProfile.resolve( + home: '/h', shellOverride: '/opt/homebrew/bin/fish', host: mac); expect(fish.isSupported, isFalse); }); }); + /// Flutter's Linux instructions (docs.flutter.dev/install/add-to-path). + /// A Linux terminal starts a non-login shell, so macOS's files would not + /// be read there at all. + group('ShellProfile on Linux', () { + const linux = HostPlatform.linux; + + ShellProfile resolve(String shell, [Map env = const {}]) => + ShellProfile.resolve( + home: '/home/a', + shellOverride: shell, + host: linux, + environment: env, + ); + + test('zsh uses .zshenv, which every zsh reads', () { + expect(resolve('/usr/bin/zsh').path, '/home/a/.zshenv'); + }); + + test('zsh with ZDOTDIR uses the .zshenv there', () { + expect( + resolve('/usr/bin/zsh', {'ZDOTDIR': '/home/a/.config/zsh'}).path, + '/home/a/.config/zsh/.zshenv', + ); + }); + + test('bash uses .bashrc, never .bash_profile', () { + // A new ~/.bash_profile would stop login bash reading ~/.profile. + expect(resolve('/bin/bash').path, '/home/a/.bashrc'); + }); + + test('sh and ksh use .profile', () { + expect(resolve('/bin/sh').path, '/home/a/.profile'); + expect(resolve('/bin/ksh').path, '/home/a/.profile'); + }); + + test('fish is shown, not guessed at', () { + expect(resolve('/usr/bin/fish').isSupported, isFalse); + }); + }); + group('withLine / withoutLine', () { const line = r'export PATH="$HOME/develop/flutter/bin:$PATH"'; From f5918c699f7988fd405884f94c8b4f85869541e2 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 11:22:53 +0100 Subject: [PATCH 07/32] fix: Answers the Linux preview's method calls on GTK's main thread. On Linux CEF runs its own message loop thread, so script results and page events arrived there, while Flutter's Linux embedder only takes method channel responses and calls on the main thread. From CEF's thread they were lost: evaluateJavascript never answered and the preview waited on "Waking Flutter" forever. Responses and events now hop to the main thread with g_main_context_invoke_full, as Windows does with PostMessage. The encoded response is also released after use; it leaked before. --- .../webview_cef/linux/webview_cef_plugin.cc | 62 +++++++++++++++---- 1 file changed, 50 insertions(+), 12 deletions(-) diff --git a/packages/webview_cef/linux/webview_cef_plugin.cc b/packages/webview_cef/linux/webview_cef_plugin.cc index 6de3d47..e879e94 100644 --- a/packages/webview_cef/linux/webview_cef_plugin.cc +++ b/packages/webview_cef/linux/webview_cef_plugin.cc @@ -5,6 +5,7 @@ #include #include +#include #include #include #include "webview_cef_keyevent.h" @@ -26,6 +27,29 @@ G_DEFINE_TYPE(WebviewCefPlugin, webview_cef_plugin, g_object_get_type()) std::unordered_map> webviewPlugins; +// Runs [fn] on GTK's main thread: at once when already on it, otherwise as +// soon as the main loop gets to it. +// +// CEF runs its own message loop thread on Linux (multi_threaded_message_loop), +// so its callbacks — a script's result, a page event — arrive there. Flutter's +// Linux engine takes method channel calls and responses on the main thread +// only; from CEF's thread they were lost, so evaluateJavascript never +// answered and App Studio's preview waited on it forever. Windows does the +// same hop with PostMessage. +static void on_main_thread(std::function fn) +{ + g_main_context_invoke_full( + nullptr, G_PRIORITY_DEFAULT, + [](gpointer data) -> gboolean + { + (*static_cast *>(data))(); + return G_SOURCE_REMOVE; + }, + new std::function(std::move(fn)), + [](gpointer data) + { delete static_cast *>(data); }); +} + class WebviewTextureRenderer : public webview_cef::WebviewTexture { public: @@ -216,16 +240,25 @@ static void webview_cef_plugin_handle_method_call( WValue *encodeArgs = encode_flvalue_to_wvalue(fl_method_call_get_args(method_call)); g_object_ref(method_call); self->m_plugin->HandleMethodCall(method, encodeArgs, [=](int ret, WValue *responseArgs){ - if (ret > 0){ - fl_method_call_respond_success(method_call, encode_wavlue_to_flvalue(responseArgs), nullptr); - } - else if (ret < 0){ - fl_method_call_respond_error(method_call, "error", "error", encode_wavlue_to_flvalue(responseArgs), nullptr); - } - else{ - fl_method_call_respond_not_implemented(method_call, nullptr); - } - g_object_unref(method_call); + // Encoded here, on whichever thread answers: responseArgs belongs to the + // caller and is gone once this returns. + FlValue *response = + ret == 0 ? nullptr : encode_wavlue_to_flvalue(responseArgs); + on_main_thread([=]() { + if (ret > 0){ + fl_method_call_respond_success(method_call, response, nullptr); + } + else if (ret < 0){ + fl_method_call_respond_error(method_call, "error", "error", response, nullptr); + } + else{ + fl_method_call_respond_not_implemented(method_call, nullptr); + } + if (response != nullptr){ + fl_value_unref(response); + } + g_object_unref(method_call); + }); }); webview_value_unref(encodeArgs); } @@ -275,10 +308,15 @@ void webview_cef_plugin_register_with_registrar(FlPluginRegistrar *registrar) g_object_ref(plugin), g_object_unref); + // Kept for the plugin's lifetime: events are sent on it long after this + // function's g_autoptr has dropped its own reference. + FlMethodChannel *events = FL_METHOD_CHANNEL(g_object_ref(channel)); plugin->m_plugin->setInvokeMethodFunc([=](std::string method, WValue *arguments) { FlValue *args = encode_wavlue_to_flvalue(arguments); - fl_method_channel_invoke_method(channel, method.c_str(), args, NULL, NULL, NULL); - fl_value_unref(args); + on_main_thread([=]() { + fl_method_channel_invoke_method(events, method.c_str(), args, NULL, NULL, NULL); + fl_value_unref(args); + }); }); plugin->m_plugin->setCreateTextureFunc([=](){ From 8ebaeb96e17c4c502c6e934f03a23ebba86d74be Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 11:24:42 +0100 Subject: [PATCH 08/32] fix: Keeps the Linux preview's frames and renderers safe across CEF's thread. CEF paints on its own thread on Linux while Flutter reads frames on its render thread and the app closes previews on GTK's. The texture freed each frame with delete instead of delete[] and swapped the buffer while the render thread could still read it; it now copies each frame under a GMutex into a buffer only the render thread touches, and hands Flutter a transparent pixel until the first frame arrives. The renderer map in common/webview_plugin.cc is guarded by a Linux-only lock, and a paint holds its own reference to the renderer, so a close can no longer free a texture mid-frame. A renderer's last reference may now go on CEF's thread, so its texture is unregistered and freed on GTK's. The texture used to leak; it is freed now. macOS and Windows keep their behaviour: the lock compiles to nothing there. --- packages/webview_cef/common/webview_plugin.cc | 61 +++++++++-- packages/webview_cef/common/webview_plugin.h | 9 +- .../webview_cef/linux/webview_cef_plugin.cc | 24 ++-- .../webview_cef/linux/webview_cef_texture.h | 103 +++++++++++++++--- 4 files changed, 162 insertions(+), 35 deletions(-) diff --git a/packages/webview_cef/common/webview_plugin.cc b/packages/webview_cef/common/webview_plugin.cc index 7582d02..9da1f4b 100644 --- a/packages/webview_cef/common/webview_plugin.cc +++ b/packages/webview_cef/common/webview_plugin.cc @@ -11,6 +11,17 @@ #include #include +// Holds m_renderersMutex for the rest of the scope on Linux; nothing on macOS +// and Windows, which keep their renderers as they always have. +#ifdef __linux__ +#define LOCK_RENDERERS() \ + std::lock_guard renderers_lock(m_renderersMutex) +#else +#define LOCK_RENDERERS() \ + do { \ + } while (false) +#endif + namespace webview_cef { CefMainArgs mainArgs; CefRefPtr app; @@ -58,6 +69,7 @@ namespace webview_cef { uninitCallback(); m_handler->CloseAllBrowsers(true); m_handler = nullptr; + LOCK_RENDERERS(); if(!m_renderers.empty()){ m_renderers.clear(); } @@ -67,8 +79,18 @@ namespace webview_cef { if (!m_init) { m_handler->onPaintCallback = [=, this](int browserId, const void* buffer, int32_t width, int32_t height) { - if (m_renderers.find(browserId) != m_renderers.end() && m_renderers[browserId] != nullptr) { - m_renderers[browserId]->onFrame(buffer, width, height); + // A reference of its own: a close on another thread may drop + // the map's while this frame is still being copied. + std::shared_ptr renderer; + { + LOCK_RENDERERS(); + auto it = m_renderers.find(browserId); + if (it != m_renderers.end()) { + renderer = it->second; + } + } + if (renderer != nullptr) { + renderer->onFrame(buffer, width, height); } }; @@ -192,10 +214,13 @@ namespace webview_cef { // raw character keys to the OS IME while a web input is focused // (the IME/delta path handles text). Focus moving to a new node // also ends any prior composition for that browser. - auto rit = m_renderers.find(nBrowserId); - if (rit != m_renderers.end() && rit->second) { - rit->second->editableFocused = bEditable; - rit->second->composing = false; + { + LOCK_RENDERERS(); + auto rit = m_renderers.find(nBrowserId); + if (rit != m_renderers.end() && rit->second) { + rit->second->editableFocused = bEditable; + rit->second->composing = false; + } } if (m_invokeFunc) { @@ -322,7 +347,10 @@ namespace webview_cef { // whose release lands in a library that has already torn itself // down. m_handler->CloseAllBrowsers(true); - m_renderers.clear(); + { + LOCK_RENDERERS(); + m_renderers.clear(); + } uninitCallback(); #ifdef OS_MAC // The close is asynchronous and nothing else drives CEF here @@ -346,7 +374,10 @@ namespace webview_cef { std::string url = webview_value_get_string(values); m_handler->createBrowser(url, [=, this](int browserId) { std::shared_ptr renderer = m_createTextureFunc(); - m_renderers[browserId] = renderer; + { + LOCK_RENDERERS(); + m_renderers[browserId] = renderer; + } WValue *response = webview_value_new_list(); webview_value_append(response, webview_value_new_int(browserId)); webview_value_append(response, webview_value_new_int(renderer->textureId)); @@ -357,8 +388,11 @@ namespace webview_cef { else if (name.compare("close") == 0) { int browserId = int(webview_value_get_int(values)); m_handler->closeBrowser(browserId); - if(m_renderers.find(browserId) != m_renderers.end() && m_renderers[browserId] != nullptr) { - m_renderers[browserId].reset(); + { + LOCK_RENDERERS(); + if(m_renderers.find(browserId) != m_renderers.end() && m_renderers[browserId] != nullptr) { + m_renderers[browserId].reset(); + } } result(1, nullptr); } @@ -445,6 +479,7 @@ namespace webview_cef { } else if (name.compare("setClientFocus") == 0) { int browserId = int(webview_value_get_int(webview_value_get_list_value(values, 0))); + LOCK_RENDERERS(); if (m_renderers.find(browserId) != m_renderers.end() && m_renderers[browserId] != nullptr) { bool focused = webview_value_get_bool(webview_value_get_list_value(values, 1)); m_renderers[browserId].get()->isFocused = focused; @@ -628,6 +663,7 @@ namespace webview_cef { if (isCefShutdown) return false; const bool delivered = m_handler->sendKeyEvent(ev); if(ev.type == KEYEVENT_RAWKEYDOWN && ev.windows_key_code == 0x7B && (ev.modifiers & EVENTFLAG_CONTROL_DOWN) != 0){ + LOCK_RENDERERS(); for(auto render : m_renderers){ if(render.second.get()->isFocused){ m_handler->openDevTools(render.first); @@ -653,6 +689,7 @@ namespace webview_cef { } bool WebviewPlugin::getAnyBrowserFocused(){ + LOCK_RENDERERS(); for(auto render : m_renderers){ if(render.second != nullptr && render.second.get()->isFocused){ return true; @@ -662,6 +699,7 @@ namespace webview_cef { } int WebviewPlugin::focusedBrowserId(){ + LOCK_RENDERERS(); for(auto& render : m_renderers){ if(render.second != nullptr && render.second->isFocused){ return render.first; @@ -671,6 +709,7 @@ namespace webview_cef { } bool WebviewPlugin::isEditableFocused(){ + LOCK_RENDERERS(); int id = focusedBrowserId(); if(id < 0){ return false; @@ -680,6 +719,7 @@ namespace webview_cef { } bool WebviewPlugin::isComposing(){ + LOCK_RENDERERS(); int id = focusedBrowserId(); if(id < 0){ return false; @@ -689,6 +729,7 @@ namespace webview_cef { } void WebviewPlugin::setComposingForBrowser(int browserId, bool composing){ + LOCK_RENDERERS(); auto it = m_renderers.find(browserId); if(it != m_renderers.end() && it->second){ it->second->composing = composing; diff --git a/packages/webview_cef/common/webview_plugin.h b/packages/webview_cef/common/webview_plugin.h index 43e2a8d..809ecfc 100644 --- a/packages/webview_cef/common/webview_plugin.h +++ b/packages/webview_cef/common/webview_plugin.h @@ -6,6 +6,7 @@ #include #include +#include namespace webview_cef { class WebviewTexture{ public: @@ -53,7 +54,6 @@ namespace webview_cef { void imeSetCompositionNative(const std::wstring& text, int cursor); void imeCommitTextNative(const std::wstring& text); void imeFinishCompositionNative(); - private : // Resolve the browserId whose renderer currently has focus, or -1. int focusedBrowserId(); @@ -65,6 +65,13 @@ namespace webview_cef { CefRefPtr m_handler; CefRefPtr m_app; std::unordered_map> m_renderers; +#ifdef __linux__ + // Guards m_renderers. On Linux CEF runs on its own thread, which + // creates and paints renderers while GTK's thread closes them and + // reads their focus on every key press. Recursive, because some + // readers call others (isEditableFocused → focusedBrowserId). + std::recursive_mutex m_renderersMutex; +#endif bool m_init = false; }; diff --git a/packages/webview_cef/linux/webview_cef_plugin.cc b/packages/webview_cef/linux/webview_cef_plugin.cc index e879e94..1120fcb 100644 --- a/packages/webview_cef/linux/webview_cef_plugin.cc +++ b/packages/webview_cef/linux/webview_cef_plugin.cc @@ -61,20 +61,30 @@ class WebviewTextureRenderer : public webview_cef::WebviewTexture textureId = (int64_t)texture; } + // Runs wherever the last reference goes: usually GTK's thread, but CEF's + // when a close lands while a frame is being copied (the paint holds its + // own reference). Flutter unregisters textures on GTK's thread, and the + // texture's GL cleanup needs its context there, so the work is handed over. virtual ~WebviewTextureRenderer() { - fl_texture_registrar_unregister_texture(register_, FL_TEXTURE(texture)); + FlTextureRegistrar *registrar = register_; + WebviewCefTexture *texture_to_free = texture; + on_main_thread([registrar, texture_to_free]() { + fl_texture_registrar_unregister_texture(registrar, + FL_TEXTURE(texture_to_free)); + // The registrar holds its own reference while registered; this drops + // ours, so the texture and its buffers are freed once Flutter lets go. + g_object_unref(texture_to_free); + }); register_ = nullptr; } + // Called on CEF's thread. The texture copies the frame under its lock; see + // webview_cef_texture.h for why it is double-buffered. virtual void onFrame(const void *buffer, int32_t width, int32_t height) override { - texture->width = width; - texture->height = height; - const auto size = width * height * 4; - delete texture->buffer; - texture->buffer = new uint8_t[size]; - webview_cef::SwapBufferFromBgraToRgba((void *)texture->buffer, buffer, width, height); + webview_cef_texture_set_frame(texture, buffer, width, height, + webview_cef::SwapBufferFromBgraToRgba); fl_texture_registrar_mark_texture_frame_available(register_, FL_TEXTURE(texture)); } FlTextureRegistrar *register_; diff --git a/packages/webview_cef/linux/webview_cef_texture.h b/packages/webview_cef/linux/webview_cef_texture.h index 0b96c5c..432b917 100644 --- a/packages/webview_cef/linux/webview_cef_texture.h +++ b/packages/webview_cef/linux/webview_cef_texture.h @@ -4,11 +4,28 @@ #include #include +#include + +// A pixel buffer texture fed from two threads. +// +// On Linux CEF runs its own message loop thread (multi_threaded_message_loop), +// so frames arrive on CEF's UI thread while Flutter reads them on its render +// thread. CEF writes into `buffer` under `mutex`; copy_pixels copies that, +// under the same lock, into `render_buffer`, which only the render thread +// touches and which stays valid after copy_pixels returns. The buffers are +// reallocated only when the size changes, and freed when the texture goes. +// +// GObject zero-fills instances and runs no C++ constructors, so the members +// are plain C: a GMutex, raw pointers, sizes. struct WebviewCefTexture{ FlPixelBufferTexture parent_instance; - uint8_t *buffer = nullptr; // your pixel buffer. - uint32_t width = 0; - uint32_t height = 0; + GMutex mutex; + uint8_t *buffer; // Written by CEF's thread, under mutex. + size_t buffer_size; + uint8_t *render_buffer; // Handed to Flutter; render thread only. + size_t render_buffer_size; + uint32_t width; + uint32_t height; }; struct WebviewCefTextureClass{ @@ -22,37 +39,89 @@ G_DEFINE_TYPE(WebviewCefTexture, #define WEBVIEW_CEF_TEXTURE(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), webview_cef_texture_get_type(), WebviewCefTexture)) +// Grows or shrinks *buffer to exactly `size` bytes, keeping it when it already +// fits. +static void webview_cef_texture_resize(uint8_t **buffer, size_t *current, + size_t size) { + if (*buffer != nullptr && *current == size) { + return; + } + delete[] *buffer; + *buffer = size == 0 ? nullptr : new uint8_t[size]; + *current = size; +} + static gboolean webview_cef_texture_copy_pixels(FlPixelBufferTexture *texture, const uint8_t **out_buffer, uint32_t *width, uint32_t *height, GError **error) { - // This method is called on Render Thread. Be careful with your - // cross-thread operation. - - // @width and @height are initially stored the canvas size in Flutter. - - // You must prepare your pixel buffer in RGBA format. - // So you may do some format conversion first if your original pixel - // buffer is not in RGBA format. - WebviewCefTexture *_texture = WEBVIEW_CEF_TEXTURE(texture); - if(_texture == nullptr){ + // Called on Flutter's render thread. + WebviewCefTexture *self = WEBVIEW_CEF_TEXTURE(texture); + g_mutex_lock(&self->mutex); + if (self->buffer == nullptr) { + g_mutex_unlock(&self->mutex); + // No frame from CEF yet. One transparent pixel rather than an error, + // which Flutter logs as a warning on every frame until CEF paints. + static const uint8_t kTransparentPixel[4] = {0, 0, 0, 0}; + *out_buffer = kTransparentPixel; + *width = 1; + *height = 1; return TRUE; } - *out_buffer = _texture->buffer; - *width = _texture->width; - *height = _texture->height; + webview_cef_texture_resize(&self->render_buffer, &self->render_buffer_size, + self->buffer_size); + memcpy(self->render_buffer, self->buffer, self->buffer_size); + *width = self->width; + *height = self->height; + g_mutex_unlock(&self->mutex); + *out_buffer = self->render_buffer; return TRUE; } + +// A frame from CEF, in BGRA; stored as the RGBA Flutter expects. Called on +// CEF's thread. +static void webview_cef_texture_set_frame(WebviewCefTexture *self, + const void *bgra, int32_t width, + int32_t height, + void (*bgra_to_rgba)(void *, + const void *, + int, int)) { + if (width <= 0 || height <= 0) { + return; + } + const size_t size = static_cast(width) * height * 4; + g_mutex_lock(&self->mutex); + webview_cef_texture_resize(&self->buffer, &self->buffer_size, size); + bgra_to_rgba(self->buffer, bgra, width, height); + self->width = static_cast(width); + self->height = static_cast(height); + g_mutex_unlock(&self->mutex); +} + static WebviewCefTexture* webview_cef_texture_new(){ return WEBVIEW_CEF_TEXTURE(g_object_new(webview_cef_texture_get_type(), nullptr)); } +static void webview_cef_texture_finalize(GObject *object) { + WebviewCefTexture *self = WEBVIEW_CEF_TEXTURE(object); + delete[] self->buffer; + delete[] self->render_buffer; + self->buffer = nullptr; + self->render_buffer = nullptr; + g_mutex_clear(&self->mutex); + G_OBJECT_CLASS(webview_cef_texture_parent_class)->finalize(object); +} + static void webview_cef_texture_class_init(WebviewCefTextureClass *klass) { FL_PIXEL_BUFFER_TEXTURE_CLASS(klass)->copy_pixels = webview_cef_texture_copy_pixels; + G_OBJECT_CLASS(klass)->finalize = webview_cef_texture_finalize; +} + +static void webview_cef_texture_init(WebviewCefTexture *self) { + g_mutex_init(&self->mutex); } -static void webview_cef_texture_init(WebviewCefTexture *self) {} #endif // WEBVIEW_CEF_TEXTURE_H_ From c835c75ea462c27abe059d0ed718e171c5b7cc21 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 11:28:05 +0100 Subject: [PATCH 09/32] build: Stops the Linux plugin from patching the app's runner at configure time. target_modifier/modify_target.sh patched linux/main.cc and linux/my_application.cc, which current Flutter no longer generates: they live in linux/runner/. It patched nothing, printed a warning on every configure, and left every CEF helper booting a full copy of the app. App Studio wires initCEFProcesses and the key handlers into its runner by hand since PR 1, so the plugin's CMake no longer runs the script. --- packages/webview_cef/linux/CMakeLists.txt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/webview_cef/linux/CMakeLists.txt b/packages/webview_cef/linux/CMakeLists.txt index b26fba3..ba854e2 100644 --- a/packages/webview_cef/linux/CMakeLists.txt +++ b/packages/webview_cef/linux/CMakeLists.txt @@ -12,12 +12,11 @@ project(${PROJECT_NAME} LANGUAGES CXX C) # CEF 149 public headers require C++20. set(CMAKE_CXX_STANDARD 20) -# Auto setup Linux target -execute_process( - COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/target_modifier/modify_target.sh" - OUTPUT_VARIABLE patch_output -) -message(WARNING "${patch_output}") +# No auto setup of the app's runner. target_modifier/modify_target.sh patches +# linux/main.cc and linux/my_application.cc, which current Flutter no longer +# generates (they live in linux/runner/), so it patched nothing and every CEF +# helper booted a full copy of the app. The app wires initCEFProcesses and +# processKeyEventForCEF into its runner by hand instead. # Setup CEF include(${CMAKE_CURRENT_SOURCE_DIR}/../third/download.cmake) From 798098c013289e94a0038e10827b147da353f93b Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 11:28:38 +0100 Subject: [PATCH 10/32] fix: Gives CEF its own cache folder inside App Studio's data folder on Linux. Without a root_cache_path CEF used ~/.config/cef_user_data, one folder and one singleton lock for every CEF app on the machine that also left it unset, so a killed run could block the next start. This is the bug the macOS and Windows ports already fixed. The Linux plugin now exports setCEFRootCachePath, and the runner sets it to $XDG_DATA_HOME/dev.serverpod.appstudio/CEF before CEF starts, inside the data folder App Studio already uses (L5), so uninstall removes it with the rest. A path that is not valid UTF-8 logs a warning and leaves CEF's default. --- linux/runner/main.cc | 8 ++++ .../include/webview_cef/webview_cef_plugin.h | 6 +++ .../webview_cef/linux/webview_cef_plugin.cc | 37 +++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/linux/runner/main.cc b/linux/runner/main.cc index e081001..a0020b7 100644 --- a/linux/runner/main.cc +++ b/linux/runner/main.cc @@ -13,6 +13,14 @@ int main(int argc, char** argv) { return exit_code; } + // CEF's own folder, inside App Studio's ($XDG_DATA_HOME/ + // dev.serverpod.appstudio, ToolchainPaths.appSupportRoot), so a crashed + // run's singleton lock cannot block another CEF app, or the next start. + // GLib reads XDG_DATA_HOME the way the Dart side does. + g_autofree gchar* cef_root = g_build_filename( + g_get_user_data_dir(), APPLICATION_ID, "CEF", nullptr); + setCEFRootCachePath(cef_root); + g_autoptr(MyApplication) app = my_application_new(); return g_application_run(G_APPLICATION(app), argc, argv); } diff --git a/packages/webview_cef/linux/include/webview_cef/webview_cef_plugin.h b/packages/webview_cef/linux/include/webview_cef/webview_cef_plugin.h index 362cd20..d6be4ed 100644 --- a/packages/webview_cef/linux/include/webview_cef/webview_cef_plugin.h +++ b/packages/webview_cef/linux/include/webview_cef/webview_cef_plugin.h @@ -25,6 +25,12 @@ G_END_DECLS FLUTTER_PLUGIN_EXPORT int initCEFProcesses(int argc, char** argv); +// CEF's root_cache_path, in UTF-8. Call before the first webview starts CEF. +// Unset, CEF uses ~/.config/cef_user_data: one directory, and one singleton +// lock, for every CEF app on the machine that also left it unset — a killed +// run then blocks the next start. +FLUTTER_PLUGIN_EXPORT void setCEFRootCachePath(const char* path); + FLUTTER_PLUGIN_EXPORT gboolean processKeyEventForCEF(GtkWidget* widget, GdkEventKey* event, gpointer data); #endif // FLUTTER_PLUGIN_WEBVIEW_CEF_PLUGIN_H_ diff --git a/packages/webview_cef/linux/webview_cef_plugin.cc b/packages/webview_cef/linux/webview_cef_plugin.cc index 1120fcb..8d3865e 100644 --- a/packages/webview_cef/linux/webview_cef_plugin.cc +++ b/packages/webview_cef/linux/webview_cef_plugin.cc @@ -343,6 +343,43 @@ FLUTTER_PLUGIN_EXPORT int initCEFProcesses(int argc, char **argv) return webview_cef::initCEFProcesses(main_args); } +// [text] as a std::wstring, or false when it is not valid UTF-8. wchar_t is +// UTF-32 on Linux, which is what g_utf8_to_ucs4 produces. +static bool utf8_to_wstring(const char *text, std::wstring &out) +{ + glong length = 0; + gunichar *wide = g_utf8_to_ucs4(text, -1, nullptr, &length, nullptr); + if (wide == nullptr) + { + return false; + } + out.clear(); + out.reserve(length); + for (glong i = 0; i < length; i++) + { + out.push_back(static_cast(wide[i])); + } + g_free(wide); + return true; +} + +FLUTTER_PLUGIN_EXPORT void setCEFRootCachePath(const char *path) +{ + if (path == nullptr) + { + webview_cef::setRootCachePath(std::wstring()); + return; + } + std::wstring root; + if (!utf8_to_wstring(path, root)) + { + g_warning("CEF cache folder is not valid UTF-8, using CEF's default: %s", + path); + return; + } + webview_cef::setRootCachePath(root); +} + FLUTTER_PLUGIN_EXPORT gboolean processKeyEventForCEF(GtkWidget *widget, GdkEventKey *event, gpointer data) { int64_t _id = int64_t(widget); From ab31c4d60d80da6680e0f53473fdf1c341321df6 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 11:31:40 +0100 Subject: [PATCH 11/32] fix: Lets App Studio's shortcuts through while the Linux preview has focus. With a page focused the plugin sent every key to CEF and reported it handled, so Flutter never saw Ctrl+R, Ctrl+L or any other app shortcut. Ctrl on a character key now goes to App Studio, except Ctrl+A/C/V/X/Y/Z, which stay the page's editing keys, as do Ctrl+Backspace, Ctrl+Enter and the other non-character keys. Keys are classified by their Windows key code, as Chromium does, so this holds on layouts without Latin letters. Modifiers go to both, a shortcut's release follows its press, and keys Flutter puts back unhandled are recognised and not sent to the page a second time. A modifier's own press now carries its own flag: GDK reports the state from before the event, and Flutter web asserted on a Ctrl press without Ctrl down. The xclip paste workaround is gone: it failed silently and xclip is not installed by default. --- packages/webview_cef/linux/CMakeLists.txt | 5 - .../webview_cef/linux/webview_cef_plugin.cc | 164 ++++++++++++++++-- 2 files changed, 152 insertions(+), 17 deletions(-) diff --git a/packages/webview_cef/linux/CMakeLists.txt b/packages/webview_cef/linux/CMakeLists.txt index ba854e2..cbe011a 100644 --- a/packages/webview_cef/linux/CMakeLists.txt +++ b/packages/webview_cef/linux/CMakeLists.txt @@ -82,11 +82,6 @@ add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper) # Find required libraries and update compiler/linker variables. FIND_LINUX_LIBRARIES("gmodule-2.0 gtk+-3.0 gthread-2.0 gtk+-unix-print-3.0 xi") -find_program(XCLIP_EXECUTABLE xclip) -if(NOT XCLIP_EXECUTABLE) - message(AUTHOR_WARNING "xclip executable not found. Users need it to paste text into CEF Area.") -endif() - # Executable target. # add_executable(${CEF_TARGET} ${CEFCLIENT_SRCS}) SET_EXECUTABLE_TARGET_PROPERTIES(${CEF_TARGET}) diff --git a/packages/webview_cef/linux/webview_cef_plugin.cc b/packages/webview_cef/linux/webview_cef_plugin.cc index 8d3865e..2900990 100644 --- a/packages/webview_cef/linux/webview_cef_plugin.cc +++ b/packages/webview_cef/linux/webview_cef_plugin.cc @@ -5,8 +5,10 @@ #include #include +#include #include #include +#include #include #include "webview_cef_keyevent.h" #include "webview_cef_texture.h" @@ -380,18 +382,163 @@ FLUTTER_PLUGIN_EXPORT void setCEFRootCachePath(const char *path) webview_cef::setRootCachePath(root); } +// Hardware keycodes whose press went to the app rather than the page, so +// their release goes there too: a key Flutter saw go down must also be seen +// to come up, or it stays pressed in Flutter's HardwareKeyboard. +static std::unordered_set appOwnedKeys; + +// Keys are classified by their Windows key code, as Chromium does, not by +// the layout's keyval. It follows the physical key on layouts without Latin +// letters, where Ctrl+C arrives as Ctrl+Cyrillic_es, and it leaves out the +// keys GDK still gives a character (Backspace, Tab, Enter, Escape, Delete). + +// A letter, digit or punctuation key. +static bool isCharacterKey(KeyboardCode code) +{ + return (code >= VKEY_0 && code <= VKEY_9) || + (code >= VKEY_A && code <= VKEY_Z) || + (code >= VKEY_OEM_1 && code <= VKEY_OEM_3) || + (code >= VKEY_OEM_4 && code <= VKEY_OEM_8) || + code == VKEY_OEM_102; +} + +// Whether [event] is one of the app's own shortcuts: Ctrl on a character key. +// Ctrl+A/C/V/X/Y/Z stay with the page — they are its editing keys — and so +// does Ctrl on any other key (arrows, Backspace, Enter, Tab), which a page +// uses for word movement and the like. AltGr characters are not Ctrl. +static bool isAppShortcut(GdkEventKey *event, KeyboardCode code) +{ + if ((event->state & GDK_CONTROL_MASK) == 0 || event->is_modifier || + !isCharacterKey(code)) + { + return false; + } + switch (code) + { + case VKEY_A: + case VKEY_C: + case VKEY_V: + case VKEY_X: + case VKEY_Y: + case VKEY_Z: + return false; + default: + return true; + } +} + +// The modifier flag a modifier key sets. GDK reports the state from before +// the event, so Ctrl's own press arrived without Ctrl down and its release +// with it, and the page's keyboard handling (Flutter web asserts on it) saw a +// modifier go down that its flags said was not. +static int modifierFlagOf(guint keyval) +{ + switch (keyval) + { + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + return EVENTFLAG_CONTROL_DOWN; + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + return EVENTFLAG_SHIFT_DOWN; + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Meta_L: + case GDK_KEY_Meta_R: + return EVENTFLAG_ALT_DOWN; + default: + return 0; + } +} + +// Events handed on to Flutter, so they are recognised when they come back. +// +// A key the framework does not handle, Flutter puts back into GTK +// (gdk_event_put in fl_view.cc), and it reaches this handler a second time. +// It must not be forwarded to the page again: modifiers would arrive twice, +// and a shortcut key's release, already taken out of appOwnedKeys, would +// reach the page without its press. A handled event never comes back, so +// the list is bounded and the oldest entry goes. +struct PassedKey +{ + guint32 time; + guint16 keycode; + GdkEventType type; +}; +static std::deque passedToFlutter; +static constexpr size_t kMaxPassedToFlutter = 32; + +static gboolean passToFlutter(GdkEventKey *event) +{ + if (passedToFlutter.size() == kMaxPassedToFlutter) + { + passedToFlutter.pop_front(); + } + passedToFlutter.push_back({event->time, event->hardware_keycode, event->type}); + return FALSE; +} + +// Whether [event] is one Flutter has put back; it is forgotten either way. +static bool isComingBack(GdkEventKey *event) +{ + for (auto it = passedToFlutter.begin(); it != passedToFlutter.end(); ++it) + { + if (it->time == event->time && it->keycode == event->hardware_keycode && + it->type == event->type) + { + passedToFlutter.erase(it); + return true; + } + } + return false; +} + +// Hands a key to the focused page, or leaves it to Flutter. +// +// Returns TRUE when the page alone takes the key. With no page focused, +// everything is Flutter's. With one focused, the app keeps its shortcuts +// (isAppShortcut) — they used to be swallowed, so Ctrl+R did nothing while +// the preview had focus — and modifier keys go to both, so Flutter knows +// Ctrl is down when the shortcut's key arrives. FLUTTER_PLUGIN_EXPORT gboolean processKeyEventForCEF(GtkWidget *widget, GdkEventKey *event, gpointer data) { + if (isComingBack(event)) + { + return FALSE; + } + if (event->type == GDK_KEY_PRESS) + { + // A press starts the key over: its last release may have gone to + // another window (a dialog this key opened) and never reached us. + appOwnedKeys.erase(event->hardware_keycode); + } + else if (appOwnedKeys.erase(event->hardware_keycode) > 0) + { + return passToFlutter(event); + } int64_t _id = int64_t(widget); if (webviewPlugins.find(_id) != webviewPlugins.end() && webviewPlugins[_id]->getAnyBrowserFocused()) { - CefKeyEvent key_event; KeyboardCode windows_key_code = GdkEventToWindowsKeyCode(event); + if (event->type == GDK_KEY_PRESS && isAppShortcut(event, windows_key_code)) + { + appOwnedKeys.insert(event->hardware_keycode); + return passToFlutter(event); + } + CefKeyEvent key_event; key_event.windows_key_code = GetWindowsKeyCodeWithoutLocation(windows_key_code); key_event.native_key_code = event->hardware_keycode; key_event.modifiers = GetCefStateModifiers(event->state); + if (event->type == GDK_KEY_PRESS) + { + key_event.modifiers |= modifierFlagOf(event->keyval); + } + else + { + key_event.modifiers &= ~modifierFlagOf(event->keyval); + } if (event->keyval >= GDK_KP_Space && event->keyval <= GDK_KP_9) { key_event.modifiers |= EVENTFLAG_IS_KEY_PAD; @@ -407,15 +554,6 @@ FLUTTER_PLUGIN_EXPORT gboolean processKeyEventForCEF(GtkWidget *widget, GdkEvent // is apparently just how webkit handles it and what it expects. key_event.unmodified_character = '\r'; } - else if((windows_key_code == KeyboardCode::VKEY_V) && (key_event.modifiers & EVENTFLAG_CONTROL_DOWN) && (event->type == GDK_KEY_PRESS)){ - //try to fix copy request freeze process problem(flutter engine will send a copy request when ctrl+v pressed) - int res = 0; - if(system("xclip -o -sel clipboard | xclip -i -sel clipboard &>/dev/null") == 0){ - res = system("xclip -o -sel clipboard | xclip -i &>/dev/null"); - } - // Suppress unused variable warning - (void)res; - } else { // FIXME: fix for non BMP chars key_event.unmodified_character = @@ -444,8 +582,10 @@ FLUTTER_PLUGIN_EXPORT gboolean processKeyEventForCEF(GtkWidget *widget, GdkEvent } webviewPlugins[_id]->sendKeyEvent(key_event); - return TRUE; + // Modifiers go to Flutter too: its shortcuts read Ctrl and Shift from + // its own keyboard state. + return event->is_modifier ? passToFlutter(event) : TRUE; } // processKeyEventForFlutter need return FALSE - return FALSE; + return passToFlutter(event); } From acf9b60a58bd684e65bcee9925a8c833438a9f2b Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 11:32:21 +0100 Subject: [PATCH 12/32] fix: Copies and pastes between the Linux preview and other apps through GTK. On Wayland a client may only set or read the clipboard while one of its surfaces has keyboard focus. CEF talks to the compositor over its own connection and draws off-screen, so it never has focus: copies stayed inside the page ("No serial found for selection" in CEF's log), and text copied elsewhere never arrived. GTK's window has the focus, so the plugin moves the text across. On Ctrl+C or Ctrl+X it puts the page's selection, which CEF reports through OnTextSelectionChanged, on the clipboard; on Ctrl+V or Shift+Insert it reads the clipboard and inserts the text the way an input method commits it. The page sees typing rather than a paste event, which is what a text field needs; a page that reads paste events, such as one pasting images, gets nothing. Running CEF on X11 through XWayland was tried first: Hyprland does not pass an unfocused X client's clipboard across. --- .../webview_cef/common/webview_handler.cc | 22 +++++ packages/webview_cef/common/webview_handler.h | 19 +++++ packages/webview_cef/common/webview_plugin.cc | 8 ++ packages/webview_cef/common/webview_plugin.h | 6 ++ .../webview_cef/linux/webview_cef_plugin.cc | 82 +++++++++++++++++++ 5 files changed, 137 insertions(+) diff --git a/packages/webview_cef/common/webview_handler.cc b/packages/webview_cef/common/webview_handler.cc index c54bb2c..665d291 100644 --- a/packages/webview_cef/common/webview_handler.cc +++ b/packages/webview_cef/common/webview_handler.cc @@ -171,6 +171,10 @@ bool WebviewHandler::DoClose(CefRefPtr browser) { void WebviewHandler::OnBeforeClose(CefRefPtr browser) { CEF_REQUIRE_UI_THREAD(); +#ifdef __linux__ + std::lock_guard lock(selected_text_mutex_); + selected_text_.erase(browser->GetIdentifier()); +#endif } bool WebviewHandler::OnBeforePopup(CefRefPtr browser, @@ -425,6 +429,24 @@ bool WebviewHandler::StartDragging(CefRefPtr browser, return true; } +#ifdef __linux__ +void WebviewHandler::OnTextSelectionChanged(CefRefPtr browser, + const CefString& selected_text, + const CefRange& selected_range) +{ + CEF_REQUIRE_UI_THREAD(); + std::lock_guard lock(selected_text_mutex_); + selected_text_[browser->GetIdentifier()] = selected_text.ToString(); +} + +std::string WebviewHandler::selectedText(int browserId) +{ + std::lock_guard lock(selected_text_mutex_); + auto it = selected_text_.find(browserId); + return it == selected_text_.end() ? std::string() : it->second; +} +#endif + void WebviewHandler::OnImeCompositionRangeChanged(CefRefPtr browser, const CefRange &selection_range, const CefRenderHandler::RectList &character_bounds) { CEF_REQUIRE_UI_THREAD(); diff --git a/packages/webview_cef/common/webview_handler.h b/packages/webview_cef/common/webview_handler.h index 6fb4512..fe217a5 100644 --- a/packages/webview_cef/common/webview_handler.h +++ b/packages/webview_cef/common/webview_handler.h @@ -9,6 +9,8 @@ #include #include +#include +#include #include #include "webview_cookieVisitor.h" @@ -148,6 +150,17 @@ public CefRenderHandler{ int x, int y) override; virtual void OnImeCompositionRangeChanged(CefRefPtr browser,const CefRange& selection_range,const CefRenderHandler::RectList& character_bounds) override; +#ifdef __linux__ + virtual void OnTextSelectionChanged(CefRefPtr browser, + const CefString& selected_text, + const CefRange& selected_range) override; + // The browser's selected text (UTF-8), as Chromium last reported it; + // empty when nothing is selected. Safe to call from any thread. On + // Wayland the off-screen browser can neither set nor read the system + // clipboard (it never has keyboard focus), so the Linux plugin copies + // this onto the clipboard through GTK. + std::string selectedText(int browserId); +#endif // Request that all existing browser windows close. void CloseAllBrowsers(bool force_close); @@ -212,6 +225,12 @@ public CefRenderHandler{ std::unordered_map browser_map_; std::unordered_map)>> js_callbacks_; +#ifdef __linux__ + // Each browser's selected text, by browser id. Written on CEF's UI thread, + // read on GTK's, so it is guarded. + std::mutex selected_text_mutex_; + std::unordered_map selected_text_; +#endif #ifdef WEBVIEW_CEF_GPU_TEXTURE // GPU diagnostic state: whether any accelerated-paint frame has arrived, and diff --git a/packages/webview_cef/common/webview_plugin.cc b/packages/webview_cef/common/webview_plugin.cc index 9da1f4b..df9ed5e 100644 --- a/packages/webview_cef/common/webview_plugin.cc +++ b/packages/webview_cef/common/webview_plugin.cc @@ -708,6 +708,14 @@ namespace webview_cef { return -1; } +#ifdef __linux__ + std::string WebviewPlugin::focusedSelectedText(){ + if (isCefShutdown) return std::string(); + int id = focusedBrowserId(); + return id < 0 ? std::string() : m_handler->selectedText(id); + } +#endif + bool WebviewPlugin::isEditableFocused(){ LOCK_RENDERERS(); int id = focusedBrowserId(); diff --git a/packages/webview_cef/common/webview_plugin.h b/packages/webview_cef/common/webview_plugin.h index 809ecfc..37f4d94 100644 --- a/packages/webview_cef/common/webview_plugin.h +++ b/packages/webview_cef/common/webview_plugin.h @@ -54,6 +54,12 @@ namespace webview_cef { void imeSetCompositionNative(const std::wstring& text, int cursor); void imeCommitTextNative(const std::wstring& text); void imeFinishCompositionNative(); +#ifdef __linux__ + // The focused browser's selected text (UTF-8), for the Linux plugin to + // put on the clipboard itself; see WebviewHandler::selectedText. + std::string focusedSelectedText(); +#endif + private : // Resolve the browserId whose renderer currently has focus, or -1. int focusedBrowserId(); diff --git a/packages/webview_cef/linux/webview_cef_plugin.cc b/packages/webview_cef/linux/webview_cef_plugin.cc index 2900990..8a3d7ac 100644 --- a/packages/webview_cef/linux/webview_cef_plugin.cc +++ b/packages/webview_cef/linux/webview_cef_plugin.cc @@ -387,6 +387,10 @@ FLUTTER_PLUGIN_EXPORT void setCEFRootCachePath(const char *path) // to come up, or it stays pressed in Flutter's HardwareKeyboard. static std::unordered_set appOwnedKeys; +// Keys whose press the plugin handled itself (paste), so their release is +// swallowed too: the page must not see a key come up that never went down. +static std::unordered_set pluginOwnedKeys; + // Keys are classified by their Windows key code, as Chromium does, not by // the layout's keyval. It follows the physical key on layouts without Latin // letters, where Ctrl+C arrives as Ctrl+Cyrillic_es, and it leaves out the @@ -427,6 +431,68 @@ static bool isAppShortcut(GdkEventKey *event, KeyboardCode code) } } +// The clipboard, through GTK. +// +// On Wayland a client may only set or read the clipboard while one of its +// surfaces has keyboard focus. CEF talks to the compositor over its own +// connection and draws off-screen, so it never has focus: its copies stayed +// inside Chromium ("No serial found for selection") and it never saw what +// other programs copied. GTK's window is the one with focus, so the plugin +// moves the text across itself. Running CEF on X11 through XWayland instead +// was tried: Hyprland does not bridge an unfocused X client's clipboard. +static bool isCopy(GdkEventKey *event, KeyboardCode code) +{ + return (event->state & GDK_CONTROL_MASK) != 0 && + (code == VKEY_C || code == VKEY_X || code == VKEY_INSERT); +} + +static bool isPaste(GdkEventKey *event, KeyboardCode code) +{ + if ((event->state & GDK_CONTROL_MASK) != 0) + { + return code == VKEY_V; + } + return (event->state & GDK_SHIFT_MASK) != 0 && code == VKEY_INSERT; +} + +// Puts the page's selection on the clipboard. The key itself still goes to +// the page, which copies or cuts as usual; Chromium reports the selection as +// it changes, so it is current when the key arrives. +static void copySelectionToClipboard(webview_cef::WebviewPlugin *plugin) +{ + const std::string text = plugin->focusedSelectedText(); + if (!text.empty()) + { + gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), + text.c_str(), static_cast(text.size())); + } +} + +// Inserts the clipboard's text into the focused page, the way an input +// method commits text. The page sees typing rather than a paste event, which +// is what a text field needs; a page that reads paste events (an image, rich +// text) gets nothing. +static void pasteClipboardIntoPage(int64_t id) +{ + gtk_clipboard_request_text( + gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), + [](GtkClipboard *, const gchar *text, gpointer data) + { + if (text == nullptr || text[0] == '\0') + { + return; + } + // Looked up again: the clipboard answers later, on the main loop. + auto it = webviewPlugins.find(reinterpret_cast(data)); + std::wstring wide; + if (it != webviewPlugins.end() && utf8_to_wstring(text, wide)) + { + it->second->imeCommitTextNative(wide); + } + }, + reinterpret_cast(id)); +} + // The modifier flag a modifier key sets. GDK reports the state from before // the event, so Ctrl's own press arrived without Ctrl down and its release // with it, and the page's keyboard handling (Flutter web asserts on it) saw a @@ -511,11 +577,16 @@ FLUTTER_PLUGIN_EXPORT gboolean processKeyEventForCEF(GtkWidget *widget, GdkEvent // A press starts the key over: its last release may have gone to // another window (a dialog this key opened) and never reached us. appOwnedKeys.erase(event->hardware_keycode); + pluginOwnedKeys.erase(event->hardware_keycode); } else if (appOwnedKeys.erase(event->hardware_keycode) > 0) { return passToFlutter(event); } + else if (pluginOwnedKeys.erase(event->hardware_keycode) > 0) + { + return TRUE; + } int64_t _id = int64_t(widget); if (webviewPlugins.find(_id) != webviewPlugins.end() && webviewPlugins[_id]->getAnyBrowserFocused()) { @@ -525,6 +596,17 @@ FLUTTER_PLUGIN_EXPORT gboolean processKeyEventForCEF(GtkWidget *widget, GdkEvent appOwnedKeys.insert(event->hardware_keycode); return passToFlutter(event); } + if (event->type == GDK_KEY_PRESS && isPaste(event, windows_key_code)) + { + // Not forwarded: Chromium would paste its own, stale copy as well. + pluginOwnedKeys.insert(event->hardware_keycode); + pasteClipboardIntoPage(_id); + return TRUE; + } + if (event->type == GDK_KEY_PRESS && isCopy(event, windows_key_code)) + { + copySelectionToClipboard(webviewPlugins[_id].get()); + } CefKeyEvent key_event; key_event.windows_key_code = GetWindowsKeyCodeWithoutLocation(windows_key_code); From 04af55d16ee401eacb478c0b5bde1a8837427966 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 12:35:52 +0100 Subject: [PATCH 13/32] fix: Keeps the Linux preview from asking for a desktop keyring. Chromium keeps the key that encrypts cookies and saved passwords in the desktop's keyring. On a desktop without an unlocked one, such as a fresh Ubuntu 26.04 or one with automatic login, GNOME asked the user to create a "Default keyring" as soon as the preview loaded. CEF now gets password-store=basic on Linux, as macOS already gets use-mock-keychain: the preview shows a local development app and stores nothing that needs the keyring. --- packages/webview_cef/common/webview_app.cc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/webview_cef/common/webview_app.cc b/packages/webview_cef/common/webview_app.cc index e894e30..a749bd2 100644 --- a/packages/webview_cef/common/webview_app.cc +++ b/packages/webview_cef/common/webview_app.cc @@ -167,7 +167,12 @@ void WebviewApp::OnBeforeCommandLineProcessing(const CefString &process_type, Ce // selected by m_uMode above, like the other platforms. #endif #ifdef __linux__ - + // Linux's use-mock-keychain. Chromium otherwise keeps the key that + // encrypts cookies and saved passwords in the desktop's keyring, and on a + // desktop without an unlocked one (a fresh Ubuntu, automatic login) GNOME + // asked the user to create a keyring as soon as the preview loaded. The + // preview shows a local development app and stores nothing worth that. + command_line->AppendSwitchWithValue("password-store", "basic"); #endif } From 038135b7e2ddbca8f130aa834653b21fb69ccf71 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 13:57:14 +0100 Subject: [PATCH 14/32] fix: Ends App Studio without exit handlers once Flutter quits on Linux. Flutter's quit on Linux (quit_application in fl_platform_handler.cc) stops the main loop but leaves the window, and the engine inside, alive: nothing shuts the engine down, and its raster thread may still be drawing the preview's last frame. exit() then ran Mesa's teardown underneath it, and App Studio crashed on quit after its own teardown had already stopped the server. Flutter only quits once Dart has answered the exit request, so that teardown is done by the time the main loop returns: main() now flushes stdio and ends the process with _exit. Measured by opening a project and closing the window the way the close button does: 2 crashes in 8 quits before, none in 12 after. --- linux/runner/main.cc | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/linux/runner/main.cc b/linux/runner/main.cc index a0020b7..e248f85 100644 --- a/linux/runner/main.cc +++ b/linux/runner/main.cc @@ -1,5 +1,9 @@ #include +#include + +#include + #include "my_application.h" int main(int argc, char** argv) { @@ -22,5 +26,16 @@ int main(int argc, char** argv) { setCEFRootCachePath(cef_root); g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); + const int status = g_application_run(G_APPLICATION(app), argc, argv); + + // Flutter's quit (quit_application in fl_platform_handler.cc) stops the + // main loop but leaves the window, and the Flutter engine inside, alive: + // nothing shuts the engine down, and its raster thread may still be drawing + // the preview's last frame. exit() then ran Mesa's teardown underneath it, + // and App Studio crashed on quit, after its own teardown had stopped the + // server. Flutter only quits once the Dart side has answered the exit + // request, so that teardown is done by now: end the process without the + // exit handlers, and let the kernel take the threads. + fflush(nullptr); + _exit(status); } From b2bdddb44c9bff91cf6fd552cfd90dcc4c824d67 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 14:14:25 +0100 Subject: [PATCH 15/32] fix: Waits for the running exit teardown on a second exit request on Linux. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dart answered every exit request after the first with "exit" at once, so on Linux a second one during the teardown quit App Studio before the server was stopped: the close button twice, or File → Quit (Ctrl+Q) and then the close button, which reach Dart by different routes. A repeat request on Linux now waits for the running teardown, at most 15 s, since the CEF quit inside it has no timeout of its own and a hung teardown must not make the app impossible to close. macOS and Windows keep answering a repeat at once; Windows already drops a second close in window_close.dart. --- lib/main.dart | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/main.dart b/lib/main.dart index 59a6b86..01b93da 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -142,6 +142,9 @@ class AppStudioApp extends StatefulWidget { State createState() => _AppStudioAppState(); } +/// How long a second exit request on Linux waits for the running teardown. +const _kLinuxExitWait = Duration(seconds: 15); + class _AppStudioAppState extends State { /// The menu bar lives above [ShadApp], so dialogs it opens need the app's /// own navigator context. @@ -164,6 +167,9 @@ class _AppStudioAppState extends State { AppLifecycleListener? _lifecycle; bool _exiting = false; + /// The exit teardown in progress, for a second exit request on Linux. + Future? _exitTeardown; + /// The project the startup notice last fired for. /// /// Tracked as a path rather than a bool: switching straight from one project @@ -228,7 +234,28 @@ class _AppStudioAppState extends State { /// unquittable, which is a far worse bug than a stray child process. The /// timeout is shorter than the one `dispose()` uses because the user is /// watching a quit here, not a relaunch. - Future _onExitRequested() async { + /// + /// A second request while the teardown runs is answered at once on macOS + /// and Windows (Windows drops a second close before it gets here, in + /// `window_close.dart`). On Linux every route ends here — the close button, + /// the window manager's close, File → Quit and Ctrl+Q — and answering "exit" + /// at once quit the app mid-teardown, before the server was stopped. There + /// it waits for the teardown instead, but at most [_kLinuxExitWait]: the CEF + /// quit inside it has no timeout of its own, and a teardown that hangs must + /// not make the app impossible to close. + Future _onExitRequested() { + final running = _exitTeardown; + if (running != null) { + if (!currentHost.isLinux) return Future.value(AppExitResponse.exit); + return running.timeout( + _kLinuxExitWait, + onTimeout: () => AppExitResponse.exit, + ); + } + return _exitTeardown = _runExitTeardown(); + } + + Future _runExitTeardown() async { if (_exiting) return AppExitResponse.exit; _exiting = true; try { From c5bbafd7cec95b2a00340f62bbf9692369ea129e Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 14:58:35 +0100 Subject: [PATCH 16/32] feat: Packs the Linux build into an AppImage. tool/linux/build_appimage.sh makes a release build and packs it into dist/linux/AppStudio--x86_64.AppImage; make appimage runs it. The bundle keeps its layout under usr/lib/appstudio, so the executable finds its libraries through its RPATH and CEF's helpers start from inside the mounted image. Libraries that still carry a symbol table are stripped, which takes libcef.so from 1.37 GB to 256 MB and the AppImage to 138 MB. The icons come from the Windows .ico, whose frames run edge to edge as Linux icons do. The desktop entry's StartupWMClass is the GTK application id, so docks match the window to it, and its X-AppImage-Version is the one version the AppImage carries: VERSION is unset for appimagetool, which would otherwise stamp whatever the caller's environment holds. The release build drops Widgetbook's url_launcher from the generated plugin files, so the script restores them, as build_release.ps1 does on Windows. Before packing, it checks the tools it needs, the bundle's files, and that the bundle was built from pubspec's version, so SKIP_BUILD cannot ship an old build under a new number. appimagetool and its runtime are pinned and checked against their sha256. With APPIMAGE_UPDATE_INFO set, the AppImage carries zsync update information for AppImageUpdate and Gear Lever, and a .zsync is written beside it; APPIMAGE_FILE_URL puts an absolute download URL in the .zsync, so each release can keep its own path. Hosting both is Serverpod's. Running it needs glibc 2.38 or newer (Ubuntu 24.04 and later). --- Makefile | 21 ++- tool/linux/build_appimage.sh | 259 +++++++++++++++++++++++++++++++++++ 2 files changed, 279 insertions(+), 1 deletion(-) create mode 100755 tool/linux/build_appimage.sh diff --git a/Makefile b/Makefile index 7fa385e..5e73d93 100644 --- a/Makefile +++ b/Makefile @@ -23,6 +23,9 @@ # make publish Upload the built zip + refresh downloads/macos.json # make build_debug Unsigned zip, local only # +# Linux: +# make appimage Release build packed as an AppImage in dist/linux +# .DEFAULT_GOAL := help # Recipes use [[ ]] and read -p. @@ -33,7 +36,7 @@ CEF_STAMP := $(ROOT)/packages/webview_cef/macos/third/cef/version.txt .PHONY: help start deps ensure_deps widgetbook start_driver widgetbook_driver \ clean clean_all \ - set_version release build build_debug publish promote + set_version release build build_debug publish promote appimage help: @echo "Run locally:" @@ -57,6 +60,9 @@ help: @echo " make publish Upload the built zip + refresh the download links" @echo " make build_debug Unsigned zip, local only" @echo "" + @echo "Linux:" + @echo " make appimage Release build packed as an AppImage in dist/linux" + @echo "" @echo "The app installs Flutter and the Serverpod CLI from their official" @echo "sources on first run, so no toolchain is needed to build or ship it." @@ -199,3 +205,16 @@ promote: @read -r -p "Make this build the live auto-update for every install? [y/N] " a; \ [[ $$a == [yY]* ]] || { echo "aborted"; exit 1; } cd "$(ROOT)" && ./tool/publish_appcast.sh + +# --------------------------------------------------------------------------- +# Linux +# +# Builds on the machine it runs on and uploads nothing: hosting, updates and +# the release pipeline are Serverpod's. CEF downloads during the first CMake +# configure, so there is no deps step. FLUTTER, SKIP_BUILD, APPIMAGETOOL, +# APPIMAGE_UPDATE_INFO and APPIMAGE_FILE_URL are read from the environment; +# see the script. +# --------------------------------------------------------------------------- + +appimage: + cd "$(ROOT)" && ./tool/linux/build_appimage.sh diff --git a/tool/linux/build_appimage.sh b/tool/linux/build_appimage.sh new file mode 100755 index 0000000..6d7dc07 --- /dev/null +++ b/tool/linux/build_appimage.sh @@ -0,0 +1,259 @@ +#!/usr/bin/env bash +# Builds App Studio for Linux and packs it into an AppImage. +# +# Usage: tool/linux/build_appimage.sh (or: make appimage) +# +# Writes dist/linux/AppStudio--x86_64.AppImage, being the +# one in pubspec.yaml (without the build number). +# +# Optional environment: +# FLUTTER the flutter to build with (default: flutter on PATH) +# SKIP_BUILD=1 package the release build that is already there +# APPIMAGETOOL path to appimagetool; the pinned release is +# downloaded into build/linux/tools if unset +# APPIMAGE_UPDATE_INFO update information for AppImageUpdate and Gear Lever, +# e.g. "zsync|https:////AppStudio-latest-x86_64.AppImage.zsync". +# With it, appimagetool also writes a .zsync file next +# to the AppImage. A release overwrites the .zsync at +# that fixed URL. Gear Lever offers an update whenever +# the .zsync's SHA-1 differs from the installed +# file's; it does not compare versions. +# APPIMAGE_FILE_URL where this AppImage will be downloaded from, written +# into the .zsync, e.g. "https:///releases/linux/ +# /b/AppStudio--x86_64.AppImage". +# Unset, the .zsync names the AppImage relative to +# itself, so every release would have to sit in the +# .zsync's folder; with it, the AppImage keeps a path +# of its own that is never overwritten. +# +# The AppImage carries App Studio, Flutter's engine and CEF. GTK 3 and the +# other desktop libraries come from the system; the build needs glibc 2.38 or +# newer at run time (Ubuntu 24.04 and later), so build on the oldest system +# it should run on. The build machine needs Flutter's Linux build tools, plus +# curl, python3, and readelf and strip (binutils). +set -euo pipefail + +root="$(cd "$(dirname "$0")/../.." && pwd)" +flutter="${FLUTTER:-flutter}" +bundle="$root/build/linux/x64/release/bundle" +appdir="$root/build/linux/AppStudio.AppDir" +dist="$root/dist/linux" +app_id="dev.serverpod.appstudio" + +full_version="$(sed -n 's/^version: *\([^ ]*\).*/\1/p' "$root/pubspec.yaml")" +version="${full_version%%+*}" +if [[ -z "$version" ]]; then + echo "No version in pubspec.yaml." >&2 + exit 1 +fi +out="$dist/AppStudio-${version}-x86_64.AppImage" + +step() { echo "==> $*"; } + +missing=() +for cmd in curl python3 readelf sha256sum strip; do + command -v "$cmd" > /dev/null || missing+=("$cmd") +done +if (( ${#missing[@]} )); then + echo "Missing on this machine: ${missing[*]}" >&2 + exit 1 +fi + +# --- Build ----------------------------------------------------------------- + +if [[ "${SKIP_BUILD:-}" != 1 ]]; then + step "flutter build linux --release" + # A release build rewrites the generated plugin files (it drops Widgetbook's + # url_launcher, a dev dependency). They are committed, so put them back + # whatever happens, as tool/windows/build_release.ps1 does. + restore_generated() { + git -C "$root" checkout -- \ + linux/flutter/generated_plugin_registrant.cc \ + linux/flutter/generated_plugins.cmake \ + windows/flutter/generated_plugin_registrant.cc \ + windows/flutter/generated_plugins.cmake + } + trap restore_generated EXIT + (cd "$root" && "$flutter" build linux --release) + restore_generated + trap - EXIT +fi + +step "Checking the bundle" +# Flutter's own files, then CEF's: libcef.so and what it loads from beside +# itself (resources, locales, ANGLE's GL libraries, SwiftShader's software +# Vulkan). +# libflutter_pty2.so is a native asset (Publish to Cloud's terminal), built by +# the package's hook rather than CMake, so nothing else would notice it gone. +for file in appstudio lib/libapp.so lib/libflutter_linux_gtk.so \ + data/flutter_assets lib/libflutter_pty2.so \ + lib/libwebview_cef_plugin.so lib/libcef.so lib/icudtl.dat \ + lib/resources.pak lib/chrome_100_percent.pak lib/chrome_200_percent.pak \ + lib/v8_context_snapshot.bin lib/locales lib/libEGL.so lib/libGLESv2.so \ + lib/libvk_swiftshader.so lib/vk_swiftshader_icd.json; do + if [[ ! -e "$bundle/$file" ]]; then + echo "Missing from the release build: $bundle/$file" >&2 + exit 1 + fi +done + +# The bundle records the version it was built with. With SKIP_BUILD it can be +# older than pubspec.yaml, and would then ship under the wrong version. +built="$(python3 -I -c 'import json, sys +v = json.load(open(sys.argv[1])) +print(v["version"] + "+" + v["build_number"])' "$bundle/data/flutter_assets/version.json")" +if [[ "$built" != "$full_version" ]]; then + echo "The release build is $built, pubspec.yaml says $full_version: build again." >&2 + exit 1 +fi + +# --- AppDir ---------------------------------------------------------------- + +step "Assembling $appdir" +rm -rf "$appdir" +# The bundle keeps its layout (appstudio, lib/, data/): the executable finds +# its libraries through its RPATH ($ORIGIN/lib) and CEF finds its resources +# beside libcef.so. CEF's helper processes are this same executable, started +# from inside the mounted image. +mkdir -p "$appdir/usr/lib/appstudio" "$appdir/usr/bin" +cp -a "$bundle"/. "$appdir/usr/lib/appstudio/" +ln -s ../lib/appstudio/appstudio "$appdir/usr/bin/appstudio" + +step "Stripping debug symbols" +# libcef.so ships with its symbols: 1.4 GB of a 1.5 GB bundle. Only files +# that still have a symbol table are stripped; the others, Flutter's engine +# among them, ship as they were built. libapp.so (the Dart AOT snapshot) is +# left alone: Flutter already strips it. +while IFS= read -r -d '' file; do + # Captured, not piped into grep -q: grep stopping at the match would cut + # readelf off, and pipefail would read that as no symbol table. + if [[ "$(readelf -S "$file")" == *.symtab* ]]; then + strip --strip-unneeded "$file" + fi +done < <(find "$appdir/usr/lib/appstudio" -type f \ + \( -name '*.so' -o -name '*.so.*' -o -name appstudio \) ! -name libapp.so -print0) + +step "Icons and desktop entry" +# Linux icons run nearly edge to edge, like Windows' and unlike the macOS +# icon, which sits on Apple's grid with a margin. So they come from the +# Windows .ico, whose frames are PNGs: one source for both. +python3 -I - "$root/windows/runner/resources/app_icon.ico" \ + "$appdir/usr/share/icons/hicolor" "$app_id" <<'PY' +import os, struct, sys +ico, hicolor, name = sys.argv[1:4] +data = open(ico, "rb").read() +count = struct.unpack(" "$appdir/usr/share/applications/$app_id.desktop" < "$appdir/AppRun" <<'APPRUN' +#!/bin/sh +here="$(dirname "$(readlink -f "$0")")" +exec "$here/usr/lib/appstudio/appstudio" "$@" +APPRUN +chmod +x "$appdir/AppRun" + +# --- AppImage -------------------------------------------------------------- + +# appimagetool and the runtime it puts in front of the image are pinned and +# checked against their sha256, as WinSparkle is on Windows. Left to itself, +# appimagetool would also fetch the runtime from the moving "continuous" +# release on every run. +appimagetool_version=1.9.1 +appimagetool_sha256=ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0 +runtime_version=20251108 +runtime_sha256=2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d +tools="$root/build/linux/tools" + +# Downloads $1 to $2 unless a file with sha256 $3 is already there. +fetch_pinned() { + local url="$1" dest="$2" sha="$3" + if [[ -f "$dest" ]] && echo "$sha $dest" | sha256sum -c --status; then + return + fi + step "Downloading $url" + mkdir -p "$(dirname "$dest")" + curl -fsSL -o "$dest.part" "$url" + if ! echo "$sha $dest.part" | sha256sum -c --status; then + rm -f "$dest.part" + echo "Checksum mismatch for $url" >&2 + exit 1 + fi + mv "$dest.part" "$dest" +} + +tool="${APPIMAGETOOL:-}" +if [[ -z "$tool" ]]; then + tool="$tools/appimagetool-$appimagetool_version-x86_64.AppImage" + fetch_pinned \ + "https://github.com/AppImage/appimagetool/releases/download/$appimagetool_version/appimagetool-x86_64.AppImage" \ + "$tool" "$appimagetool_sha256" + chmod +x "$tool" +fi +runtime="$tools/runtime-$runtime_version-x86_64" +fetch_pinned \ + "https://github.com/AppImage/type2-runtime/releases/download/$runtime_version/runtime-x86_64" \ + "$runtime" "$runtime_sha256" + +update=() +if [[ -n "${APPIMAGE_UPDATE_INFO:-}" ]]; then + update=(--updateinformation "$APPIMAGE_UPDATE_INFO") + if [[ -n "${APPIMAGE_FILE_URL:-}" ]]; then + update+=(--file-url "$APPIMAGE_FILE_URL") + fi +elif [[ -n "${APPIMAGE_FILE_URL:-}" ]]; then + echo "APPIMAGE_FILE_URL needs APPIMAGE_UPDATE_INFO: it only goes into the .zsync." >&2 + exit 1 +fi + +step "Packing $out" +mkdir -p "$dist" +rm -f "$out" "$out.zsync" +# CI runners have no FUSE; extract-and-run works everywhere. appimagetool +# writes the .zsync into the working directory. VERSION is unset because +# appimagetool would write it over the desktop entry's X-AppImage-Version: a +# VERSION left in the caller's environment would ship as App Studio's. +( + cd "$dist" + env -u VERSION APPIMAGE_EXTRACT_AND_RUN=1 ARCH=x86_64 \ + "$tool" --runtime-file "$runtime" "${update[@]}" "$appdir" "$out" +) +if [[ -n "${APPIMAGE_UPDATE_INFO:-}" && ! -s "$out.zsync" ]]; then + echo "appimagetool wrote no $out.zsync." >&2 + exit 1 +fi + +step "Built $out ($(du -h "$out" | cut -f1))" From 0203a32677f314370c6e67cd59aa2b115b76704b Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 15:28:11 +0100 Subject: [PATCH 17/32] fix: Lets launchers find App Studio by typing "appstudio". Launcher search matches the start of each word of a desktop entry's Name, so "app" and "studio" found App Studio but "appstudio" found nothing (seen in GNOME on Ubuntu). The desktop entry now carries Keywords for its one-word name and for Serverpod, Flutter and Dart. --- tool/linux/build_appimage.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tool/linux/build_appimage.sh b/tool/linux/build_appimage.sh index 6d7dc07..09cf458 100755 --- a/tool/linux/build_appimage.sh +++ b/tool/linux/build_appimage.sh @@ -163,6 +163,8 @@ ln -s "$app_id.png" "$appdir/.DirIcon" # StartupWMClass is the GTK application id the runner sets (APPLICATION_ID in # linux/CMakeLists.txt): it is how a dock matches the window to this entry. # X-AppImage-Version is the version AppImage managers such as Gear Lever show. +# Launchers match the start of each word of Name, so "appstudio" would find +# nothing without Keywords. mkdir -p "$appdir/usr/share/applications" cat > "$appdir/usr/share/applications/$app_id.desktop" < Date: Fri, 27 Nov 2026 16:58:27 +0100 Subject: [PATCH 18/32] feat: Says why the AppImage cannot start on a system that cannot load it. On a system that cannot load App Studio, with a glibc or C++ runtime too old or a system library such as GTK missing, the executable failed before any of App Studio ran, so a double-click did nothing visible and only a terminal showed the loader's error. AppRun now asks the loader first (LD_TRACE_LOADED_OBJECTS, which lists what the app needs without running it) and, when something is missing, says what: a newer Linux with glibc 2.38 or later and distributions that have it, no glibc at all, or the libraries to install. The message goes to the terminal and, when there is a display, to a window through zenity, kdialog or notify-send, falling through to the next tool when one cannot show it. The glibc version is read from the build, as the highest GLIBC_ version any ELF file in the bundle references, and a build that needs another version stops until the distributions the message names are updated. Tested with the packed AppImage on Debian 11 (glibc 2.31), Alpine (no glibc) and Ubuntu 24.04. --- tool/linux/build_appimage.sh | 116 ++++++++++++++++++++++++++++++++++- 1 file changed, 115 insertions(+), 1 deletion(-) diff --git a/tool/linux/build_appimage.sh b/tool/linux/build_appimage.sh index 09cf458..715e5c1 100755 --- a/tool/linux/build_appimage.sh +++ b/tool/linux/build_appimage.sh @@ -182,11 +182,125 @@ X-AppImage-Version=$version DESKTOP ln -s "usr/share/applications/$app_id.desktop" "$appdir/$app_id.desktop" +step "Start script" +# A system that cannot load the bundle (a glibc or C++ runtime too old, or a +# system library missing) fails before any of App Studio runs, so a +# double-click does nothing visible. AppRun asks the loader first and says +# what is wrong. Its message names a glibc version and distributions that +# have it: the version is the highest GLIBC_ version any ELF file in the +# bundle references, read from the build so it cannot drift, and a build that +# needs another one stops here until the distributions are updated. They go +# into a shell string, so they are limited to plain characters. +glibc_expected=2.38 +glibc_examples="Ubuntu 24.04, Fedora 39, Debian 13 or newer" +if [[ ! "$glibc_examples" =~ ^[A-Za-z0-9\ .,]+$ ]]; then + echo "glibc_examples may hold letters, digits, spaces, dots and commas only." >&2 + exit 1 +fi +glibc_versions=() +while IFS= read -r -d '' file; do + # ELF files by their header, not their name: chrome-sandbox has no .so. + # NUL bytes are dropped first, as bash warns about them in $(...); the ELF + # header has none. + [[ "$(head -c 4 "$file" | tr -d '\0')" == $'\x7fELF' ]] || continue + # In the main shell, so a readelf that fails stops the build. + syms="$(readelf --dyn-syms -W "$file")" + for v in $(grep -o 'GLIBC_[0-9][0-9.]*' <<< "$syms" || true); do + glibc_versions+=("${v#GLIBC_}") + done +done < <(find "$appdir/usr/lib/appstudio" -path "$appdir/usr/lib/appstudio/data" -prune \ + -o -type f -print0) +glibc_required="$(printf '%s\n' "${glibc_versions[@]}" | sort -V -u | tail -n 1)" +if [[ "$glibc_required" != "$glibc_expected" ]]; then + echo "The bundle needs glibc ${glibc_required:-(none found)}, not $glibc_expected." >&2 + echo "Update glibc_expected and glibc_examples in $0." >&2 + exit 1 +fi + cat > "$appdir/AppRun" <<'APPRUN' #!/bin/sh +# Starts App Studio from the mounted image. On a system that cannot load it, +# the executable fails before any of App Studio runs and a double-click does +# nothing visible, so this asks the loader first and says what is wrong. here="$(dirname "$(readlink -f "$0")")" -exec "$here/usr/lib/appstudio/appstudio" "$@" +app="$here/usr/lib/appstudio/appstudio" +required="@GLIBC_REQUIRED@" +examples="@GLIBC_EXAMPLES@" + +# Joins the non-empty lines on stdin with ", ". +join() { + joined="" + while IFS= read -r line; do + [ -n "$line" ] && joined="${joined:+$joined, }$line" + done + printf '%s' "$joined" +} + +# Shows title $1 and text $2 through the first tool that manages to. Exit 1 +# with nothing on stderr is a dialog the user closed; any other failure, such +# as a display the tool cannot open, hands over to the next tool. +show_window() { + for tool in zenity kdialog notify-send; do + command -v "$tool" > /dev/null 2>&1 || continue + case "$tool" in + zenity) err="$(zenity --error --no-markup --title="$1" --text="$2" 2>&1 > /dev/null)" ;; + kdialog) err="$(kdialog --title "$1" --error "$2" 2>&1 > /dev/null)" ;; + notify-send) err="$(notify-send "$1" "$2" 2>&1 > /dev/null)" ;; + esac + status=$? + if [ "$status" -eq 0 ] || { [ "$status" -eq 1 ] && [ -z "$err" ]; }; then + return 0 + fi + done + return 1 +} + +# "glibc 2.39"; "none" where getconf exists but knows no glibc (musl); empty +# where there is no getconf, which then does not count against the system. +glibc="" +if command -v getconf > /dev/null 2>&1; then + glibc="$(getconf GNU_LIBC_VERSION 2> /dev/null)" + case "$glibc" in + "glibc "[0-9]*) ;; + *) glibc="none" ;; + esac +fi + +if [ "$glibc" != none ]; then + # The loader lists what the app needs without running it, and says + # "not found" for each library or symbol version this system lacks. + trace="$(LD_TRACE_LOADED_OBJECTS=1 "$app" 2>&1)" + missing_versions="$(printf '%s\n' "$trace" | + sed -n "s/.*version [\`']\([^']*\)' not found.*/\1/p" | sort -u | join)" + missing_libs="$(printf '%s\n' "$trace" | + sed -n 's/^[[:space:]]*\([^[:space:]]*\) => not found.*/\1/p' | sort -u | join)" + # Nothing recognisably missing: start, and let any other failure speak. + if [ -z "$missing_versions$missing_libs" ]; then + exec "$app" "$@" + fi +fi + +if [ "$glibc" = none ]; then + title="App Studio needs a Linux with glibc" + text="App Studio needs glibc $required or later ($examples). This system has no glibc." +elif [ -n "$missing_versions" ]; then + title="App Studio needs a newer Linux" + # Libraries missing as well are left out: a newer Linux is the fix either + # way, and on an old system the list runs to dozens. + text="App Studio needs glibc $required or later ($examples). This system ${glibc:+has $glibc and }lacks $missing_versions." +else + title="App Studio is missing system libraries" + text="App Studio needs these libraries, which this system does not have: $missing_libs. Install them with your distribution's package manager." +fi +printf '%s\n' "$text" >&2 +# Started from a launcher, nobody reads stderr: show a window as well. +if [ -n "$WAYLAND_DISPLAY$DISPLAY" ]; then + show_window "$title" "$text" +fi +exit 1 APPRUN +sed -i -e "s/@GLIBC_REQUIRED@/$glibc_required/" \ + -e "s/@GLIBC_EXAMPLES@/$glibc_examples/" "$appdir/AppRun" chmod +x "$appdir/AppRun" # --- AppImage -------------------------------------------------------------- From 2a51c15a6d69740281bb7a9d79da84c6a10586bb Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Fri, 27 Nov 2026 22:22:52 +0100 Subject: [PATCH 19/32] docs: Adds the plan for adding the AppImage to the app menu. Without Gear Lever or AppImageLauncher, the AppImage never appears in the app menu and the dock shows a generic icon. The plan has App Studio offer to add itself on first start: it moves the file to ~/AppImages/AppStudio-x86_64.AppImage, copies its icons and writes a desktop entry with a marker, so Remove from Applications (and the uninstall in PR 5) takes away only what App Studio wrote. It asks only when no tool has added it yet. When someone starts a second copy, it offers to replace the copy in the app menu with a newer one, or to open the newer one instead of an older one. The spec also records the AppRun check that is already built, text for the download page, and that updates from inside the app come later. --- specs/linux_appimage.md | 393 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 393 insertions(+) create mode 100644 specs/linux_appimage.md diff --git a/specs/linux_appimage.md b/specs/linux_appimage.md new file mode 100644 index 0000000..9c6e29e --- /dev/null +++ b/specs/linux_appimage.md @@ -0,0 +1,393 @@ +# Linux AppImage: adding App Studio to the app menu + +Status: **draft, 2026-11-27.** Follows PR 4 (`make appimage`, +`tool/linux/build_appimage.sh`) on the step branch `linux/4b-appimage`, which +merges into `linux/port` like the other steps. + +## The plan in short + +The AppImage works well **once a tool has added it to the app menu**: +[Gear Lever](https://github.com/mijorus/gearlever) (an app for managing +AppImages), [AppImageLauncher](https://github.com/TheAssassin/AppImageLauncher) +(which steps in when an AppImage it has not integrated yet starts, and asks +"Integrate and run" or "Run once") or +[appimaged](https://github.com/probonopd/go-appimage) (a daemon that adds +every AppImage it finds in the folders it watches). Without one of them, App +Studio never appears in the app menu and the dock shows a generic icon, +because no desktop entry names it. Part A closes that gap from inside App +Studio. + +| Part | What | Where | State | +|---|---|---|---| +| A | **Add to Applications**: on start, until it is in the app menu, App Studio offers to add itself; **Remove from Applications** undoes it | App Studio (Dart), Linux only | being built | +| B | Updates from inside the app | App Studio and Serverpod's release pipeline | later (below) | +| C | **A clear message on a system that cannot load App Studio**, instead of nothing happening | `AppRun` in the AppImage | done | +| D | **Download page text** for Serverpod's website | text in this spec | written; needs A | +| E | Uninstall removes what A added | App Studio (Dart) | with PR 5 | + +**B, updates, come later.** Until then **Help → Check for Updates** stays +greyed out on Linux, and the AppImage carries no update information: where +builds are hosted, and with it the `.zsync` URL Gear Lever would read +(`specs/linux_port.md` 4.5), is Serverpod's to decide together with the +updater. Part A's fixed path (A2) lets that updater replace the file in place +without touching the menu entry. + +This spec covers the AppImage. Whether the `.deb` and `.rpm` of +`specs/linux_port.md` (4.5) still follow is open with Serverpod. + +### Decisions + +| # | Decision | +|---|---| +| A1 | **App Studio asks before it writes anything outside its own folders**, at most once per start. It does not offer to add itself when it is in the app menu already, whoever put it there; which tools are installed does not matter. The one question it asks then is about a second copy of its own (see Another copy). | +| A2 | **An added AppImage lives at one fixed path, `~/AppImages/AppStudio-x86_64.AppImage`.** No version in the name, so replacing the file keeps the menu entry valid. `~/AppImages` is Gear Lever's default folder, and by default neither AppImageLauncher nor appimaged watches it; both add whatever appears in `~/Applications`, so a file moved there would show up in the menu twice. (Either can be told to watch more folders; appimaged also watches every folder on `PATH`.) | +| A3 | **The desktop entry App Studio writes carries a marker**, `X-AppStudio-AddedBy=appstudio`, so Remove from Applications (and PR 5's uninstall) removes only that entry. An entry another tool wrote stays. | +| C1 | **No older build base.** The AppImage needs glibc 2.38 (Ubuntu 24.04 and later); part C makes that readable rather than lower. | + +--- + +## A. Add to Applications + +### Four states + +Everything in part A follows from one of four states, read from the disk +whenever a question or the Help menu needs it: + +| State | Meaning | +|---|---| +| `unavailable` | Not running as an AppImage (condition 1 below). Nothing to offer. | +| `managedByOther` | In the app menu through another tool, or a package. Theirs. | +| `addedByAppStudio` | App Studio's own entry (A3), and the file its `TryExec` names exists. | +| `notAdded` | None of the above: App Studio offers to add itself. | + +1. **Running as an AppImage** means: the AppImage runtime set `$APPIMAGE` + (the file's path) and `$APPDIR` (where the image is mounted), **and** App + Studio's executable is inside `$APPDIR`. The variables are inherited by + child processes, so a development build started from a terminal inside + another AppImage (an editor, say) sees that one's; only the executable + tells them apart. A *portable* AppImage, one with a `.AppImage.home` + folder beside it, counts as `unavailable` too: the runtime points `HOME` + there, so an entry written under it never reaches the desktop. +2. **In the app menu** means a desktop entry, in `$XDG_DATA_HOME/applications` + (default `~/.local/share/applications`) or an `applications` folder under + `$XDG_DATA_DIRS`, sub-folders included, that is called + `dev.serverpod.appstudio.desktop` or names + `StartupWMClass=dev.serverpod.appstudio`. Gear Lever, AppImageLauncher and + appimaged name their entries after the app or a hash, but keep the + AppImage's own `StartupWMClass`, so one check finds all of them, and a + copy they added is found even when started from a terminal. + - An entry whose `TryExec` names a file that no longer exists does not + count: it is left over from an AppImage the user deleted. This covers + App Studio's own entry too, which the next Add then writes over. + (appimaged's `TryExec` names appimaged itself, so its entries always + count.) + - An installed tool that did not add App Studio does not count. With + AppImageLauncher, a user who chose "Run once" in its question is then + asked by App Studio as well. + +### When App Studio asks + +Over the start page: on a normal start once it shows, and on a first run as +soon as setup ends, in the same run, so the question never lands among +setup's own dialogs. The checks read the disk; if a project opens before they +are done, no question comes that run. A project opened while the question is +up closes it (the routes over the start page are cleared, as for every +project open). + +In state `notAdded` it asks to add itself, unless the user said "Don't ask +again" (preference `linux.add_to_applications_declined`). In state +`addedByAppStudio` it may ask about another copy (below). In the other two +states it asks nothing. + +### The question + +```text +Add App Studio to your applications? + +App Studio will appear in your app menu, and the file moves from +~/Downloads to ~/AppImages. + +[ ] Don't ask again [Not now] [Add] +``` + +The sentence about the file names the folder it is in now. It is left out +when the file is in `~/AppImages` already (where Add at most renames it to the +fixed name), and when an earlier Add in the same run already moved it. +**Not now** asks again on the next start; with the box ticked it never asks +again on start. + +### The Help menu + +Exactly one of two items shows in Help on Linux, or neither: + +- **Add to Applications...** in state `notAdded`, so "Don't ask again" is + never a dead end. It opens the same dialog with **Cancel** instead of + Not now, and no checkbox. +- **Remove from Applications...** in state `addedByAppStudio`. It confirms + first: + + ```text + Remove App Studio from your applications? + + App Studio leaves your app menu. The file stays at + ~/AppImages/AppStudio-x86_64.AppImage, and App Studio will not ask to + add itself again. + + [Cancel] [Remove] + ``` + +Neither shows in states `unavailable` and `managedByOther`. + +### What Add does + +The dialog stays open while it runs and shows any error in it. + +1. **Moves the AppImage to `~/AppImages/AppStudio-x86_64.AppImage`** (A2), + creating the folder if needed. A rename where it can be. Where the rename + fails (another file system, or a folder the file cannot be taken out of, + such as a root-owned `/opt`), a copy to a temporary name in `~/AppImages`, + made executable, then renamed onto the target, and the original deleted. + A file already at the target is replaced only by a rename, so it is never + half-written. If the original cannot be deleted, the copy is added anyway + and the original stays. + + Moving a running AppImage is safe. The runtime's squashfuse opens the file + once, when it mounts the image, and reads every block through that + descriptor. Checked with the 0.4.1 AppImage: after the file was copied to + another file system and the original deleted, all of `libcef.so` read back + from the mount and the loader still resolved the executable's libraries. +2. **Copies the icons** from `$APPDIR/usr/share/icons/hicolor/` into + `$XDG_DATA_HOME/icons/hicolor/`, under the same names. +3. **Writes `$XDG_DATA_HOME/applications/dev.serverpod.appstudio.desktop`** + from the AppImage's own entry: `Exec` set to the new path, quoted as the + Desktop Entry spec requires for an argument; `TryExec` set to the same + path as a plain, unquoted string; the marker (A3); and the running version + as `X-AppStudio-Version` and `X-AppStudio-Build`. Every other key and group + is kept. It is written to a temporary name and renamed, so a launcher never + reads half an entry. The file name is the application id, so on Wayland + the dock can match the window to it by its app id as well as by + `StartupWMClass`. +4. **Rebuilds the icon cache if there is one**: when + `$XDG_DATA_HOME/icons/hicolor/icon-theme.cache` exists, it runs + `gtk-update-icon-cache -f -t` on that folder (best effort). Without a + cache, icons are looked up on disk. +5. **Shows a toast**: "Added to your applications". + +`update-desktop-database` is not run: it only writes `mimeinfo.cache` from +`MimeType=` keys, and the entry has none. GNOME (through GLib's file monitor +on each `applications` folder) and KDE (through kded's directory watch) pick a +new entry up on their own, going by their source; to confirm in the VM. + +**If a step fails**, the icons and entry that this Add created are removed; +ones that were there before (a Replace, below) are kept, so the entry already +in the menu still shows its icon. The dialog shows the step and the reason. A +moved file is not moved back, since App Studio runs on from its new place, so +the error then also says that the AppImage is now at +`~/AppImages/AppStudio-x86_64.AppImage`. Pressing Add again (or Help → Add +later) finds the file there, though `$APPIMAGE` still names its old place, +and carries on from step 2; if the original could not be deleted, it is +copied again. + +### What Remove does + +Deletes the entry App Studio wrote and the `dev.serverpod.appstudio.png` +icons under `$XDG_DATA_HOME/icons/hicolor/`, only when the entry carries the +marker, and rebuilds the icon cache as Add does. The AppImage stays where it +is. Removing sets "Don't ask again" first (the user just said no), so a +removal that fails halfway does not bring the question back either. A toast +says "Removed from your applications", or, on failure, "Could not remove App +Studio from your applications" with the reason. + +### Another copy than the one in the app menu + +Someone who downloads App Studio again and starts the new file is in state +`addedByAppStudio`, so the question above never comes. When the running file +is not the one App Studio's entry names, App Studio compares the two by build +number, which orders releases: + +- **This copy is newer:** + + ```text + Replace App Studio 0.4.1 with this version? + + This copy is App Studio 0.4.2, newer than the 0.4.1 in your app menu. + Replace moves it from ~/Downloads to ~/AppImages, in place of the older + one. + + [Not now] [Replace] + ``` + + When the copy is in `~/AppImages` already, the second sentence reads + "Replace puts it in place of the older one." Replace runs Add, so + everything above applies: the file is renamed over the old one, and the + entry is rewritten with the new version. Once the move has happened the + older copy is gone; if a later step fails, the existing entry and icons + stay, and the entry points at the new file while still naming the old + version. A toast says "App Studio 0.4.2 is in your applications". +- **This copy is older:** + + ```text + A newer App Studio is in your app menu + + This copy is App Studio 0.4.0. Your app menu has 0.4.1. + + [Keep using this one] [Open 0.4.1] + ``` + + Open quits this copy, through the same teardown as File → Quit, and starts + the newer one once this process has ended: the two share the preview's + browser profile, which only one can hold at a time. (A small detached `sh` + waits for the process, for at most 30 s.) If the added file is gone, Open + says so in a toast and nothing quits. Replacing the newer copy with the + older one is not offered: a downgrade is too easy to click by accident. It + stays possible in two deliberate steps, Remove and then Add. +- **The same build:** nothing is said. It is a second download. + +The versions shown are the marketing versions, with the build added when +both copies share one. The running copy's comes from the `version.json` +Flutter writes into the bundle. The added copy's is not mounted, so Add +records it in the entry as `X-AppStudio-Version` and `X-AppStudio-Build`. +Without them nothing is said. A copy Gear Lever or another tool added is +theirs: Gear Lever has its own update. There is no "Don't ask again" here; +the question is about one file, and comes up only when someone starts a +second copy by hand. + +Nothing stops two copies running at once (the GTK application is +`G_APPLICATION_NON_UNIQUE`, as before this spec). Replace while the added copy +also runs swaps its file underneath it, which the running copy does not +notice (its image stays mounted); Open while it runs starts a second +instance of it. Both are left as they are. + +### Living alongside the other tools + +- **AppImageLauncher** asks when an AppImage it has not integrated yet + starts, before App Studio runs. After "Integrate and run" App Studio finds + its entry and stays quiet; after "Run once" App Studio asks too. By default + its daemon does not watch `~/AppImages`, so App Studio's Add gets no second + entry from it. +- **appimaged** adds every AppImage in the Downloads folder, the desktop, + `~/Applications`, the folders on `PATH` and more, but not `~/AppImages`. A + downloaded App Studio is already in the menu by the time it starts, and the + entry check finds it. +- **Gear Lever** lists an entry in `~/.local/share/applications` as one of + its own when its `TryExec` names a file in Gear Lever's folder (default + `~/AppImages`), or anywhere while its "manage files outside the default + folder" setting is on (the default). So the entry App Studio writes + usually shows up there too. Removing it in Gear Lever moves the AppImage to + the trash and deletes the entry; the icons App Studio copied stay behind. + Updating it through Gear Lever rewrites the entry from the AppImage's own, + which drops App Studio's marker: App Studio then reads it as + `managedByOther`, which is what it has become. + +### Where it lives + +- `lib/platform/linux/desktop_integration.dart`: the states, Add, Remove and + the comparison of copies, with the environment and the executable injected + so the tests point `HOME` at a temporary folder and run on every host; and + `DesktopIntegrationController`, the state the menu strip listens to. +- `lib/platform/linux/app_version.dart`: a version and build, and how two + copies compare; free of `dart:io`. +- `lib/ui/add_to_applications_dialog.dart`: the dialogs, free of `dart:io` + so Widgetbook shows them. +- `lib/ui/desktop_integration_commands.dart`: what the question and the Help + items run, including the preference, which the caller writes as the + project notices do. + +--- + +## C. A system that cannot load App Studio (done) + +On a system with an older glibc (Ubuntu 22.04, Debian 12, Linux Mint 21), or +without a library such as GTK, `appstudio` fails before any of App Studio +runs: a double-click does **nothing visible**, and only a terminal shows the +loader's error. Dart never runs, so the check sits in `AppRun`. + +- **`AppRun` asks the loader first.** `LD_TRACE_LOADED_OBJECTS=1` lists what + the executable needs without running it, with "not found" for each library + or symbol version the system lacks. With nothing missing it starts App + Studio. Otherwise it says why, in one of three ways: + - **a symbol version missing** (any, such as `GLIBC_2.38` or + `GLIBCXX_3.4.29`): "App Studio needs a newer Linux", naming the glibc + version needed, distributions that have it, the system's glibc and the + versions it lacks. Missing libraries are left out of this message: a + newer Linux is the fix either way, and on an old system the list runs to + dozens; + - **no glibc at all** (`getconf` knows none, as on Alpine): "App Studio + needs a Linux with glibc"; + - **only libraries missing**: "App Studio is missing system libraries", + listing them, with a hint to install them with the distribution's + package manager. +- The message goes to stderr always and, when there is a display, to a + window through the first of `zenity`, `kdialog` or `notify-send` that + manages to show it. Then `AppRun` exits with 1. +- **The glibc version is read from the build**: the highest `GLIBC_x.y` any + ELF file in the bundle references, `data/` excluded (today 2.38). The + distributions the message names are tied to that version, so a build that + needs another one stops until they are updated. +- Tested by hand with the packed AppImage in containers: Debian 11 (glibc + 2.31) shows "needs a newer Linux", Alpine shows "needs a Linux with glibc", + and on Ubuntu 24.04 the check passes and App Studio's executable is + started. There is no automated test. + +--- + +## D. Download page text + +For Serverpod's website, next to the macOS and Windows downloads, once part A +ships. The requirement line follows part C's glibc version; the +distributions named have that glibc, which is not the same as tested (App +Studio is tested on Ubuntu 26.04 and Arch). + +```text +App Studio for Linux (x86_64) + +Needs a 64-bit Linux with glibc 2.38 or later, such as Ubuntu 24.04, +Fedora 39 or Debian 13, or newer. Tested on Ubuntu and Arch. + +Allow the downloaded file to run, then double-click it: + - GNOME (Ubuntu, Fedora): right-click → Properties → "Executable as Program" + - KDE: right-click → Properties → Permissions → "Allow executing file as + program" ("Is executable" on older versions) + - Terminal: chmod +x AppStudio-*-x86_64.AppImage +Once its setup is done, App Studio offers to add itself to your app menu. + +If you use Gear Lever, open the file with it and choose +"Move to the app menu" instead. +``` + +--- + +## E. Uninstall (PR 5) + +App Studio's uninstall on Linux, in PR 5, runs the same removal as Remove +from Applications. Whether it also deletes the AppImage itself is decided +there. + +## Testing + +- **Unit tests on every host** through `HostPlatform.linux` + (`test/platform/linux/desktop_integration_test.dart`): each condition of + of the four states (inherited variables, a portable AppImage, entries in + sub-folders, a deleted `TryExec`), the entry it writes (including an + `Exec` path that needs quoting), a move within and across file systems and + out of a folder the file cannot leave, a failed step undoing only what it + created, a retry after the move, Remove leaving an entry without the marker + alone, and how another copy compares (newer, older, the same, no recorded + version). The dialogs and the Help items have widget tests, and + `test/ui/desktop_integration_commands_test.dart` pins the preference both + ways: "Don't ask again" and Remove set it, Not now, Add and a cancelled + Remove do not. +- **Widgetbook:** the question (from Downloads, already in `~/AppImages`, + from the Help menu), another copy (newer, older) and the Remove + confirmation. +- **Ubuntu VM from `clean-install`:** + - without Gear Lever: download in Firefox, allow it to run, start; after + setup the question appears; Add; App Studio is in the app menu with its + icon, starts from there, and the question does not come back; + - Remove from Applications: the menu entry goes, the file stays; + - after Gear Lever added it: no question, and no Help item; + - with Gear Lever installed but not used: the question appears; + - another copy: start a newer build from `~/Downloads` and Replace; start + an older one and Open, and the newer copy comes up once the older one + has quit. +- **Omarchy:** the same Add and Remove, through Walker. From 2efdaa1181bf177688d4eef5d6b62dd681725bd6 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 11:33:59 +0100 Subject: [PATCH 20/32] feat: Offers to add the AppImage to the app menu on Linux. Without Gear Lever, AppImageLauncher or appimaged, a downloaded AppImage never appears in the app menu and the dock shows a generic icon. App Studio now asks once it reaches the start page, as long as no desktop entry names it. Add moves the file to ~/AppImages/AppStudio-x86_64.AppImage, copies the icons and writes dev.serverpod.appstudio.desktop with an X-AppStudio-AddedBy marker and the version it added. Help gets Add to Applications or Remove from Applications, whichever applies. Remove deletes only an entry carrying the marker and leaves the file where it is. Starting another copy while App Studio's own entry exists asks whether to Replace it with a newer build, or offers to Open the newer one from an older build. The same build says nothing. After a failed Replace the entry no longer records a version, so a later download is never offered in place of a newer copy. --- lib/main.dart | 52 +- lib/platform/linux/app_version.dart | 35 + lib/platform/linux/desktop_integration.dart | 770 ++++++++++++++++ .../linux/desktop_integration_status.dart | 19 + lib/platform/windows_app_menu.dart | 29 + lib/ui/add_to_applications_dialog.dart | 297 +++++++ lib/ui/desktop_integration_commands.dart | 235 +++++ specs/linux_appimage.md | 50 +- .../linux/desktop_integration_test.dart | 825 ++++++++++++++++++ test/platform/windows_app_menu_test.dart | 66 ++ test/ui/add_to_applications_dialog_test.dart | 186 ++++ .../ui/desktop_integration_commands_test.dart | 269 ++++++ widgetbook/use_cases/start.dart | 86 ++ 13 files changed, 2902 insertions(+), 17 deletions(-) create mode 100644 lib/platform/linux/app_version.dart create mode 100644 lib/platform/linux/desktop_integration.dart create mode 100644 lib/platform/linux/desktop_integration_status.dart create mode 100644 lib/ui/add_to_applications_dialog.dart create mode 100644 lib/ui/desktop_integration_commands.dart create mode 100644 test/platform/linux/desktop_integration_test.dart create mode 100644 test/ui/add_to_applications_dialog_test.dart create mode 100644 test/ui/desktop_integration_commands_test.dart diff --git a/lib/main.dart b/lib/main.dart index 01b93da..bc2dce9 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -10,6 +10,7 @@ import 'cloud/cloud_publish.dart'; import 'platform/afunix_settle.dart'; import 'platform/compact_window.dart'; import 'platform/host.dart'; +import 'platform/linux/desktop_integration.dart'; import 'platform/window_close.dart'; import 'platform/windows/win32_system.dart'; import 'platform/windows/windows_roots.dart'; @@ -27,6 +28,7 @@ import 'update/session_teardown.dart'; import 'update/update_controller.dart'; import 'platform/macos_app_menu.dart'; import 'ui/about_dialog.dart'; +import 'ui/desktop_integration_commands.dart'; import 'ui/migration_commands.dart'; import 'ui/server_log/log_view_controller.dart'; import 'ui/new_project_dialog.dart'; @@ -69,6 +71,10 @@ Future main() async { final cloud = CloudPublishController(toolchains: toolchains, session: session); final previewMode = PreviewModeController(window: CompactWindowChannel()); final logView = LogViewController(); + // Linux: whether the AppImage is in the app menu. Read from disk in the + // background; the menu item appears when it lands. + final desktopIntegration = DesktopIntegrationController(); + if (currentHost.isLinux) unawaited(desktopIntegration.refresh()); // Never blocks launch: create() swallows its own failures and reports the // updater as unavailable. @@ -108,6 +114,7 @@ Future main() async { updates: updates, previewMode: previewMode, logView: logView, + desktopIntegration: desktopIntegration, ), ); } @@ -125,6 +132,7 @@ class AppStudioApp extends StatefulWidget { required this.updates, required this.previewMode, required this.logView, + required this.desktopIntegration, }); final ThemeController themeController; @@ -137,6 +145,7 @@ class AppStudioApp extends StatefulWidget { final UpdateController updates; final PreviewModeController previewMode; final LogViewController logView; + final DesktopIntegrationController desktopIntegration; @override State createState() => _AppStudioAppState(); @@ -184,6 +193,11 @@ class _AppStudioAppState extends State { /// those overlapping would duplicate entries. Only the transition matters. bool? _menuCanOpenProjects; + /// Linux: offers to add the AppImage to the app menu, once per run. + late final _addToApplications = AddToApplicationsOffer( + widget.desktopIntegration, + ); + @override void initState() { super.initState(); @@ -225,6 +239,13 @@ class _AppStudioAppState extends State { await _onExitRequested(); }; unawaited(_macMenu!.install()); + // With setup done, the start page is the first screen: offer once it is + // up. Otherwise the end of setup offers (`_onToolchainsChanged`). + if (!_needsToolchainSetup) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => _offerAddToApplications(), + ); + } // Clear anything a crashed install left behind. Fire and forget, so it // never delays launch; ToolchainSetupScreen drives the install itself. unawaited(widget.toolchains.collectGarbage()); @@ -305,9 +326,18 @@ class _AppStudioAppState extends State { widget.updates, widget.toolchains, widget.previewMode, + widget.desktopIntegration, ]), // The compact preview is the phone frame alone. stripHidden: () => widget.previewMode.compactWindow, + desktopIntegrationStatus: () => widget.desktopIntegration.status, + onAddToApplications: () => _withNavigatorContext( + (context) => addToApplications(context, widget.desktopIntegration), + ), + onRemoveFromApplications: () => _withNavigatorContext( + (context) => + removeFromApplications(context, widget.desktopIntegration), + ), child: child ?? const SizedBox.shrink(), ); @@ -334,11 +364,30 @@ class _AppStudioAppState extends State { // current for exactly that reason: a second pop here would take `home` with // it and leave an empty navigator. WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) _clearPushedRoutes(); + if (!mounted) return; + _clearPushedRoutes(); + // After the clear, or it would take the question with it. + if (canOpen) _offerAddToApplications(); }); _syncMenu(); } + /// Linux, as an AppImage nobody added to the app menu: asks whether to, + /// once per run, over the start page and never among setup's dialogs. + void _offerAddToApplications() { + if (!mounted) return; + _withNavigatorContext( + (context) => _addToApplications.offerOnce( + context, + onStartPage: () => + mounted && + widget.session.projectPath == null && + !_needsToolchainSetup && + _uninstalled == null, + ), + ); + } + /// Whether the first-run setup screen owns the window — see /// [ToolchainController.needsSetup]. bool get _needsToolchainSetup => widget.toolchains.needsSetup; @@ -529,6 +578,7 @@ class _AppStudioAppState extends State { widget.themeController.dispose(); widget.previewMode.dispose(); widget.logView.dispose(); + widget.desktopIntegration.dispose(); super.dispose(); } diff --git a/lib/platform/linux/app_version.dart b/lib/platform/linux/app_version.dart new file mode 100644 index 0000000..05f2453 --- /dev/null +++ b/lib/platform/linux/app_version.dart @@ -0,0 +1,35 @@ +import 'package:flutter/foundation.dart'; + +/// A version of App Studio: `0.4.1` and the build counter (`25`) that orders +/// releases. +@immutable +class AppVersion { + const AppVersion(this.version, this.build); + + final String version; + final int build; + + @override + bool operator ==(Object other) => + other is AppVersion && other.version == version && other.build == build; + + @override + int get hashCode => Object.hash(version, build); + + @override + String toString() => '$version+$build'; +} + +/// Another copy of App Studio than the one in the app menu is running: one +/// downloaded again, say. Only for a copy App Studio added itself; Gear +/// Lever updates its own. +@immutable +class OtherCopy { + const OtherCopy({required this.running, required this.added}); + + final AppVersion running; + final AppVersion added; + + bool get runningIsNewer => running.build > added.build; + bool get runningIsOlder => running.build < added.build; +} diff --git a/lib/platform/linux/desktop_integration.dart b/lib/platform/linux/desktop_integration.dart new file mode 100644 index 0000000..82b2933 --- /dev/null +++ b/lib/platform/linux/desktop_integration.dart @@ -0,0 +1,770 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; + +import '../host.dart'; +import 'app_version.dart'; +import 'desktop_integration_status.dart'; + +export 'app_version.dart'; +export 'desktop_integration_status.dart'; + +/// The GTK application id (`APPLICATION_ID` in `linux/CMakeLists.txt`). The +/// AppImage's desktop entry and icons are named after it, and its +/// `StartupWMClass` is it. +const kLinuxAppId = 'dev.serverpod.appstudio'; + +/// The key App Studio adds to the desktop entry it writes, so it removes only +/// that one and never an entry Gear Lever or AppImageLauncher wrote. +const kAddedByKey = 'X-AppStudio-AddedBy'; +const kAddedByValue = 'appstudio'; + +/// The version and build of the AppImage App Studio added, written into its +/// entry: the added file is not mounted, so this is the only place to read +/// them from when another copy starts. +const kAddedVersionKey = 'X-AppStudio-Version'; +const kAddedBuildKey = 'X-AppStudio-Build'; + +/// The added AppImage's name: no version in it, so replacing the file keeps +/// the desktop entry valid. +const kAddedAppImageName = 'AppStudio-x86_64.AppImage'; + +/// The running build's version, from the `version.json` Flutter writes +/// beside the executable (`data/flutter_assets/`). On Linux the updater has +/// no native side to ask. +Future readRunningVersion() async { + try { + final file = File( + p.join( + p.dirname(Platform.resolvedExecutable), + 'data', + 'flutter_assets', + 'version.json', + ), + ); + final json = jsonDecode(await file.readAsString()); + if (json is! Map) return null; + final version = json['version']; + final build = int.tryParse('${json['build_number']}'); + if (version is! String || build == null) return null; + return AppVersion(version, build); + } catch (e) { + debugPrint('could not read the running version: $e'); + return null; + } +} + +/// What failed while adding App Studio to the app menu, and why. +class DesktopIntegrationException implements Exception { + const DesktopIntegrationException(this.step, this.reason); + + /// What App Studio was doing, as a sentence fragment: "Moving the AppImage". + final String step; + final String reason; + + @override + String toString() => '$step failed: $reason'; +} + +/// Adds the running AppImage to the app menu the way Gear Lever and +/// AppImageLauncher do, and removes what it added again. +/// +/// Adding moves the AppImage to `~/AppImages/AppStudio-x86_64.AppImage`, +/// copies its icons into the user's icon theme folder and writes a desktop +/// entry named after the application id. Everything is under the user's home +/// directory, so nothing needs a password. +/// +/// Every path comes from [environment], so tests point `HOME` at a +/// temporary folder; with [host] set to Linux they run on any machine. +/// Paths are built with this machine's own `package:path` context rather +/// than [host]'s: every one of them is read or written here, so on another +/// OS a test's temporary folder has to stay in that OS's form. +class DesktopIntegration { + DesktopIntegration({ + Map? environment, + HostPlatform? host, + Future Function()? runningVersion, + String? executable, + }) : environment = environment ?? Platform.environment, + host = host ?? currentHost, + _runningVersion = runningVersion ?? readRunningVersion, + _executable = executable ?? Platform.resolvedExecutable; + + final Map environment; + + /// Decides whether there is anything to offer: only Linux has an app menu + /// this class writes to. + final HostPlatform host; + final Future Function() _runningVersion; + + /// This process's executable: inside `$APPDIR` when App Studio is the + /// AppImage that set the variables. + final String _executable; + + String? get _home { + final home = environment['HOME']; + return home == null || home.isEmpty ? null : home; + } + + String? _variable(String name) { + final value = environment[name]; + return value == null || value.isEmpty ? null : value; + } + + /// `$XDG_DATA_HOME`, or `~/.local/share`. A relative value is invalid by + /// the XDG base directory spec and is ignored. + String? get _dataHome { + final value = _variable('XDG_DATA_HOME'); + if (value != null && p.isAbsolute(value)) return value; + final home = _home; + return home == null ? null : p.join(home, '.local', 'share'); + } + + /// `$XDG_DATA_DIRS`, or the spec's default. + List get _dataDirs { + final value = _variable('XDG_DATA_DIRS'); + final dirs = value == null + ? const ['/usr/local/share', '/usr/share'] + : value.split(':'); + return [ + for (final dir in dirs) + if (p.isAbsolute(dir)) dir, + ]; + } + + /// The running AppImage's own path, as its runtime set it. After [add] it + /// names where the file *was*. + String? get _appImage => _variable('APPIMAGE'); + + /// Where the running image is mounted. + String? get _appDir => _variable('APPDIR'); + + /// Where an added AppImage lives, or null without a home directory. + /// + /// `~/AppImages` is Gear Lever's folder, and nothing else watches it. + /// AppImageLauncher's daemon adds whatever appears in `~/Applications`, and + /// appimaged watches that folder too, so a file moved there could end up + /// in the menu twice. + String? get addedAppImagePath { + final home = _home; + return home == null ? null : p.join(home, 'AppImages', kAddedAppImageName); + } + + String? get _entryPath { + final dataHome = _dataHome; + return dataHome == null + ? null + : p.join(dataHome, 'applications', '$kLinuxAppId.desktop'); + } + + /// The folder the AppImage is in now, for the question's wording: Add + /// moves it from there. Null when it is in `~/AppImages` already, where + /// Add at most renames it. + Future currentFolder() async { + final appImage = _appImage; + final target = addedAppImagePath; + // Gone: an earlier Add in this run moved it. + if (appImage == null || !await File(appImage).exists()) return null; + final folder = p.dirname(appImage); + if (target != null && p.equals(folder, p.dirname(target))) return null; + return folder; + } + + /// Whether [add] would replace another file at [addedAppImagePath]: a copy + /// left there after Remove, or after its entry was deleted by hand. It may + /// be a newer build, so the question says so. + Future replacesAnotherFile() async { + final appImage = _appImage; + final target = addedAppImagePath; + if (appImage == null || target == null || alreadyInPlace) return false; + // After this copy's own Add, `$APPIMAGE` names where it was and the file + // at the target is this one. + return await File(appImage).exists() && await File(target).exists(); + } + + /// Whether the AppImage is already where [add] would move it. + bool get alreadyInPlace { + final appImage = _appImage; + final target = addedAppImagePath; + return appImage != null && target != null && p.equals(appImage, target); + } + + Future status() async { + final appDir = _appDir; + if (!host.isLinux || _appImage == null || appDir == null) { + return DesktopIntegrationStatus.unavailable; + } + // Children inherit `$APPIMAGE` and `$APPDIR`: a development build started + // from a terminal inside another AppImage (an editor, say) sees that + // one's. Only an executable inside the mount is this AppImage. + if (!p.isWithin(appDir, _executable)) { + return DesktopIntegrationStatus.unavailable; + } + final entryPath = _entryPath; + if (entryPath == null) return DesktopIntegrationStatus.unavailable; + // A portable AppImage: the runtime pointed HOME at `.home`, so + // an entry written under it would never reach the desktop. + if (await Directory('${_appImage!}.home').exists()) { + return DesktopIntegrationStatus.unavailable; + } + + final own = await _readEntry(entryPath); + if (own != null && _isOurs(own) && await _targetExists(own)) { + return DesktopIntegrationStatus.addedByAppStudio; + } + // Whether another tool is installed does not matter, only whether it + // added App Studio: an entry is what puts it in the menu. + if (await _otherEntryExists(ownEntry: entryPath)) { + return DesktopIntegrationStatus.managedByOther; + } + return DesktopIntegrationStatus.notAdded; + } + + /// An entry of ours whose AppImage is gone (the user deleted the file) adds + /// nothing to the menu — launchers hide it by its `TryExec` — so it does not + /// count, and [add] writes over it. + Future _targetExists(Map entry) async { + final tryExec = entry['TryExec']; + return tryExec != null && await File(tryExec).exists(); + } + + bool _isOurs(Map entry) => + entry[kAddedByKey] == kAddedByValue; + + /// Any other entry for App Studio, in the user's folder or the system's: + /// named after the application id, or naming it as its window class. + /// AppImageLauncher and appimaged name their entries after a hash of the + /// file, but keep the AppImage's own `StartupWMClass`. + Future _otherEntryExists({required String ownEntry}) async { + final dataHome = _dataHome; + final folders = [ + if (dataHome != null) p.join(dataHome, 'applications'), + for (final dir in _dataDirs) p.join(dir, 'applications'), + ]; + for (final folder in folders) { + final dir = Directory(folder); + if (!await dir.exists()) continue; + try { + // Recursive: a desktop file id may sit in a sub-folder (`kde4/…`). + // A sub-folder that cannot be read is skipped, not the rest of the + // folder with it. + final files = dir + .list(recursive: true, followLinks: true) + .handleError( + (Object e) => debugPrint('Skipping in $folder: $e'), + test: (e) => e is FileSystemException, + ); + await for (final file in files) { + if (file is! File || !file.path.endsWith('.desktop')) continue; + final entry = await _readEntry(file.path); + if (entry == null) continue; + final named = p.basename(file.path) == '$kLinuxAppId.desktop'; + final matches = entry['StartupWMClass'] == kLinuxAppId; + if (!named && !matches) continue; + if (p.equals(file.path, ownEntry) && _isOurs(entry)) continue; + // An entry whose program is gone is hidden by launchers: a tool's + // leftover after the user deleted the AppImage. (appimaged's + // `TryExec` names appimaged itself, which stays.) + final tryExec = entry['TryExec']; + if (tryExec != null && + p.isAbsolute(tryExec) && + !await File(tryExec).exists()) { + continue; + } + return true; + } + } on FileSystemException { + continue; + } + } + return false; + } + + /// Adds the running AppImage to the app menu. Throws + /// [DesktopIntegrationException] naming the step that failed; the steps + /// before it are undone, apart from the move, since the AppImage runs on + /// from its new place either way. + Future add() async { + final appImage = _appImage; + final appDir = _appDir; + final target = addedAppImagePath; + final dataHome = _dataHome; + final entryPath = _entryPath; + if (appImage == null || + appDir == null || + target == null || + dataHome == null || + entryPath == null) { + throw const DesktopIntegrationException( + 'Adding App Studio', + 'App Studio is not running as an AppImage.', + ); + } + + await _step('Moving the AppImage to ~/AppImages', () async { + if (alreadyInPlace) return; + if (await File(appImage).exists()) { + await _move(appImage, target); + } else if (!await File(target).exists()) { + throw FileSystemException('The AppImage is gone', appImage); + } + // Otherwise an earlier try moved it, and `$APPIMAGE` still names the + // place it was. + }); + + final written = []; + try { + await _step('Copying the icons', () async { + final source = Directory( + p.join(appDir, 'usr', 'share', 'icons', 'hicolor'), + ); + final destination = p.join(dataHome, 'icons', 'hicolor'); + await for (final file in source.list(recursive: true)) { + if (file is! File) continue; + final to = p.join( + destination, + p.relative(file.path, from: source.path), + ); + await Directory(p.dirname(to)).create(recursive: true); + // Only what this Add created is undone. An icon already there + // (a Replace) is the one the existing entry shows. + final existed = await File(to).exists(); + await file.copy(to); + if (!existed) written.add(to); + } + }); + await _step('Writing the app menu entry', () async { + final source = await _sourceEntry(appDir); + final entry = desktopEntryFor( + source, + appImagePath: target, + version: await _runningVersion(), + ); + await Directory(p.dirname(entryPath)).create(recursive: true); + final temporary = File('$entryPath.$pid.part'); + await temporary.writeAsString(entry, flush: true); + written.add(temporary.path); + final existed = await File(entryPath).exists(); + await temporary.rename(entryPath); + written.remove(temporary.path); + if (!existed) written.add(entryPath); + }); + } on DesktopIntegrationException catch (e) { + for (final path in written.reversed) { + try { + await File(path).delete(); + } on FileSystemException { + // Already gone, or never written. + } + } + if (!written.contains(entryPath)) { + await _forgetRecordedVersion(entryPath); + } + // The move is not undone, so say where the file went. + throw DesktopIntegrationException( + e.step, + alreadyInPlace + ? e.reason + : '${e.reason} The AppImage is now at ' + '~/AppImages/$kAddedAppImageName.', + ); + } + await _refreshIconCache(dataHome); + } + + /// After a failed Add, an entry of ours that was there before stays, so + /// the menu keeps working. Its `TryExec` names the fixed path, which may + /// hold another build by now, so the version it records is dropped: + /// compared with the next download, a wrong one could offer to replace a + /// newer copy with an older one. Without it, no copy is compared until the + /// next Add writes the entry again. Best effort, like the cleanup before. + Future _forgetRecordedVersion(String entryPath) async { + final file = File(entryPath); + if (!await file.exists()) return; + try { + final contents = await file.readAsString(); + final entry = parseDesktopEntry(contents); + if (!_isOurs(entry) || + (!entry.containsKey(kAddedVersionKey) && + !entry.containsKey(kAddedBuildKey))) { + return; + } + final kept = []; + var inGroup = false; + for (final line in contents.split('\n')) { + if (line.startsWith('[')) { + inGroup = line.trimRight() == '[Desktop Entry]'; + } else if (inGroup) { + final key = line.split('=').first.trim(); + if (key == kAddedVersionKey || key == kAddedBuildKey) continue; + } + kept.add(line); + } + final temporary = File('$entryPath.$pid.part'); + await temporary.writeAsString(kept.join('\n'), flush: true); + await temporary.rename(entryPath); + } on FileSystemException catch (e) { + debugPrint('Could not drop the recorded version from $entryPath: $e'); + } on FormatException catch (e) { + debugPrint('Could not drop the recorded version from $entryPath: $e'); + } + } + + /// Rebuilds the user's icon cache, but only where one exists: without a + /// cache, icons are looked up on disk and a new one shows at once. Best + /// effort; a stale cache only costs the icon until the next rebuild. + Future _refreshIconCache(String dataHome) async { + final hicolor = p.join(dataHome, 'icons', 'hicolor'); + if (!await File(p.join(hicolor, 'icon-theme.cache')).exists()) return; + try { + await Process.run('gtk-update-icon-cache', ['-f', '-t', hicolor]); + } on ProcessException catch (e) { + debugPrint('gtk-update-icon-cache failed: $e'); + } + } + + /// Removes the desktop entry App Studio wrote and the icons it copied — + /// only when the entry carries [kAddedByKey], so an entry another tool + /// wrote under the same name stays. The AppImage itself stays. Throws when + /// there is no entry of App Studio's to remove: another tool may have + /// rewritten it since the menu last looked. + Future remove() async { + const step = 'Removing the app menu entry'; + final entryPath = _entryPath; + final dataHome = _dataHome; + if (entryPath == null || dataHome == null) { + throw const DesktopIntegrationException(step, 'There is no home folder.'); + } + final entry = await _readEntry(entryPath); + if (entry == null) { + throw const DesktopIntegrationException( + step, + 'App Studio is not in your app menu.', + ); + } + if (!_isOurs(entry)) { + throw const DesktopIntegrationException( + step, + 'Another app manages App Studio\'s entry in your app menu now.', + ); + } + + await _step(step, () async { + await File(entryPath).delete(); + }); + await _step('Removing the icons', () async { + final hicolor = Directory(p.join(dataHome, 'icons', 'hicolor')); + if (!await hicolor.exists()) return; + await for (final size in hicolor.list()) { + if (size is! Directory) continue; + final icon = File(p.join(size.path, 'apps', '$kLinuxAppId.png')); + if (await icon.exists()) await icon.delete(); + } + }); + await _refreshIconCache(dataHome); + } + + /// The running copy and the one in the app menu, when they are different + /// files and App Studio added the latter. Null otherwise, and when either + /// version is unknown: then there is nothing reliable to say. + Future otherCopy() async { + if (await status() != DesktopIntegrationStatus.addedByAppStudio) { + return null; + } + final appImage = _appImage; + final entryPath = _entryPath; + if (appImage == null || entryPath == null || alreadyInPlace) return null; + // After this copy's own Add, `$APPIMAGE` names where it was. + if (!await File(appImage).exists()) return null; + final entry = await _readEntry(entryPath); + final addedVersion = entry?[kAddedVersionKey]; + final addedBuild = int.tryParse(entry?[kAddedBuildKey] ?? ''); + final running = await _runningVersion(); + if (addedVersion == null || addedBuild == null || running == null) { + return null; + } + return OtherCopy( + running: running, + added: AppVersion(addedVersion, addedBuild), + ); + } + + /// Starts the copy in the app menu once this process has ended, so the two + /// never run at once — they share the preview's browser profile, which only + /// one can hold. The caller quits right after. A copy that has not ended + /// after 30 s starts anyway. [afterPid] is the process to wait for; tests + /// hand it one of their own, since this one never ends during a test. + Future openAddedCopyAfterExit({ + @visibleForTesting int? afterPid, + }) async { + final target = addedAppImagePath; + if (target == null || !await File(target).exists()) { + throw FileSystemException('The AppImage is gone', target); + } + await Process.start('/bin/sh', [ + '-c', + r'i=0; while kill -0 "$1" 2>/dev/null && [ "$i" -lt 150 ]; do ' + r'sleep 0.2; i=$((i + 1)); done; exec "$2"', + 'sh', + '${afterPid ?? pid}', + target, + ], mode: ProcessStartMode.detached); + } + + /// A rename where it can be; across file systems a copy to a temporary + /// name beside [to], a rename onto it, then the original goes. A file + /// already at [to] is only ever replaced by a rename, so it is never half + /// written. An original that cannot be deleted stays: the copy works. + Future _move(String from, String to) async { + await Directory(p.dirname(to)).create(recursive: true); + try { + await File(from).rename(to); + return; + } on FileSystemException { + // Another file system (EXDEV), or a folder the file cannot be taken out + // of (EACCES on a root-owned one): a copy still works. A problem with + // the target shows up again in the copy, with its own reason. + } + final temporary = '$to.$pid.part'; + try { + await File(from).copy(temporary); + await _makeExecutable(temporary); + await File(temporary).rename(to); + } catch (_) { + try { + await File(temporary).delete(); + } on FileSystemException { + // Never written. + } + rethrow; + } + try { + await File(from).delete(); + } on FileSystemException catch (e) { + debugPrint('Could not delete $from after copying it: $e'); + } + } + + /// `File.copy` keeps the mode on Linux today, but an AppImage that is not + /// executable does not start at all, so it is set rather than relied on. + /// Dart has no chmod. + Future _makeExecutable(String path) async { + final result = await Process.run('chmod', ['755', path]); + if (result.exitCode != 0) { + throw FileSystemException( + 'chmod failed: ${(result.stderr as String).trim()}', + path, + ); + } + } + + Future _sourceEntry(String appDir) async { + for (final path in [ + p.join(appDir, 'usr', 'share', 'applications', '$kLinuxAppId.desktop'), + p.join(appDir, '$kLinuxAppId.desktop'), + ]) { + final file = File(path); + if (await file.exists()) return file.readAsString(); + } + throw FileSystemException('The AppImage carries no desktop entry', appDir); + } + + Future _step(String step, Future Function() run) async { + try { + await run(); + } on DesktopIntegrationException { + rethrow; + } on FileSystemException catch (e) { + final reason = e.osError?.message ?? e.message; + throw DesktopIntegrationException( + step, + e.path == null ? reason : '$reason (${e.path})', + ); + } on ProcessException catch (e) { + throw DesktopIntegrationException(step, e.message); + } on FormatException catch (e) { + throw DesktopIntegrationException(step, e.message); + } + } + + /// The `[Desktop Entry]` group's keys, or null when there is no readable + /// file there. + Future?> _readEntry(String path) async { + try { + return parseDesktopEntry(await File(path).readAsString()); + } on FileSystemException { + return null; + } on FormatException { + // Not UTF-8: not an entry anyone could have meant for App Studio. + return null; + } + } +} + +/// The keys of [contents]' `[Desktop Entry]` group. Localised keys +/// (`Name[de]`) are kept under their full name; values are returned as +/// written, unescaped only for the `\s`, `\n`, `\t`, `\r` and `\\` escapes. +@visibleForTesting +Map parseDesktopEntry(String contents) { + final keys = {}; + var inGroup = false; + for (final raw in contents.split('\n')) { + final line = raw.trimRight(); + if (line.startsWith('[')) { + inGroup = line == '[Desktop Entry]'; + continue; + } + if (!inGroup || line.startsWith('#')) continue; + final equals = line.indexOf('='); + if (equals <= 0) continue; + keys[line.substring(0, equals).trim()] = _unescape( + line.substring(equals + 1).trimLeft(), + ); + } + return keys; +} + +String _unescape(String value) => value.replaceAllMapped( + RegExp(r'\\(.)'), + (m) => switch (m[1]) { + 's' => ' ', + 'n' => '\n', + 't' => '\t', + 'r' => '\r', + '\\' => r'\', + _ => m[0]!, + }, +); + +/// [source] — the AppImage's own entry — pointed at [appImagePath]: `Exec` +/// and `TryExec` replaced, the marker added, and with it the [version] of the +/// file being added. Every other line, the other +/// groups included, is kept as it was. +@visibleForTesting +String desktopEntryFor( + String source, { + required String appImagePath, + AppVersion? version, +}) { + if (appImagePath.contains(RegExp(r'[\n\r]'))) { + throw FileSystemException( + 'A path with a line break cannot go in a desktop entry', + appImagePath, + ); + } + final out = []; + var inGroup = false; + var wroteKeys = false; + void writeKeys() { + if (wroteKeys) return; + out + ..add('Exec=${_execArgument(appImagePath)}') + ..add('TryExec=${_escapeString(appImagePath)}') + ..add('$kAddedByKey=$kAddedByValue'); + if (version != null) { + out + ..add('$kAddedVersionKey=${_escapeString(version.version)}') + ..add('$kAddedBuildKey=${version.build}'); + } + wroteKeys = true; + } + + final lines = source.split('\n'); + if (lines.isNotEmpty && lines.last.isEmpty) lines.removeLast(); + for (final line in lines) { + if (line.startsWith('[')) { + if (inGroup) writeKeys(); + inGroup = line.trimRight() == '[Desktop Entry]'; + out.add(line); + continue; + } + if (inGroup) { + final key = line.split('=').first.trim(); + if (const { + 'Exec', + 'TryExec', + kAddedByKey, + kAddedVersionKey, + kAddedBuildKey, + }.contains(key)) { + continue; + } + } + out.add(line); + } + if (inGroup) writeKeys(); + if (!wroteKeys) { + throw const FormatException('The AppImage entry has no [Desktop Entry]'); + } + return '${out.join('\n')}\n'; +} + +/// A string value: a backslash is written as two. +String _escapeString(String value) => value.replaceAll(r'\', r'\\'); + +/// One `Exec` argument, quoted as the Desktop Entry spec says: inside double +/// quotes, `"`, `` ` ``, `$` and `\` take a backslash, and `%` is doubled. +/// The string escaping applies on top, which is why a backslash ends up as +/// four. +String _execArgument(String value) { + final quoted = value + .replaceAllMapped(RegExp(r'["`$\\]'), (m) => '\\${m[0]}') + .replaceAll('%', '%%'); + return _escapeString('"$quoted"'); +} + +/// [DesktopIntegration]'s state for the UI: the menu strip listens to it, and +/// the question on first start reads it. +class DesktopIntegrationController extends ChangeNotifier { + DesktopIntegrationController({DesktopIntegration? integration}) + : integration = integration ?? DesktopIntegration(); + + final DesktopIntegration integration; + + DesktopIntegrationStatus _status = DesktopIntegrationStatus.unavailable; + DesktopIntegrationStatus get status => _status; + + bool _disposed = false; + + /// Reads the state from disk. Never throws: anything unreadable counts as + /// "nothing to offer". + Future refresh() async { + DesktopIntegrationStatus status; + try { + status = await integration.status(); + } catch (e) { + debugPrint('desktop integration status failed: $e'); + status = DesktopIntegrationStatus.unavailable; + } + if (_disposed || status == _status) return; + _status = status; + notifyListeners(); + } + + /// [DesktopIntegration.add], then a fresh [status]. Throws what `add` + /// throws, after refreshing, since a failed step may still have moved the + /// file. + Future add() async { + try { + await integration.add(); + } finally { + await refresh(); + } + } + + Future remove() async { + try { + await integration.remove(); + } finally { + await refresh(); + } + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/lib/platform/linux/desktop_integration_status.dart b/lib/platform/linux/desktop_integration_status.dart new file mode 100644 index 0000000..5fc4c8a --- /dev/null +++ b/lib/platform/linux/desktop_integration_status.dart @@ -0,0 +1,19 @@ +/// Where App Studio stands in the app menu on Linux. +/// +/// In a file of its own, free of `dart:io`, so the menu strip can switch on +/// it without importing what reads the disk. +enum DesktopIntegrationStatus { + /// Not running as an AppImage: a development build, a package, or another + /// OS. There is nothing to add. + unavailable, + + /// Already in the app menu through another tool — Gear Lever, + /// AppImageLauncher, appimaged — or a package. Theirs to manage. + managedByOther, + + /// App Studio added it: Remove from Applications undoes that. + addedByAppStudio, + + /// Nobody added it yet: App Studio offers to. + notAdded, +} diff --git a/lib/platform/windows_app_menu.dart b/lib/platform/windows_app_menu.dart index d0dc45e..7b5dcae 100644 --- a/lib/platform/windows_app_menu.dart +++ b/lib/platform/windows_app_menu.dart @@ -15,6 +15,7 @@ import '../ui/server_log/server_log_view.dart'; import '../util/open_url.dart'; import '../util/prompt_generator.dart'; import 'host_platform.dart'; +import 'linux/desktop_integration_status.dart'; /// The Windows and Linux counterpart of [MacAppMenu]: the same commands with /// the same rules for when each is live, as a menu strip across the top of the @@ -55,6 +56,9 @@ class WindowsAppMenuBar extends StatefulWidget { required this.child, this.stripHidden, this.host = HostPlatform.windows, + this.desktopIntegrationStatus, + this.onAddToApplications, + this.onRemoveFromApplications, }); /// Windows or Linux: the two differ in how quitting is named and bound, and @@ -93,6 +97,12 @@ class WindowsAppMenuBar extends StatefulWidget { /// shortcuts stay live, as the macOS menu bar's do. final bool Function()? stripHidden; + /// Linux: whether App Studio is in the app menu, for Help → Add to + /// Applications or Remove from Applications. Neither shows without it. + final DesktopIntegrationStatus Function()? desktopIntegrationStatus; + final VoidCallback? onAddToApplications; + final VoidCallback? onRemoveFromApplications; + @override State createState() => _WindowsAppMenuBarState(); } @@ -495,6 +505,25 @@ class _WindowsAppMenuBarState extends State { _item('Uninstall App Studio...', onPressed: widget.onUninstall), _divider, ], + // Only one of the two, and only for an AppImage nobody else added. + if (widget.host.isLinux) + ...switch (widget.desktopIntegrationStatus?.call()) { + DesktopIntegrationStatus.notAdded => [ + _item( + 'Add to Applications...', + onPressed: widget.onAddToApplications, + ), + _divider, + ], + DesktopIntegrationStatus.addedByAppStudio => [ + _item( + 'Remove from Applications...', + onPressed: widget.onRemoveFromApplications, + ), + _divider, + ], + _ => const [], + }, _item('About App Studio', onPressed: widget.onAbout), ]; } diff --git a/lib/ui/add_to_applications_dialog.dart b/lib/ui/add_to_applications_dialog.dart new file mode 100644 index 0000000..b1732e0 --- /dev/null +++ b/lib/ui/add_to_applications_dialog.dart @@ -0,0 +1,297 @@ +import 'package:flutter/material.dart'; +import 'package:shad/shad.dart'; + +import '../platform/linux/app_version.dart'; +import '../theme/app_theme.dart'; +import '../util/pretty_path.dart'; +import '../widgets/dialog_body.dart'; +import '../widgets/error_banner.dart'; + +/// How the user answered [AddToApplicationsDialog]. +enum AddToApplicationsAnswer { + /// App Studio is in the app menu now. + added, + + /// Ask again on the next start. + notNow, + + /// Never ask again on start. Help → Add to Applications still offers it. + never, +} + +/// Offers to add the running AppImage to the app menu (Linux only). +/// +/// Runs [onAdd] itself and stays open on failure with the error, so a failed +/// step is said where the user asked for it. Writing the "don't ask again" +/// preference is the caller's job, which keeps this widget free of `dart:io`. +class AddToApplicationsDialog extends StatefulWidget { + const AddToApplicationsDialog({ + super.key, + required this.onAdd, + this.currentFolder, + this.replacedFile, + this.offerDontAskAgain = true, + }); + + /// Adds App Studio to the app menu; throws with a message on failure. + final Future Function() onAdd; + + /// The folder the AppImage is in now, named in the text because Add moves + /// it. Null when it is already in `~/AppImages`. + final String? currentFolder; + + /// Another file at the path Add moves this one to, left there by an + /// earlier Add. It may be a newer build, so the question says Add replaces + /// it. Null when there is none. + final String? replacedFile; + + /// False from the Help menu: the user asked, so there is nothing to stop + /// asking about, and the way out is Cancel rather than Not now. + final bool offerDontAskAgain; + + @override + State createState() => + _AddToApplicationsDialogState(); +} + +class _AddToApplicationsDialogState extends State { + bool _dontAskAgain = false; + bool _adding = false; + String? _error; + + Future _add() async { + setState(() { + _adding = true; + _error = null; + }); + try { + await widget.onAdd(); + if (!mounted) return; + Navigator.of(context).pop(AddToApplicationsAnswer.added); + } catch (e) { + if (!mounted) return; + setState(() { + _adding = false; + _error = '$e'; + }); + } + } + + void _close() => Navigator.of(context).pop( + _dontAskAgain + ? AddToApplicationsAnswer.never + : AddToApplicationsAnswer.notNow, + ); + + @override + Widget build(BuildContext context) { + final folder = widget.currentFolder; + final buttons = [ + ShadButton.outline( + enabled: !_adding, + onPressed: _adding ? null : _close, + child: Text(widget.offerDontAskAgain ? 'Not now' : 'Cancel'), + ), + ShadButton( + enabled: !_adding, + onPressed: _adding ? null : _add, + child: Text(_adding ? 'Adding…' : 'Add'), + ), + ]; + // The alert variant: no close X, since Not now is the way out. + return ShadDialog.alert( + title: const Text('Add App Studio to your applications?'), + description: Text( + [ + folder == null + ? 'App Studio will appear in your app menu.' + : 'App Studio will appear in your app menu, and the file moves ' + 'from ${prettyPath(folder)} to ~/AppImages.', + if (widget.replacedFile case final replaced?) + 'It replaces the App Studio already at ${prettyPath(replaced)}.', + ].join(' '), + ), + actionsMainAxisSize: MainAxisSize.max, + actionsMainAxisAlignment: widget.offerDontAskAgain + ? MainAxisAlignment.spaceBetween + : MainAxisAlignment.end, + actions: [ + if (widget.offerDontAskAgain) + // Flexible: with two buttons beside it the checkbox is the part + // that can wrap. + Flexible( + child: ShadCheckbox( + value: _dontAskAgain, + enabled: !_adding, + onChanged: (v) => setState(() => _dontAskAgain = v), + label: Text("Don't ask again", style: kWeightMedium), + ), + ), + Row(mainAxisSize: MainAxisSize.min, spacing: 8, children: buttons), + ], + child: DialogBody( + child: switch (_error) { + final error? => ErrorBanner(message: error), + null => null, + }, + ), + ); + } +} + +/// Confirms Help → Remove from Applications. Pops true to remove. +class RemoveFromApplicationsDialog extends StatelessWidget { + const RemoveFromApplicationsDialog({super.key, required this.appImagePath}); + + /// Where the AppImage stays, named so the user knows it is still there. + final String appImagePath; + + @override + Widget build(BuildContext context) { + return ShadDialog.alert( + title: const Text('Remove App Studio from your applications?'), + description: Text( + 'App Studio leaves your app menu. The file stays at ' + '${prettyPath(appImagePath)}, and App Studio will not ask to add ' + 'itself again.', + ), + actions: [ + ShadButton.outline( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + ShadButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Remove'), + ), + ], + child: const DialogBody(), + ); + } +} + +/// A version for these dialogs: `0.4.2`, with the build when both copies +/// share the version and only the build tells them apart. +String copyVersionLabel(AppVersion version, AppVersion other) => + version.version == other.version + ? '${version.version} (build ${version.build})' + : version.version; + +/// This copy is newer than the one App Studio added to the app menu: offers +/// to put it in that one's place. Runs [onReplace] itself and stays open on +/// failure, as [AddToApplicationsDialog] does. Pops true once replaced. +class ReplaceAddedCopyDialog extends StatefulWidget { + const ReplaceAddedCopyDialog({ + super.key, + required this.running, + required this.added, + required this.onReplace, + this.currentFolder, + }); + + final AppVersion running; + final AppVersion added; + final Future Function() onReplace; + + /// The folder this copy is in, which Replace moves it out of. Null when it + /// is in `~/AppImages` already. + final String? currentFolder; + + @override + State createState() => _ReplaceAddedCopyDialogState(); +} + +class _ReplaceAddedCopyDialogState extends State { + bool _replacing = false; + String? _error; + + Future _replace() async { + setState(() { + _replacing = true; + _error = null; + }); + try { + await widget.onReplace(); + if (!mounted) return; + Navigator.of(context).pop(true); + } catch (e) { + if (!mounted) return; + setState(() { + _replacing = false; + _error = '$e'; + }); + } + } + + @override + Widget build(BuildContext context) { + final running = copyVersionLabel(widget.running, widget.added); + final added = copyVersionLabel(widget.added, widget.running); + final folder = widget.currentFolder; + return ShadDialog.alert( + title: Text('Replace App Studio $added with this version?'), + description: Text( + 'This copy is App Studio $running, newer than the $added in your app ' + 'menu. ${folder == null ? 'Replace puts it' : 'Replace moves it from ' + '${prettyPath(folder)} to ~/AppImages,'} in place of the older ' + 'one.', + ), + actions: [ + ShadButton.outline( + enabled: !_replacing, + onPressed: _replacing ? null : () => Navigator.of(context).pop(false), + child: const Text('Not now'), + ), + ShadButton( + enabled: !_replacing, + onPressed: _replacing ? null : _replace, + child: Text(_replacing ? 'Replacing…' : 'Replace'), + ), + ], + child: DialogBody( + child: switch (_error) { + final error? => ErrorBanner(message: error), + null => null, + }, + ), + ); + } +} + +/// This copy is older than the one App Studio added to the app menu: says +/// so, and offers to open that one instead. Pops true to open it. Replacing +/// the newer copy with this one is not offered: a downgrade is too easy to +/// click by accident. +class OlderCopyDialog extends StatelessWidget { + const OlderCopyDialog({ + super.key, + required this.running, + required this.added, + }); + + final AppVersion running; + final AppVersion added; + + @override + Widget build(BuildContext context) { + final running = copyVersionLabel(this.running, this.added); + final added = copyVersionLabel(this.added, this.running); + return ShadDialog.alert( + title: const Text('A newer App Studio is in your app menu'), + description: Text( + 'This copy is App Studio $running. Your app menu has $added.', + ), + actions: [ + ShadButton.outline( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Keep using this one'), + ), + ShadButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text('Open $added'), + ), + ], + child: const DialogBody(), + ); + } +} diff --git a/lib/ui/desktop_integration_commands.dart b/lib/ui/desktop_integration_commands.dart new file mode 100644 index 0000000..0dd8da9 --- /dev/null +++ b/lib/ui/desktop_integration_commands.dart @@ -0,0 +1,235 @@ +import 'dart:ui' show AppExitType; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:shad/shad.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../platform/host.dart'; +import '../platform/linux/desktop_integration.dart'; +import '../widgets/app_dialog.dart'; +import 'add_to_applications_dialog.dart'; + +/// Set by "Don't ask again", and by Remove from Applications. +const kAddToApplicationsDeclinedKey = 'linux.add_to_applications_declined'; + +/// Asks [maybeOfferAddToApplications] at most once per run, and only on +/// Linux. The app calls [offerOnce] from two places, the first start page +/// and the end of setup, and whichever comes first asks. +class AddToApplicationsOffer { + AddToApplicationsOffer(this.integration, {HostPlatform? host}) + : host = host ?? currentHost; + + final DesktopIntegrationController integration; + final HostPlatform host; + bool _offered = false; + + Future offerOnce( + BuildContext context, { + required bool Function() onStartPage, + }) async { + if (!host.isLinux || _offered) return; + _offered = true; + await maybeOfferAddToApplications( + context, + integration, + onStartPage: onStartPage, + ); + } +} + +/// The question on start, once the start page shows: when App Studio runs as +/// an AppImage nobody has added to the app menu yet, whether to add it, +/// unless the user said not to ask again. When App Studio added another copy, +/// whether to replace that one (this one is newer) or open it (it is). +/// +/// [onStartPage] is checked again right before a dialog goes up: the checks +/// read the disk, and a project opened meanwhile must not get the question +/// over it. [quit] is File → Quit's teardown and exit, replaceable in tests. +Future maybeOfferAddToApplications( + BuildContext context, + DesktopIntegrationController integration, { + required bool Function() onStartPage, + @visibleForTesting Future Function()? quit, +}) async { + await integration.refresh(); + if (integration.status == DesktopIntegrationStatus.addedByAppStudio) { + if (context.mounted) { + await _offerForOtherCopy( + context, + integration, + onStartPage: onStartPage, + quit: quit ?? _quit, + ); + } + return; + } + if (integration.status != DesktopIntegrationStatus.notAdded) return; + final prefs = await SharedPreferences.getInstance(); + if (prefs.getBool(kAddToApplicationsDeclinedKey) ?? false) return; + final folder = await integration.integration.currentFolder(); + final replaced = await integration.integration.replacesAnotherFile() + ? integration.integration.addedAppImagePath + : null; + if (!context.mounted || !onStartPage()) return; + final answer = await _showAddDialog( + context, + integration, + fromMenu: false, + currentFolder: folder, + replacedFile: replaced, + ); + if (answer == AddToApplicationsAnswer.never) { + await prefs.setBool(kAddToApplicationsDeclinedKey, true); + } +} + +/// Help → Add to Applications. +Future addToApplications( + BuildContext context, + DesktopIntegrationController integration, +) async { + await integration.refresh(); + if (integration.status != DesktopIntegrationStatus.notAdded) return; + final folder = await integration.integration.currentFolder(); + final replaced = await integration.integration.replacesAnotherFile() + ? integration.integration.addedAppImagePath + : null; + if (!context.mounted) return; + await _showAddDialog( + context, + integration, + fromMenu: true, + currentFolder: folder, + replacedFile: replaced, + ); +} + +Future _showAddDialog( + BuildContext context, + DesktopIntegrationController integration, { + required bool fromMenu, + required String? currentFolder, + required String? replacedFile, +}) async { + final answer = await showAppDialog( + context: context, + // Not now is the way out; a stray click beside the dialog must not throw + // away a ticked "Don't ask again", nor close it while Add runs. + barrierDismissible: false, + builder: (context) => AddToApplicationsDialog( + onAdd: integration.add, + currentFolder: currentFolder, + replacedFile: replacedFile, + offerDontAskAgain: !fromMenu, + ), + ); + if (answer == AddToApplicationsAnswer.added && context.mounted) { + ShadToaster.maybeOf( + context, + )?.show(const ShadToast(title: Text('Added to your applications'))); + } + return answer; +} + +/// Help → Remove from Applications. +Future removeFromApplications( + BuildContext context, + DesktopIntegrationController integration, +) async { + await integration.refresh(); + final appImage = integration.integration.addedAppImagePath; + if (integration.status != DesktopIntegrationStatus.addedByAppStudio || + appImage == null || + !context.mounted) { + return; + } + final confirmed = await showAppDialog( + context: context, + builder: (context) => RemoveFromApplicationsDialog(appImagePath: appImage), + ); + if (confirmed != true || !context.mounted) return; + final toaster = ShadToaster.maybeOf(context); + // Before the removal, so a removal that fails halfway — the entry gone, an + // icon left — still does not ask again on the next start. + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(kAddToApplicationsDeclinedKey, true); + try { + await integration.remove(); + } catch (e) { + toaster?.show( + ShadToast.destructive( + title: const Text('Could not remove App Studio from your applications'), + description: Text('$e'), + ), + ); + return; + } + toaster?.show(const ShadToast(title: Text('Removed from your applications'))); +} + +/// No "Don't ask again" here: the question is about this one file, and only +/// comes up when the user starts a second copy by hand. +Future _offerForOtherCopy( + BuildContext context, + DesktopIntegrationController integration, { + required bool Function() onStartPage, + required Future Function() quit, +}) async { + final desktop = integration.integration; + final copy = await desktop.otherCopy(); + final folder = await desktop.currentFolder(); + if (copy == null || !context.mounted || !onStartPage()) return; + final toaster = ShadToaster.maybeOf(context); + + if (copy.runningIsNewer) { + final replaced = await showAppDialog( + context: context, + barrierDismissible: false, + builder: (context) => ReplaceAddedCopyDialog( + running: copy.running, + added: copy.added, + onReplace: integration.add, + currentFolder: folder, + ), + ); + if (replaced == true) { + toaster?.show( + ShadToast( + title: Text( + 'App Studio ${copyVersionLabel(copy.running, copy.added)} ' + 'is in your applications', + ), + ), + ); + } + return; + } + + if (copy.runningIsOlder) { + final open = await showAppDialog( + context: context, + builder: (context) => + OlderCopyDialog(running: copy.running, added: copy.added), + ); + if (open != true) return; + try { + await desktop.openAddedCopyAfterExit(); + } catch (e) { + toaster?.show( + ShadToast.destructive( + title: const Text('Could not open the newer App Studio'), + description: Text('$e'), + ), + ); + return; + } + // The newer copy starts once this process is gone. + await quit(); + } +} + +/// The same quit as File → Quit, teardown included. +Future _quit() async { + await ServicesBinding.instance.exitApplication(AppExitType.cancelable); +} diff --git a/specs/linux_appimage.md b/specs/linux_appimage.md index 9c6e29e..21f6159 100644 --- a/specs/linux_appimage.md +++ b/specs/linux_appimage.md @@ -70,7 +70,8 @@ whenever a question or the Help menu needs it: there, so an entry written under it never reaches the desktop. 2. **In the app menu** means a desktop entry, in `$XDG_DATA_HOME/applications` (default `~/.local/share/applications`) or an `applications` folder under - `$XDG_DATA_DIRS`, sub-folders included, that is called + `$XDG_DATA_DIRS`, sub-folders included (one that cannot be read is + skipped), that is called `dev.serverpod.appstudio.desktop` or names `StartupWMClass=dev.serverpod.appstudio`. Gear Lever, AppImageLauncher and appimaged name their entries after the app or a hash, but keep the @@ -112,7 +113,11 @@ App Studio will appear in your app menu, and the file moves from The sentence about the file names the folder it is in now. It is left out when the file is in `~/AppImages` already (where Add at most renames it to the -fixed name), and when an earlier Add in the same run already moved it. +fixed name), and when an earlier Add in the same run already moved it. When +another file is at `~/AppImages/AppStudio-x86_64.AppImage` already (a copy +left there by Remove, or whose entry was deleted by hand), the question adds +"It replaces the App Studio already at ~/AppImages/AppStudio-x86_64.AppImage.", +since that copy may be newer. **Not now** asks again on the next start; with the box ticked it never asks again on start. @@ -196,7 +201,9 @@ marker, and rebuilds the icon cache as Add does. The AppImage stays where it is. Removing sets "Don't ask again" first (the user just said no), so a removal that fails halfway does not bring the question back either. A toast says "Removed from your applications", or, on failure, "Could not remove App -Studio from your applications" with the reason. +Studio from your applications" with the reason. Finding no entry of App +Studio's to remove is a failure too: another tool may have rewritten it since +the Help menu last looked. ### Another copy than the one in the app menu @@ -222,8 +229,11 @@ number, which orders releases: everything above applies: the file is renamed over the old one, and the entry is rewritten with the new version. Once the move has happened the older copy is gone; if a later step fails, the existing entry and icons - stay, and the entry points at the new file while still naming the old - version. A toast says "App Studio 0.4.2 is in your applications". + stay and point at the new file. The entry then no longer records a + version: the one it named is gone, and compared with the next download it + could offer to replace a newer copy with an older one. Until an Add writes + the entry again, no copy is compared with it. A toast says "App Studio + 0.4.2 is in your applications". - **This copy is older:** ```text @@ -287,6 +297,8 @@ instance of it. Both are left as they are. `DesktopIntegrationController`, the state the menu strip listens to. - `lib/platform/linux/app_version.dart`: a version and build, and how two copies compare; free of `dart:io`. +- `lib/platform/linux/desktop_integration_status.dart`: the four states, + free of `dart:io` so the menu strip can read them. - `lib/ui/add_to_applications_dialog.dart`: the dialogs, free of `dart:io` so Widgetbook shows them. - `lib/ui/desktop_integration_commands.dart`: what the question and the Help @@ -360,25 +372,31 @@ If you use Gear Lever, open the file with it and choose ## E. Uninstall (PR 5) App Studio's uninstall on Linux, in PR 5, runs the same removal as Remove -from Applications. Whether it also deletes the AppImage itself is decided +from Applications, and counts "not in your app menu" as done: Remove reports +it as a failure, which is right for the Help item but not for an uninstall +on a machine where nothing was ever added. Whether it also deletes the AppImage itself is decided there. ## Testing - **Unit tests on every host** through `HostPlatform.linux` (`test/platform/linux/desktop_integration_test.dart`): each condition of - of the four states (inherited variables, a portable AppImage, entries in - sub-folders, a deleted `TryExec`), the entry it writes (including an - `Exec` path that needs quoting), a move within and across file systems and - out of a folder the file cannot leave, a failed step undoing only what it - created, a retry after the move, Remove leaving an entry without the marker - alone, and how another copy compares (newer, older, the same, no recorded - version). The dialogs and the Help items have widget tests, and + the four states (inherited variables, a portable AppImage, entries in + sub-folders, an unreadable sub-folder, a deleted `TryExec`), the entry it + writes (including an `Exec` path that needs quoting), a move within and + across file systems and out of a folder the file cannot leave, a Replace + across file systems, a failed step undoing only what it created, a retry + after the move, a failed Replace dropping the recorded version, Remove + leaving an entry without the marker alone and saying so, how another copy + compares (newer, older, the same, no recorded version), and Open starting + the added copy only once the given process has ended. The dialogs and the + Help items have widget tests, and `test/ui/desktop_integration_commands_test.dart` pins the preference both - ways: "Don't ask again" and Remove set it, Not now, Add and a cancelled - Remove do not. + ways ("Don't ask again" and Remove set it, Not now, Add and a cancelled + Remove do not), the question asked once per run and only on Linux, and + Open quitting this copy only when the newer one could be started. - **Widgetbook:** the question (from Downloads, already in `~/AppImages`, - from the Help menu), another copy (newer, older) and the Remove + replacing a copy left there, from the Help menu), another copy (newer, older) and the Remove confirmation. - **Ubuntu VM from `clean-install`:** - without Gear Lever: download in Firefox, allow it to run, start; after diff --git a/test/platform/linux/desktop_integration_test.dart b/test/platform/linux/desktop_integration_test.dart new file mode 100644 index 0000000..106cd43 --- /dev/null +++ b/test/platform/linux/desktop_integration_test.dart @@ -0,0 +1,825 @@ +import 'dart:io'; + +import 'package:appstudio/platform/host_platform.dart'; +import 'package:appstudio/platform/linux/desktop_integration.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +/// Add to Applications, against a home folder in a temporary directory, so +/// it runs on any host. +void main() { + late Directory root; + late String home; + late String appDir; + late String appImage; + late Map env; + late AppVersion running; + + const sourceEntry = ''' +[Desktop Entry] +Type=Application +Name=App Studio +Exec=appstudio +Icon=dev.serverpod.appstudio +StartupWMClass=dev.serverpod.appstudio +X-AppImage-Version=0.4.1 + +[Desktop Action Extra] +Name=Extra +Exec=appstudio --extra +'''; + + setUp(() async { + running = const AppVersion('0.4.1', 25); + root = await Directory.systemTemp.createTemp('desktop_integration'); + home = p.join(root.path, 'home'); + appDir = p.join(root.path, 'mount'); + appImage = p.join(home, 'Downloads', 'AppStudio-0.4.1-x86_64.AppImage'); + await File(appImage).create(recursive: true); + await File(appImage).writeAsString('the image'); + for (final size in ['16x16', '256x256']) { + final icon = File( + p.join( + appDir, + 'usr', + 'share', + 'icons', + 'hicolor', + size, + 'apps', + 'dev.serverpod.appstudio.png', + ), + ); + await icon.create(recursive: true); + await icon.writeAsString('icon $size'); + } + final entry = File( + p.join( + appDir, + 'usr', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ), + ); + await entry.create(recursive: true); + await entry.writeAsString(sourceEntry); + env = { + 'HOME': home, + 'APPIMAGE': appImage, + 'APPDIR': appDir, + // No system folders: the machine running the tests may have its own. + 'XDG_DATA_DIRS': p.join(root.path, 'system'), + }; + }); + + tearDown(() => root.delete(recursive: true)); + + DesktopIntegration integration([ + Map? extra, + String? executable, + ]) => DesktopIntegration( + environment: {...env, ...?extra}, + host: HostPlatform.linux, + runningVersion: () async => running, + executable: + executable ?? p.join(appDir, 'usr', 'lib', 'appstudio', 'appstudio'), + ); + + String icon(String size) => p.join( + home, + '.local', + 'share', + 'icons', + 'hicolor', + size, + 'apps', + 'dev.serverpod.appstudio.png', + ); + + String entryPath() => p.join( + home, + '.local', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ); + String target() => p.join(home, 'AppImages', 'AppStudio-x86_64.AppImage'); + + Future writeEntry(String folder, String name, String contents) async { + final file = File(p.join(folder, name)); + await file.create(recursive: true); + await file.writeAsString(contents); + } + + group('status', () { + test('an AppImage nobody added is not added', () async { + expect(await integration().status(), DesktopIntegrationStatus.notAdded); + }); + + test('there is nothing to add outside an AppImage', () async { + final noImage = DesktopIntegration( + environment: {'HOME': home}, + host: HostPlatform.linux, + ); + expect(await noImage.status(), DesktopIntegrationStatus.unavailable); + }); + + test('there is nothing to add on another OS', () async { + final mac = DesktopIntegration( + environment: env, + host: HostPlatform.macos, + ); + expect(await mac.status(), DesktopIntegrationStatus.unavailable); + }); + + test('an installed tool that did not add it does not count', () async { + // AppImageLauncher's "Run once" sets this without adding anything. + await File( + p.join( + home, + '.local', + 'lib', + 'appimagelauncher-lite', + 'appimagelauncher-lite.AppImage', + ), + ).create(recursive: true); + expect( + await integration({'DESKTOPINTEGRATION': 'AppImageLauncher'}).status(), + DesktopIntegrationStatus.notAdded, + ); + }); + + test( + 'an entry with App Studio\'s window class is another tool\'s', + () async { + await writeEntry( + p.join(home, '.local', 'share', 'applications'), + 'appimagekit_0123abcd-App_Studio.desktop', + '[Desktop Entry]\nName=App Studio\n' + 'StartupWMClass=dev.serverpod.appstudio\n', + ); + expect( + await integration().status(), + DesktopIntegrationStatus.managedByOther, + ); + }, + ); + + test( + 'an unmarked entry under the application id is another tool\'s', + () async { + await writeEntry( + p.join(home, '.local', 'share', 'applications'), + 'dev.serverpod.appstudio.desktop', + '[Desktop Entry]\nName=App Studio\nExec=/opt/appstudio\n', + ); + expect( + await integration().status(), + DesktopIntegrationStatus.managedByOther, + ); + }, + ); + + test('a system entry counts too', () async { + await writeEntry( + p.join(root.path, 'system', 'applications'), + 'dev.serverpod.appstudio.desktop', + '[Desktop Entry]\nName=App Studio\n', + ); + expect( + await integration().status(), + DesktopIntegrationStatus.managedByOther, + ); + }); + + test('a window class in another group does not count', () async { + await writeEntry( + p.join(home, '.local', 'share', 'applications'), + 'other.desktop', + '[Desktop Entry]\nName=Other\n\n[Desktop Action A]\n' + 'StartupWMClass=dev.serverpod.appstudio\n', + ); + expect(await integration().status(), DesktopIntegrationStatus.notAdded); + }); + + test('App Studio\'s entry for a deleted AppImage does not count', () async { + await integration().add(); + await File(target()).delete(); + expect(await integration().status(), DesktopIntegrationStatus.notAdded); + }); + }); + + group('status, an unreadable folder', () { + test( + 'does not hide an entry beside it', + () async { + final uid = await Process.run('id', ['-u']); + if ('${uid.stdout}'.trim() == '0') { + markTestSkipped('root can read any folder'); + return; + } + final applications = p.join(root.path, 'system', 'applications'); + // The listing order is the file system's, so the entry sits among + // locked folders, created before and after it: whichever order the + // file system lists in, a locked one comes first (unless the entry + // happens to, when the test proves nothing but cannot fail wrongly). + Future lock(String name) async { + final folder = p.join(applications, name); + await Directory(folder).create(recursive: true); + await Process.run('chmod', ['000', folder]); + addTearDown(() => Process.run('chmod', ['755', folder])); + } + + for (var i = 0; i < 10; i++) { + await lock('a-locked-$i'); + } + await writeEntry( + p.join(applications, 'm-readable'), + 'gearlever_appstudio.desktop', + '[Desktop Entry]\nStartupWMClass=dev.serverpod.appstudio\n', + ); + for (var i = 0; i < 10; i++) { + await lock('z-locked-$i'); + } + + expect( + await integration().status(), + DesktopIntegrationStatus.managedByOther, + ); + }, + tags: 'process', + testOn: '!windows', + ); + }); + + group('status, beside other tools', () { + test('a portable AppImage has nothing to add', () async { + await Directory('$appImage.home').create(); + expect( + await integration().status(), + DesktopIntegrationStatus.unavailable, + ); + }); + + test( + 'another tool\'s entry for a deleted AppImage does not count', + () async { + await writeEntry( + p.join(home, '.local', 'share', 'applications'), + 'app_studio.desktop', + '[Desktop Entry]\nName=App Studio\n' + 'TryExec=${p.join(home, 'AppImages', 'app_studio.appimage')}\n' + 'StartupWMClass=dev.serverpod.appstudio\n', + ); + expect(await integration().status(), DesktopIntegrationStatus.notAdded); + }, + ); + + test('the question names no folder for a file in ~/AppImages', () async { + final inFolder = p.join(home, 'AppImages', 'AppStudio-0.4.1.AppImage'); + await File(inFolder).create(recursive: true); + expect(await integration({'APPIMAGE': inFolder}).currentFolder(), isNull); + expect(await integration().currentFolder(), p.join(home, 'Downloads')); + }); + + test('nor for a file an earlier Add moved', () async { + await integration().add(); + expect(await integration().currentFolder(), isNull); + }); + + test('variables inherited from another AppImage do not count', () async { + // A development build started from a terminal inside an AppImage + // editor: the variables are that one's, the executable is not in it. + expect( + await integration(null, '/home/dev/appstudio/build/appstudio').status(), + DesktopIntegrationStatus.unavailable, + ); + }); + + test('an entry in a sub-folder of applications counts', () async { + await writeEntry( + p.join(home, '.local', 'share', 'applications', 'kde4'), + 'appstudio.desktop', + '[Desktop Entry]\nStartupWMClass=dev.serverpod.appstudio\n', + ); + expect( + await integration().status(), + DesktopIntegrationStatus.managedByOther, + ); + }); + }); + + group('add', () { + test('moves the AppImage, copies the icons and writes the entry', () async { + await integration().add(); + + expect(await File(appImage).exists(), isFalse); + expect(await File(target()).readAsString(), 'the image'); + for (final size in ['16x16', '256x256']) { + expect( + await File( + p.join( + home, + '.local', + 'share', + 'icons', + 'hicolor', + size, + 'apps', + 'dev.serverpod.appstudio.png', + ), + ).readAsString(), + 'icon $size', + ); + } + final entry = parseDesktopEntry(await File(entryPath()).readAsString()); + expect(entry['Exec'], '"${target()}"'); + expect(entry['TryExec'], target()); + expect(entry[kAddedByKey], kAddedByValue); + expect(entry['StartupWMClass'], 'dev.serverpod.appstudio'); + expect( + await integration().status(), + DesktopIntegrationStatus.addedByAppStudio, + ); + }); + + test('leaves an AppImage already in place where it is', () async { + await File(target()).create(recursive: true); + await File(target()).writeAsString('in place'); + await integration({'APPIMAGE': target()}).add(); + + expect(await File(target()).readAsString(), 'in place'); + expect( + await integration({'APPIMAGE': target()}).status(), + DesktopIntegrationStatus.addedByAppStudio, + ); + }); + + test('replaces an older AppImage at the target', () async { + await File(target()).create(recursive: true); + await File(target()).writeAsString('older'); + await integration().add(); + + expect(await File(target()).readAsString(), 'the image'); + }); + + test('honours XDG_DATA_HOME', () async { + final dataHome = p.join(root.path, 'data'); + await integration({'XDG_DATA_HOME': dataHome}).add(); + + expect( + await File( + p.join(dataHome, 'applications', 'dev.serverpod.appstudio.desktop'), + ).exists(), + isTrue, + ); + }); + + test('a failed step undoes the ones before it and says which', () async { + await File( + p.join( + appDir, + 'usr', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ), + ).delete(); + + await expectLater( + integration().add(), + throwsA( + isA().having( + (e) => e.step, + 'step', + 'Writing the app menu entry', + ), + ), + ); + expect( + await Directory( + p.join(home, '.local', 'share', 'icons', 'hicolor'), + ).list(recursive: true).where((e) => e is File).isEmpty, + isTrue, + ); + expect(await File(entryPath()).exists(), isFalse); + }); + + test('a retry after a failed step finds the file it moved', () async { + final entry = File( + p.join( + appDir, + 'usr', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ), + ); + await entry.rename('${entry.path}.away'); + + await expectLater( + integration().add(), + throwsA( + isA().having( + (e) => e.reason, + 'reason', + contains('now at ~/AppImages/AppStudio-x86_64.AppImage'), + ), + ), + ); + expect(await File(target()).exists(), isTrue); + + await File('${entry.path}.away').rename(entry.path); + await integration().add(); + expect( + await integration().status(), + DesktopIntegrationStatus.addedByAppStudio, + ); + }); + + test( + 'copies out of a folder it cannot take the file from', + () async { + final uid = await Process.run('id', ['-u']); + if ('${uid.stdout}'.trim() == '0') { + markTestSkipped('root can take files out of any folder'); + return; + } + final folder = p.dirname(appImage); + await Process.run('chmod', ['555', folder]); + addTearDown(() => Process.run('chmod', ['755', folder])); + + await integration().add(); + + expect(await File(target()).readAsString(), 'the image'); + expect(await File(appImage).exists(), isTrue, reason: 'it stays'); + }, + tags: 'process', + testOn: 'linux', + ); + + test( + 'moves across file systems', + () async { + // /dev/shm is its own tmpfs on Linux, apart from the temp folder. + final shm = Directory('/dev/shm'); + if (!await shm.exists() || + (await shm.stat()).type != FileSystemEntityType.directory) { + markTestSkipped('needs /dev/shm'); + return; + } + final elsewhere = await shm.createTemp('desktop_integration'); + addTearDown(() => elsewhere.delete(recursive: true)); + final source = p.join(elsewhere.path, 'AppStudio.AppImage'); + await File(source).writeAsString('from afar'); + + await integration({'APPIMAGE': source}).add(); + + expect(await File(source).exists(), isFalse); + expect(await File(target()).readAsString(), 'from afar'); + expect((await File(target()).stat()).modeString(), 'rwxr-xr-x'); + }, + tags: 'process', + testOn: 'linux', + ); + }); + + group('a file already at the target', () { + test('is named when Add would replace it', () async { + await File(target()).create(recursive: true); + expect(await integration().replacesAnotherFile(), isTrue); + }); + + test('is not there on a first Add', () async { + expect(await integration().replacesAnotherFile(), isFalse); + }); + + test('is this copy itself once it was added', () async { + await integration().add(); + // After its own Add, `$APPIMAGE` names where it was. + expect(await integration().replacesAnotherFile(), isFalse); + expect( + await integration({'APPIMAGE': target()}).replacesAnotherFile(), + isFalse, + ); + }); + + test( + 'is replaced across file systems', + () async { + final shm = Directory('/dev/shm'); + if (!await shm.exists()) { + markTestSkipped('needs /dev/shm'); + return; + } + await File(target()).create(recursive: true); + await File(target()).writeAsString('the older one'); + final elsewhere = await shm.createTemp('desktop_integration'); + addTearDown(() => elsewhere.delete(recursive: true)); + final source = p.join(elsewhere.path, 'AppStudio.AppImage'); + await File(source).writeAsString('the newer one'); + + await integration({'APPIMAGE': source}).add(); + + expect(await File(source).exists(), isFalse); + expect(await File(target()).readAsString(), 'the newer one'); + final folder = Directory(p.dirname(target())); + expect(await folder.list().map((f) => p.basename(f.path)).toList(), [ + p.basename(target()), + ], reason: 'no temporary file left behind'); + }, + tags: 'process', + testOn: 'linux', + ); + }); + + group('another copy', () { + /// Adds a 0.4.1 (build 25), then downloads [version] to ~/Downloads and + /// returns an integration for it. + Future downloadAnother(AppVersion version) async { + await integration().add(); + await File(appImage).writeAsString('another download'); + running = version; + return integration(); + } + + test('the added copy itself is not another copy', () async { + await integration().add(); + expect(await integration({'APPIMAGE': target()}).otherCopy(), isNull); + // After its own Add, `$APPIMAGE` names where it was. + expect(await integration().otherCopy(), isNull); + }); + + test('a newer download is newer', () async { + final newer = await downloadAnother(const AppVersion('0.4.2', 26)); + final copy = (await newer.otherCopy())!; + + expect(copy.running, const AppVersion('0.4.2', 26)); + expect(copy.added, const AppVersion('0.4.1', 25)); + expect(copy.runningIsNewer, isTrue); + }); + + test('an older download is older', () async { + final older = await downloadAnother(const AppVersion('0.4.0', 24)); + expect((await older.otherCopy())!.runningIsOlder, isTrue); + }); + + test('the same build is neither', () async { + final same = await downloadAnother(const AppVersion('0.4.1', 25)); + final copy = (await same.otherCopy())!; + expect(copy.runningIsNewer || copy.runningIsOlder, isFalse); + }); + + test('replacing puts the newer copy in place and records it', () async { + final newer = await downloadAnother(const AppVersion('0.4.2', 26)); + await newer.add(); + + expect(await File(target()).readAsString(), 'another download'); + final entry = parseDesktopEntry(await File(entryPath()).readAsString()); + expect(entry[kAddedVersionKey], '0.4.2'); + expect(entry[kAddedBuildKey], '26'); + }); + + test('nothing is said without a recorded version', () async { + running = const AppVersion('0.4.1', 25); + await integration().add(); + final entry = File(entryPath()); + await entry.writeAsString( + (await entry.readAsString()) + .split('\n') + .where((l) => !l.startsWith('X-AppStudio-Build=')) + .join('\n'), + ); + await File(appImage).writeAsString('another download'); + running = const AppVersion('0.4.2', 26); + + expect(await integration().otherCopy(), isNull); + }); + }); + + group('a failed Replace', () { + test('keeps the icons and entry the older copy had', () async { + await integration().add(); + final before = await File(entryPath()).readAsString(); + // A newer download whose mount has no entry: step 3 fails. + await File(appImage).writeAsString('another download'); + await File( + p.join( + appDir, + 'usr', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ), + ).delete(); + + await expectLater( + integration().add(), + throwsA(isA()), + ); + expect(await File(icon('256x256')).exists(), isTrue); + // The entry stays, but no longer claims the build the file had. + final after = await File(entryPath()).readAsString(); + expect( + after, + before + .split('\n') + .where((l) => !l.startsWith('X-AppStudio-Version=')) + .where((l) => !l.startsWith('X-AppStudio-Build=')) + .join('\n'), + ); + expect(parseDesktopEntry(after)[kAddedByKey], kAddedByValue); + }); + + test('never offers to replace a newer file with an older one', () async { + // The entry records 0.4.0 while the file is 0.4.2 after a failed + // Replace. A 0.4.1 download must not be offered as newer. + running = const AppVersion('0.4.0', 20); + await integration().add(); + await File(appImage).writeAsString('0.4.2'); + running = const AppVersion('0.4.2', 26); + await File( + p.join( + appDir, + 'usr', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ), + ).delete(); + await expectLater( + integration().add(), + throwsA(isA()), + ); + + await File(appImage).writeAsString('0.4.1'); + running = const AppVersion('0.4.1', 25); + expect(await integration().otherCopy(), isNull); + }); + }); + + group('open the added copy', () { + /// Puts a script at the target that writes [marker] when it runs. + Future scriptAtTarget() async { + final marker = p.join(root.path, 'started'); + await File(target()).create(recursive: true); + await File( + target(), + ).writeAsString('#!/bin/sh\necho started > "$marker"\n'); + await Process.run('chmod', ['755', target()]); + return marker; + } + + Future appears(String path, Duration within) async { + final end = DateTime.now().add(within); + while (DateTime.now().isBefore(end)) { + if (await File(path).exists()) return true; + await Future.delayed(const Duration(milliseconds: 50)); + } + return false; + } + + test( + 'starts it once this process has ended', + () async { + final marker = await scriptAtTarget(); + final ended = await Process.start('true', []); + await ended.exitCode; + + await integration().openAddedCopyAfterExit(afterPid: ended.pid); + + expect(await appears(marker, const Duration(seconds: 5)), isTrue); + }, + tags: 'process', + testOn: '!windows', + ); + + test( + 'waits while this process runs', + () async { + final marker = await scriptAtTarget(); + final running = await Process.start('sleep', ['30']); + addTearDown(running.kill); + + await integration().openAddedCopyAfterExit(afterPid: running.pid); + + expect( + await appears(marker, const Duration(milliseconds: 800)), + isFalse, + ); + running.kill(); + await running.exitCode; + expect(await appears(marker, const Duration(seconds: 5)), isTrue); + }, + tags: 'process', + testOn: '!windows', + ); + + test('refuses when the added file is gone', () async { + await expectLater( + integration().openAddedCopyAfterExit(), + throwsA(isA()), + ); + }); + }); + + group('remove', () { + test('removes the entry and icons, and leaves the AppImage', () async { + await integration().add(); + await integration().remove(); + + expect(await File(entryPath()).exists(), isFalse); + expect( + await File( + p.join( + home, + '.local', + 'share', + 'icons', + 'hicolor', + '256x256', + 'apps', + 'dev.serverpod.appstudio.png', + ), + ).exists(), + isFalse, + ); + expect(await File(target()).exists(), isTrue); + expect(await integration().status(), DesktopIntegrationStatus.notAdded); + }); + + test( + 'leaves an entry App Studio did not write alone, and says so', + () async { + const theirs = '[Desktop Entry]\nName=App Studio\nExec=/opt/x\n'; + await writeEntry( + p.dirname(entryPath()), + 'dev.serverpod.appstudio.desktop', + theirs, + ); + await expectLater( + integration().remove(), + throwsA(isA()), + ); + + expect(await File(entryPath()).readAsString(), theirs); + }, + ); + + test('says so when there is no entry to remove', () async { + await expectLater( + integration().remove(), + throwsA(isA()), + ); + }); + }); + + group('desktopEntryFor', () { + test('quotes the path as the Desktop Entry spec says', () { + final entry = desktopEntryFor( + sourceEntry, + appImagePath: r'/home/a b/$x`"%\y.AppImage', + ); + expect(entry, contains(r'Exec="/home/a b/\\$x\\`\\"%%\\\\y.AppImage"')); + expect(entry, contains(r'TryExec=/home/a b/$x`"%\\y.AppImage')); + }); + + test('replaces Exec in the main group only and keeps the rest', () { + final entry = desktopEntryFor(sourceEntry, appImagePath: '/a.AppImage'); + final lines = entry.split('\n'); + expect(lines.where((l) => l.startsWith('Exec=')), [ + 'Exec="/a.AppImage"', + 'Exec=appstudio --extra', + ]); + expect(entry, contains('X-AppImage-Version=0.4.1')); + expect(entry, contains('[Desktop Action Extra]')); + expect( + entry.indexOf('$kAddedByKey='), + lessThan(entry.indexOf('[Desktop Action Extra]')), + ); + }); + + test('records the version, replacing one already there', () { + final entry = desktopEntryFor( + sourceEntry.replaceFirst( + 'X-AppImage-Version=0.4.1', + 'X-AppImage-Version=0.4.1\n$kAddedBuildKey=1', + ), + appImagePath: '/a.AppImage', + version: const AppVersion('0.4.1', 25), + ); + expect(entry, contains('$kAddedVersionKey=0.4.1\n')); + expect(entry.split('\n').where((l) => l.startsWith('$kAddedBuildKey=')), [ + '$kAddedBuildKey=25', + ]); + }); + + test('refuses a path with a line break', () { + expect( + () => desktopEntryFor(sourceEntry, appImagePath: '/a\nb'), + throwsA(isA()), + ); + }); + }); +} diff --git a/test/platform/windows_app_menu_test.dart b/test/platform/windows_app_menu_test.dart index 1a5d6f2..8c4033f 100644 --- a/test/platform/windows_app_menu_test.dart +++ b/test/platform/windows_app_menu_test.dart @@ -1,5 +1,6 @@ import 'package:appstudio/agent/agent_controller.dart'; import 'package:appstudio/platform/host_platform.dart'; +import 'package:appstudio/platform/linux/desktop_integration.dart'; import 'package:appstudio/platform/windows_app_menu.dart'; import 'package:appstudio/process/serverpod_process.dart'; import 'package:appstudio/session/project_session.dart'; @@ -52,6 +53,7 @@ void main() { bool Function()? stripHidden, Widget child = const SizedBox.expand(), HostPlatform host = HostPlatform.windows, + DesktopIntegrationStatus? desktopIntegration, }) async { await tester.pumpWidget( ShadApp( @@ -75,6 +77,10 @@ void main() { changes: changes ?? ChangeNotifier(), stripHidden: stripHidden, host: host, + desktopIntegrationStatus: + desktopIntegration == null ? null : () => desktopIntegration, + onAddToApplications: () {}, + onRemoveFromApplications: () {}, child: child, ), ), @@ -217,6 +223,66 @@ void main() { expect(find.text('Uninstall App Studio...'), findsNothing); }); + testWidgets('Linux offers Add to Applications for an AppImage nobody added', + (tester) async { + await pumpMenu( + tester, + host: HostPlatform.linux, + desktopIntegration: DesktopIntegrationStatus.notAdded, + ); + + await openMenu(tester, 'Help'); + + expect(find.text('Add to Applications...'), findsOneWidget); + expect(find.text('Remove from Applications...'), findsNothing); + }); + + testWidgets('Linux offers Remove from Applications once App Studio added it', + (tester) async { + await pumpMenu( + tester, + host: HostPlatform.linux, + desktopIntegration: DesktopIntegrationStatus.addedByAppStudio, + ); + + await openMenu(tester, 'Help'); + + expect(find.text('Remove from Applications...'), findsOneWidget); + expect(find.text('Add to Applications...'), findsNothing); + }); + + testWidgets('neither item shows where another tool or no AppImage is', + (tester) async { + for (final status in [ + DesktopIntegrationStatus.managedByOther, + DesktopIntegrationStatus.unavailable, + ]) { + await pumpMenu( + tester, + host: HostPlatform.linux, + desktopIntegration: status, + ); + + await openMenu(tester, 'Help'); + + expect(find.text('Add to Applications...'), findsNothing); + expect(find.text('Remove from Applications...'), findsNothing); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + } + }); + + testWidgets('Windows never offers either item', (tester) async { + await pumpMenu( + tester, + desktopIntegration: DesktopIntegrationStatus.notAdded, + ); + + await openMenu(tester, 'Help'); + + expect(find.text('Add to Applications...'), findsNothing); + }); + testWidgets('Linux binds the same Ctrl shortcuts', (tester) async { await pumpMenu(tester, host: HostPlatform.linux); diff --git a/test/ui/add_to_applications_dialog_test.dart b/test/ui/add_to_applications_dialog_test.dart new file mode 100644 index 0000000..ea26895 --- /dev/null +++ b/test/ui/add_to_applications_dialog_test.dart @@ -0,0 +1,186 @@ +import 'package:appstudio/platform/linux/app_version.dart'; +import 'package:appstudio/ui/add_to_applications_dialog.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shad/shad.dart'; + +void main() { + /// Opens the dialog over a page. The returned function gives what it + /// popped, and fails while it is still open. + Future open( + WidgetTester tester, { + required Future Function() onAdd, + String? currentFolder = '/home/alex/Downloads', + bool offerDontAskAgain = true, + }) async { + AddToApplicationsAnswer? answer; + var popped = false; + await tester.pumpWidget( + ShadApp( + home: Builder( + builder: (context) => ShadButton( + onPressed: () async { + answer = await showShadDialog( + context: context, + builder: (_) => AddToApplicationsDialog( + onAdd: onAdd, + currentFolder: currentFolder, + offerDontAskAgain: offerDontAskAgain, + ), + ); + popped = true; + }, + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + return () { + expect(popped, isTrue, reason: 'the dialog is still open'); + return answer; + }; + } + + testWidgets('Add runs, closes and answers added', (tester) async { + var added = 0; + final result = await open(tester, onAdd: () async => added++); + + expect( + find.textContaining('from /home/alex/Downloads to ~/AppImages'), + findsOneWidget, + ); + await tester.tap(find.text('Add')); + await tester.pumpAndSettle(); + + expect(added, 1); + expect(result(), AddToApplicationsAnswer.added); + }); + + testWidgets('a failed Add stays open with the error', (tester) async { + await open( + tester, + onAdd: () async => throw Exception('Copying the icons failed: denied'), + ); + + await tester.tap(find.text('Add')); + await tester.pumpAndSettle(); + + expect( + find.textContaining('Copying the icons failed: denied'), + findsOneWidget, + ); + expect(find.text('Add'), findsOneWidget); + }); + + testWidgets('Not now asks again; with the box ticked it never does', ( + tester, + ) async { + var result = await open(tester, onAdd: () async {}); + await tester.tap(find.text('Not now')); + await tester.pumpAndSettle(); + expect(result(), AddToApplicationsAnswer.notNow); + + result = await open(tester, onAdd: () async {}); + await tester.tap(find.text("Don't ask again")); + await tester.pump(); + await tester.tap(find.text('Not now')); + await tester.pumpAndSettle(); + expect(result(), AddToApplicationsAnswer.never); + }); + + testWidgets('from the menu it offers Cancel and no checkbox', (tester) async { + await open(tester, onAdd: () async {}, offerDontAskAgain: false); + + expect(find.text('Cancel'), findsOneWidget); + expect(find.text('Not now'), findsNothing); + expect(find.text("Don't ask again"), findsNothing); + }); + + testWidgets('a file already in place names no folder', (tester) async { + await open(tester, onAdd: () async {}, currentFolder: null); + + expect( + find.text('App Studio will appear in your app menu.'), + findsOneWidget, + ); + }); + + /// Shows [dialog] over a page; the function gives what it popped. + Future show(WidgetTester tester, Widget dialog) async { + Object? answer; + await tester.pumpWidget( + ShadApp( + home: Builder( + builder: (context) => ShadButton( + onPressed: () async { + answer = await showShadDialog( + context: context, + builder: (_) => dialog, + ); + }, + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + return () => answer; + } + + const older = AppVersion('0.4.1', 25); + const newer = AppVersion('0.4.2', 26); + + testWidgets('a newer copy offers to replace the older one', (tester) async { + var replaced = 0; + final result = await show( + tester, + ReplaceAddedCopyDialog( + running: newer, + added: older, + currentFolder: '/home/alex/Downloads', + onReplace: () async => replaced++, + ), + ); + + expect( + find.text('Replace App Studio 0.4.1 with this version?'), + findsOneWidget, + ); + expect( + find.textContaining('This copy is App Studio 0.4.2'), + findsOneWidget, + ); + await tester.tap(find.text('Replace')); + await tester.pumpAndSettle(); + + expect(replaced, 1); + expect(result(), isTrue); + }); + + testWidgets('an older copy offers to open the newer one', (tester) async { + final result = await show( + tester, + const OlderCopyDialog(running: older, added: newer), + ); + + expect( + find.text('This copy is App Studio 0.4.1. Your app menu has 0.4.2.'), + findsOneWidget, + ); + await tester.tap(find.text('Open 0.4.2')); + await tester.pumpAndSettle(); + + expect(result(), isTrue); + }); + + test('the build tells two copies of one version apart', () { + expect(copyVersionLabel(newer, older), '0.4.2'); + expect( + copyVersionLabel(const AppVersion('0.4.1', 26), older), + '0.4.1 (build 26)', + ); + }); +} diff --git a/test/ui/desktop_integration_commands_test.dart b/test/ui/desktop_integration_commands_test.dart new file mode 100644 index 0000000..9939fe3 --- /dev/null +++ b/test/ui/desktop_integration_commands_test.dart @@ -0,0 +1,269 @@ +import 'dart:io'; + +import 'package:appstudio/platform/host_platform.dart'; +import 'package:appstudio/platform/linux/desktop_integration.dart'; +import 'package:appstudio/ui/desktop_integration_commands.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shad/shad.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// The preference behind "Don't ask again" is a one-way door, so both +/// directions are pinned: what sets it, and what must not. +void main() { + late _FakeIntegration desktop; + late DesktopIntegrationController controller; + + setUp(() { + SharedPreferences.setMockInitialValues({}); + desktop = _FakeIntegration(); + controller = DesktopIntegrationController(integration: desktop); + }); + + Future declined() async => (await SharedPreferences.getInstance()) + .getBool(kAddToApplicationsDeclinedKey); + + /// Pumps a page whose button runs [command] with the navigator's context. + Future run( + WidgetTester tester, + Future Function(BuildContext) command, + ) async { + await tester.pumpWidget( + ShadApp( + home: Builder( + builder: (context) => ShadButton( + onPressed: () => command(context), + child: const Text('go'), + ), + ), + ), + ); + await tester.tap(find.text('go')); + await tester.pumpAndSettle(); + } + + Future offer(WidgetTester tester, {bool onStartPage = true}) => run( + tester, + (context) => maybeOfferAddToApplications( + context, + controller, + onStartPage: () => onStartPage, + ), + ); + + testWidgets('Not now leaves the question for the next start', (tester) async { + await offer(tester); + await tester.tap(find.text('Not now')); + await tester.pumpAndSettle(); + + expect(await declined(), isNull); + }); + + testWidgets("Don't ask again stops the question", (tester) async { + await offer(tester); + await tester.tap(find.text("Don't ask again")); + await tester.pump(); + await tester.tap(find.text('Not now')); + await tester.pumpAndSettle(); + + expect(await declined(), isTrue); + }); + + testWidgets('Add does not write the preference', (tester) async { + await offer(tester); + await tester.tap(find.text('Add')); + await tester.pumpAndSettle(); + + expect(desktop.added, 1); + expect(await declined(), isNull); + }); + + testWidgets('a declined question is not asked', (tester) async { + SharedPreferences.setMockInitialValues({ + kAddToApplicationsDeclinedKey: true, + }); + await offer(tester); + + expect(find.text('Add'), findsNothing); + }); + + testWidgets('no question once a project is open', (tester) async { + await offer(tester, onStartPage: false); + + expect(find.text('Add'), findsNothing); + }); + + testWidgets('Remove stops the question, even when it fails halfway', ( + tester, + ) async { + desktop + ..current = DesktopIntegrationStatus.addedByAppStudio + ..removeFails = true; + await run(tester, (context) => removeFromApplications(context, controller)); + await tester.tap(find.text('Remove')); + await tester.pumpAndSettle(); + + expect(desktop.removed, 1); + expect(await declined(), isTrue); + }); + + testWidgets('a file already at the target is named', (tester) async { + desktop.replaces = true; + await offer(tester); + + expect( + find.textContaining( + 'It replaces the App Studio already at ' + '/home/alex/AppImages/AppStudio-x86_64.AppImage.', + ), + findsOneWidget, + ); + }); + + group('the newer copy in the app menu', () { + late int quits; + + setUp(() { + quits = 0; + desktop + ..current = DesktopIntegrationStatus.addedByAppStudio + ..copy = const OtherCopy( + running: AppVersion('0.4.0', 24), + added: AppVersion('0.4.1', 25), + ); + }); + + Future offerOlder(WidgetTester tester) => run( + tester, + (context) => maybeOfferAddToApplications( + context, + controller, + onStartPage: () => true, + quit: () async => quits++, + ), + ); + + testWidgets('Open starts it and quits this copy', (tester) async { + await offerOlder(tester); + await tester.tap(find.text('Open 0.4.1')); + await tester.pumpAndSettle(); + + expect(desktop.opened, 1); + expect(quits, 1); + }); + + testWidgets('Keep using this one does neither', (tester) async { + await offerOlder(tester); + await tester.tap(find.text('Keep using this one')); + await tester.pumpAndSettle(); + + expect(desktop.opened, 0); + expect(quits, 0); + }); + + testWidgets('a gone file is said, and nothing quits', (tester) async { + desktop.openFails = true; + await offerOlder(tester); + await tester.tap(find.text('Open 0.4.1')); + await tester.pumpAndSettle(); + + expect(find.text('Could not open the newer App Studio'), findsOneWidget); + expect(quits, 0); + }); + }); + + group('once per run', () { + Future offerOnce(WidgetTester tester, AddToApplicationsOffer offer) => + run( + tester, + (context) => offer.offerOnce(context, onStartPage: () => true), + ); + + testWidgets('asks the first time only', (tester) async { + final offer = AddToApplicationsOffer( + controller, + host: HostPlatform.linux, + ); + await offerOnce(tester, offer); + expect(find.text('Add'), findsOneWidget); + await tester.tap(find.text('Not now')); + await tester.pumpAndSettle(); + + await offerOnce(tester, offer); + expect(find.text('Add'), findsNothing); + }); + + testWidgets('never asks on another OS', (tester) async { + await offerOnce( + tester, + AddToApplicationsOffer(controller, host: HostPlatform.macos), + ); + expect(find.text('Add'), findsNothing); + }); + }); + + testWidgets('cancelling Remove leaves the preference alone', (tester) async { + desktop.current = DesktopIntegrationStatus.addedByAppStudio; + await run(tester, (context) => removeFromApplications(context, controller)); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(desktop.removed, 0); + expect(await declined(), isNull); + }); +} + +class _FakeIntegration extends DesktopIntegration { + _FakeIntegration() + : super( + environment: const {'HOME': '/home/alex'}, + host: HostPlatform.linux, + executable: '/x', + ); + + DesktopIntegrationStatus current = DesktopIntegrationStatus.notAdded; + bool removeFails = false; + bool replaces = false; + bool openFails = false; + OtherCopy? copy; + int added = 0; + int removed = 0; + int opened = 0; + + @override + Future status() async => current; + + @override + Future currentFolder() async => '/home/alex/Downloads'; + + /// Fixed, so the text the tests expect does not depend on the host's + /// path separator. + @override + String get addedAppImagePath => + '/home/alex/AppImages/AppStudio-x86_64.AppImage'; + + @override + Future replacesAnotherFile() async => replaces; + + @override + Future otherCopy() async => copy; + + @override + Future openAddedCopyAfterExit({int? afterPid}) async { + if (openFails) throw const FileSystemException('The AppImage is gone'); + opened++; + } + + @override + Future add() async { + added++; + current = DesktopIntegrationStatus.addedByAppStudio; + } + + @override + Future remove() async { + removed++; + if (removeFails) throw Exception('Removing the icons failed: denied'); + current = DesktopIntegrationStatus.notAdded; + } +} diff --git a/widgetbook/use_cases/start.dart b/widgetbook/use_cases/start.dart index 0ed79f6..dc9d630 100644 --- a/widgetbook/use_cases/start.dart +++ b/widgetbook/use_cases/start.dart @@ -1,5 +1,7 @@ +import 'package:appstudio/platform/linux/app_version.dart'; import 'package:appstudio/process/ide_integration.dart'; import 'package:appstudio/process/new_project_view.dart'; +import 'package:appstudio/ui/add_to_applications_dialog.dart'; import 'package:appstudio/ui/new_project_dialog.dart'; import 'package:appstudio/ui/start_page.dart'; import 'package:flutter/material.dart'; @@ -33,6 +35,13 @@ Widget _createProject( ), ); +/// A Linux dialog over the start page, where the question on first start +/// appears. +DialogUseCase _overStartPage(Widget dialog) => DialogUseCase( + backdrop: StartPage(session: FakeRecentProjects(), onNewProject: () {}), + dialog: dialog, + ); + final startFolder = WidgetbookFolder( name: 'Start', children: [ @@ -124,5 +133,82 @@ final startFolder = WidgetbookFolder( ), ], ), + WidgetbookComponent( + name: 'Add to Applications (Linux)', + useCases: [ + WidgetbookUseCase( + name: 'On first start', + builder: (_) => _overStartPage( + AddToApplicationsDialog( + onAdd: () async {}, + currentFolder: homePath('Downloads'), + ), + ), + ), + WidgetbookUseCase( + name: 'Already in ~/AppImages', + builder: (_) => + _overStartPage(AddToApplicationsDialog(onAdd: () async {})), + ), + WidgetbookUseCase( + name: 'Replacing a copy left in ~/AppImages', + builder: (_) => _overStartPage( + AddToApplicationsDialog( + onAdd: () async {}, + currentFolder: homePath('Downloads'), + replacedFile: homePath('AppImages/AppStudio-x86_64.AppImage'), + ), + ), + ), + WidgetbookUseCase( + name: 'From the Help menu', + builder: (_) => _overStartPage( + AddToApplicationsDialog( + onAdd: () async {}, + currentFolder: homePath('Downloads'), + offerDontAskAgain: false, + ), + ), + ), + ], + ), + WidgetbookComponent( + name: 'Another copy (Linux)', + useCases: [ + WidgetbookUseCase( + name: 'Newer than the one in the app menu', + builder: (_) => _overStartPage( + ReplaceAddedCopyDialog( + running: const AppVersion('0.4.2', 26), + added: const AppVersion('0.4.1', 25), + currentFolder: homePath('Downloads'), + onReplace: () async {}, + ), + ), + ), + WidgetbookUseCase( + name: 'Older than the one in the app menu', + builder: (_) => _overStartPage( + const OlderCopyDialog( + running: AppVersion('0.4.0', 24), + added: AppVersion('0.4.1', 25), + ), + ), + ), + ], + ), + WidgetbookComponent( + name: 'Remove from Applications (Linux)', + useCases: [ + WidgetbookUseCase( + name: 'Default', + builder: (_) => _overStartPage( + RemoveFromApplicationsDialog( + appImagePath: homePath('AppImages/AppStudio-x86_64.AppImage'), + ), + ), + ), + ], + ), ], ); From 9cd4e512fb04c6a07907e8e54d7475d868307fcd Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 12:45:31 +0100 Subject: [PATCH 21/32] feat: Updates the Linux AppImage from inside the app. macOS updates through Sparkle and Windows through WinSparkle; Linux had no updater, so Check for Updates stayed greyed out. App Studio now does the same job in Dart, with the same Sparkle appcast and the same rules: Help -> Check for Updates, and a daily check (on by default, over the start page only, so it never interrupts a running server). An update downloads beside the AppImage, is checked against its length and an Ed25519 signature, and is renamed over the running file. The running copy stays mounted, quits through the usual teardown, and the new file starts once it is gone. App Studio's menu entry records the new version. Feeds and downloads must be https; plain http is accepted only to this machine or a private address, for a local test feed. The feed URL and public key live in linux/release.json, as on Windows, and are empty until a feed exists: such a build reports updates as unavailable. build_appimage.sh compiles them in, and tool/linux/appcast.sh signs an AppImage and adds it to a feed. Adds cryptography for the signature check and makes xml a direct dependency. --- lib/main.dart | 69 ++- lib/platform/linux/app_version.dart | 7 + lib/platform/linux/desktop_integration.dart | 90 ++- lib/platform/linux/running_app_image.dart | 37 ++ lib/ui/add_to_applications_dialog.dart | 7 - lib/update/linux/appcast.dart | 116 ++++ lib/update/linux/linux_update_commands.dart | 120 ++++ lib/update/linux/linux_update_dialog.dart | 268 ++++++++ lib/update/linux/linux_updater.dart | 433 +++++++++++++ lib/update/linux/update_signals.dart | 23 + lib/update/update_controller.dart | 19 + linux/release.json | 4 + pubspec.lock | 10 +- pubspec.yaml | 4 + specs/linux_appimage.md | 135 +++- .../linux/desktop_integration_test.dart | 43 ++ test/update/linux/appcast_test.dart | 131 ++++ .../linux/linux_update_commands_test.dart | 225 +++++++ .../linux/linux_update_dialog_test.dart | 280 +++++++++ test/update/linux/linux_updater_test.dart | 582 ++++++++++++++++++ test/update/update_controller_test.dart | 48 ++ tool/linux/appcast.sh | 181 ++++++ tool/linux/build_appimage.sh | 62 +- widgetbook/use_cases/start.dart | 67 ++ 24 files changed, 2905 insertions(+), 56 deletions(-) create mode 100644 lib/platform/linux/running_app_image.dart create mode 100644 lib/update/linux/appcast.dart create mode 100644 lib/update/linux/linux_update_commands.dart create mode 100644 lib/update/linux/linux_update_dialog.dart create mode 100644 lib/update/linux/linux_updater.dart create mode 100644 lib/update/linux/update_signals.dart create mode 100644 linux/release.json create mode 100644 test/update/linux/appcast_test.dart create mode 100644 test/update/linux/linux_update_commands_test.dart create mode 100644 test/update/linux/linux_update_dialog_test.dart create mode 100644 test/update/linux/linux_updater_test.dart create mode 100755 tool/linux/appcast.sh diff --git a/lib/main.dart b/lib/main.dart index bc2dce9..3c43cf4 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -24,6 +24,8 @@ import 'session/project_session.dart'; import 'theme/app_theme.dart'; import 'theme/theme_controller.dart'; import 'toolchain/toolchain_controller.dart'; +import 'update/linux/linux_update_commands.dart'; +import 'update/linux/linux_updater.dart'; import 'update/session_teardown.dart'; import 'update/update_controller.dart'; import 'platform/macos_app_menu.dart'; @@ -75,6 +77,8 @@ Future main() async { // background; the menu item appears when it lands. final desktopIntegration = DesktopIntegrationController(); if (currentHost.isLinux) unawaited(desktopIntegration.refresh()); + // Linux has no Sparkle: updates are App Studio's own (lib/update/linux/). + final linuxUpdater = currentHost.isLinux ? LinuxUpdater() : null; // Never blocks launch: create() swallows its own failures and reports the // updater as unavailable. @@ -82,6 +86,7 @@ Future main() async { process: process, agent: agent, cloud: cloud, + linux: linuxUpdater, ); // Installed before the first event so nothing fires into the no-op default. @@ -115,6 +120,7 @@ Future main() async { previewMode: previewMode, logView: logView, desktopIntegration: desktopIntegration, + linuxUpdater: linuxUpdater, ), ); } @@ -133,6 +139,7 @@ class AppStudioApp extends StatefulWidget { required this.previewMode, required this.logView, required this.desktopIntegration, + this.linuxUpdater, }); final ThemeController themeController; @@ -147,6 +154,10 @@ class AppStudioApp extends StatefulWidget { final LogViewController logView; final DesktopIntegrationController desktopIntegration; + /// The updater on Linux; null on macOS and Windows, where Sparkle and + /// WinSparkle update. + final LinuxUpdater? linuxUpdater; + @override State createState() => _AppStudioAppState(); } @@ -198,6 +209,14 @@ class _AppStudioAppState extends State { widget.desktopIntegration, ); + /// Linux: the automatic update check, and the timer that runs it hourly + /// (it looks only once the last check is a day old). + late final _linuxUpdates = switch (widget.linuxUpdater) { + final updater? => LinuxUpdateSchedule(updater), + null => null, + }; + Timer? _linuxUpdateTimer; + @override void initState() { super.initState(); @@ -246,6 +265,12 @@ class _AppStudioAppState extends State { (_) => _offerAddToApplications(), ); } + if (_linuxUpdates != null) { + _linuxUpdateTimer = Timer.periodic( + const Duration(hours: 1), + (_) => _withNavigatorContext(_checkForUpdatesIfDue), + ); + } // Clear anything a crashed install left behind. Fire and forget, so it // never delays launch; ToolchainSetupScreen drives the install itself. unawaited(widget.toolchains.collectGarbage()); @@ -307,7 +332,16 @@ class _AppStudioAppState extends State { themeController: widget.themeController, logView: widget.logView, onNewProject: _showNewProjectScreen, - onCheckForUpdates: () => unawaited(widget.updates.checkForUpdates()), + onCheckForUpdates: switch (widget.linuxUpdater) { + final updater? => () => _withNavigatorContext( + (context) => checkForUpdatesOnLinux( + context, + updater, + onChecked: () => unawaited(widget.updates.refresh()), + ), + ), + null => () => unawaited(widget.updates.checkForUpdates()), + }, onUninstall: _confirmUninstall, onAbout: _showAbout, canCheckForUpdates: () => widget.updates.state.canCheck, @@ -374,17 +408,31 @@ class _AppStudioAppState extends State { /// Linux, as an AppImage nobody added to the app menu: asks whether to, /// once per run, over the start page and never among setup's dialogs. + /// + /// Then, on Linux, the automatic update check, so the two questions come + /// one after the other rather than on top of each other. void _offerAddToApplications() { if (!mounted) return; - _withNavigatorContext( - (context) => _addToApplications.offerOnce( - context, - onStartPage: () => - mounted && - widget.session.projectPath == null && - !_needsToolchainSetup && - _uninstalled == null, - ), + _withNavigatorContext((context) async { + await _addToApplications.offerOnce(context, onStartPage: _onStartPage); + if (context.mounted) await _checkForUpdatesIfDue(context); + }); + } + + /// Whether the start page is what the window shows: no project open, no + /// setup, no uninstall. + bool _onStartPage() => + mounted && + widget.session.projectPath == null && + !_needsToolchainSetup && + _uninstalled == null; + + /// Linux: the daily update check, over the start page only. + Future _checkForUpdatesIfDue(BuildContext context) async { + await _linuxUpdates?.checkIfDue( + context, + onStartPage: _onStartPage, + onChecked: () => unawaited(widget.updates.refresh()), ); } @@ -551,6 +599,7 @@ class _AppStudioAppState extends State { @override void dispose() { + _linuxUpdateTimer?.cancel(); _lifecycle?.dispose(); widget.updates.removeListener(_syncMenu); widget.toolchains.removeListener(_onToolchainsChanged); diff --git a/lib/platform/linux/app_version.dart b/lib/platform/linux/app_version.dart index 05f2453..92f7489 100644 --- a/lib/platform/linux/app_version.dart +++ b/lib/platform/linux/app_version.dart @@ -20,6 +20,13 @@ class AppVersion { String toString() => '$version+$build'; } +/// A version for a dialog that names two of them: `0.4.2`, with the build +/// when both share the version and only the build tells them apart. +String copyVersionLabel(AppVersion version, AppVersion other) => + version.version == other.version + ? '${version.version} (build ${version.build})' + : version.version; + /// Another copy of App Studio than the one in the app menu is running: one /// downloaded again, say. Only for a copy App Studio added itself; Gear /// Lever updates its own. diff --git a/lib/platform/linux/desktop_integration.dart b/lib/platform/linux/desktop_integration.dart index 82b2933..4165541 100644 --- a/lib/platform/linux/desktop_integration.dart +++ b/lib/platform/linux/desktop_integration.dart @@ -7,6 +7,7 @@ import 'package:path/path.dart' as p; import '../host.dart'; import 'app_version.dart'; import 'desktop_integration_status.dart'; +import 'running_app_image.dart'; export 'app_version.dart'; export 'desktop_integration_status.dart'; @@ -192,14 +193,7 @@ class DesktopIntegration { } Future status() async { - final appDir = _appDir; - if (!host.isLinux || _appImage == null || appDir == null) { - return DesktopIntegrationStatus.unavailable; - } - // Children inherit `$APPIMAGE` and `$APPDIR`: a development build started - // from a terminal inside another AppImage (an editor, say) sees that - // one's. Only an executable inside the mount is this AppImage. - if (!p.isWithin(appDir, _executable)) { + if (!host.isLinux || runningAppImage(environment, _executable) == null) { return DesktopIntegrationStatus.unavailable; } final entryPath = _entryPath; @@ -380,17 +374,53 @@ class DesktopIntegration { /// compared with the next download, a wrong one could offer to replace a /// newer copy with an older one. Without it, no copy is compared until the /// next Add writes the entry again. Best effort, like the cleanup before. - Future _forgetRecordedVersion(String entryPath) async { + Future _forgetRecordedVersion(String entryPath) => + _setRecordedVersion(entryPath, null); + + /// After an update replaced [appImagePath] in place: App Studio's entry, + /// when it names that file, records [version] from now on, so another + /// copy is compared with the build that is really there. Best effort. + Future recordUpdatedVersion( + String appImagePath, + AppVersion version, + ) async { + final entryPath = _entryPath; + if (entryPath == null) return; + final entry = await _readEntry(entryPath); + if (entry == null || !_isOurs(entry)) return; + final tryExec = entry['TryExec']; + if (tryExec == null || !p.equals(tryExec, appImagePath)) return; + await _setRecordedVersion(entryPath, version); + } + + /// The version App Studio's entry records for [appImagePath], or null + /// when there is no entry of App Studio's naming that file, or no version. + Future recordedVersionOf(String appImagePath) async { + final entryPath = _entryPath; + if (entryPath == null) return null; + final entry = await _readEntry(entryPath); + if (entry == null || !_isOurs(entry)) return null; + final tryExec = entry['TryExec']; + if (tryExec == null || !p.equals(tryExec, appImagePath)) return null; + final version = entry[kAddedVersionKey]; + final build = int.tryParse(entry[kAddedBuildKey] ?? ''); + if (version == null || build == null) return null; + return AppVersion(version, build); + } + + /// Rewrites the version keys of App Studio's entry at [entryPath]: drops + /// them, then writes [version] after the marker when there is one. Every + /// other line stays as it was. + Future _setRecordedVersion( + String entryPath, + AppVersion? version, + ) async { final file = File(entryPath); if (!await file.exists()) return; try { final contents = await file.readAsString(); final entry = parseDesktopEntry(contents); - if (!_isOurs(entry) || - (!entry.containsKey(kAddedVersionKey) && - !entry.containsKey(kAddedBuildKey))) { - return; - } + if (!_isOurs(entry)) return; final kept = []; var inGroup = false; for (final line in contents.split('\n')) { @@ -399,16 +429,25 @@ class DesktopIntegration { } else if (inGroup) { final key = line.split('=').first.trim(); if (key == kAddedVersionKey || key == kAddedBuildKey) continue; + if (key == kAddedByKey && version != null) { + kept + ..add(line) + ..add('$kAddedVersionKey=${_escapeString(version.version)}') + ..add('$kAddedBuildKey=${version.build}'); + continue; + } } kept.add(line); } + final updated = kept.join('\n'); + if (updated == contents) return; final temporary = File('$entryPath.$pid.part'); - await temporary.writeAsString(kept.join('\n'), flush: true); + await temporary.writeAsString(updated, flush: true); await temporary.rename(entryPath); } on FileSystemException catch (e) { - debugPrint('Could not drop the recorded version from $entryPath: $e'); + debugPrint('Could not record the version in $entryPath: $e'); } on FormatException catch (e) { - debugPrint('Could not drop the recorded version from $entryPath: $e'); + debugPrint('Could not record the version in $entryPath: $e'); } } @@ -491,11 +530,9 @@ class DesktopIntegration { ); } - /// Starts the copy in the app menu once this process has ended, so the two - /// never run at once — they share the preview's browser profile, which only - /// one can hold. The caller quits right after. A copy that has not ended - /// after 30 s starts anyway. [afterPid] is the process to wait for; tests - /// hand it one of their own, since this one never ends during a test. + /// Starts the copy in the app menu once this process has ended (see + /// [startAfterExit]); the caller quits right after. [afterPid] is the + /// process to wait for; tests hand it one of their own. Future openAddedCopyAfterExit({ @visibleForTesting int? afterPid, }) async { @@ -503,14 +540,7 @@ class DesktopIntegration { if (target == null || !await File(target).exists()) { throw FileSystemException('The AppImage is gone', target); } - await Process.start('/bin/sh', [ - '-c', - r'i=0; while kill -0 "$1" 2>/dev/null && [ "$i" -lt 150 ]; do ' - r'sleep 0.2; i=$((i + 1)); done; exec "$2"', - 'sh', - '${afterPid ?? pid}', - target, - ], mode: ProcessStartMode.detached); + await startAfterExit(target, afterPid: afterPid); } /// A rename where it can be; across file systems a copy to a temporary diff --git a/lib/platform/linux/running_app_image.dart b/lib/platform/linux/running_app_image.dart new file mode 100644 index 0000000..b352369 --- /dev/null +++ b/lib/platform/linux/running_app_image.dart @@ -0,0 +1,37 @@ +import 'dart:io'; + +import 'package:path/path.dart' as p; + +/// The AppImage this process runs from, or null when it runs from anything +/// else: a development build, a package, or another OS's build. +/// +/// The AppImage runtime sets `$APPIMAGE` (the file) and `$APPDIR` (where the +/// image is mounted). Children inherit both, so a development build started +/// from a terminal inside another AppImage (an editor, say) sees that one's. +/// Only an [executable] inside the mount is this AppImage. +String? runningAppImage(Map environment, String executable) { + final appImage = environment['APPIMAGE']; + final appDir = environment['APPDIR']; + if (appImage == null || appImage.isEmpty) return null; + if (appDir == null || appDir.isEmpty) return null; + return p.isWithin(appDir, executable) ? appImage : null; +} + +/// Starts [path] once the process [afterPid] (this one, by default) has +/// ended, so two copies of App Studio never run at once: they share the +/// preview's browser profile, which only one can hold. The caller quits +/// right after. A process that has not ended after 30 s is not waited for +/// any longer. +/// +/// A detached `sh` does the waiting, since this process is the one going +/// away. +Future startAfterExit(String path, {int? afterPid}) async { + await Process.start('/bin/sh', [ + '-c', + r'i=0; while kill -0 "$1" 2>/dev/null && [ "$i" -lt 150 ]; do ' + r'sleep 0.2; i=$((i + 1)); done; exec "$2"', + 'sh', + '${afterPid ?? pid}', + path, + ], mode: ProcessStartMode.detached); +} diff --git a/lib/ui/add_to_applications_dialog.dart b/lib/ui/add_to_applications_dialog.dart index b1732e0..25ddb38 100644 --- a/lib/ui/add_to_applications_dialog.dart +++ b/lib/ui/add_to_applications_dialog.dart @@ -170,13 +170,6 @@ class RemoveFromApplicationsDialog extends StatelessWidget { } } -/// A version for these dialogs: `0.4.2`, with the build when both copies -/// share the version and only the build tells them apart. -String copyVersionLabel(AppVersion version, AppVersion other) => - version.version == other.version - ? '${version.version} (build ${version.build})' - : version.version; - /// This copy is newer than the one App Studio added to the app menu: offers /// to put it in that one's place. Runs [onReplace] itself and stays open on /// failure, as [AddToApplicationsDialog] does. Pops true once replaced. diff --git a/lib/update/linux/appcast.dart b/lib/update/linux/appcast.dart new file mode 100644 index 0000000..5e0145a --- /dev/null +++ b/lib/update/linux/appcast.dart @@ -0,0 +1,116 @@ +import 'package:xml/xml.dart'; + +import '../../platform/linux/app_version.dart'; + +/// The Sparkle namespace the appcast's enclosure attributes live in. +const kSparkleNamespace = 'http://www.andymatuschak.org/xml-namespaces/sparkle'; + +/// The `sparkle:os` value of a Linux AppImage in the feed. +const kLinuxAppcastOs = 'linux-x86_64'; + +/// Whether [url] may carry an update: https, or plain http to this machine +/// (`localhost`, `127/8`, `::1`) or a private IPv4 network (`10/8`, +/// `172.16/12`, `192.168/16`), which only a development build's local feed +/// uses. `tool/linux/build_appimage.sh` and `appcast.sh` apply the same +/// rule. The signature covers the file, not the feed: over plain http +/// on a real network, anyone between could serve an older signed build as +/// a newer one. +bool isSecureUpdateUrl(Uri url) { + if (url.scheme == 'https') return url.host.isNotEmpty; + if (url.scheme != 'http') return false; + final host = url.host; + if (host == 'localhost' || host == '::1') return true; + // Dotted decimal only: a leading zero (`0127.0.0.1`) means octal to the + // resolver, which would make it a public address this check never saw. + final octet = r'(0|[1-9][0-9]{0,2})'; + if (!RegExp('^$octet(\\.$octet){3}\$').hasMatch(host)) return false; + final parts = host.split('.').map(int.parse).toList(); + if (parts.any((n) => n > 255)) return false; + final [a, b, _, _] = parts; + return a == 127 || + a == 10 || + (a == 172 && b >= 16 && b <= 31) || + (a == 192 && b == 168); +} + +/// One release in the appcast: where to download it and how to check it. +class AppcastItem { + const AppcastItem({ + required this.version, + required this.url, + required this.length, + required this.signature, + }); + + /// `sparkle:shortVersionString` and `sparkle:version` (the build number). + final AppVersion version; + final Uri url; + + /// The file's size in bytes, checked before the signature. + final int length; + + /// `sparkle:edSignature`: Ed25519 over the whole file, base64. + final String signature; +} + +/// The newest Linux release in [feed] with a build above [current], or null +/// when there is none. An item that is not for Linux, or that lacks anything +/// a download needs, is skipped: a feed may carry items this build cannot +/// read. Throws [FormatException] when [feed] is not an appcast at all. +AppcastItem? newestUpdate(String feed, {required int current}) { + final XmlDocument document; + try { + document = XmlDocument.parse(feed); + } on XmlException catch (e) { + throw FormatException('The update feed is not valid XML: ${e.message}'); + } + final channel = document.findAllElements('channel').firstOrNull; + if (channel == null) { + throw const FormatException('The update feed has no .'); + } + AppcastItem? newest; + for (final item in channel.findElements('item')) { + final parsed = _parse(item); + if (parsed == null || parsed.version.build <= current) continue; + if (newest == null || parsed.version.build > newest.version.build) { + newest = parsed; + } + } + return newest; +} + +AppcastItem? _parse(XmlElement item) { + final enclosure = item.findElements('enclosure').firstOrNull; + if (enclosure == null) return null; + String? sparkle(String name) => + enclosure.getAttribute(name, namespaceUri: kSparkleNamespace) ?? + // Older feeds put them on the item as elements. + item + .findElements(name, namespaceUri: kSparkleNamespace) + .firstOrNull + ?.innerText; + + if (sparkle('os') != kLinuxAppcastOs) return null; + final build = int.tryParse(sparkle('version') ?? ''); + final version = sparkle('shortVersionString'); + final url = Uri.tryParse(enclosure.getAttribute('url') ?? ''); + final length = int.tryParse(enclosure.getAttribute('length') ?? ''); + final signature = sparkle('edSignature'); + if (build == null || + version == null || + version.isEmpty || + url == null || + !url.hasScheme || + length == null || + length <= 0 || + signature == null || + signature.isEmpty) { + return null; + } + return AppcastItem( + version: AppVersion(version, build), + url: url, + length: length, + signature: signature, + ); +} diff --git a/lib/update/linux/linux_update_commands.dart b/lib/update/linux/linux_update_commands.dart new file mode 100644 index 0000000..2f34127 --- /dev/null +++ b/lib/update/linux/linux_update_commands.dart @@ -0,0 +1,120 @@ +import 'dart:async'; +import 'dart:ui' show AppExitType; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../../widgets/app_dialog.dart'; +import 'appcast.dart'; +import 'linux_update_dialog.dart'; +import 'linux_updater.dart'; + +/// Help → Check for Updates on Linux. [onChecked] runs after every check, +/// so the menu can refresh what it shows. [quit] is File → Quit's teardown +/// and exit, replaceable in tests. +Future checkForUpdatesOnLinux( + BuildContext context, + LinuxUpdater updater, { + VoidCallback? onChecked, + @visibleForTesting Future Function()? quit, +}) async { + final current = await updater.runningVersion(); + if (current == null || !context.mounted) return; + await showAppDialog( + context: context, + barrierDismissible: false, + builder: (context) => LinuxUpdateDialog.check( + current: current, + check: () async { + try { + return await updater.check(); + } finally { + onChecked?.call(); + } + }, + install: _installer(updater, quit ?? _quitApp), + onSkip: updater.skip, + ), + ); +} + +/// The automatic check: at most once a day, and only over the start page, +/// where no server is running. An update the user skipped is not offered +/// again; a newer one is. Says nothing when there is no update, or when +/// the check fails. +class LinuxUpdateSchedule { + LinuxUpdateSchedule( + this.updater, { + DateTime Function()? now, + @visibleForTesting Future Function()? quit, + }) : _now = now ?? DateTime.now, + _quit = quit ?? _quitApp; + + final LinuxUpdater updater; + final DateTime Function() _now; + final Future Function() _quit; + bool _running = false; + + Future checkIfDue( + BuildContext context, { + required bool Function() onStartPage, + VoidCallback? onChecked, + }) async { + if (_running) return; + _running = true; + try { + if (!onStartPage() || !await updater.isCheckDue(_now())) return; + final AppcastItem? update; + try { + update = await updater.check(); + } on LinuxUpdateException catch (e) { + debugPrint('Automatic update check failed: $e'); + return; + } finally { + onChecked?.call(); + } + if (update == null) return; + final skipped = await updater.skippedBuild(); + if (skipped != null && update.version.build <= skipped) return; + final current = await updater.runningVersion(); + // Checked again: the check took time, and a project may be open now. + if (current == null || !context.mounted || !onStartPage()) return; + await showAppDialog( + context: context, + barrierDismissible: false, + builder: (context) => LinuxUpdateDialog.offer( + current: current, + update: update!, + install: _installer(updater, _quit), + onSkip: updater.skip, + ), + ); + } finally { + _running = false; + } + } +} + +InstallUpdate _installer(LinuxUpdater updater, Future Function() quit) => + (item, {required onProgress, required cancellation}) async { + final verified = await updater.download( + item, + onProgress: onProgress, + cancellation: cancellation, + ); + if (verified == null) return false; + // The dialog may have gone while the signature was checked. + if (cancellation.isCancelled) { + await updater.discard(verified.path); + return false; + } + await updater.install(verified); + await quit(); + return true; + }; + +/// The same quit as File → Quit, teardown included; the new AppImage starts +/// once this process has ended. +Future _quitApp() async { + await ServicesBinding.instance.exitApplication(AppExitType.cancelable); +} diff --git a/lib/update/linux/linux_update_dialog.dart b/lib/update/linux/linux_update_dialog.dart new file mode 100644 index 0000000..ff45eb5 --- /dev/null +++ b/lib/update/linux/linux_update_dialog.dart @@ -0,0 +1,268 @@ +import 'package:flutter/material.dart'; +import 'package:shad/shad.dart'; + +import '../../platform/linux/app_version.dart'; +import '../../widgets/determinate_progress.dart'; +import '../../widgets/dialog_body.dart'; +import '../../widgets/error_banner.dart'; +import 'appcast.dart'; +import 'update_signals.dart'; + +/// Downloads [item], checks it, replaces the AppImage and quits. Reports +/// progress through [onProgress] and stops when [cancellation] asks. Returns +/// false when cancelled, and throws with a message the user can read. +typedef InstallUpdate = + Future Function( + AppcastItem item, { + required void Function(int received, int total) onProgress, + required UpdateCancellation cancellation, + }); + +enum _Phase { + checking, + upToDate, + checkFailed, + available, + downloading, + installing, + failed, + + /// The new version is in place, but did not start: nothing to retry. + installedNotStarted, +} + +/// App Studio's update dialog on Linux, where no Sparkle draws one: checks +/// (from Help), offers a newer build, downloads it with a progress bar and +/// installs it. Every step that touches the disk or the network is a +/// callback, which keeps this widget free of `dart:io`. +class LinuxUpdateDialog extends StatefulWidget { + /// Help → Check for Updates: starts by checking. + const LinuxUpdateDialog.check({ + super.key, + required this.current, + required Future Function() this.check, + required this.install, + this.onSkip, + }) : update = null; + + /// The automatic check found [update]: starts by offering it. + const LinuxUpdateDialog.offer({ + super.key, + required this.current, + required AppcastItem this.update, + required this.install, + this.onSkip, + }) : check = null; + + /// The running build. + final AppVersion current; + final Future Function()? check; + final AppcastItem? update; + final InstallUpdate install; + + /// Skip This Version; the button only shows with it. + final Future Function(AppcastItem item)? onSkip; + + @override + State createState() => _LinuxUpdateDialogState(); +} + +class _LinuxUpdateDialogState extends State { + late _Phase _phase; + AppcastItem? _update; + String? _error; + int _received = 0; + int _total = 0; + UpdateCancellation? _cancellation; + + @override + void initState() { + super.initState(); + _update = widget.update; + _phase = _update == null ? _Phase.checking : _Phase.available; + if (_phase == _Phase.checking) _check(); + } + + @override + void dispose() { + // Taken off by something else — a project opening clears the routes — + // while downloading: stop, rather than quit the app later mid-work. + _cancellation?.cancel(); + super.dispose(); + } + + Future _check() async { + try { + final update = await widget.check!(); + if (!mounted) return; + setState(() { + _update = update; + _phase = update == null ? _Phase.upToDate : _Phase.available; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _error = '$e'; + _phase = _Phase.checkFailed; + }); + } + } + + Future _install() async { + final update = _update!; + final cancellation = UpdateCancellation(); + setState(() { + _cancellation = cancellation; + _received = 0; + _total = update.length; + _error = null; + _phase = _Phase.downloading; + }); + try { + final installing = await widget.install( + update, + onProgress: (received, total) { + if (!mounted) return; + setState(() { + _received = received; + _total = total; + // The last byte is in: what follows is the signature and the + // replacement, which cannot be cancelled. + if (received >= total) _phase = _Phase.installing; + }); + }, + cancellation: cancellation, + ); + if (!mounted) return; + // Installing ends with the app quitting, so the dialog stays as it is + // until then. A cancelled download goes back to the offer. + if (!installing) setState(() => _phase = _Phase.available); + } on UpdateInstalledException catch (e) { + if (!mounted) return; + setState(() { + _error = e.message; + _phase = _Phase.installedNotStarted; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _error = '$e'; + _phase = _Phase.failed; + }); + } + } + + Future _skip() async { + await widget.onSkip!(_update!); + if (mounted) Navigator.of(context).pop(); + } + + void _close() => Navigator.of(context).pop(); + + String get _newVersion => copyVersionLabel(_update!.version, widget.current); + String get _currentVersion => + copyVersionLabel(widget.current, _update!.version); + + @override + Widget build(BuildContext context) => switch (_phase) { + _Phase.checking => ShadDialog.alert( + title: const Text('Checking for updates…'), + actions: [ + ShadButton.outline(onPressed: _close, child: const Text('Cancel')), + ], + child: const DialogBody(child: DeterminateProgress(fraction: null)), + ), + _Phase.upToDate => ShadDialog.alert( + title: const Text("You're up to date"), + description: Text( + 'App Studio ${widget.current.version} is the newest version.', + ), + actions: [ShadButton(onPressed: _close, child: const Text('OK'))], + child: const DialogBody(), + ), + _Phase.checkFailed => ShadDialog.alert( + title: const Text('Could not check for updates'), + actions: [ShadButton(onPressed: _close, child: const Text('OK'))], + child: DialogBody(child: ErrorBanner(message: _error ?? '')), + ), + _Phase.available => ShadDialog.alert( + title: Text('App Studio $_newVersion is available'), + description: Text( + 'You have $_currentVersion. Installing restarts App Studio, which ' + 'stops the server if it is running.', + ), + actionsMainAxisSize: MainAxisSize.max, + actionsMainAxisAlignment: widget.onSkip == null + ? MainAxisAlignment.end + : MainAxisAlignment.spaceBetween, + actions: [ + if (widget.onSkip != null) + // The part that gives way when the row is short of room, rather + // than the dialog overflowing. + Flexible( + child: FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: ShadButton.ghost( + onPressed: _skip, + child: const Text('Skip This Version'), + ), + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + spacing: 8, + children: [ + ShadButton.outline(onPressed: _close, child: const Text('Later')), + ShadButton( + onPressed: _install, + child: const Text('Install and Restart'), + ), + ], + ), + ], + child: const DialogBody(), + ), + _Phase.downloading || _Phase.installing => ShadDialog.alert( + title: Text( + _phase == _Phase.downloading + ? 'Downloading App Studio $_newVersion' + : 'Installing App Studio $_newVersion', + ), + actions: [ + // Dims rather than disappears once there is nothing left to cancel. + ShadButton.outline( + enabled: _phase == _Phase.downloading, + onPressed: _phase == _Phase.downloading + ? () => _cancellation?.cancel() + : null, + child: const Text('Cancel'), + ), + ], + child: DialogBody( + child: DeterminateProgress( + fraction: _phase == _Phase.downloading && _total > 0 + ? _received / _total + : null, + caption: _phase == _Phase.downloading + ? formatTransferCaption(received: _received, total: _total) + : 'Checking the download and restarting…', + reserveCaptionLine: true, + ), + ), + ), + _Phase.installedNotStarted => ShadDialog.alert( + title: Text('App Studio $_newVersion is installed'), + actions: [ShadButton(onPressed: _close, child: const Text('OK'))], + child: DialogBody(child: ErrorBanner(message: _error ?? '')), + ), + _Phase.failed => ShadDialog.alert( + title: const Text('Could not update App Studio'), + actions: [ + ShadButton.outline(onPressed: _close, child: const Text('Close')), + ShadButton(onPressed: _install, child: const Text('Try Again')), + ], + child: DialogBody(child: ErrorBanner(message: _error ?? '')), + ), + }; +} diff --git a/lib/update/linux/linux_updater.dart b/lib/update/linux/linux_updater.dart new file mode 100644 index 0000000..5e4b85a --- /dev/null +++ b/lib/update/linux/linux_updater.dart @@ -0,0 +1,433 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:isolate'; + +import 'package:cryptography/cryptography.dart'; +import 'package:cryptography/dart.dart'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; +import 'package:path/path.dart' as p; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../platform/linux/desktop_integration.dart'; +import '../../platform/linux/running_app_image.dart'; +import '../update_state.dart'; +import 'appcast.dart'; +import 'update_signals.dart'; + +export 'update_signals.dart'; + +/// Where the feed is and which key signs the downloads, compiled in by +/// `tool/linux/build_appimage.sh` from `linux/release.json`. +@immutable +class LinuxUpdateConfig { + const LinuxUpdateConfig({required this.appcastUrl, required this.publicKey}); + + static const compiledIn = LinuxUpdateConfig( + appcastUrl: String.fromEnvironment('APPSTUDIO_APPCAST_URL'), + publicKey: String.fromEnvironment('APPSTUDIO_EDDSA_PUBLIC_KEY'), + ); + + final String appcastUrl; + + /// The Ed25519 public key, base64 of its 32 bytes. + final String publicKey; + + bool get isComplete => appcastUrl.isNotEmpty && publicKey.isNotEmpty; +} + +/// Something the user should read: why a check or an update failed. +class LinuxUpdateException implements Exception { + const LinuxUpdateException(this.message); + + final String message; + + @override + String toString() => message; +} + +/// A download that arrived whole and carries a valid signature, ready to +/// take the running AppImage's place. +class VerifiedUpdate { + const VerifiedUpdate._(this.path, this.item); + + /// Only [LinuxUpdater.download] makes a real one: this skips the check. + @visibleForTesting + const VerifiedUpdate.forTesting(this.path, this.item); + + /// The hidden file beside the AppImage. + final String path; + final AppcastItem item; +} + +/// App Studio's updater on Linux, where neither Sparkle nor WinSparkle runs: +/// reads the appcast, downloads a newer AppImage beside the running one, +/// checks its signature and renames it over the running file. A running +/// AppImage stays mounted when its file is replaced, so this copy carries on +/// until it quits and the new file starts. +/// +/// Every outside thing is injected — the environment, the executable, the +/// HTTP client, the version — so the tests run on any host. +class LinuxUpdater { + LinuxUpdater({ + LinuxUpdateConfig? config, + Map? environment, + String? executable, + http.Client? client, + Future Function()? runningVersion, + DesktopIntegration? desktop, + }) : config = config ?? LinuxUpdateConfig.compiledIn, + _environment = environment ?? Platform.environment, + _executable = executable ?? Platform.resolvedExecutable, + _client = client ?? http.Client(), + _runningVersion = runningVersion ?? readRunningVersion, + _desktop = + desktop ?? + DesktopIntegration( + environment: environment, + executable: executable, + runningVersion: runningVersion, + ); + + static const automaticKey = 'linux.updates.automatic'; + static const lastCheckKey = 'linux.updates.last_check'; + static const skippedBuildKey = 'linux.updates.skipped_build'; + + /// How often the automatic check looks, as Sparkle's default on macOS. + static const checkInterval = Duration(days: 1); + + /// The hidden file a download goes to, beside the AppImage. + static const partName = '.AppStudio-update.part'; + + final LinuxUpdateConfig config; + final Map _environment; + final String _executable; + final http.Client _client; + final Future Function() _runningVersion; + final DesktopIntegration _desktop; + + /// A download is running. The menu stays usable under the update dialog, + /// so a second check or download can start meanwhile: neither may touch + /// the file the first is writing. + bool _downloading = false; + + /// The AppImage this process was started from, as its runtime named it, + /// or null when this is not one. + String? get appImage => runningAppImage(_environment, _executable); + + /// The file an update replaces: [appImage], unless Add to Applications + /// moved it in this run, when `$APPIMAGE` still names where it was and + /// the file is at `~/AppImages` now. Null when neither is there. + Future liveAppImage() async { + final started = appImage; + if (started == null) return null; + if (await File(started).exists()) return started; + // Only the copy this one became: App Studio's entry names it and + // records this build. Any other file there (one left after Remove, + // perhaps newer) is not this App Studio's to replace. + final added = _desktop.addedAppImagePath; + final running = await _runningVersion(); + if (added != null && + running != null && + await File(added).exists() && + await _desktop.recordedVersionOf(added) == running) { + return added; + } + return null; + } + + Future _requireLiveAppImage() async { + final live = await liveAppImage(); + if (live == null) { + throw const LinuxUpdateException( + 'The AppImage App Studio was started from is gone.', + ); + } + return live; + } + + Future runningVersion() => _runningVersion(); + + /// What the menu, About and the analytics read, in the same shape the + /// macOS and Windows updaters report. + Future state() async { + final prefs = await SharedPreferences.getInstance(); + final version = await _runningVersion(); + final lastCheck = prefs.getInt(lastCheckKey); + return UpdateState( + configured: config.isComplete && appImage != null, + currentVersion: version?.version ?? '', + currentBuild: version == null ? '' : '${version.build}', + automaticallyChecks: prefs.getBool(automaticKey) ?? true, + lastCheck: lastCheck == null + ? null + : DateTime.fromMillisecondsSinceEpoch(lastCheck), + ); + } + + Future setAutomaticallyChecks(bool enabled) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(automaticKey, enabled); + } + + /// Whether the automatic check should look now: configured, switched on, + /// and the last check at least [checkInterval] ago. + Future isCheckDue(DateTime now) async { + final state = await this.state(); + if (!state.canCheck || !state.automaticallyChecks) return false; + final last = state.lastCheck; + return last == null || now.difference(last) >= checkInterval; + } + + /// The build the user chose to skip, which the automatic check leaves out. + Future skippedBuild() async => + (await SharedPreferences.getInstance()).getInt(skippedBuildKey); + + Future skip(AppcastItem item) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt(skippedBuildKey, item.version.build); + } + + /// Reads the feed and returns the newest release above the running build, + /// or null when this one is the newest. Records the check either way, so a + /// failing feed is not asked again every hour. Throws + /// [LinuxUpdateException]. + Future check() async { + final running = await _runningVersion(); + if (!config.isComplete || appImage == null || running == null) { + throw const LinuxUpdateException( + 'Updates are not available in this build.', + ); + } + final feed = Uri.tryParse(config.appcastUrl); + if (feed == null || !isSecureUpdateUrl(feed)) { + throw LinuxUpdateException( + 'The update feed ${config.appcastUrl} is not an https address.', + ); + } + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt(lastCheckKey, DateTime.now().millisecondsSinceEpoch); + // A download a crash or a kill interrupted is ~140 MB nobody would find: + // it is hidden. No download runs while a check does. + final live = await liveAppImage(); + if (live != null && !_downloading) { + await discard(p.join(p.dirname(live), partName)); + } + final http.Response response; + try { + response = await _client.get(feed).timeout(const Duration(seconds: 30)); + } on TimeoutException { + throw const LinuxUpdateException('The update server did not answer.'); + } on Exception catch (e) { + throw LinuxUpdateException('Could not reach the update server: $e'); + } + if (response.statusCode != 200) { + throw LinuxUpdateException( + 'The update server answered ${response.statusCode}.', + ); + } + try { + return newestUpdate( + utf8.decode(response.bodyBytes), + current: running.build, + ); + } on FormatException catch (e) { + throw LinuxUpdateException(e.message); + } + } + + /// Downloads [item] beside the AppImage and checks its length and + /// signature. [onProgress] gets the bytes so far and the total. Deletes + /// what it wrote when anything fails or [cancellation] asks it to stop; + /// a cancelled download returns null. Throws [LinuxUpdateException]. + Future download( + AppcastItem item, { + void Function(int received, int total)? onProgress, + UpdateCancellation? cancellation, + }) async { + if (!isSecureUpdateUrl(item.url)) { + throw LinuxUpdateException( + 'The update feed names ${item.url}, which is not an https address.', + ); + } + if (_downloading) { + throw const LinuxUpdateException('An update is downloading already.'); + } + _downloading = true; + try { + return await _download( + item, + onProgress: onProgress, + cancellation: cancellation, + ); + } finally { + _downloading = false; + } + } + + Future _download( + AppcastItem item, { + void Function(int received, int total)? onProgress, + UpdateCancellation? cancellation, + }) async { + final target = await _requireLiveAppImage(); + final folder = p.dirname(target); + final part = File(p.join(folder, partName)); + final IOSink sink; + try { + // Created anew, never opened through whatever is there: a link left + // in its place would otherwise be followed. + await discard(part.path); + await part.create(exclusive: true); + sink = part.openWrite(); + } on FileSystemException { + throw LinuxUpdateException( + 'App Studio cannot replace itself in $folder. Move the AppImage to ' + 'a folder of your own, such as ~/AppImages (Help → Add to ' + 'Applications), then try again.', + ); + } + + var complete = false; + try { + final response = await _client + .send(http.Request('GET', item.url)) + .timeout(const Duration(seconds: 30)); + if (response.statusCode != 200) { + throw LinuxUpdateException( + 'The download answered ${response.statusCode}.', + ); + } + var received = 0; + await for (final chunk in response.stream.timeout( + const Duration(seconds: 60), + )) { + if (cancellation?.isCancelled ?? false) break; + received += chunk.length; + if (received > item.length) break; + sink.add(chunk); + onProgress?.call(received, item.length); + } + await sink.close(); + if (cancellation?.isCancelled ?? false) return null; + if (received != item.length) { + throw LinuxUpdateException( + 'The download is $received bytes, not the ${item.length} the ' + 'update feed names.', + ); + } + // Locals only: the closure is sent to the isolate, and this object + // (its HTTP client) cannot be. + final path = part.path; + final signature = item.signature; + final publicKey = config.publicKey; + final valid = await Isolate.run( + () => verifyEd25519File(path, signature, publicKey), + ); + if (!valid) { + throw const LinuxUpdateException( + 'The download does not carry a valid signature, so it was not ' + 'installed.', + ); + } + final chmod = await Process.run('chmod', ['755', part.path]); + if (chmod.exitCode != 0) { + throw LinuxUpdateException( + 'Could not make the download executable: ' + '${(chmod.stderr as String).trim()}', + ); + } + complete = true; + return VerifiedUpdate._(part.path, item); + } on TimeoutException { + throw const LinuxUpdateException('The download stopped answering.'); + } on LinuxUpdateException { + rethrow; + } on Exception catch (e) { + throw LinuxUpdateException('The download failed: $e'); + } finally { + if (!complete) { + try { + await sink.close(); + } on Object { + // Closed already, or never written. + } + await discard(part.path); + } + } + } + + /// Replaces the running AppImage with [update], records the new version in + /// App Studio's menu entry when it names this file, and starts the new + /// file once this process has ended. The caller quits right after. + /// + /// Throws [LinuxUpdateException] when the replacement fails, which leaves + /// the running file as it was, and [UpdateInstalledException] when only + /// the restart fails, after it. + Future install( + VerifiedUpdate update, { + @visibleForTesting int? afterPid, + }) async { + final String target; + try { + target = await _requireLiveAppImage(); + } on LinuxUpdateException { + await discard(update.path); + rethrow; + } + try { + await File(update.path).rename(target); + } on FileSystemException catch (e) { + await discard(update.path); + throw LinuxUpdateException( + 'Could not replace $target: ${e.osError?.message ?? e.message}', + ); + } + await _desktop.recordUpdatedVersion(target, update.item.version); + try { + await startAfterExit(target, afterPid: afterPid); + } on ProcessException catch (e) { + throw UpdateInstalledException( + update.item.version.version, + 'App Studio could not start it (${e.message}). Quit App Studio and ' + 'start it again.', + ); + } + } + + /// Deletes a download that will not be installed. + Future discard(String path) async { + try { + await File(path).delete(); + } on FileSystemException { + // Never written, or gone already. + } + } +} + +/// Whether [signature] (base64) is a valid Ed25519 signature over the whole +/// file at [path] for [publicKey] (base64 of its 32 bytes). Runs in an +/// isolate: it reads the whole file, ~140 MB. +Future verifyEd25519File( + String path, + String signature, + String publicKey, +) async { + final List signatureBytes; + final List keyBytes; + try { + signatureBytes = base64.decode(signature.trim()); + keyBytes = base64.decode(publicKey.trim()); + } on FormatException { + return false; + } + if (signatureBytes.length != 64 || keyBytes.length != 32) return false; + return DartEd25519().verify( + await File(path).readAsBytes(), + signature: Signature( + signatureBytes, + publicKey: SimplePublicKey(keyBytes, type: KeyPairType.ed25519), + ), + ); +} diff --git a/lib/update/linux/update_signals.dart b/lib/update/linux/update_signals.dart new file mode 100644 index 0000000..d51b902 --- /dev/null +++ b/lib/update/linux/update_signals.dart @@ -0,0 +1,23 @@ +/// What the updater and its dialog tell each other, in a file of its own, +/// free of `dart:io`, so the dialog can use it. +library; + +/// Asked between chunks of a download, which stops when it says so. +class UpdateCancellation { + bool _cancelled = false; + bool get isCancelled => _cancelled; + void cancel() => _cancelled = true; +} + +/// The new AppImage is in place, but App Studio could not start it: there +/// is nothing to try again, only to start it by hand. +class UpdateInstalledException implements Exception { + const UpdateInstalledException(this.version, this.message); + + /// The version now installed. + final String version; + final String message; + + @override + String toString() => message; +} diff --git a/lib/update/update_controller.dart b/lib/update/update_controller.dart index 82a6480..a86170f 100644 --- a/lib/update/update_controller.dart +++ b/lib/update/update_controller.dart @@ -7,6 +7,7 @@ import '../agent/agent_controller.dart'; import '../cloud/cloud_publish.dart'; import '../platform/afunix_settle.dart'; import '../process/serverpod_process.dart'; +import 'linux/linux_updater.dart'; import 'session_teardown.dart'; import 'update_state.dart'; @@ -20,6 +21,11 @@ import 'update_state.dart'; /// vetoed without Swift having to call back into a possibly-busy engine; /// * runs the teardown when Sparkle is about to relaunch. /// +/// On Linux there is no native side: [linux] does the updating in Dart, and +/// this class reads its state from there, so the menu, About and the +/// analytics see the version as on the other two systems. Its dialogs run +/// from `lib/update/linux/linux_update_commands.dart`. +/// /// Every channel call is guarded. An updater that throws during startup, or on /// a machine where the channel is absent (tests, a non-macOS host), must leave /// the app fully usable — nobody should lose their IDE because the updater is @@ -29,6 +35,7 @@ class UpdateController extends ChangeNotifier { required this.process, required this.agent, required this.cloud, + this.linux, @visibleForTesting MethodChannel? channel, }) : _channel = channel ?? const MethodChannel(kUpdateChannel); @@ -38,6 +45,9 @@ class UpdateController extends ChangeNotifier { final ServerpodProcessController process; final AgentController agent; final CloudPublishController cloud; + + /// The updater on Linux; null on macOS and Windows. + final LinuxUpdater? linux; final MethodChannel _channel; UpdateState _state = UpdateState.unavailable; @@ -52,12 +62,14 @@ class UpdateController extends ChangeNotifier { required ServerpodProcessController process, required AgentController agent, required CloudPublishController cloud, + LinuxUpdater? linux, @visibleForTesting MethodChannel? channel, }) async { final controller = UpdateController( process: process, agent: agent, cloud: cloud, + linux: linux, channel: channel, ); controller._channel.setMethodCallHandler(controller._handleCall); @@ -76,9 +88,11 @@ class UpdateController extends ChangeNotifier { } Future refresh() async { + final linux = this.linux; final next = await _guard( 'getState', () async { + if (linux != null) return linux.state(); final reply = await _channel.invokeMapMethod('getState'); return reply == null ? UpdateState.unavailable : UpdateState.fromMap(reply); @@ -107,6 +121,8 @@ class UpdateController extends ChangeNotifier { notifyListeners(); } await _guard('setAutomaticallyChecks', () async { + final linux = this.linux; + if (linux != null) return linux.setAutomaticallyChecks(enabled); await _channel.invokeMethod( 'setAutomaticallyChecks', {'enabled': enabled}, @@ -129,6 +145,9 @@ class UpdateController extends ChangeNotifier { } void _syncSessionBusy() { + // On Linux the automatic check runs over the start page only, where no + // session is live. + if (linux != null) return; final busy = process.canStop || agent.isServeRunning; if (busy == _sessionBusy) return; _sessionBusy = busy; diff --git a/linux/release.json b/linux/release.json new file mode 100644 index 0000000..2225dab --- /dev/null +++ b/linux/release.json @@ -0,0 +1,4 @@ +{ + "appcastUrl": "", + "eddsaPublicKey": "" +} diff --git a/pubspec.lock b/pubspec.lock index 19683af..5921f0d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -97,6 +97,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.7" + cryptography: + dependency: "direct main" + description: + name: cryptography + sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0" + url: "https://pub.dev" + source: hosted + version: "2.9.0" device_frame_plus: dependency: transitive description: @@ -995,7 +1003,7 @@ packages: source: hosted version: "1.1.0" xml: - dependency: transitive + dependency: "direct main" description: name: xml sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4" diff --git a/pubspec.yaml b/pubspec.yaml index b9ddcee..2d16811 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -35,6 +35,10 @@ dependencies: xterm: ^4.0.0 flutter_pty2: ^3.0.0 yaml: ^3.1.4 + # Linux updates (lib/update/linux/): the Sparkle appcast, and the Ed25519 + # signature on each download, which Sparkle and WinSparkle check natively. + xml: ^7.0.1 + cryptography: ^2.9.0 dev_dependencies: flutter_test: sdk: flutter diff --git a/specs/linux_appimage.md b/specs/linux_appimage.md index 21f6159..af85965 100644 --- a/specs/linux_appimage.md +++ b/specs/linux_appimage.md @@ -20,17 +20,17 @@ Studio. | Part | What | Where | State | |---|---|---|---| | A | **Add to Applications**: on start, until it is in the app menu, App Studio offers to add itself; **Remove from Applications** undoes it | App Studio (Dart), Linux only | being built | -| B | Updates from inside the app | App Studio and Serverpod's release pipeline | later (below) | +| B | **Updates from inside the app**: Help → Check for Updates, and a daily check, replace the AppImage in place | App Studio (Dart), `tool/linux/`; feed and key are Serverpod's | being built | | C | **A clear message on a system that cannot load App Studio**, instead of nothing happening | `AppRun` in the AppImage | done | | D | **Download page text** for Serverpod's website | text in this spec | written; needs A | | E | Uninstall removes what A added | App Studio (Dart) | with PR 5 | -**B, updates, come later.** Until then **Help → Check for Updates** stays -greyed out on Linux, and the AppImage carries no update information: where -builds are hosted, and with it the `.zsync` URL Gear Lever would read -(`specs/linux_port.md` 4.5), is Serverpod's to decide together with the -updater. Part A's fixed path (A2) lets that updater replace the file in place -without touching the menu entry. +**B is built and tested against a local feed.** Where builds are hosted, +the feed's URL and the signing key are Serverpod's to decide: until +`linux/release.json` names a feed and a key, a release build reports updates +as unavailable, as a build without them does on Windows. The AppImage still +carries no `.zsync` update information for Gear Lever; that is a separate +choice for the same people (`specs/linux_port.md` 4.5). This spec covers the AppImage. Whether the `.deb` and `.rpm` of `specs/linux_port.md` (4.5) still follow is open with Serverpod. @@ -307,6 +307,103 @@ instance of it. Both are left as they are. --- +## B. Updates from inside the app + +macOS updates through Sparkle and Windows through WinSparkle; Linux has no +such library, so App Studio does the same job in Dart, with the same feed +format and the same rules. + +| # | Decision | +|---|---| +| B1 | **The feed is a Sparkle appcast**, like the macOS and Windows ones: one `` per release, its `` carrying `url`, `length`, `sparkle:version` (the build number, which orders releases), `sparkle:shortVersionString`, `sparkle:os="linux-x86_64"` and `sparkle:edSignature`. | +| B2 | **Every download is checked against an Ed25519 signature** over the whole file, as Sparkle and WinSparkle check theirs. The public key is compiled in; the private one never leaves Serverpod. A key pair from `openssl genpkey -algorithm ed25519` works, and so does signing with `openssl pkeyutl -sign -rawin`. | +| B3 | **The feed URL and public key live in `linux/release.json`** (`appcastUrl`, `eddsaPublicKey`), as Windows keeps them in `windows/release.json`. `build_appimage.sh` passes them to `flutter build` as `--dart-define`s; `APPSTUDIO_APPCAST_URL` and `APPSTUDIO_EDDSA_PUBLIC_KEY` in the environment override them, for a local feed. Empty, updates are unavailable. | +| B4 | **The build number is pubspec's**, the same `+N` the macOS build uses, so `make set_version` covers Linux too. | +| B5 | **The AppImage is replaced in place**, at whatever path it runs from, and started again from there. A menu entry, App Studio's or another tool's, keeps working because the path stays the same. After an Add in the same run, that is `~/AppImages/AppStudio-x86_64.AppImage`, although `$APPIMAGE` still names the folder the file came from; it is taken only while App Studio's entry names it and records the running build, so another copy left there is never replaced. | +| B6 | **https only**, for the feed and every download: the signature covers the file, not the feed, so over plain http anyone in between could serve an older signed build as a newer one. Plain http is accepted only to this machine (`localhost`, `127/8`, `::1`) or a private IPv4 network (`10/8`, `172.16/12`, `192.168/16`), written in dotted decimal, which only a local test feed uses. The app, `build_appimage.sh` and `appcast.sh` check the same rule; the scripts also refuse a few odd spellings (percent-escaped hosts) the app lets through to the very host it checked. | + +### When it checks + +- **Help → Check for Updates...**, any time. It says when App Studio is up + to date, and why when the check fails. +- **Automatically, once a day** (Help → Check for Updates Automatically, + on by default, as on macOS): on start after the Add question, and every + hour after that whenever the last check is a day old. Only over the start + page: a project open means a running server, and an update dialog there + would interrupt work, as Sparkle's busy veto avoids on macOS and Windows. + An automatic check that finds nothing, or fails, says nothing. +- Only when running as an AppImage (part A's condition 1). A development + build, or one without a feed, shows "Check for Updates (unavailable in this + build)". + +### The dialog + +```text +App Studio 0.4.2 is available + +You have 0.4.1. Installing restarts App Studio, which stops the server if +it is running. + +[Skip This Version] [Later] [Install and Restart] +``` + +**Skip This Version** stops the automatic check offering that build; Help → +Check for Updates still offers it, as Sparkle does. **Install and Restart** +downloads with a progress bar and Cancel, then checks and installs: + +1. **Downloads** to a hidden file beside the AppImage + (`.AppStudio-update.part`), so the final rename stays on one file system + and is atomic. The file is created anew, never opened through whatever + is in its place, and one an interrupted run left behind is deleted by the + next check. One download runs at a time: the Help menu stays usable under + the dialog, so a second one is refused, and a check leaves a running + download's file alone. A folder App Studio cannot write to fails here, before + anything is downloaded, and says to move the AppImage to a folder of the + user's own, such as `~/AppImages` (Help → Add to Applications). +2. **Checks** the length and the signature (B2). A mismatch deletes the + file and says so; nothing is replaced. +3. **Replaces** the AppImage: made executable, then renamed over the running + file. The running copy is unaffected, as part A's move showed: its image + stays mounted. +4. **Updates App Studio's menu entry**, when it names this file: its + recorded version becomes the new one (part A, Another copy). +5. **Restarts**: the same quit as File → Quit, teardown included, and the + new file starts once this process has ended (part A's Open). + +A failure in steps 1 to 3 leaves the running AppImage as it was and shows +the reason with **Try Again**. A failed restart (step 5) comes after the +replacement, so the dialog says the new version is installed, and to quit +and start it again, with nothing to try again. + +### Gear Lever and other tools + +Replacing the file in place keeps their menu entries working. Gear Lever +shows the version it read when it added the file until it looks again; its +own update (through `.zsync`) stays a separate route, and it stays off until +the AppImage carries update information. + +### Where it lives + +- `lib/update/linux/appcast.dart`: reads the feed and picks the newest + item for Linux; free of `dart:io`. +- `lib/update/linux/linux_updater.dart`: the configuration, the check, the + download, the signature, the replacement and the preferences (automatic + checks, last check, skipped build), with the environment, the HTTP client + and the paths injected so the tests run on every host. +- `lib/update/linux/linux_update_dialog.dart`: the dialog, and + `update_signals.dart`, what it and the updater tell each other (a + cancellation, an update installed but not started); both free of + `dart:io`. +- `lib/update/linux/linux_update_commands.dart`: what Help and the daily + check run. +- `UpdateController` reads its state from `LinuxUpdater` on Linux, so the + menu, About and analytics see the version as on the other two systems. +- `tool/linux/appcast.sh`: signs an AppImage and adds it to a feed, newest + first, refusing a build number the feed already has or has passed, and + checking the signature against the key in `linux/release.json`. + +--- + ## C. A system that cannot load App Studio (done) On a system with an older glibc (Ubuntu 22.04, Debian 12, Linux Mint 21), or @@ -409,3 +506,27 @@ there. an older one and Open, and the newer copy comes up once the older one has quit. - **Omarchy:** the same Add and Remove, through Walker. +- **Part B, unit tests on every host:** the feed (newest Linux item, other + systems and incomplete items left out, the namespace rather than the + prefix, https only); the updater against a fake HTTP server with real + Ed25519 signatures (a wrong signature, another key, another length, a + cancel, one download at a time, a folder it cannot write, a link in the + download's place, another copy in `~/AppImages` never taken, an + http feed or download, a leftover download cleared, the replacement and + restart, the new version recorded in App Studio's entry, the file in + `~/AppImages` after an Add in the same run, and a signature made by + `openssl` accepted); the dialog's phases; the daily check (due or not, + only over the start page, a skipped build and a newer one). +- **Part B, Ubuntu VM** with two builds made against a local feed + (`APPSTUDIO_APPCAST_URL` and `APPSTUDIO_EDDSA_PUBLIC_KEY`, never + committed) and a feed from `appcast.sh` naming the newer one: + - start the older from `~/Downloads`, Add, and the update is offered + right after; Install and Restart; the newer build comes up from + `~/AppImages`, its entry records the new version, and no + `.AppStudio-update.part` is left; + - Help → Check for Updates in the newer build says it is up to date; + - in an older copy: Cancel during the download goes back to the offer + and leaves no file; Skip This Version; a feed whose signature does not + match is refused and nothing is replaced; + - with a project open and the server running, Install and Restart stops + the server and the newer build starts. diff --git a/test/platform/linux/desktop_integration_test.dart b/test/platform/linux/desktop_integration_test.dart index 106cd43..7d5fc03 100644 --- a/test/platform/linux/desktop_integration_test.dart +++ b/test/platform/linux/desktop_integration_test.dart @@ -724,6 +724,49 @@ Exec=appstudio --extra }); }); + group('an update in place', () { + test('records the new version in App Studio\'s entry', () async { + await integration().add(); + await integration().recordUpdatedVersion( + target(), + const AppVersion('0.4.2', 26), + ); + + final entry = parseDesktopEntry(await File(entryPath()).readAsString()); + expect(entry[kAddedVersionKey], '0.4.2'); + expect(entry[kAddedBuildKey], '26'); + expect(entry[kAddedByKey], kAddedByValue); + expect(entry['TryExec'], target()); + }); + + test('leaves an entry for another file alone', () async { + await integration().add(); + final before = await File(entryPath()).readAsString(); + await integration().recordUpdatedVersion( + p.join(home, 'elsewhere.AppImage'), + const AppVersion('0.4.2', 26), + ); + + expect(await File(entryPath()).readAsString(), before); + }); + + test('leaves an entry App Studio did not write alone', () async { + const theirs = + '[Desktop Entry]\nName=App Studio\nExec=/opt/x\nTryExec=/opt/x\n'; + await writeEntry( + p.dirname(entryPath()), + 'dev.serverpod.appstudio.desktop', + theirs, + ); + await integration().recordUpdatedVersion( + '/opt/x', + const AppVersion('0.4.2', 26), + ); + + expect(await File(entryPath()).readAsString(), theirs); + }); + }); + group('remove', () { test('removes the entry and icons, and leaves the AppImage', () async { await integration().add(); diff --git a/test/update/linux/appcast_test.dart b/test/update/linux/appcast_test.dart new file mode 100644 index 0000000..910b02d --- /dev/null +++ b/test/update/linux/appcast_test.dart @@ -0,0 +1,131 @@ +import 'package:appstudio/update/linux/appcast.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// A feed with [items] in its channel. +String feed(String items, {String prefix = 'sparkle'}) => + ''' + + + + App Studio + $items + + +'''; + +String item({ + int build = 26, + String version = '0.4.2', + String os = 'linux-x86_64', + String? length = '100', + String? signature = 'c2ln', + String url = 'https://example.com/AppStudio-0.4.2-x86_64.AppImage', + String prefix = 'sparkle', +}) => + ''' + + +'''; + +void main() { + test('picks the newest Linux item above the running build', () { + final update = newestUpdate( + feed( + item(build: 26, version: '0.4.2') + + item(build: 28, version: '0.4.4') + + item(build: 27, version: '0.4.3'), + ), + current: 25, + )!; + + expect(update.version.version, '0.4.4'); + expect(update.version.build, 28); + expect(update.length, 100); + expect(update.signature, 'c2ln'); + expect(update.url.host, 'example.com'); + }); + + test('says nothing when the running build is the newest', () { + expect(newestUpdate(feed(item(build: 25)), current: 25), isNull); + expect(newestUpdate(feed(item(build: 24)), current: 25), isNull); + expect(newestUpdate(feed(''), current: 25), isNull); + }); + + test('leaves out items for other systems', () { + expect( + newestUpdate( + feed(item(build: 30, os: 'windows-x64') + item(build: 31, os: 'macos')), + current: 25, + ), + isNull, + ); + }); + + test('leaves out items it could not download or check', () { + final update = newestUpdate( + feed( + item(build: 30, signature: null) + + item(build: 31, length: null) + + item(build: 32, length: '0') + + item(build: 33, url: 'not a url') + + item(build: 26), + ), + current: 25, + ); + expect(update!.version.build, 26); + }); + + test('reads the namespace, not the prefix', () { + final update = newestUpdate( + feed(item(prefix: 'sp'), prefix: 'sp'), + current: 25, + ); + expect(update!.version.build, 26); + }); + + test('only https carries an update, or http to a local address', () { + for (final ok in [ + 'https://asdl.serverpod.dev/appcast/linux/appcast.xml', + 'http://localhost:8000/appcast.xml', + 'http://127.0.0.1/a', + 'http://192.168.122.1:8000/a', + 'http://10.0.0.2/a', + 'http://172.20.1.1/a', + 'http://[::1]:8000/a', + 'HTTPS://asdl.serverpod.dev/a', + ]) { + expect(isSecureUpdateUrl(Uri.parse(ok)), isTrue, reason: ok); + } + for (final bad in [ + 'http://asdl.serverpod.dev/appcast.xml', + 'http://172.32.0.1/a', + 'http://8.8.8.8/a', + 'ftp://example.com/a', + 'file:///home/alex/a', + 'https:///nohost', + // Octal to the resolver: 87.0.0.1, a public address. + 'http://0127.0.0.1/a', + 'http://169.254.1.1/a', + 'http://[fe80::1]/a', + ]) { + expect(isSecureUpdateUrl(Uri.parse(bad)), isFalse, reason: bad); + } + }); + + test('a feed that is not an appcast is an error', () { + expect( + () => newestUpdate('', current: 25), + throwsA(isA()), + ); + expect( + () => newestUpdate('', current: 25), + throwsA(isA()), + ); + }); +} diff --git a/test/update/linux/linux_update_commands_test.dart b/test/update/linux/linux_update_commands_test.dart new file mode 100644 index 0000000..b3b12b3 --- /dev/null +++ b/test/update/linux/linux_update_commands_test.dart @@ -0,0 +1,225 @@ +import 'package:appstudio/platform/linux/app_version.dart'; +import 'package:appstudio/update/linux/appcast.dart'; +import 'package:appstudio/update/linux/linux_update_commands.dart'; +import 'package:appstudio/update/linux/linux_updater.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shad/shad.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +AppcastItem build(int build) => AppcastItem( + version: AppVersion('0.4.$build', build), + url: Uri.parse('https://updates.test/$build.AppImage'), + length: 10, + signature: 'c2ln', +); + +/// The automatic check says something only when there is something to +/// install, and only over the start page. +void main() { + late _FakeUpdater updater; + + setUp(() { + SharedPreferences.setMockInitialValues({}); + updater = _FakeUpdater(); + }); + + Future run( + WidgetTester tester, + Future Function(BuildContext) command, + ) async { + await tester.pumpWidget( + ShadApp( + home: Builder( + builder: (context) => ShadButton( + onPressed: () => command(context), + child: const Text('go'), + ), + ), + ), + ); + await tester.tap(find.text('go')); + await tester.pumpAndSettle(); + } + + Future checkIfDue(WidgetTester tester, {bool onStartPage = true}) => + run( + tester, + (context) => LinuxUpdateSchedule( + updater, + ).checkIfDue(context, onStartPage: () => onStartPage), + ); + + testWidgets('offers a newer build when a check is due', (tester) async { + updater.update = build(26); + await checkIfDue(tester); + + expect(updater.checks, 1); + expect(find.text('App Studio 0.4.26 is available'), findsOneWidget); + expect(find.text('Skip This Version'), findsOneWidget); + }); + + testWidgets('does not look before a day has passed', (tester) async { + updater + ..due = false + ..update = build(26); + await checkIfDue(tester); + + expect(updater.checks, 0); + expect(find.text('Install and Restart'), findsNothing); + }); + + testWidgets('does not look with a project open', (tester) async { + updater.update = build(26); + await checkIfDue(tester, onStartPage: false); + + expect(updater.checks, 0); + }); + + testWidgets('says nothing when there is no update', (tester) async { + await checkIfDue(tester); + + expect(updater.checks, 1); + expect(find.text('Install and Restart'), findsNothing); + }); + + testWidgets('says nothing when the check fails', (tester) async { + updater.fails = true; + await checkIfDue(tester); + + expect(find.textContaining('Could not'), findsNothing); + }); + + testWidgets('leaves out a skipped build, not a newer one', (tester) async { + updater + ..skipped = 26 + ..update = build(26); + await checkIfDue(tester); + expect(find.text('Install and Restart'), findsNothing); + + updater.update = build(27); + await checkIfDue(tester); + expect(find.text('Install and Restart'), findsOneWidget); + }); + + testWidgets('Help offers a skipped build anyway', (tester) async { + updater + ..skipped = 26 + ..update = build(26); + await run(tester, (context) => checkForUpdatesOnLinux(context, updater)); + + expect(find.text('Install and Restart'), findsOneWidget); + }); + + testWidgets('Install downloads, installs and quits', (tester) async { + var quits = 0; + updater.update = build(26); + await run( + tester, + (context) => + checkForUpdatesOnLinux(context, updater, quit: () async => quits++), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(updater.installed, 1); + expect(quits, 1); + }); + + testWidgets('an update installed but not started does not quit', ( + tester, + ) async { + var quits = 0; + updater + ..update = build(26) + ..installFailsToStart = true; + await run( + tester, + (context) => + checkForUpdatesOnLinux(context, updater, quit: () async => quits++), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pumpAndSettle(); + + expect(quits, 0); + expect(find.text('App Studio 0.4.26 is installed'), findsOneWidget); + }); + + testWidgets('a cancelled download installs nothing and stays', ( + tester, + ) async { + var quits = 0; + updater + ..update = build(26) + ..downloadCancelled = true; + await run( + tester, + (context) => + checkForUpdatesOnLinux(context, updater, quit: () async => quits++), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pumpAndSettle(); + + expect(updater.installed, 0); + expect(quits, 0); + }); +} + +class _FakeUpdater extends LinuxUpdater { + _FakeUpdater() + : super( + config: const LinuxUpdateConfig(appcastUrl: 'x', publicKey: 'y'), + environment: const {}, + executable: '/x', + ); + + bool due = true; + bool fails = false; + bool downloadCancelled = false; + bool installFailsToStart = false; + int? skipped; + AppcastItem? update; + int checks = 0; + int installed = 0; + + @override + Future runningVersion() async => const AppVersion('0.4.1', 25); + + @override + Future isCheckDue(DateTime now) async => due; + + @override + Future skippedBuild() async => skipped; + + @override + Future check() async { + checks++; + if (fails) { + throw const LinuxUpdateException('The update server answered 500.'); + } + return update; + } + + @override + Future download( + AppcastItem item, { + void Function(int received, int total)? onProgress, + UpdateCancellation? cancellation, + }) async { + onProgress?.call(item.length, item.length); + if (downloadCancelled) return null; + return VerifiedUpdate.forTesting('/tmp/part', item); + } + + @override + Future install(VerifiedUpdate update, {int? afterPid}) async { + installed++; + if (installFailsToStart) { + throw UpdateInstalledException( + update.item.version.version, + 'App Studio could not start it. Quit App Studio and start it again.', + ); + } + } +} diff --git a/test/update/linux/linux_update_dialog_test.dart b/test/update/linux/linux_update_dialog_test.dart new file mode 100644 index 0000000..1267a68 --- /dev/null +++ b/test/update/linux/linux_update_dialog_test.dart @@ -0,0 +1,280 @@ +import 'dart:async'; + +import 'package:appstudio/platform/linux/app_version.dart'; +import 'package:appstudio/update/linux/appcast.dart'; +import 'package:appstudio/update/linux/linux_update_dialog.dart'; +import 'package:appstudio/update/linux/update_signals.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shad/shad.dart'; + +final update = AppcastItem( + version: const AppVersion('0.4.2', 26), + url: Uri.parse('https://updates.test/AppStudio-0.4.2.AppImage'), + length: 1000, + signature: 'c2ln', +); +const current = AppVersion('0.4.1', 25); + +void main() { + /// Opens [dialog] over a page. The returned function says whether it has + /// closed. + Future open(WidgetTester tester, Widget dialog) async { + var closed = false; + await tester.pumpWidget( + ShadApp( + home: Builder( + builder: (context) => ShadButton( + onPressed: () async { + await showShadDialog( + context: context, + builder: (_) => dialog, + ); + closed = true; + }, + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + // The checking phase spins forever: fixed pumps, never pumpAndSettle. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + return () => closed; + } + + Future neverInstalls( + AppcastItem item, { + required void Function(int, int) onProgress, + required UpdateCancellation cancellation, + }) async => throw StateError('not expected'); + + testWidgets('a check that finds nothing says so', (tester) async { + final check = Completer(); + final closed = await open( + tester, + LinuxUpdateDialog.check( + current: current, + check: () => check.future, + install: neverInstalls, + ), + ); + expect(find.text('Checking for updates…'), findsOneWidget); + + check.complete(null); + await tester.pumpAndSettle(); + expect(find.text("You're up to date"), findsOneWidget); + expect(find.textContaining('0.4.1 is the newest'), findsOneWidget); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + expect(closed(), isTrue); + }); + + testWidgets('a failed check says why', (tester) async { + await open( + tester, + LinuxUpdateDialog.check( + current: current, + check: () async => throw Exception('The update server answered 500.'), + install: neverInstalls, + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Could not check for updates'), findsOneWidget); + expect(find.textContaining('answered 500'), findsOneWidget); + }); + + testWidgets('a check that finds a build offers it', (tester) async { + await open( + tester, + LinuxUpdateDialog.check( + current: current, + check: () async => update, + install: neverInstalls, + ), + ); + await tester.pumpAndSettle(); + expect(find.text('App Studio 0.4.2 is available'), findsOneWidget); + expect(find.textContaining('You have 0.4.1.'), findsOneWidget); + expect(find.text('Install and Restart'), findsOneWidget); + }); + + testWidgets('the same version names the builds', (tester) async { + await open( + tester, + LinuxUpdateDialog.offer( + current: const AppVersion('0.4.2', 25), + update: update, + install: neverInstalls, + ), + ); + await tester.pumpAndSettle(); + expect( + find.text('App Studio 0.4.2 (build 26) is available'), + findsOneWidget, + ); + }); + + testWidgets('Later closes and installs nothing', (tester) async { + final closed = await open( + tester, + LinuxUpdateDialog.offer( + current: current, + update: update, + install: neverInstalls, + ), + ); + await tester.tap(find.text('Later')); + await tester.pumpAndSettle(); + expect(closed(), isTrue); + }); + + testWidgets('Skip This Version skips it and closes', (tester) async { + AppcastItem? skipped; + final closed = await open( + tester, + LinuxUpdateDialog.offer( + current: current, + update: update, + install: neverInstalls, + onSkip: (item) async => skipped = item, + ), + ); + await tester.tap(find.text('Skip This Version')); + await tester.pumpAndSettle(); + expect(skipped, update); + expect(closed(), isTrue); + }); + + testWidgets('installing shows the download, then cannot be cancelled', ( + tester, + ) async { + late void Function(int, int) progress; + final done = Completer(); + await open( + tester, + LinuxUpdateDialog.offer( + current: current, + update: update, + install: (item, {required onProgress, required cancellation}) { + progress = onProgress; + return done.future; + }, + ), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pump(); + expect(find.text('Downloading App Studio 0.4.2'), findsOneWidget); + + progress(500, 1000); + await tester.pump(); + expect(find.textContaining('of'), findsOneWidget); + + progress(1000, 1000); + await tester.pump(); + expect(find.text('Installing App Studio 0.4.2'), findsOneWidget); + final cancel = tester.widget( + find.widgetWithText(ShadButton, 'Cancel'), + ); + expect(cancel.enabled, isFalse); + + // The app quits from here; finish so the test does not leak a future. + done.complete(true); + await tester.pump(); + }); + + testWidgets('Cancel stops the download and offers it again', (tester) async { + UpdateCancellation? seen; + await open( + tester, + LinuxUpdateDialog.offer( + current: current, + update: update, + install: (item, {required onProgress, required cancellation}) async { + seen = cancellation; + while (!cancellation.isCancelled) { + await Future.delayed(const Duration(milliseconds: 10)); + } + return false; + }, + ), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pump(); + await tester.tap(find.text('Cancel')); + await tester.pump(const Duration(milliseconds: 50)); + await tester.pumpAndSettle(); + + expect(seen!.isCancelled, isTrue); + expect(find.text('Install and Restart'), findsOneWidget); + }); + + testWidgets('a failed install says why and tries again', (tester) async { + var tries = 0; + await open( + tester, + LinuxUpdateDialog.offer( + current: current, + update: update, + install: (item, {required onProgress, required cancellation}) async { + tries++; + throw Exception('The download does not carry a valid signature.'); + }, + ), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pumpAndSettle(); + expect(find.text('Could not update App Studio'), findsOneWidget); + expect(find.textContaining('valid signature'), findsOneWidget); + + await tester.tap(find.text('Try Again')); + await tester.pumpAndSettle(); + expect(tries, 2); + }); + + testWidgets('installed but not started says so, with nothing to retry', ( + tester, + ) async { + await open( + tester, + LinuxUpdateDialog.offer( + current: current, + update: update, + install: (item, {required onProgress, required cancellation}) async => + throw const UpdateInstalledException( + '0.4.2', + 'App Studio could not start it. Quit App Studio and start it ' + 'again.', + ), + ), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pumpAndSettle(); + + expect(find.text('App Studio 0.4.2 is installed'), findsOneWidget); + expect(find.textContaining('start it again'), findsOneWidget); + expect(find.text('Try Again'), findsNothing); + }); + + testWidgets('taken off while downloading, it cancels', (tester) async { + UpdateCancellation? seen; + await open( + tester, + LinuxUpdateDialog.offer( + current: current, + update: update, + install: (item, {required onProgress, required cancellation}) { + seen = cancellation; + return Completer().future; + }, + ), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pump(); + + // A project opening clears every route. + await tester.pumpWidget(const SizedBox()); + expect(seen!.isCancelled, isTrue); + }); +} diff --git a/test/update/linux/linux_updater_test.dart b/test/update/linux/linux_updater_test.dart new file mode 100644 index 0000000..4a6d046 --- /dev/null +++ b/test/update/linux/linux_updater_test.dart @@ -0,0 +1,582 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:appstudio/platform/host_platform.dart'; +import 'package:appstudio/platform/linux/desktop_integration.dart'; +import 'package:appstudio/update/linux/appcast.dart'; +import 'package:appstudio/update/linux/linux_updater.dart'; +import 'package:cryptography/cryptography.dart'; +import 'package:cryptography/dart.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:path/path.dart' as p; +import 'package:shared_preferences/shared_preferences.dart'; + +/// The Linux updater against a temporary folder and a fake HTTP server, so +/// it runs on any host. The signatures are real Ed25519 ones. +void main() { + late Directory root; + late String appImage; + late String appDir; + late Map env; + late SimpleKeyPair keys; + late String publicKey; + late AppVersion running; + + /// What the fake server serves: the feed, and the files by URL path. + late String feedBody; + late Map> files; + late int feedStatus; + + final newer = utf8.encode('#!/bin/sh\necho the newer build\n'); + + Future sign(List bytes) async => + base64.encode((await DartEd25519().sign(bytes, keyPair: keys)).bytes); + + Future feedFor( + List bytes, { + int build = 26, + int? length, + String? signature, + }) async => + ''' + + +'''; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + running = const AppVersion('0.4.1', 25); + root = await Directory.systemTemp.createTemp('linux_updater'); + appDir = p.join(root.path, 'mount'); + appImage = p.join(root.path, 'AppImages', 'AppStudio-x86_64.AppImage'); + await File(appImage).create(recursive: true); + await File(appImage).writeAsString('the running build'); + env = { + 'HOME': p.join(root.path, 'home'), + 'APPIMAGE': appImage, + 'APPDIR': appDir, + 'XDG_DATA_DIRS': p.join(root.path, 'system'), + }; + keys = await DartEd25519().newKeyPair(); + publicKey = base64.encode((await keys.extractPublicKey()).bytes); + files = {'/AppStudio-0.4.2.AppImage': newer}; + feedStatus = 200; + feedBody = await feedFor(newer); + }); + + tearDown(() => root.delete(recursive: true)); + + http.Client client() => MockClient.streaming((request, _) async { + if (request.url.path == '/appcast.xml') { + return http.StreamedResponse( + Stream.value(utf8.encode(feedBody)), + feedStatus, + ); + } + final body = files[request.url.path]; + if (body == null) return http.StreamedResponse(const Stream.empty(), 404); + // In chunks, as a real download arrives. + return http.StreamedResponse( + Stream.fromIterable([ + for (var i = 0; i < body.length; i += 8) + body.sublist(i, i + 8 > body.length ? body.length : i + 8), + ]), + 200, + ); + }); + + LinuxUpdater updater({ + LinuxUpdateConfig? config, + Map? environment, + }) { + final e = environment ?? env; + final executable = p.join(appDir, 'usr', 'lib', 'appstudio', 'appstudio'); + return LinuxUpdater( + config: + config ?? + LinuxUpdateConfig( + appcastUrl: 'https://updates.test/appcast.xml', + publicKey: publicKey, + ), + environment: e, + executable: executable, + client: client(), + runningVersion: () async => running, + desktop: DesktopIntegration( + environment: e, + host: HostPlatform.linux, + executable: executable, + runningVersion: () async => running, + ), + ); + } + + String part() => p.join(p.dirname(appImage), LinuxUpdater.partName); + + /// App Studio's own menu entry, naming [file] and recording [version]. + Future writeOwnEntry(String file, AppVersion version) async { + final entry = File( + p.join( + env['HOME']!, + '.local', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ), + ); + await entry.create(recursive: true); + await entry.writeAsString( + '[Desktop Entry]\nName=App Studio\nTryExec=$file\n' + 'X-AppStudio-AddedBy=appstudio\n' + 'X-AppStudio-Version=${version.version}\n' + 'X-AppStudio-Build=${version.build}\n', + ); + } + + group('state', () { + test('is configured as an AppImage with a feed and a key', () async { + final state = await updater().state(); + expect(state.canCheck, isTrue); + expect(state.currentVersion, '0.4.1'); + expect(state.currentBuild, '25'); + expect(state.automaticallyChecks, isTrue, reason: 'on by default'); + }); + + test('is not without a feed or a key', () async { + for (final config in const [ + LinuxUpdateConfig(appcastUrl: '', publicKey: 'k'), + LinuxUpdateConfig(appcastUrl: 'https://x', publicKey: ''), + ]) { + expect((await updater(config: config).state()).canCheck, isFalse); + } + }); + + test('is not outside an AppImage, but still knows the version', () async { + final state = await updater(environment: const {}).state(); + expect(state.canCheck, isFalse); + expect(state.currentVersion, '0.4.1'); + }); + + test('remembers automatic checks switched off', () async { + await updater().setAutomaticallyChecks(false); + expect((await updater().state()).automaticallyChecks, isFalse); + }); + }); + + group('check', () { + test('finds the newer build and records the check', () async { + final update = await updater().check(); + expect(update!.version, const AppVersion('0.4.2', 26)); + expect((await updater().state()).lastCheck, isNotNull); + }); + + test('finds nothing when this is the newest', () async { + running = const AppVersion('0.4.2', 26); + expect(await updater().check(), isNull); + }); + + test('says why a feed cannot be read', () async { + feedStatus = 404; + await expectLater( + updater().check(), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('404'), + ), + ), + ); + feedStatus = 200; + feedBody = ''; + await expectLater( + updater().check(), + throwsA(isA()), + ); + expect( + (await updater().state()).lastCheck, + isNotNull, + reason: 'a failing feed is not asked again every hour', + ); + }); + + test('refuses a feed over plain http', () async { + await expectLater( + updater( + config: LinuxUpdateConfig( + appcastUrl: 'http://updates.example.com/appcast.xml', + publicKey: publicKey, + ), + ).check(), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('https'), + ), + ), + ); + }); + + test('clears a download an earlier run left behind', () async { + await File(part()).writeAsString('half a download'); + await updater().check(); + expect(await File(part()).exists(), isFalse); + }); + + test('refuses to run without a feed', () async { + await expectLater( + updater( + config: const LinuxUpdateConfig(appcastUrl: '', publicKey: ''), + ).check(), + throwsA(isA()), + ); + }); + }); + + group('is a check due', () { + test('when there was none, or the last is a day old', () async { + final now = DateTime.now(); + expect(await updater().isCheckDue(now), isTrue); + await updater().check(); + expect(await updater().isCheckDue(now), isFalse); + expect( + await updater().isCheckDue( + now.add(const Duration(days: 1, minutes: 1)), + ), + isTrue, + ); + }); + + test('never with automatic checks off', () async { + await updater().setAutomaticallyChecks(false); + expect(await updater().isCheckDue(DateTime.now()), isFalse); + }); + }); + + group('download', () { + Future item() async => (await updater().check())!; + + test('writes a checked, executable file beside the AppImage', () async { + final progress = []; + final verified = await updater().download( + await item(), + onProgress: (received, _) => progress.add(received), + ); + + expect(verified!.path, part()); + expect(await File(part()).readAsBytes(), newer); + expect(progress.last, newer.length); + if (!Platform.isWindows) { + expect((await File(part()).stat()).modeString(), 'rwxr-xr-x'); + } + expect(await File(appImage).readAsString(), 'the running build'); + }); + + test('refuses a file with another signature, and deletes it', () async { + feedBody = await feedFor( + newer, + signature: await sign(utf8.encode('something else')), + ); + await expectLater( + updater().download(await item()), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('signature'), + ), + ), + ); + expect(await File(part()).exists(), isFalse); + }); + + test('refuses a file signed with another key', () async { + final other = await DartEd25519().newKeyPair(); + feedBody = await feedFor( + newer, + signature: base64.encode( + (await DartEd25519().sign(newer, keyPair: other)).bytes, + ), + ); + await expectLater( + updater().download(await item()), + throwsA(isA()), + ); + }); + + test('refuses a download over plain http', () async { + final insecure = AppcastItem( + version: const AppVersion('0.4.2', 26), + url: Uri.parse('http://updates.example.com/AppStudio.AppImage'), + length: newer.length, + signature: await sign(newer), + ); + await expectLater( + updater().download(insecure), + throwsA(isA()), + ); + expect(await File(part()).exists(), isFalse); + }); + + test('does not write through a link left in its place', () async { + if (Platform.isWindows) return; + final elsewhere = p.join(root.path, 'elsewhere'); + await File(elsewhere).writeAsString('not ours to change'); + await Link(part()).create(elsewhere); + + await updater().download(await item()); + + expect(await File(elsewhere).readAsString(), 'not ours to change'); + expect(await File(part()).readAsBytes(), newer); + }); + + test('runs one download at a time, and a check leaves it alone', () async { + final u = updater(); + final first = (await u.check())!; + var checkedDuring = false; + final verified = await u.download( + first, + onProgress: (received, _) async { + if (checkedDuring) return; + checkedDuring = true; + // The menu stays usable under the dialog: a second download is + // refused, and a check must not delete this one's file. + await expectLater( + u.download(first), + throwsA(isA()), + ); + await u.check(); + expect(await File(part()).exists(), isTrue); + }, + ); + expect(checkedDuring, isTrue); + expect(verified, isNotNull); + expect(await File(part()).readAsBytes(), newer); + }); + + test('refuses a file of another length', () async { + feedBody = await feedFor(newer, length: newer.length + 1); + await expectLater( + updater().download(await item()), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('bytes'), + ), + ), + ); + expect(await File(part()).exists(), isFalse); + }); + + test('stops when cancelled, and deletes what it wrote', () async { + final cancellation = UpdateCancellation(); + final verified = await updater().download( + await item(), + cancellation: cancellation, + onProgress: (_, _) => cancellation.cancel(), + ); + expect(verified, isNull); + expect(await File(part()).exists(), isFalse); + }); + + test('says so where the AppImage cannot be replaced', () async { + if (Platform.isWindows) return; + final uid = await Process.run('id', ['-u']); + if ('${uid.stdout}'.trim() == '0') { + markTestSkipped('root can write anywhere'); + return; + } + final folder = p.dirname(appImage); + await Process.run('chmod', ['555', folder]); + addTearDown(() => Process.run('chmod', ['755', folder])); + + await expectLater( + updater().download(await item()), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('cannot replace itself'), + ), + ), + ); + }, tags: 'process'); + }); + + group('install', () { + test( + 'replaces the AppImage and starts it once this process has ended', + () async { + final marker = p.join(root.path, 'started'); + files['/AppStudio-0.4.2.AppImage'] = utf8.encode( + '#!/bin/sh\necho started > "$marker"\n', + ); + feedBody = await feedFor(files['/AppStudio-0.4.2.AppImage']!); + final u = updater(); + final verified = await u.download((await u.check())!); + final ended = await Process.start('true', []); + await ended.exitCode; + + await u.install(verified!, afterPid: ended.pid); + + expect(await File(part()).exists(), isFalse); + expect(await File(appImage).readAsString(), contains('started')); + final end = DateTime.now().add(const Duration(seconds: 5)); + while (!await File(marker).exists() && DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 50)); + } + expect(await File(marker).exists(), isTrue); + }, + tags: 'process', + testOn: '!windows', + ); + + test( + 'records the new version in App Studio\'s menu entry', + () async { + final entry = File( + p.join( + env['HOME']!, + '.local', + 'share', + 'applications', + 'dev.serverpod.appstudio.desktop', + ), + ); + await entry.create(recursive: true); + await entry.writeAsString( + '[Desktop Entry]\nName=App Studio\nTryExec=$appImage\n' + 'X-AppStudio-AddedBy=appstudio\nX-AppStudio-Version=0.4.1\n' + 'X-AppStudio-Build=25\n', + ); + final u = updater(); + final verified = await u.download((await u.check())!); + final ended = await Process.start('true', []); + await ended.exitCode; + + await u.install(verified!, afterPid: ended.pid); + + final keys = parseDesktopEntry(await entry.readAsString()); + expect(keys['X-AppStudio-Version'], '0.4.2'); + expect(keys['X-AppStudio-Build'], '26'); + }, + tags: 'process', + testOn: '!windows', + ); + }); + + group('after Add to Applications in the same run', () { + test('never takes another file it finds in ~/AppImages', () async { + // The started copy was deleted, not moved; a newer one sits in + // ~/AppImages, left there after Remove. It is not this App Studio. + final other = p.join( + env['HOME']!, + 'AppImages', + 'AppStudio-x86_64.AppImage', + ); + await File(other).create(recursive: true); + await writeOwnEntry(other, const AppVersion('0.4.3', 27)); + await File(appImage).delete(); + + expect(await updater().liveAppImage(), isNull); + }); + + test( + 'replaces the file in ~/AppImages, not where it was started from', + () async { + // Add moved the running file; `$APPIMAGE` still names the old place. + final added = p.join( + env['HOME']!, + 'AppImages', + 'AppStudio-x86_64.AppImage', + ); + await File(added).create(recursive: true); + await File(appImage).rename(added); + await writeOwnEntry(added, running); + final u = updater(); + + expect(await u.liveAppImage(), added); + final verified = await u.download((await u.check())!); + expect(p.dirname(verified!.path), p.dirname(added)); + final ended = await Process.start('true', []); + await ended.exitCode; + await u.install(verified, afterPid: ended.pid); + + expect(await File(added).readAsBytes(), newer); + expect(await File(appImage).exists(), isFalse); + }, + tags: 'process', + testOn: '!windows', + ); + }); + + group('verifyEd25519File', () { + test( + 'accepts what openssl signs, as the release pipeline does', + () async { + final openssl = await Process.run('which', ['openssl']); + if (openssl.exitCode != 0) { + markTestSkipped('needs openssl'); + return; + } + final key = p.join(root.path, 'key.pem'); + final file = p.join(root.path, 'file'); + await File(file).writeAsBytes(newer); + await Process.run('openssl', [ + 'genpkey', + '-algorithm', + 'ed25519', + '-out', + key, + ]); + final sig = p.join(root.path, 'sig'); + await Process.run('openssl', [ + 'pkeyutl', + '-sign', + '-inkey', + key, + '-rawin', + '-in', + file, + '-out', + sig, + ]); + final der = await Process.run('openssl', [ + 'pkey', + '-in', + key, + '-pubout', + '-outform', + 'DER', + ], stdoutEncoding: null); + final derBytes = der.stdout as List; + final public = base64.encode(derBytes.sublist(derBytes.length - 32)); + final signature = base64.encode(await File(sig).readAsBytes()); + + expect(await verifyEd25519File(file, signature, public), isTrue); + await File(file).writeAsString('changed'); + expect(await verifyEd25519File(file, signature, public), isFalse); + }, + tags: 'process', + testOn: '!windows', + ); + + test('rejects a malformed signature or key', () async { + final file = p.join(root.path, 'file'); + await File(file).writeAsBytes(newer); + expect(await verifyEd25519File(file, 'not base64!', publicKey), isFalse); + expect( + await verifyEd25519File(file, base64.encode([1]), publicKey), + isFalse, + ); + }); + }); +} diff --git a/test/update/update_controller_test.dart b/test/update/update_controller_test.dart index da28a49..22fa854 100644 --- a/test/update/update_controller_test.dart +++ b/test/update/update_controller_test.dart @@ -2,6 +2,8 @@ import 'package:appstudio/agent/agent_controller.dart'; import 'package:appstudio/cloud/cloud_publish.dart'; import 'package:appstudio/process/serverpod_process.dart'; import 'package:appstudio/session/project_session.dart'; +import 'package:appstudio/platform/linux/app_version.dart'; +import 'package:appstudio/update/linux/linux_updater.dart'; import 'package:appstudio/update/update_controller.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -231,6 +233,52 @@ void main() { expect(calls, isEmpty); }); + + group('on Linux', () { + Future createLinux() => UpdateController.create( + process: process, + agent: agent, + cloud: CloudPublishController( + toolchains: process.toolchains, + session: process.session, + ), + linux: LinuxUpdater( + config: const LinuxUpdateConfig( + appcastUrl: 'https://updates.test/appcast.xml', + publicKey: 'key', + ), + environment: const { + 'APPIMAGE': '/home/alex/AppImages/AppStudio-x86_64.AppImage', + 'APPDIR': '/tmp/.mount_App', + }, + executable: '/tmp/.mount_App/usr/lib/appstudio/appstudio', + runningVersion: () async => const AppVersion('0.4.1', 25), + ), + ); + + test('reads its state from the Linux updater, not a channel', () async { + mockChannel({}); + final controller = await createLinux(); + addTearDown(controller.dispose); + + expect(controller.state.canCheck, isTrue); + expect(controller.state.versionLabel, 'Version 0.4.1 (build 25)'); + expect(calls, isEmpty); + }); + + test('keeps automatic checks in its preferences', () async { + mockChannel({}); + final controller = await createLinux(); + addTearDown(controller.dispose); + + await controller.setAutomaticallyChecks(false); + + expect(controller.state.automaticallyChecks, isFalse); + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getBool(LinuxUpdater.automaticKey), isFalse); + expect(calls, isEmpty); + }); + }); } /// Sentinel telling the mock handler to throw for that method. diff --git a/tool/linux/appcast.sh b/tool/linux/appcast.sh new file mode 100755 index 0000000..64f6dc0 --- /dev/null +++ b/tool/linux/appcast.sh @@ -0,0 +1,181 @@ +#!/usr/bin/env bash +# Signs an AppImage and adds it to a Linux update feed, newest first. +# +# Usage: +# tool/linux/appcast.sh --key --url \ +# --feed -x86_64.AppImage> +# +# --key the Ed25519 private key, PEM, as `openssl genpkey -algorithm +# ed25519` writes it. Never commit it. +# --url where the AppImage will be downloaded from, as installed copies +# will fetch it: https (plain http only to a private address). +# --feed the appcast to add the item to; created when it does not exist. +# +# The version and build come from the AppImage itself (the version.json +# Flutter writes into the bundle), so a feed can never describe a file as +# another build. The script refuses a build the feed already has or has +# passed: installed copies order releases by build alone, and one served +# twice, or lower, would never be offered. +# +# The signature is checked against the public key in linux/release.json, the +# key installed copies carry, before the feed is written. With no key there +# yet (a local feed), the key is derived from --key and the script says so; +# such a feed only reaches builds made with +# APPSTUDIO_EDDSA_PUBLIC_KEY set to that key. +# +# Needs: openssl, python3, base64. +set -euo pipefail + +root="$(cd "$(dirname "$0")/../.." && pwd)" +key="" url="" feed="" +while (( $# )); do + case "$1" in + --key) key="$2"; shift 2 ;; + --url) url="$2"; shift 2 ;; + --feed) feed="$2"; shift 2 ;; + -*) echo "Unknown option: $1" >&2; exit 2 ;; + *) break ;; + esac +done +if [[ -z "$key" || -z "$url" || -z "$feed" || $# -ne 1 ]]; then + sed -n '4,6p' "$0" | sed 's/^# //' >&2 + exit 2 +fi +appimage="$1" +for cmd in openssl python3 base64; do + command -v "$cmd" > /dev/null || { echo "Missing on this machine: $cmd" >&2; exit 1; } +done +[[ -f "$appimage" ]] || { echo "No such file: $appimage" >&2; exit 1; } +# Its version is read by running it (--appimage-extract). +[[ -x "$appimage" ]] || { echo "Not executable (chmod +x it): $appimage" >&2; exit 1; } +# https only, as installed copies insist; plain http only to this machine or +# a private address, for a local feed. +if ! python3 -c ' +import ipaddress, re, sys, urllib.parse +# The same rule as isSecureUpdateUrl in lib/update/linux/appcast.dart. +u = urllib.parse.urlsplit(sys.argv[1]) +host = u.hostname or "" +if u.scheme.lower() == "https" and host: + sys.exit(0) +if u.scheme.lower() != "http": + sys.exit(1) +if host in ("localhost", "::1"): + sys.exit(0) +octet = r"(0|[1-9][0-9]{0,2})" +if not re.fullmatch(rf"{octet}(\.{octet}){{3}}", host): + sys.exit(1) +try: + ip = ipaddress.IPv4Address(host) +except ValueError: + sys.exit(1) +nets = ("127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16") +sys.exit(0 if any(ip in ipaddress.ip_network(n) for n in nets) else 1)' "$url"; then + echo "The download URL must be an https address: $url" >&2 + exit 1 +fi +[[ -f "$key" ]] || { echo "No such key: $key" >&2; exit 1; } + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# --- What the AppImage is ---------------------------------------------------- + +appimage_abs="$(cd "$(dirname "$appimage")" && pwd)/$(basename "$appimage")" +(cd "$work" && "$appimage_abs" --appimage-extract \ + usr/lib/appstudio/data/flutter_assets/version.json > /dev/null) +version_json="$work/squashfs-root/usr/lib/appstudio/data/flutter_assets/version.json" +[[ -f "$version_json" ]] || { echo "No version.json in $appimage." >&2; exit 1; } +read -r version build < <(python3 -c ' +import json, sys +v = json.load(open(sys.argv[1])) +print(v["version"], v["build_number"])' "$version_json") +length="$(stat -c %s "$appimage")" +echo "==> AppStudio $version (build $build), $length bytes" + +# --- Signature --------------------------------------------------------------- + +openssl pkeyutl -sign -inkey "$key" -rawin -in "$appimage" -out "$work/sig.bin" +signature="$(base64 -w0 "$work/sig.bin")" + +shipped="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1])).get("eddsaPublicKey", ""))' \ + "$root/linux/release.json")" +if [[ -z "$shipped" ]]; then + shipped="$(openssl pkey -in "$key" -pubout -outform DER | tail -c 32 | base64 -w0)" + echo "linux/release.json names no public key: checking against the key's own." + echo "Builds see this feed only with APPSTUDIO_EDDSA_PUBLIC_KEY=$shipped" +fi +# The raw 32-byte key, wrapped as the DER openssl reads. +python3 -c ' +import base64, sys +raw = base64.b64decode(sys.argv[1], validate=True) +assert len(raw) == 32, "the public key is not 32 bytes" +der = bytes.fromhex("302a300506032b6570032100") + raw +sys.stdout.buffer.write(der)' "$shipped" > "$work/public.der" +if ! openssl pkeyutl -verify -pubin -keyform DER -inkey "$work/public.der" \ + -rawin -in "$appimage" -sigfile "$work/sig.bin" > /dev/null; then + echo "The signature does not verify against the shipped public key." >&2 + exit 1 +fi + +# --- The feed ---------------------------------------------------------------- + +python3 - "$feed" "$version" "$build" "$url" "$length" "$signature" << 'PY' +import email.utils, os, re, sys, tempfile +import xml.etree.ElementTree as ET +from xml.sax.saxutils import quoteattr, escape + +feed, version, build, url, length, signature = sys.argv[1:] +build = int(build) +SPARKLE = "http://www.andymatuschak.org/xml-namespaces/sparkle" + +if os.path.exists(feed): + text = open(feed, encoding="utf-8").read() + channel = ET.fromstring(text).find("channel") + if channel is None: + sys.exit("The feed has no .") + builds = [ + int(e.get(f"{{{SPARKLE}}}version")) + for e in channel.iter("enclosure") + if e.get(f"{{{SPARKLE}}}os") == "linux-x86_64" + ] + if builds and build <= max(builds): + sys.exit(f"The feed already serves build {max(builds)}; this is {build}.") +else: + text = ( + '\n' + f'\n' + " \n" + " App Studio for Linux\n" + " https://serverpod.dev\n" + " \n" + "\n" + ) + +item = f""" + Version {escape(version)} + {email.utils.formatdate(usegmt=True)} + + + """ +# Newest first: before the first item, or at the end of the channel. +first = text.find("") +if first >= 0: + text = text[:first] + item + text[first:] +else: + text = re.sub(r"(\s*)", "\n " + item.rstrip() + r"\1", text, count=1) + +ET.fromstring(text) # still well-formed +folder = os.path.dirname(os.path.abspath(feed)) +fd, tmp = tempfile.mkstemp(dir=folder, prefix=".appcast-") +with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(text) +os.chmod(tmp, 0o644) +os.replace(tmp, feed) +PY +echo "==> Added build $build to $feed" diff --git a/tool/linux/build_appimage.sh b/tool/linux/build_appimage.sh index 715e5c1..c249617 100755 --- a/tool/linux/build_appimage.sh +++ b/tool/linux/build_appimage.sh @@ -9,6 +9,7 @@ # Optional environment: # FLUTTER the flutter to build with (default: flutter on PATH) # SKIP_BUILD=1 package the release build that is already there +# (with the update feed it was built with) # APPIMAGETOOL path to appimagetool; the pinned release is # downloaded into build/linux/tools if unset # APPIMAGE_UPDATE_INFO update information for AppImageUpdate and Gear Lever, @@ -18,6 +19,12 @@ # that fixed URL. Gear Lever offers an update whenever # the .zsync's SHA-1 differs from the installed # file's; it does not compare versions. +# APPSTUDIO_APPCAST_URL, APPSTUDIO_EDDSA_PUBLIC_KEY +# the update feed and the public key that checks its +# downloads, compiled in. They come from +# linux/release.json (appcastUrl, eddsaPublicKey); +# set here they override it, for a local feed. Empty, +# the build reports updates as unavailable. # APPIMAGE_FILE_URL where this AppImage will be downloaded from, written # into the .zsync, e.g. "https:///releases/linux/ # /b/AppStudio--x86_64.AppImage". @@ -59,6 +66,52 @@ if (( ${#missing[@]} )); then exit 1 fi +# --- Update feed ----------------------------------------------------------- + +# From linux/release.json unless the environment overrides it, as +# windows/release.json does for Windows. In-app updates need both. +read_release() { + python3 -c 'import json, sys; print(json.load(open(sys.argv[1])).get(sys.argv[2], ""))' \ + "$root/linux/release.json" "$1" +} +appcast_url="${APPSTUDIO_APPCAST_URL:-$(read_release appcastUrl)}" +eddsa_public_key="${APPSTUDIO_EDDSA_PUBLIC_KEY:-$(read_release eddsaPublicKey)}" +# https only, as the app itself insists: the signature covers the file, not +# the feed. Plain http is allowed to this machine or a private address, for +# a local feed. +secure_url() { + python3 -c ' +import ipaddress, re, sys, urllib.parse +# The same rule as isSecureUpdateUrl in lib/update/linux/appcast.dart. +u = urllib.parse.urlsplit(sys.argv[1]) +host = u.hostname or "" +if u.scheme.lower() == "https" and host: + sys.exit(0) +if u.scheme.lower() != "http": + sys.exit(1) +if host in ("localhost", "::1"): + sys.exit(0) +octet = r"(0|[1-9][0-9]{0,2})" +if not re.fullmatch(rf"{octet}(\.{octet}){{3}}", host): + sys.exit(1) +try: + ip = ipaddress.IPv4Address(host) +except ValueError: + sys.exit(1) +nets = ("127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16") +sys.exit(0 if any(ip in ipaddress.ip_network(n) for n in nets) else 1)' "$1" +} +if [[ -n "$appcast_url" ]] && ! secure_url "$appcast_url"; then + echo "The update feed must be an https address: $appcast_url" >&2 + exit 1 +fi +if [[ -n "$eddsa_public_key" ]] && + ! python3 -c 'import base64, sys; sys.exit(len(base64.b64decode(sys.argv[1], validate=True)) != 32)' \ + "$eddsa_public_key" 2> /dev/null; then + echo "The update public key is not base64 of 32 bytes." >&2 + exit 1 +fi + # --- Build ----------------------------------------------------------------- if [[ "${SKIP_BUILD:-}" != 1 ]]; then @@ -74,7 +127,14 @@ if [[ "${SKIP_BUILD:-}" != 1 ]]; then windows/flutter/generated_plugins.cmake } trap restore_generated EXIT - (cd "$root" && "$flutter" build linux --release) + if [[ -n "$appcast_url" && -n "$eddsa_public_key" ]]; then + echo "In-app updates from $appcast_url" + else + echo "In-app updates off: no feed or no key (linux/release.json)" + fi + (cd "$root" && "$flutter" build linux --release \ + --dart-define="APPSTUDIO_APPCAST_URL=$appcast_url" \ + --dart-define="APPSTUDIO_EDDSA_PUBLIC_KEY=$eddsa_public_key") restore_generated trap - EXIT fi diff --git a/widgetbook/use_cases/start.dart b/widgetbook/use_cases/start.dart index dc9d630..94908e8 100644 --- a/widgetbook/use_cases/start.dart +++ b/widgetbook/use_cases/start.dart @@ -1,9 +1,14 @@ +import 'dart:async'; + import 'package:appstudio/platform/linux/app_version.dart'; import 'package:appstudio/process/ide_integration.dart'; import 'package:appstudio/process/new_project_view.dart'; import 'package:appstudio/ui/add_to_applications_dialog.dart'; import 'package:appstudio/ui/new_project_dialog.dart'; import 'package:appstudio/ui/start_page.dart'; +import 'package:appstudio/update/linux/appcast.dart'; +import 'package:appstudio/update/linux/linux_update_dialog.dart'; +import 'package:appstudio/update/linux/update_signals.dart'; import 'package:flutter/material.dart'; import 'package:widgetbook/widgetbook.dart'; @@ -35,6 +40,21 @@ Widget _createProject( ), ); +final _sampleUpdate = AppcastItem( + version: const AppVersion('0.4.2', 26), + url: Uri.parse('https://example.com/AppStudio-0.4.2-x86_64.AppImage'), + length: 143997432, + signature: '', +); + +/// The catalog never installs: Install and Restart waits forever. +Future _neverInstalls( + AppcastItem item, { + required void Function(int received, int total) onProgress, + required UpdateCancellation cancellation, +}) => + Completer().future; + /// A Linux dialog over the start page, where the question on first start /// appears. DialogUseCase _overStartPage(Widget dialog) => DialogUseCase( @@ -197,6 +217,53 @@ final startFolder = WidgetbookFolder( ), ], ), + WidgetbookComponent( + name: 'Update (Linux)', + useCases: [ + WidgetbookUseCase( + name: 'Checking', + builder: (_) => _overStartPage( + LinuxUpdateDialog.check( + current: const AppVersion('0.4.1', 25), + check: () => Completer().future, + install: _neverInstalls, + ), + ), + ), + WidgetbookUseCase( + name: 'Up to date', + builder: (_) => _overStartPage( + LinuxUpdateDialog.check( + current: const AppVersion('0.4.1', 25), + check: () async => null, + install: _neverInstalls, + ), + ), + ), + WidgetbookUseCase( + name: 'Could not check', + builder: (_) => _overStartPage( + LinuxUpdateDialog.check( + current: const AppVersion('0.4.1', 25), + check: () async => + throw Exception('The update server answered 503.'), + install: _neverInstalls, + ), + ), + ), + WidgetbookUseCase( + name: 'Available', + builder: (_) => _overStartPage( + LinuxUpdateDialog.offer( + current: const AppVersion('0.4.1', 25), + update: _sampleUpdate, + install: _neverInstalls, + onSkip: (_) async {}, + ), + ), + ), + ], + ), WidgetbookComponent( name: 'Remove from Applications (Linux)', useCases: [ From 97a09ac8ddfffd3b417f37743ce9852fe140dd94 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 13:16:17 +0100 Subject: [PATCH 22/32] fix: Shows App Studio's icon in the app menu right after Add. Add copies the icons into ~/.local/share/icons/hicolor//apps, but GTK rescans a theme, and judges an icon cache stale, only when the hicolor folder itself changes. When those folders were already there (any app that puts icons there, or an earlier Remove), the app menu showed a generic icon until the next login. Add and Remove now add a file to the hicolor folder and take it away again before rebuilding an icon cache, as xdg-icon-resource does. Remove no longer creates the folder where there was none. --- lib/platform/linux/desktop_integration.dart | 22 +++++++-- specs/linux_appimage.md | 15 ++++-- .../linux/desktop_integration_test.dart | 49 +++++++++++++++++++ 3 files changed, 79 insertions(+), 7 deletions(-) diff --git a/lib/platform/linux/desktop_integration.dart b/lib/platform/linux/desktop_integration.dart index 4165541..526a810 100644 --- a/lib/platform/linux/desktop_integration.dart +++ b/lib/platform/linux/desktop_integration.dart @@ -451,11 +451,27 @@ class DesktopIntegration { } } - /// Rebuilds the user's icon cache, but only where one exists: without a - /// cache, icons are looked up on disk and a new one shows at once. Best - /// effort; a stale cache only costs the icon until the next rebuild. + /// Tells the desktop the icons changed, as `xdg-icon-resource` does. + /// GTK rescans a theme only when the theme folder's own modification time + /// moves, not its size folders', and judges an icon cache stale the same + /// way: icons copied into folders an earlier Add left behind stayed + /// generic until the next login. So the folder's time is moved first, by + /// adding a file and taking it away again (xdg's `.xdg-icon-resource-dummy` + /// does the same), and then an icon cache, where there is one, is + /// rebuilt. Should the rebuild fail, the moved time still marks the old + /// cache stale, and icons are looked up on disk. Best effort; a missed + /// refresh only costs the icon until the next one. Future _refreshIconCache(String dataHome) async { final hicolor = p.join(dataHome, 'icons', 'hicolor'); + // Nothing to refresh, and no folder to create, where none is. + if (!await Directory(hicolor).exists()) return; + try { + final marker = File(p.join(hicolor, '.appstudio-$pid')); + await marker.create(); + await marker.delete(); + } on FileSystemException catch (e) { + debugPrint('Could not refresh the icons in $hicolor: $e'); + } if (!await File(p.join(hicolor, 'icon-theme.cache')).exists()) return; try { await Process.run('gtk-update-icon-cache', ['-f', '-t', hicolor]); diff --git a/specs/linux_appimage.md b/specs/linux_appimage.md index af85965..4be6926 100644 --- a/specs/linux_appimage.md +++ b/specs/linux_appimage.md @@ -172,10 +172,17 @@ The dialog stays open while it runs and shows any error in it. reads half an entry. The file name is the application id, so on Wayland the dock can match the window to it by its app id as well as by `StartupWMClass`. -4. **Rebuilds the icon cache if there is one**: when - `$XDG_DATA_HOME/icons/hicolor/icon-theme.cache` exists, it runs - `gtk-update-icon-cache -f -t` on that folder (best effort). Without a - cache, icons are looked up on disk. +4. **Tells the desktop the icons changed**, as `xdg-icon-resource` does. + GTK rescans the theme, and judges an icon cache stale, only when the + `hicolor` folder's own modification time moves, not its size folders'. + Copied into folders an earlier Add left behind (Remove keeps them), the + icon stayed generic until the next login. So Add first moves the + folder's time, by adding a file and taking it away again (xdg's + `.xdg-icon-resource-dummy`), then runs `gtk-update-icon-cache -f -t` on + the folder when `$XDG_DATA_HOME/icons/hicolor/icon-theme.cache` exists + (best effort; should it fail, the old cache is already stale and icons + are looked up on disk). Remove does the same, and creates no folder + where there was none. 5. **Shows a toast**: "Added to your applications". `update-desktop-database` is not run: it only writes `mimeinfo.cache` from diff --git a/test/platform/linux/desktop_integration_test.dart b/test/platform/linux/desktop_integration_test.dart index 7d5fc03..3025934 100644 --- a/test/platform/linux/desktop_integration_test.dart +++ b/test/platform/linux/desktop_integration_test.dart @@ -344,6 +344,43 @@ Exec=appstudio --extra ); }); + test( + 'tells the desktop about icons copied into folders that were there', + () async { + // An earlier Add and Remove left the size folders; GTK only rescans + // when the theme folder itself changes. + final hicolor = p.join(home, '.local', 'share', 'icons', 'hicolor'); + await Directory( + p.join(hicolor, '256x256', 'apps'), + ).create(recursive: true); + await Directory( + p.join(hicolor, '16x16', 'apps'), + ).create(recursive: true); + // `-t` reads the same on GNU and BSD touch. + final backdated = await Process.run('touch', [ + '-t', + '200001010000', + hicolor, + ]); + expect(backdated.exitCode, 0, reason: '${backdated.stderr}'); + expect((await Directory(hicolor).stat()).modified.year, 2000); + + await integration().add(); + + final modified = (await Directory(hicolor).stat()).modified; + expect(modified.year, greaterThan(2000)); + expect( + await Directory( + hicolor, + ).list().map((e) => p.basename(e.path)).toList(), + unorderedEquals(['256x256', '16x16']), + reason: 'nothing left behind', + ); + }, + tags: 'process', + testOn: '!windows', + ); + test('leaves an AppImage already in place where it is', () async { await File(target()).create(recursive: true); await File(target()).writeAsString('in place'); @@ -810,6 +847,18 @@ Exec=appstudio --extra }, ); + test('leaves no icon folder behind where there was none', () async { + await integration().add(); + final hicolor = Directory( + p.join(home, '.local', 'share', 'icons', 'hicolor'), + ); + await hicolor.delete(recursive: true); + + await integration().remove(); + + expect(await hicolor.exists(), isFalse); + }); + test('says so when there is no entry to remove', () async { await expectLater( integration().remove(), From e543bc0902e2e590a18181948d08b1c73e509dfd Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:28:57 +0100 Subject: [PATCH 23/32] fix: Keeps a version from the update feed out of the menu entry's other lines. The feed is not signed, only the file is, and its shortVersionString was written into App Studio's desktop entry as it came. A version carrying a line break ( in the XML) would have added a line of its own, such as an Exec= key, which the signature never covered. An item whose version is not letters, digits, '.', '+' and '-' (64 at most) is now left out of the feed, and every value written to the entry has its line breaks, tabs and carriage returns escaped as the Desktop Entry spec says. --- lib/platform/linux/desktop_integration.dart | 10 ++++- lib/update/linux/appcast.dart | 8 +++- .../linux/desktop_integration_test.dart | 38 +++++++++++++++++++ test/update/linux/appcast_test.dart | 16 ++++++++ 4 files changed, 69 insertions(+), 3 deletions(-) diff --git a/lib/platform/linux/desktop_integration.dart b/lib/platform/linux/desktop_integration.dart index 526a810..7be170f 100644 --- a/lib/platform/linux/desktop_integration.dart +++ b/lib/platform/linux/desktop_integration.dart @@ -747,8 +747,14 @@ String desktopEntryFor( return '${out.join('\n')}\n'; } -/// A string value: a backslash is written as two. -String _escapeString(String value) => value.replaceAll(r'\', r'\\'); +/// A string value, escaped as the Desktop Entry spec says: a backslash, a +/// newline, a tab and a carriage return each become two characters, so no +/// value can start a line of its own. +String _escapeString(String value) => value + .replaceAll(r'\', r'\\') + .replaceAll('\n', r'\n') + .replaceAll('\t', r'\t') + .replaceAll('\r', r'\r'); /// One `Exec` argument, quoted as the Desktop Entry spec says: inside double /// quotes, `"`, `` ` ``, `$` and `\` take a backslash, and `%` is doubled. diff --git a/lib/update/linux/appcast.dart b/lib/update/linux/appcast.dart index 5e0145a..f01be19 100644 --- a/lib/update/linux/appcast.dart +++ b/lib/update/linux/appcast.dart @@ -79,6 +79,12 @@ AppcastItem? newestUpdate(String feed, {required int current}) { return newest; } +/// What a version may look like: `0.4.2`, `1.0.0-beta.1`. The feed is not +/// signed, only the file is, and the version is written into the app menu's +/// entry, so anything else (a newline above all) is refused rather than +/// escaped. +final _versionPattern = RegExp(r'^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$'); + AppcastItem? _parse(XmlElement item) { final enclosure = item.findElements('enclosure').firstOrNull; if (enclosure == null) return null; @@ -98,7 +104,7 @@ AppcastItem? _parse(XmlElement item) { final signature = sparkle('edSignature'); if (build == null || version == null || - version.isEmpty || + !_versionPattern.hasMatch(version) || url == null || !url.hasScheme || length == null || diff --git a/test/platform/linux/desktop_integration_test.dart b/test/platform/linux/desktop_integration_test.dart index 3025934..adb3ed1 100644 --- a/test/platform/linux/desktop_integration_test.dart +++ b/test/platform/linux/desktop_integration_test.dart @@ -787,6 +787,24 @@ Exec=appstudio --extra expect(await File(entryPath()).readAsString(), before); }); + test('a version cannot add a line to the entry', () async { + await integration().add(); + await integration().recordUpdatedVersion( + target(), + const AppVersion('0.4.2\nExec=/tmp/x', 26), + ); + + final lines = (await File(entryPath()).readAsString()).split('\n'); + expect(lines.where((l) => l.startsWith('Exec=/tmp')), isEmpty); + expect( + lines, + contains( + '$kAddedVersionKey=' + r'0.4.2\nExec=/tmp/x', + ), + ); + }); + test('leaves an entry App Studio did not write alone', () async { const theirs = '[Desktop Entry]\nName=App Studio\nExec=/opt/x\nTryExec=/opt/x\n'; @@ -907,6 +925,26 @@ Exec=appstudio --extra ]); }); + test('a version cannot start a line of its own', () { + final entry = desktopEntryFor( + sourceEntry, + appImagePath: '/a.AppImage', + version: const AppVersion('0.4.1\nExec=/tmp/x\t\r', 25), + ); + expect( + entry, + contains( + '$kAddedVersionKey=' + r'0.4.1\nExec=/tmp/x\t\r' + '\n', + ), + ); + expect( + entry.split('\n').where((l) => l.startsWith('Exec=/tmp')), + isEmpty, + ); + }); + test('refuses a path with a line break', () { expect( () => desktopEntryFor(sourceEntry, appImagePath: '/a\nb'), diff --git a/test/update/linux/appcast_test.dart b/test/update/linux/appcast_test.dart index 910b02d..a3286c1 100644 --- a/test/update/linux/appcast_test.dart +++ b/test/update/linux/appcast_test.dart @@ -1,3 +1,4 @@ +import 'package:appstudio/platform/linux/app_version.dart'; import 'package:appstudio/update/linux/appcast.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -81,6 +82,21 @@ void main() { expect(update!.version.build, 26); }); + test('leaves out an item whose version is not a version', () { + // The feed is not signed and the version ends up in the app menu's + // entry, where a line break would start a key of its own. + final update = newestUpdate( + feed( + item(build: 30, version: '0.4.3 Exec=/tmp/x') + + item(build: 31, version: '') + + item(build: 32, version: '0.4.5 beta') + + item(build: 26, version: '0.4.2-beta.1'), + ), + current: 25, + ); + expect(update!.version, const AppVersion('0.4.2-beta.1', 26)); + }); + test('reads the namespace, not the prefix', () { final update = newestUpdate( feed(item(prefix: 'sp'), prefix: 'sp'), From 1ce70490663e357b6b4e03ba134279106d3d924f Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:29:46 +0100 Subject: [PATCH 24/32] fix: Keeps the Linux update offer off New Project and Settings. The hourly update check only asked whether a project was open, so once a check was due its offer could open over the New Project screen or the Settings dialog, both routes over the start page. Its Install button quits App Studio, which would have left serverpod create or a tool install half-done. The start page now counts as showing only when nothing is pushed over it. The Add to Applications question reads the same check. --- lib/main.dart | 9 +- lib/update/linux/linux_update_commands.dart | 48 +++++---- lib/widgets/nothing_pushed.dart | 7 ++ .../linux/linux_update_commands_test.dart | 102 ++++++++++++++++++ 4 files changed, 145 insertions(+), 21 deletions(-) create mode 100644 lib/widgets/nothing_pushed.dart diff --git a/lib/main.dart b/lib/main.dart index 3c43cf4..1ba80a8 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -41,6 +41,7 @@ import 'ui/uninstall/uninstalled_screen.dart'; import 'uninstall/uninstaller.dart'; import 'ui/toolchain/toolchain_setup_screen.dart'; import 'ui/studio_shell.dart'; +import 'widgets/nothing_pushed.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -420,12 +421,16 @@ class _AppStudioAppState extends State { } /// Whether the start page is what the window shows: no project open, no - /// setup, no uninstall. + /// setup, no uninstall, and nothing pushed over it. New Project and + /// Settings are routes over the start page, and a question raised over + /// them could quit the app in the middle of `serverpod create` or a tool + /// install. bool _onStartPage() => mounted && widget.session.projectPath == null && !_needsToolchainSetup && - _uninstalled == null; + _uninstalled == null && + nothingPushedOver(_navigatorKey); /// Linux: the daily update check, over the start page only. Future _checkForUpdatesIfDue(BuildContext context) async { diff --git a/lib/update/linux/linux_update_commands.dart b/lib/update/linux/linux_update_commands.dart index 2f34127..c70188e 100644 --- a/lib/update/linux/linux_update_commands.dart +++ b/lib/update/linux/linux_update_commands.dart @@ -32,7 +32,7 @@ Future checkForUpdatesOnLinux( onChecked?.call(); } }, - install: _installer(updater, quit ?? _quitApp), + install: _installer(updater, quit ?? _quitApp, ModalRoute.of(context)), onSkip: updater.skip, ), ); @@ -85,7 +85,7 @@ class LinuxUpdateSchedule { builder: (context) => LinuxUpdateDialog.offer( current: current, update: update!, - install: _installer(updater, _quit), + install: _installer(updater, _quit, ModalRoute.of(context)), onSkip: updater.skip, ), ); @@ -95,23 +95,33 @@ class LinuxUpdateSchedule { } } -InstallUpdate _installer(LinuxUpdater updater, Future Function() quit) => - (item, {required onProgress, required cancellation}) async { - final verified = await updater.download( - item, - onProgress: onProgress, - cancellation: cancellation, - ); - if (verified == null) return false; - // The dialog may have gone while the signature was checked. - if (cancellation.isCancelled) { - await updater.discard(verified.path); - return false; - } - await updater.install(verified); - await quit(); - return true; - }; +/// Installs only while [dialog] is the route on top. The menu strip's +/// shortcuts still work under the dialog, so New Project (Ctrl+N) or +/// Settings (Ctrl+,) can open over it while it downloads, and installing +/// then would quit App Studio in the middle of `serverpod create` or a +/// tool install. A covered dialog drops its download and goes back to the +/// offer, as a cancel does. +InstallUpdate _installer( + LinuxUpdater updater, + Future Function() quit, + ModalRoute? dialog, +) => (item, {required onProgress, required cancellation}) async { + final verified = await updater.download( + item, + onProgress: onProgress, + cancellation: cancellation, + ); + if (verified == null) return false; + // The dialog may have gone, or been covered, while the signature was + // checked. + if (cancellation.isCancelled || !(dialog?.isCurrent ?? false)) { + await updater.discard(verified.path); + return false; + } + await updater.install(verified); + await quit(); + return true; +}; /// The same quit as File → Quit, teardown included; the new AppImage starts /// once this process has ended. diff --git a/lib/widgets/nothing_pushed.dart b/lib/widgets/nothing_pushed.dart new file mode 100644 index 0000000..e3dca71 --- /dev/null +++ b/lib/widgets/nothing_pushed.dart @@ -0,0 +1,7 @@ +import 'package:flutter/widgets.dart'; + +/// Whether [navigator] shows its first route alone, with nothing pushed over +/// it: no dialog, no full-screen route such as New Project. True before the +/// navigator exists, since nothing can be pushed over it yet. +bool nothingPushedOver(GlobalKey navigator) => + !(navigator.currentState?.canPop() ?? false); diff --git a/test/update/linux/linux_update_commands_test.dart b/test/update/linux/linux_update_commands_test.dart index b3b12b3..cf5a37d 100644 --- a/test/update/linux/linux_update_commands_test.dart +++ b/test/update/linux/linux_update_commands_test.dart @@ -1,7 +1,10 @@ +import 'dart:async'; + import 'package:appstudio/platform/linux/app_version.dart'; import 'package:appstudio/update/linux/appcast.dart'; import 'package:appstudio/update/linux/linux_update_commands.dart'; import 'package:appstudio/update/linux/linux_updater.dart'; +import 'package:appstudio/widgets/nothing_pushed.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shad/shad.dart'; @@ -18,10 +21,12 @@ AppcastItem build(int build) => AppcastItem( /// install, and only over the start page. void main() { late _FakeUpdater updater; + late GlobalKey navigator; setUp(() { SharedPreferences.setMockInitialValues({}); updater = _FakeUpdater(); + navigator = GlobalKey(); }); Future run( @@ -30,6 +35,7 @@ void main() { ) async { await tester.pumpWidget( ShadApp( + navigatorKey: navigator, home: Builder( builder: (context) => ShadButton( onPressed: () => command(context), @@ -42,6 +48,21 @@ void main() { await tester.pumpAndSettle(); } + /// A full-screen route over the start page, as New Project is. + void pushNewProject() => unawaited( + navigator.currentState!.push( + PageRouteBuilder( + pageBuilder: (_, _, _) => const Text('New Project'), + ), + ), + ); + + /// The automatic check with the start page test `main.dart` uses. + Future checkIfDueOverStartPage(BuildContext context) => + LinuxUpdateSchedule( + updater, + ).checkIfDue(context, onStartPage: () => nothingPushedOver(navigator)); + Future checkIfDue(WidgetTester tester, {bool onStartPage = true}) => run( tester, @@ -76,6 +97,47 @@ void main() { expect(updater.checks, 0); }); + testWidgets('does not look with New Project open over the start page', ( + tester, + ) async { + updater.update = build(26); + late BuildContext startPage; + await run(tester, (context) async => startPage = context); + pushNewProject(); + await tester.pumpAndSettle(); + + unawaited(checkIfDueOverStartPage(startPage)); + await tester.pumpAndSettle(); + + expect(updater.checks, 0); + expect(find.text('Install and Restart'), findsNothing); + + navigator.currentState!.pop(); + await tester.pumpAndSettle(); + unawaited(checkIfDueOverStartPage(startPage)); + await tester.pumpAndSettle(); + expect(find.text('Install and Restart'), findsOneWidget); + }); + + testWidgets('offers nothing when New Project opened during the check', ( + tester, + ) async { + updater.update = build(26); + final answer = Completer(); + updater.checkGate = answer.future; + await run(tester, (context) async { + unawaited(checkIfDueOverStartPage(context)); + }); + expect(updater.checks, 1); + + pushNewProject(); + await tester.pumpAndSettle(); + answer.complete(); + await tester.pumpAndSettle(); + + expect(find.text('Install and Restart'), findsNothing); + }); + testWidgets('says nothing when there is no update', (tester) async { await checkIfDue(tester); @@ -146,6 +208,38 @@ void main() { expect(find.text('App Studio 0.4.26 is installed'), findsOneWidget); }); + testWidgets('a download covered by New Project installs nothing', ( + tester, + ) async { + // The menu strip's Ctrl+N still works under the dialog. + var quits = 0; + final downloaded = Completer(); + updater + ..update = build(26) + ..downloadGate = downloaded.future; + await run( + tester, + (context) => + checkForUpdatesOnLinux(context, updater, quit: () async => quits++), + ); + await tester.tap(find.text('Install and Restart')); + await tester.pump(); + + pushNewProject(); + await tester.pumpAndSettle(); + downloaded.complete(); + await tester.pumpAndSettle(); + + expect(updater.installed, 0); + expect(updater.discarded, ['/tmp/part']); + expect(quits, 0); + + // Back under it, the dialog offers the update again. + navigator.currentState!.pop(); + await tester.pumpAndSettle(); + expect(find.text('Install and Restart'), findsOneWidget); + }); + testWidgets('a cancelled download installs nothing and stays', ( tester, ) async { @@ -182,6 +276,9 @@ class _FakeUpdater extends LinuxUpdater { AppcastItem? update; int checks = 0; int installed = 0; + Future? checkGate; + Future? downloadGate; + final discarded = []; @override Future runningVersion() async => const AppVersion('0.4.1', 25); @@ -195,6 +292,7 @@ class _FakeUpdater extends LinuxUpdater { @override Future check() async { checks++; + await checkGate; if (fails) { throw const LinuxUpdateException('The update server answered 500.'); } @@ -207,11 +305,15 @@ class _FakeUpdater extends LinuxUpdater { void Function(int received, int total)? onProgress, UpdateCancellation? cancellation, }) async { + await downloadGate; onProgress?.call(item.length, item.length); if (downloadCancelled) return null; return VerifiedUpdate.forTesting('/tmp/part', item); } + @override + Future discard(String path) async => discarded.add(path); + @override Future install(VerifiedUpdate update, {int? afterPid}) async { installed++; From 6428ac6e12e2585ac2e34067795e112a5f620331 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:48:57 +0100 Subject: [PATCH 25/32] fix: Lets Cancel stop a Linux update download at once. Cancel was only read when the next chunk arrived. With a server that had stopped sending, the dialog waited out the 60 s timeout and then reported "The download stopped answering." instead of going back. UpdateCancellation now completes a future when it is cancelled, and the download stops waiting on the connection or the next chunk as soon as it does. One listener serves the whole download. A response that arrives after Cancel has its body let go, so its connection does not stay open. The new tests stall the server, once while connecting and once mid-download, and fail on the old code. --- lib/update/linux/linux_updater.dart | 55 +++++++++++++++++----- lib/update/linux/update_signals.dart | 17 +++++-- test/update/linux/linux_updater_test.dart | 56 ++++++++++++++++++++++- 3 files changed, 112 insertions(+), 16 deletions(-) diff --git a/lib/update/linux/linux_updater.dart b/lib/update/linux/linux_updater.dart index 5e4b85a..fff15d0 100644 --- a/lib/update/linux/linux_updater.dart +++ b/lib/update/linux/linux_updater.dart @@ -289,25 +289,39 @@ class LinuxUpdater { ); } + // One listener for the whole download, not one per chunk. + final cancelled = cancellation?.whenCancelled.then((_) => null); var complete = false; try { - final response = await _client - .send(http.Request('GET', item.url)) - .timeout(const Duration(seconds: 30)); + final response = await _orCancelled( + _client + .send(http.Request('GET', item.url)) + .timeout(const Duration(seconds: 30)), + cancelled, + // A response that arrives after Cancel would hold its connection + // open: nobody reads its body. + dropLate: (late) => late.stream.listen(null).cancel(), + ); + if (response == null) return null; if (response.statusCode != 200) { throw LinuxUpdateException( 'The download answered ${response.statusCode}.', ); } var received = 0; - await for (final chunk in response.stream.timeout( - const Duration(seconds: 60), - )) { - if (cancellation?.isCancelled ?? false) break; - received += chunk.length; - if (received > item.length) break; - sink.add(chunk); - onProgress?.call(received, item.length); + final chunks = StreamIterator( + response.stream.timeout(const Duration(seconds: 60)), + ); + try { + while (await _orCancelled(chunks.moveNext(), cancelled) ?? false) { + final chunk = chunks.current; + received += chunk.length; + if (received > item.length) break; + sink.add(chunk); + onProgress?.call(received, item.length); + } + } finally { + await chunks.cancel(); } await sink.close(); if (cancellation?.isCancelled ?? false) return null; @@ -341,6 +355,7 @@ class LinuxUpdater { complete = true; return VerifiedUpdate._(part.path, item); } on TimeoutException { + if (cancellation?.isCancelled ?? false) return null; throw const LinuxUpdateException('The download stopped answering.'); } on LinuxUpdateException { rethrow; @@ -431,3 +446,21 @@ Future verifyEd25519File( ), ); } + +/// [future]'s value, or null as soon as [cancelled] completes. A value +/// [future] gives after that goes to [dropLate], and an error it raises is +/// dropped: nobody is waiting for either. +Future _orCancelled( + Future future, + Future? cancelled, { + void Function(T late)? dropLate, +}) { + if (cancelled == null) return future; + var settled = false; + // Registered before the race's own listeners, so a value that wins the + // race arrives here first, while settled is still false. + future.then((value) { + if (settled) dropLate?.call(value); + }, onError: (Object _) {}); + return Future.any([future, cancelled]).whenComplete(() => settled = true); +} diff --git a/lib/update/linux/update_signals.dart b/lib/update/linux/update_signals.dart index d51b902..487ab7e 100644 --- a/lib/update/linux/update_signals.dart +++ b/lib/update/linux/update_signals.dart @@ -2,11 +2,20 @@ /// free of `dart:io`, so the dialog can use it. library; -/// Asked between chunks of a download, which stops when it says so. +import 'dart:async'; + +/// Stops a download: at once, even while it waits on a server that has +/// stopped sending. class UpdateCancellation { - bool _cancelled = false; - bool get isCancelled => _cancelled; - void cancel() => _cancelled = true; + final _completer = Completer(); + bool get isCancelled => _completer.isCompleted; + + /// Completes when [cancel] is called. + Future get whenCancelled => _completer.future; + + void cancel() { + if (!_completer.isCompleted) _completer.complete(); + } } /// The new AppImage is in place, but App Studio could not start it: there diff --git a/test/update/linux/linux_updater_test.dart b/test/update/linux/linux_updater_test.dart index 4a6d046..6099303 100644 --- a/test/update/linux/linux_updater_test.dart +++ b/test/update/linux/linux_updater_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -94,6 +95,7 @@ void main() { LinuxUpdater updater({ LinuxUpdateConfig? config, Map? environment, + http.Client? httpClient, }) { final e = environment ?? env; final executable = p.join(appDir, 'usr', 'lib', 'appstudio', 'appstudio'); @@ -106,7 +108,7 @@ void main() { ), environment: e, executable: executable, - client: client(), + client: httpClient ?? client(), runningVersion: () async => running, desktop: DesktopIntegration( environment: e, @@ -387,6 +389,58 @@ void main() { expect(await File(part()).exists(), isFalse); }); + test( + 'stops at once when cancelled while the server sends nothing', + () async { + // One chunk, then silence: the stream never ends, and the download + // would otherwise wait out its 60 s timeout and report a failure. + final stalled = StreamController>(); + addTearDown(stalled.close); + stalled.add(newer.sublist(0, 8)); + final cancellation = UpdateCancellation(); + final verified = + await updater( + httpClient: MockClient.streaming( + (_, _) async => http.StreamedResponse(stalled.stream, 200), + ), + ) + .download( + await item(), + cancellation: cancellation, + onProgress: (_, _) => Timer( + const Duration(milliseconds: 50), + cancellation.cancel, + ), + ) + .timeout(const Duration(seconds: 5)); + expect(verified, isNull); + expect(await File(part()).exists(), isFalse); + }, + ); + + test('stops at once when cancelled while connecting', () async { + final never = Completer(); + final cancellation = UpdateCancellation(); + Timer(const Duration(milliseconds: 50), cancellation.cancel); + final verified = + await updater( + httpClient: MockClient.streaming((_, _) => never.future), + ) + .download(await item(), cancellation: cancellation) + .timeout(const Duration(seconds: 5)); + expect(verified, isNull); + expect(await File(part()).exists(), isFalse); + + // The response turns up after all: its body is let go, so the + // connection does not stay open. + final body = StreamController>(); + final released = Completer(); + body.onCancel = released.complete; + body.onListen = () {}; + never.complete(http.StreamedResponse(body.stream, 200)); + await released.future.timeout(const Duration(seconds: 5)); + }); + test('says so where the AppImage cannot be replaced', () async { if (Platform.isWindows) return; final uid = await Process.run('id', ['-u']); From e4f5988a26b1ab8c1eb990e5841832e65520c9b7 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:50:20 +0100 Subject: [PATCH 26/32] fix: Updates the app menu's copy after Add had to copy rather than move. When Add to Applications cannot take the AppImage out of its folder (a root-owned one such as /opt), it copies it to ~/AppImages and leaves the original. The updater still preferred $APPIMAGE because the original existed, so the download failed in a folder it cannot write to. The updater now replaces the app menu's copy whenever App Studio's entry names it and records the running build, and the started file otherwise. A second copy of the same build, run from ~/Downloads say, therefore updates the menu's copy and restarts that one. A download an interrupted run left behind is cleared beside both. --- lib/update/linux/linux_updater.dart | 33 +++++++++--- test/update/linux/linux_updater_test.dart | 66 +++++++++++++++++++++++ 2 files changed, 91 insertions(+), 8 deletions(-) diff --git a/lib/update/linux/linux_updater.dart b/lib/update/linux/linux_updater.dart index fff15d0..50a514a 100644 --- a/lib/update/linux/linux_updater.dart +++ b/lib/update/linux/linux_updater.dart @@ -116,13 +116,22 @@ class LinuxUpdater { /// or null when this is not one. String? get appImage => runningAppImage(_environment, _executable); - /// The file an update replaces: [appImage], unless Add to Applications - /// moved it in this run, when `$APPIMAGE` still names where it was and - /// the file is at `~/AppImages` now. Null when neither is there. + /// The file an update replaces: the copy in the app menu when it is this + /// build, otherwise [appImage]. Null when neither is there. + /// + /// The menu's copy comes first because Add to Applications may have + /// put it there in this run: `$APPIMAGE` still names where the file was, + /// and when Add had to copy rather than move (a folder the file could not + /// be taken out of, such as /opt), the original is still there and still + /// cannot be written to. The menu's copy is also the one started next. + /// + /// So a second copy of the same build, run from `~/Downloads` say, + /// updates the menu's copy and restarts that one. The copy that ran stays + /// as it is, and when it is started again it offers to open the newer + /// one in the app menu (the "another copy" question). Future liveAppImage() async { final started = appImage; if (started == null) return null; - if (await File(started).exists()) return started; // Only the copy this one became: App Studio's entry names it and // records this build. Any other file there (one left after Remove, // perhaps newer) is not this App Studio's to replace. @@ -134,6 +143,7 @@ class LinuxUpdater { await _desktop.recordedVersionOf(added) == running) { return added; } + if (await File(started).exists()) return started; return null; } @@ -209,10 +219,17 @@ class LinuxUpdater { final prefs = await SharedPreferences.getInstance(); await prefs.setInt(lastCheckKey, DateTime.now().millisecondsSinceEpoch); // A download a crash or a kill interrupted is ~140 MB nobody would find: - // it is hidden. No download runs while a check does. - final live = await liveAppImage(); - if (live != null && !_downloading) { - await discard(p.join(p.dirname(live), partName)); + // it is hidden. It can sit beside either copy, since which one an update + // replaces depends on the app menu at the time. No download runs while + // a check does. + if (!_downloading) { + final folders = { + for (final path in [appImage, await liveAppImage()]) + if (path != null) p.dirname(path), + }; + for (final folder in folders) { + await discard(p.join(folder, partName)); + } } final http.Response response; try { diff --git a/test/update/linux/linux_updater_test.dart b/test/update/linux/linux_updater_test.dart index 6099303..1cf084f 100644 --- a/test/update/linux/linux_updater_test.dart +++ b/test/update/linux/linux_updater_test.dart @@ -572,6 +572,72 @@ void main() { ); }); + group('after Add copied rather than moved', () { + test('clears a leftover download beside either copy', () async { + final added = p.join( + env['HOME']!, + 'AppImages', + 'AppStudio-x86_64.AppImage', + ); + await File(added).create(recursive: true); + await writeOwnEntry(added, running); + final besideStarted = File(part()); + final besideAdded = File(p.join(p.dirname(added), LinuxUpdater.partName)); + await besideStarted.writeAsString('half a download'); + await besideAdded.writeAsString('half a download'); + + await updater().check(); + + expect(await besideStarted.exists(), isFalse); + expect(await besideAdded.exists(), isFalse); + }); + + test( + 'replaces the copy in ~/AppImages, not the original left behind', + () async { + // Add could not take the file out of its folder (/opt, say), so it + // copied it; the original is still where `$APPIMAGE` names it. + final added = p.join( + env['HOME']!, + 'AppImages', + 'AppStudio-x86_64.AppImage', + ); + await File(added).create(recursive: true); + await File(appImage).copy(added); + await writeOwnEntry(added, running); + final original = await File(appImage).readAsBytes(); + final u = updater(); + + expect(await u.liveAppImage(), added); + final verified = await u.download((await u.check())!); + expect(p.dirname(verified!.path), p.dirname(added)); + final ended = await Process.start('true', []); + await ended.exitCode; + await u.install(verified, afterPid: ended.pid); + + expect(await File(added).readAsBytes(), newer); + expect(await File(appImage).readAsBytes(), original); + }, + tags: 'process', + testOn: '!windows', + ); + + test( + 'replaces the started file when the menu\'s copy is another build', + () async { + final added = p.join( + env['HOME']!, + 'AppImages', + 'AppStudio-x86_64.AppImage', + ); + await File(added).create(recursive: true); + await writeOwnEntry(added, const AppVersion('0.4.0', 24)); + + expect(await updater().liveAppImage(), appImage); + }, + ); + }); + group('verifyEd25519File', () { test( 'accepts what openssl signs, as the release pipeline does', From c660b3ab1b8bedb4f00b9f7b2bab4875f956d434 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:53:07 +0100 Subject: [PATCH 27/32] fix: Skips closed browsers when Ctrl+F12 looks for the focused one. Closing a webview keeps its entry in m_renderers with a null renderer. The Ctrl+F12 loop that opens DevTools dereferenced every entry, so the shortcut crashed after any preview had been closed. It now skips null entries, as getAnyBrowserFocused already does. --- packages/webview_cef/common/webview_plugin.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/webview_cef/common/webview_plugin.cc b/packages/webview_cef/common/webview_plugin.cc index df9ed5e..8294d5f 100644 --- a/packages/webview_cef/common/webview_plugin.cc +++ b/packages/webview_cef/common/webview_plugin.cc @@ -665,7 +665,8 @@ namespace webview_cef { if(ev.type == KEYEVENT_RAWKEYDOWN && ev.windows_key_code == 0x7B && (ev.modifiers & EVENTFLAG_CONTROL_DOWN) != 0){ LOCK_RENDERERS(); for(auto render : m_renderers){ - if(render.second.get()->isFocused){ + // A closed browser keeps its entry with a null renderer. + if(render.second != nullptr && render.second.get()->isFocused){ m_handler->openDevTools(render.first); } } From d01718fe027b678f910d03131531e542d3798b83 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:54:11 +0100 Subject: [PATCH 28/32] fix: Stops the Linux release scripts early on a setup they cannot use. build_appimage.sh accepted a release config with only one of appcastUrl and eddsaPublicKey, said "In-app updates off" and built an AppImage that would never check for updates. It now refuses unless both or neither are set. appcast.sh only works on Linux (it runs the AppImage to read its version, and uses GNU stat and base64), but on macOS it failed with an exec format error. It now says so up front, and its header lists OpenSSL 3, python3 and GNU coreutils. --- tool/linux/appcast.sh | 10 +++++++++- tool/linux/build_appimage.sh | 11 ++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/tool/linux/appcast.sh b/tool/linux/appcast.sh index 64f6dc0..336348a 100755 --- a/tool/linux/appcast.sh +++ b/tool/linux/appcast.sh @@ -23,9 +23,17 @@ # such a feed only reaches builds made with # APPSTUDIO_EDDSA_PUBLIC_KEY set to that key. # -# Needs: openssl, python3, base64. +# Runs on Linux only: it runs the AppImage to read its version, and uses GNU +# stat and base64. Needs OpenSSL 3 (for `pkeyutl -rawin`), python3 and GNU +# coreutils. set -euo pipefail +if [[ "$(uname -s)" != Linux ]]; then + echo "appcast.sh runs on Linux only: it runs the AppImage to read its" \ + "version. Run it on the machine or CI job that built the AppImage." >&2 + exit 1 +fi + root="$(cd "$(dirname "$0")/../.." && pwd)" key="" url="" feed="" while (( $# )); do diff --git a/tool/linux/build_appimage.sh b/tool/linux/build_appimage.sh index c249617..902857f 100755 --- a/tool/linux/build_appimage.sh +++ b/tool/linux/build_appimage.sh @@ -111,6 +111,15 @@ if [[ -n "$eddsa_public_key" ]] && echo "The update public key is not base64 of 32 bytes." >&2 exit 1 fi +# Both or neither: a build with only one never checks for updates, and +# nothing else would notice until users stopped getting them. +if [[ -n "$appcast_url" && -z "$eddsa_public_key" ]] || + [[ -z "$appcast_url" && -n "$eddsa_public_key" ]]; then + echo "In-app updates need both appcastUrl and eddsaPublicKey" \ + "(linux/release.json or APPSTUDIO_APPCAST_URL /" \ + "APPSTUDIO_EDDSA_PUBLIC_KEY), or neither." >&2 + exit 1 +fi # --- Build ----------------------------------------------------------------- @@ -130,7 +139,7 @@ if [[ "${SKIP_BUILD:-}" != 1 ]]; then if [[ -n "$appcast_url" && -n "$eddsa_public_key" ]]; then echo "In-app updates from $appcast_url" else - echo "In-app updates off: no feed or no key (linux/release.json)" + echo "In-app updates off: no feed and no key (linux/release.json)" fi (cd "$root" && "$flutter" build linux --release \ --dart-define="APPSTUDIO_APPCAST_URL=$appcast_url" \ From be897785f4f20cf5a7b0da440cdb7c85a423bd52 Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:55:18 +0100 Subject: [PATCH 29/32] test: Makes two Linux desktop entry tests able to fail. "There is nothing to add on another OS" passed no executable, so the running file was not inside APPDIR and the status was unavailable even on Linux. It now runs in the same AppImage environment as the Linux tests, so only the OS check can make it unavailable. The line break test for a recorded version now also reads the version back, so it pins the escaping in both directions. --- test/platform/linux/desktop_integration_test.dart | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/platform/linux/desktop_integration_test.dart b/test/platform/linux/desktop_integration_test.dart index adb3ed1..9bd632a 100644 --- a/test/platform/linux/desktop_integration_test.dart +++ b/test/platform/linux/desktop_integration_test.dart @@ -126,9 +126,12 @@ Exec=appstudio --extra }); test('there is nothing to add on another OS', () async { + // Everything else as in a real AppImage, so only the OS says no. final mac = DesktopIntegration( environment: env, host: HostPlatform.macos, + runningVersion: () async => running, + executable: p.join(appDir, 'usr', 'lib', 'appstudio', 'appstudio'), ); expect(await mac.status(), DesktopIntegrationStatus.unavailable); }); @@ -803,6 +806,11 @@ Exec=appstudio --extra r'0.4.2\nExec=/tmp/x', ), ); + // And it reads back as it was written. + expect( + await integration().recordedVersionOf(target()), + const AppVersion('0.4.2\nExec=/tmp/x', 26), + ); }); test('leaves an entry App Studio did not write alone', () async { From 17d197b16b1e860bd158bfa6cedf4142a1cdb8bb Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 14:56:30 +0100 Subject: [PATCH 30/32] docs: Describes the Linux port as built. CLAUDE.md (AGENTS.md) gets a Linux section: the dev machine, where things are, quitting and the _exit() it ends with, CEF, keys and the GTK clipboard bridge, the AppImage, Add to Applications and in-app updates. Its first line no longer calls App Studio a macOS IDE. specs/linux_port.md keeps the plan agreed with Serverpod and says where the build differs: the AppImage updates itself and .deb and .rpm follow only if asked, how quitting was fixed, the clipboard and its limits, the 670x600 minimum, and the checklist ticked for what is done. specs/linux_appimage.md marks parts A and B done and records the review fixes: which copy an update replaces, why nothing in the feed is trusted beyond the file's signature, no offer over New Project or Settings, and Cancel. --- AGENTS.md | 91 +++++++++++++++++++++++++++++++++- Makefile | 4 +- specs/linux_appimage.md | 20 +++++--- specs/linux_port.md | 105 ++++++++++++++++++++++++++-------------- 4 files changed, 173 insertions(+), 47 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4c0f66f..5b1d14e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # App Studio — agent notes -macOS Flutter IDE for **Serverpod 4.1** projects: open a project, start or attach to its Serverpod runner, show the runner's structured log natively, and preview the Flutter web app in CEF at the URL the runner publishes. +Flutter IDE for **Serverpod 4.1** projects, on macOS, Windows and Linux: open a project, start or attach to its Serverpod runner, show the runner's structured log natively, and preview the Flutter web app in CEF at the URL the runner publishes. ## Project layout @@ -21,8 +21,10 @@ widgetbook/ # `make widgetbook`: catalog, host, fakes (see Widgetbo packages/ mac_menu_bar/ # Local fork — SF Symbol icons, separators, reset() webview_cef/ # Local fork — CEF resize + skip Helper (Alerts) +linux/ # GTK runner (CEF hooks, _exit on quit), release.json tool/ distribute_macos.sh, publish_*.sh, set_version.sh # releasing the app + linux/build_appimage.sh, linux/appcast.sh # the Linux AppImage and its feed ``` UI reference for design patterns: `../cloudui/cloudui_flutter/`. @@ -2174,6 +2176,7 @@ Windows needs Developer Mode, then Git for Windows, Flutter and Serverpod go to the page. - **Menus:** a shad menu strip (`windows_app_menu.dart`) with Ctrl shortcuts. It repeats `MacAppMenu`'s enable rules, so change both together. + Linux mounts the same strip (see Linux). - **Tooltips and copy** use `shortcutHint()`. - **Notifications:** toasts from the runner (`toast_notifications.cpp`). They need the installer's Start menu shortcut. @@ -2227,6 +2230,92 @@ The repository is public, so the GitHub API works without a token. It allows not count against that limit. Logs need a GitHub sign-in, but annotations do not, which is why the jobs report through `::notice`/`::error`. +## Linux + +The plan and what was built are in `specs/linux_port.md`; the AppImage's +app menu entry and in-app updates are in `specs/linux_appimage.md`. As with +Windows, macOS and Windows must not regress: every Linux path is behind a +host check (`currentHost.isLinux`, `HostPlatform.linux` in tests), and +`packages/webview_cef/common/` changes only behind `__linux__`, or where the +change is behaviour-neutral on all three (a null check, say). + +### Dev machine + +- Flutter 3.44+ on `PATH`, plus Flutter's Linux desktop dependencies + (Ubuntu: `clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev + libstdc++-12-dev`; Arch: `clang cmake ninja pkgconf gtk3`). CEF downloads on the first CMake configure. +- `flutter run -d linux`. The Makefile's run targets (`start`, + `widgetbook`, the `_driver` ones) are macOS only and run `pod install`, so + on Linux the Dart MCP server's rule "launch through `make`" cannot be + followed: run `flutter run -d linux` (or `-t widgetbook/main.dart`) + yourself, and check first that the user has no run of their own going. +- `make appimage` builds `dist/linux/AppStudio--x86_64.AppImage`. + The AppImage needs glibc 2.38 on the machine it runs on (Ubuntu 24.04+); + its `AppRun` says so on an older one. A release build rewrites + `linux/flutter/generated_plugin*` and the Windows ones; the script puts + them back. Never commit that change. +- `flutter test` and an IDE's automatic `pub get` rewrite `pubspec.lock` on + a machine with another Dart. Do not commit it. +- There is no AF_UNIX crash on Linux: the `process` tests run as on macOS. + +### Where things are + +| What | Linux | +|---|---| +| App data and preferences | `$XDG_DATA_HOME/dev.serverpod.appstudio` (`~/.local/share/…`), one folder | +| CEF cache | `/CEF`, set by `linux/runner/main.cc` before CEF starts | +| Flutter | `~/develop/flutter`, from `releases_linux.json` (`.tar.xz`) | +| Serverpod CLI | `$XDG_STATE_HOME/Dart/install/bin` (`~/.local/state/…`) | +| `PATH` | `~/.zshenv` (or `$ZDOTDIR/.zshenv`) for zsh, `~/.bashrc` for bash, `~/.profile` for sh and ksh; fish by hand | +| System packages | git, curl, unzip, xz: checked, never installed (no `sudo`); setup gives the distro's command and **Check again** | +| The app | an AppImage; after Add to Applications, `~/AppImages/AppStudio-x86_64.AppImage` | + +### The window, CEF and keys + +- **Quitting:** every way out (close button, the window manager's close, + File → Quit, Ctrl+Q) reaches `_onExitRequested`. A second request while + the teardown runs waits for it, at most 15 s (`_kLinuxExitWait`); macOS + and Windows answer at once. `linux/runner/main.cc` then ends with + `_exit()`: Flutter's Linux quit leaves the engine running, and `exit()` + raced Mesa's exit handlers against the raster thread and crashed. Do not + turn it back into a `return`. +- **CEF's helpers start from the app's own executable**, so + `initCEFProcesses` runs first in `main()`. The plugin's own patch script + targets a file current Flutter no longer generates and is out of its + CMake. +- **Minimum window** 670×600, Windows' (`my_application.cc`), not macOS's + 720. No compact window: Wayland does not let a program place its window. +- **Keys in the preview:** the page gets them; Ctrl on any other character + key stays the app's shortcut. Ctrl+A/C/V/X/Y/Z stay with the page. +- **Clipboard goes through GTK.** On Wayland only a focused window may use + the clipboard, and CEF draws off-screen. Ctrl+C/X copy the page's + selection to GTK's clipboard; Ctrl+V types the clipboard's text into the + page. No paste event reaches the page, and a copy made by the page's own + code (`Clipboard.setData`) does not leave it. +- **Chromium's keyring is off** (`password-store=basic`): otherwise a + desktop without an unlocked keyring (a fresh Ubuntu, automatic login) + asks the user to create one as soon as the preview loads. +- **Menus:** the Windows strip (`windows_app_menu.dart`), with Quit on + Ctrl+Q instead of Exit on Alt+F4, Add to / Remove from Applications in + Help, and no Uninstall yet. **Fonts:** shad's Inter, as on Windows, and + the generic `monospace`. **URLs:** `xdg-open`. + +### The AppImage + +- **Add to Applications** (`lib/platform/linux/desktop_integration.dart`) + moves the AppImage to `~/AppImages` and writes + `dev.serverpod.appstudio.desktop` with an `X-AppStudio-AddedBy` marker, + recording the version and build. It is offered once per run over the + start page, unless another tool's entry already names App Studio. +- **Updates** (`lib/update/linux/`) are App Studio's own, from a Sparkle + appcast with an Ed25519 signature over the file, written by + `tool/linux/appcast.sh`. The feed URL and public key are in + `linux/release.json`; both empty means no updates, and the build refuses + only one. The feed itself is not signed: nothing from it but the file may + be trusted, which is why the version is validated before it reaches the + desktop entry. The automatic check only runs over the start page with + nothing pushed over it, since Install quits the app. + ## Conventions for agents - After a UI change, look at it running — Widgetbook through the Dart MCP diff --git a/Makefile b/Makefile index 5e73d93..827b0a7 100644 --- a/Makefile +++ b/Makefile @@ -209,8 +209,8 @@ promote: # --------------------------------------------------------------------------- # Linux # -# Builds on the machine it runs on and uploads nothing: hosting, updates and -# the release pipeline are Serverpod's. CEF downloads during the first CMake +# Builds on the machine it runs on and uploads nothing: hosting, the update +# feed and the release pipeline are Serverpod's. CEF downloads during the first CMake # configure, so there is no deps step. FLUTTER, SKIP_BUILD, APPIMAGETOOL, # APPIMAGE_UPDATE_INFO and APPIMAGE_FILE_URL are read from the environment; # see the script. diff --git a/specs/linux_appimage.md b/specs/linux_appimage.md index 4be6926..2bdeb4c 100644 --- a/specs/linux_appimage.md +++ b/specs/linux_appimage.md @@ -1,6 +1,6 @@ # Linux AppImage: adding App Studio to the app menu -Status: **draft, 2026-11-27.** Follows PR 4 (`make appimage`, +Status: **A, B and C built, 2026-11-28.** Follows PR 4 (`make appimage`, `tool/linux/build_appimage.sh`) on the step branch `linux/4b-appimage`, which merges into `linux/port` like the other steps. @@ -19,8 +19,8 @@ Studio. | Part | What | Where | State | |---|---|---|---| -| A | **Add to Applications**: on start, until it is in the app menu, App Studio offers to add itself; **Remove from Applications** undoes it | App Studio (Dart), Linux only | being built | -| B | **Updates from inside the app**: Help → Check for Updates, and a daily check, replace the AppImage in place | App Studio (Dart), `tool/linux/`; feed and key are Serverpod's | being built | +| A | **Add to Applications**: on start, until it is in the app menu, App Studio offers to add itself; **Remove from Applications** undoes it | App Studio (Dart), Linux only | done | +| B | **Updates from inside the app**: Help → Check for Updates, and a daily check, replace the AppImage in place | App Studio (Dart), `tool/linux/`; feed and key are Serverpod's | done | | C | **A clear message on a system that cannot load App Studio**, instead of nothing happening | `AppRun` in the AppImage | done | | D | **Download page text** for Serverpod's website | text in this spec | written; needs A | | E | Uninstall removes what A added | App Studio (Dart) | with PR 5 | @@ -326,8 +326,9 @@ format and the same rules. | B2 | **Every download is checked against an Ed25519 signature** over the whole file, as Sparkle and WinSparkle check theirs. The public key is compiled in; the private one never leaves Serverpod. A key pair from `openssl genpkey -algorithm ed25519` works, and so does signing with `openssl pkeyutl -sign -rawin`. | | B3 | **The feed URL and public key live in `linux/release.json`** (`appcastUrl`, `eddsaPublicKey`), as Windows keeps them in `windows/release.json`. `build_appimage.sh` passes them to `flutter build` as `--dart-define`s; `APPSTUDIO_APPCAST_URL` and `APPSTUDIO_EDDSA_PUBLIC_KEY` in the environment override them, for a local feed. Empty, updates are unavailable. | | B4 | **The build number is pubspec's**, the same `+N` the macOS build uses, so `make set_version` covers Linux too. | -| B5 | **The AppImage is replaced in place**, at whatever path it runs from, and started again from there. A menu entry, App Studio's or another tool's, keeps working because the path stays the same. After an Add in the same run, that is `~/AppImages/AppStudio-x86_64.AppImage`, although `$APPIMAGE` still names the folder the file came from; it is taken only while App Studio's entry names it and records the running build, so another copy left there is never replaced. | +| B5 | **The AppImage is replaced in place**, at whatever path it runs from, and started again from there. A menu entry, App Studio's or another tool's, keeps working because the path stays the same. When App Studio's entry names `~/AppImages/AppStudio-x86_64.AppImage` and records the running build, that file is the one replaced, even though `$APPIMAGE` still names the folder the file came from: after an Add in the same run, and also when Add had to copy rather than move and the original is still in a folder App Studio cannot write to (`/opt`, say). Another copy left there, of another build, is never replaced. So a second copy of the same build, run from `~/Downloads` say, updates the menu's copy and restarts that one; started again, the copy that ran offers to open the newer one. A leftover download is cleared beside both. | | B6 | **https only**, for the feed and every download: the signature covers the file, not the feed, so over plain http anyone in between could serve an older signed build as a newer one. Plain http is accepted only to this machine (`localhost`, `127/8`, `::1`) or a private IPv4 network (`10/8`, `172.16/12`, `192.168/16`), written in dotted decimal, which only a local test feed uses. The app, `build_appimage.sh` and `appcast.sh` check the same rule; the scripts also refuse a few odd spellings (percent-escaped hosts) the app lets through to the very host it checked. | +| B7 | **The feed is not signed, so nothing in it is trusted beyond the file's signature.** `sparkle:shortVersionString` is written into App Studio's menu entry, so an item whose version is not letters, digits, `.`, `+` and `-` (64 at most) is left out, and every value written to the entry has its line breaks escaped. `build_appimage.sh` refuses a build with only one of the feed and the key. | ### When it checks @@ -336,8 +337,11 @@ format and the same rules. - **Automatically, once a day** (Help → Check for Updates Automatically, on by default, as on macOS): on start after the Add question, and every hour after that whenever the last check is a day old. Only over the start - page: a project open means a running server, and an update dialog there - would interrupt work, as Sparkle's busy veto avoids on macOS and Windows. + page, with nothing pushed over it: a project open means a running server, + and an update dialog there would interrupt work, as Sparkle's busy veto + avoids on macOS and Windows. New Project and Settings count as work too, + since Install quits the app in the middle of `serverpod create` or a tool + install. An automatic check that finds nothing, or fails, says nothing. - Only when running as an AppImage (part A's condition 1). A development build, or one without a feed, shows "Check for Updates (unavailable in this @@ -356,7 +360,9 @@ it is running. **Skip This Version** stops the automatic check offering that build; Help → Check for Updates still offers it, as Sparkle does. **Install and Restart** -downloads with a progress bar and Cancel, then checks and installs: +downloads with a progress bar and Cancel, then checks and installs. Cancel +stops the download at once, even while the server has stopped sending; a +server that stays silent for 60 s fails the download. 1. **Downloads** to a hidden file beside the AppImage (`.AppStudio-update.part`), so the final rename stays on one file system diff --git a/specs/linux_port.md b/specs/linux_port.md index 7f5f6ee..64c0dc4 100644 --- a/specs/linux_port.md +++ b/specs/linux_port.md @@ -3,6 +3,8 @@ Status: **agreed with Serverpod on 2026-11-25** (scope, the five PRs and the Tuesday milestone). The details per subsystem below are the working plan. Date: 2026-11-26. Baseline: `main` @ `6b3686c`, App Studio 0.4.0+24. +Updated 2026-11-28 to what was built: where the build differs from the plan, +the section says so. ## The plan in short @@ -16,9 +18,15 @@ Five PRs, each merged into `linux/port` once tested: | 4 | **Packaging** | AppImage, `.deb`, `.rpm`, reusing an existing Flutter Linux packaging setup, including AppImage updates through Gear Lever | | 5 | **Polish** | "Open in…" editors, notifications, uninstall | -**CI, the release pipeline and auto-updates run on Serverpod's -infrastructure, so Serverpod owns them.** This port delivers the build -scripts. +**Since then:** PR 4 became the AppImage alone, followed by a step that +adds it to the app menu and lets it update itself in place +(`specs/linux_appimage.md`, parts A and B). The `.deb` and `.rpm` are not +built: in-app updates cover what they were for, so they follow only if +Serverpod asks for them. + +**CI, the release pipeline and the update feed (its hosting, URL and signing +key) run on Serverpod's infrastructure, so Serverpod owns them.** This port +delivers the build scripts and the updater inside the app. Estimate: 15–25 hours. @@ -81,7 +89,8 @@ with Windows read as "macOS and Windows": scattered around the code. - **The existing suite stays green on macOS and Windows at every step.** - **Native code shared with macOS or Windows** (`packages/webview_cef/common/`) - is changed only behind `OS_LINUX` / `__linux__` guards. + is changed only behind `OS_LINUX` / `__linux__` guards, or where the change + is behaviour-neutral on all three (a null check, say). - **The macOS and Windows release tooling is not touched.** **Branches.** The work happens on a fork. `linux/port` is the root branch, @@ -174,7 +183,7 @@ macOS paths and commands: |---|---|---| | M1 | The `linux/` Flutter runner (`.metadata` lists only `root`, `macos`, `windows`). | 1 | | M2 | CEF hooks in that runner, wired by hand (section 2). | 1 | -| M3 | Window close → teardown on GTK (to verify, 4.2). | 1 | +| M3 | Window close → teardown on GTK (done, 4.2). | 1 | | M4 | Packaging: AppImage, `.deb`, `.rpm`, a `.desktop` file, the icon. | 4 | --- @@ -199,18 +208,24 @@ App data and preferences share one folder (L5), so uninstall is one delete. - `flutter create --platforms=linux --org dev.serverpod .`, then commit `linux/`. `APPLICATION_ID` `dev.serverpod.appstudio`, binary - `appstudio`, window title "App Studio", 1280×800, minimum 670×720 (in step - with `kMinAppWindowSize`). + `appstudio`, window title "App Studio", 1280×800, minimum 670×600 (in step + with `kMinAppWindowSize`): Windows' minimum, since 720 high does not fit a + 1080p laptop screen at 150%. A tiling window manager ignores both. - **CEF hooks by hand**: `initCEFProcesses(argc, argv)` first in `main()`, so helper processes return before GTK starts; the key press and release handlers on the `FlView`. Without them the app does not run at all, which is why they are in PR 1 and the rest of the CEF work is in PR 3. -- **Window close → teardown, to verify first.** On Windows the close - skipped `onExitRequested` because CEF keeps hidden top-level windows. On - GTK, the check is: does clicking close (and Super+Q on Hyprland) run the - teardown that stops the runner? If not, the runner's `delete-event` - handler asks Dart over `dev.serverpod.appstudio/lifecycle`, the channel - Windows already uses (`window_close.dart`). +- **Window close → teardown.** On GTK every way out reaches + `onExitRequested`: the close button, the window manager's close (Super+Q + on Hyprland), File → Quit and Ctrl+Q. No `delete-event` handler was + needed. Two things did need fixing: + - A second exit request while the teardown runs waits for it, at most + 15 s (`_kLinuxExitWait` in `main.dart`), instead of quitting before the + server has stopped. macOS and Windows still answer at once. + - `linux/runner/main.cc` ends with `_exit()` after `g_application_run`. + Flutter's Linux quit leaves the engine running, and a normal `exit()` + raced Mesa's exit handlers against the raster thread and crashed about + one quit in four. - **Menus (F10):** mount the Windows shad menu strip (`windows_app_menu.dart`) on Linux too. Same commands, same Ctrl shortcuts, same enable rules. - **Shortcut hints (F11):** `shortcutHint()` gives the Ctrl form on Linux. @@ -259,7 +274,8 @@ App data and preferences share one folder (L5), so uninstall is one delete. ### 4.4 The preview (PR 3) -All in `packages/webview_cef/linux/`, or behind `__linux__` in `common/`: +All in `packages/webview_cef/linux/`, or behind `__linux__` in `common/` +unless the change is behaviour-neutral on all three: - **Auto-setup:** take `modify_target.sh` out of the plugin's CMake. The hooks live in the runner (PR 1), and the script is what breaks on current @@ -268,7 +284,18 @@ All in `packages/webview_cef/linux/`, or behind `__linux__` in `common/`: it from the runner with `/CEF` before CEF starts. - **Shortcuts:** with the preview focused, the page gets the keys, but Ctrl on any other character key stays App Studio's shortcut, as on Windows. - Ctrl+X/C/V/A/Z go to the page as edit commands. + Ctrl+A/C/V/X/Y/Z stay with the page. +- **Clipboard, through GTK.** On Wayland only a window with keyboard focus + may use the clipboard, and CEF draws off-screen, so it never has focus: + its copies stayed inside Chromium and it never saw what others copied. + The plugin carries the text across itself. Ctrl+C and Ctrl+X put the + page's selection on the clipboard, and Ctrl+V types the clipboard's text + into the page, as an input method would. Two limits follow: + - The page gets no paste event, so a page that reads paste events (an + image, rich text) gets nothing. + - Only a selection Chromium sees is copied. A copy made by the page's own + code (`Clipboard.setData`, Flutter web's `SelectionArea`) does not reach + other programs. - **Frame buffer:** the memory bug from the spike. - **The `xclip` workaround:** remove it (not needed, section 2). - **End to end:** hard reload and the project-switch clear @@ -277,13 +304,17 @@ All in `packages/webview_cef/linux/`, or behind `__linux__` in `common/`: ### 4.5 Packaging (PR 4) -- **AppImage first** (Tuesday), built on the dev machine, from an existing - Flutter Linux AppImage setup with zsync update info, so Gear Lever can - update it. The CEF helpers must resolve their own paths inside the - mounted image; check that early. -- **`.deb`, then `.rpm`:** dependencies on git, curl, unzip and xz, plus - CEF's runtime libraries (libnss3, libgbm1, libasound2 and the rest; to - list from `ldd` on the bundle). +- **AppImage** (Tuesday), built on the dev machine by `make appimage` + (`tool/linux/build_appimage.sh`), from an existing Flutter Linux AppImage + setup. The CEF helpers resolve their own paths inside the mounted image. +- **Updates come from inside the app** (`specs/linux_appimage.md` part B): + a signed feed that `tool/linux/appcast.sh` writes, and the feed and key + in `linux/release.json`. zsync update information for Gear Lever is still + possible (`APPIMAGE_UPDATE_INFO`) but off unless the build is given it. +- **`.deb` and `.rpm`: not built**, only if asked (see the plan in short). + They would declare git, curl, unzip and xz, plus CEF's runtime libraries + (libnss3, libgbm1, libasound2 and the rest; to list from `ldd` on the + bundle). - **Every format:** a `.desktop` file with `StartupWMClass` matching the GTK application id, so the dock and window match; the icon in hicolor sizes. - **Size:** strip the bundle (1.5 GB unstripped). The macOS app is 350 MB @@ -342,8 +373,8 @@ macOS and Windows CI green. ### PR 4: Packaging (`linux/4-packaging`) -- The AppImage for Tuesday (4.5); the `.deb` if time allows; the `.rpm` - later. +- The AppImage for Tuesday (4.5). Then, in `linux/4b-appimage`, Add to + Applications and in-app updates. No `.deb` or `.rpm` unless asked. - Done when (Tuesday): the AppImage runs on Ubuntu and on Omarchy and passes the smoke checklist (section 6). @@ -353,8 +384,8 @@ macOS and Windows CI green. ### Serverpod's side -- CI (a Linux job, if wanted), the release pipeline, hosting and - auto-updates, using the build scripts from PR 4. +- CI (a Linux job, if wanted), the release pipeline, and the update feed's + hosting and signing key, using the build scripts from PR 4. --- @@ -401,10 +432,9 @@ macOS and Windows CI green. For Serverpod, since updates and releases are theirs: -1. **Updates.** The AppImage carries zsync update info, so Gear Lever (and - AppImageUpdate) can update it from wherever Serverpod hosts it. Is that - enough, or should updates go through apt/dnf repositories (which need GPG - signing and hosting)? +1. **Updates.** App Studio updates the AppImage itself from a signed feed. + Where is it hosted, and who holds the signing key? Are `.deb` and `.rpm` + wanted on top? 2. **Ubuntu baseline.** 24.04 LTS? --- @@ -414,7 +444,7 @@ For Serverpod, since updates and releases are theirs: | What | Why | How | |---|---|---| | Flutter ≥ 3.44 (stable) | Host SDK for building App Studio | any stable SDK on `PATH`; not in `~/develop/flutter`, which is where App Studio installs its own | -| Flutter's Linux desktop dependencies | `flutter build linux` | Ubuntu: `sudo apt install clang cmake ninja-build pkg-config libgtk-3-dev`; Arch: `sudo pacman -S --needed clang cmake ninja pkgconf gtk3` | +| Flutter's Linux desktop dependencies | `flutter build linux` | Ubuntu: `sudo apt install clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev`; Arch: `sudo pacman -S --needed clang cmake ninja pkgconf gtk3` | | git, curl, unzip, xz | Flutter itself, and App Studio's own setup check | usually there already | | ~2 GB free and network on the first build | CEF downloads during the first CMake configure | — | @@ -428,14 +458,15 @@ laptop with a fresh Ubuntu covers the AppImage on a clean system. Tuesday: -- [ ] PR 1: App runs -- [ ] PR 2: Setup works -- [ ] PR 3: Preview works -- [ ] AppImage runs on Ubuntu (smoke checklist) -- [ ] AppImage runs on Omarchy (smoke checklist) +- [x] PR 1: App runs +- [x] PR 2: Setup works +- [x] PR 3: Preview works +- [x] AppImage runs on Ubuntu (smoke checklist) +- [x] AppImage runs on Omarchy (smoke checklist) After Tuesday: -- [ ] PR 4: `.deb` and `.rpm` +- [x] AppImage: Add to Applications and in-app updates +- [ ] `.deb` and `.rpm`, only if asked - [ ] PR 5: Polish ("Open in…" editors, notifications, uninstall) - [ ] Build scripts handed over for Serverpod's CI and release pipeline From 991a080913e55ff12c9294374b44db61acaf9e3e Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 16:19:30 +0100 Subject: [PATCH 31/32] fix: Lets App Studio start from a terminal as a background job on Linux. Started from a terminal with `&`, App Studio froze before showing its window. To find Flutter it runs the user's login shell as an interactive shell, and an interactive bash opens the terminal it shares with App Studio to set up job control. As a background job, the terminal answers with SIGTTIN and stops the whole process group, App Studio included, so not even the probe's own timeout fired: "Stopped (tty input)". On Linux the shell now runs in a session of its own with no terminal (ProcessStartMode.detachedWithStdio). Its output still comes back through the pipes, and the kill after the answer still reaches it. macOS keeps the normal start. --- AGENTS.md | 1 + lib/toolchain/login_shell_path.dart | 9 +++++++++ test/toolchain/login_shell_path_test.dart | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 5b1d14e..c54bea6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -891,6 +891,7 @@ Earlier builds kept every tool under - **It is a fallback, not a replacement.** `_which` tries the inherited `PATH` first and only then spawns a shell (~80 ms). The result — including a failure — is memoised per `ToolProbe`. - **Discovery only.** Candidates found this way are still executed by absolute path under the probe's own controlled environment. - **Do not wait for the shell's stdout to reach EOF.** The shell's children inherit that pipe, so an rc that backgrounds anything holds it open long after the answer is written. The reader completes on the closing marker instead, which is also what makes the timeout fire. `${PATH}` is braced for the same class of reason: unbraced, the trailing marker is read as part of the variable *name* and the answer comes back silently empty. + - **On Linux the shell runs in a session of its own, with no terminal** (`ProcessStartMode.detachedWithStdio`, which calls `setsid`). Started from a terminal as a background job (`./AppStudio….AppImage &`), App Studio shares that terminal, and an interactive bash opens it for job control: the terminal stops the whole process group with SIGTTIN, App Studio included, and not even the timeout fires. Seen on Ubuntu as `Stopped (tty input)`. The pipes still carry the answer, and `kill` still reaches the shell. macOS keeps the normal start. - **Serverpod's candidates check `~/Library/Application Support/Dart/install/bin` first**, ahead of `~/.pub-cache/bin`. That is where `dart install serverpod_cli` puts it; the pub-cache copy is the one that goes stale. - `PUB_CACHE` is deliberately **not** set: `package_config.json` stores absolute paths, so a private cache would make every switch to an external editor re-resolve the project. - Version rules live in `tool_version.dart`. A numeric-only suffix is a *packaging revision*, not a prerelease — `2.53.0-3` is newer than `2.53.0`, while `4.0.0-beta.1` is older than `4.0.0`. diff --git a/lib/toolchain/login_shell_path.dart b/lib/toolchain/login_shell_path.dart index b90afc1..130dc80 100644 --- a/lib/toolchain/login_shell_path.dart +++ b/lib/toolchain/login_shell_path.dart @@ -75,6 +75,15 @@ Future captureLoginShellPath({ 'APP_STUDIO_SHELL_PROBE': '1', }, runInShell: false, + // Linux: in a session of its own, with no terminal. Started from a + // terminal as a background job (`./AppStudio….AppImage &`), App Studio + // shares that terminal, and an interactive bash opens it to set up job + // control: the terminal stops the whole process group with SIGTTIN, + // App Studio included, so not even the timeout below fires. Output + // still comes back through the pipes. macOS keeps its normal start. + mode: (host ?? currentHost).isLinux + ? ProcessStartMode.detachedWithStdio + : ProcessStartMode.normal, ); } catch (_) { return null; diff --git a/test/toolchain/login_shell_path_test.dart b/test/toolchain/login_shell_path_test.dart index a0b1e12..c41ac8d 100644 --- a/test/toolchain/login_shell_path_test.dart +++ b/test/toolchain/login_shell_path_test.dart @@ -72,6 +72,24 @@ void main() { final shell = await fakeShell('#!/bin/sh\necho "just noise"\n'); expect(await captureLoginShellPath(shellOverride: shell), isNull); }); + + test( + 'runs the shell in a session of its own on Linux, away from any ' + 'terminal', () async { + // Started from a terminal as a background job, App Studio shares that + // terminal; an interactive bash in the same session would take it for + // job control and get the whole process group stopped. The fake shell + // reports its session id in place of a PATH. + final shell = await fakeShell('#!/bin/sh\n' + "printf '__APP_STUDIO_PATH__%s__APP_STUDIO_PATH__' " + '"\$(ps -o sid= -p \$\$ | tr -d " ")"\n'); + final ours = await Process.run('ps', ['-o', 'sid=', '-p', '$pid']); + + final theirs = await captureLoginShellPath(shellOverride: shell); + + expect(theirs, isNotNull); + expect(theirs, isNot('${ours.stdout}'.trim())); + }, testOn: 'linux'); }); group('shellPathScript', () { From c7f10311690f466a0cd1876486ed7909223faccb Mon Sep 17 00:00:00 2001 From: Ben Auer Date: Sat, 28 Nov 2026 16:24:23 +0100 Subject: [PATCH 32/32] fix: Says Add copies the AppImage where it cannot move it. Started from a folder App Studio may not take the file out of (a root-owned /opt, a read-only file system, or a shared sticky folder such as /tmp holding someone else's file), Add copies the AppImage to ~/AppImages and the original stays. The question still said the file moves. The Add and Replace questions now say a copy goes to ~/AppImages and the original stays. Whether that is the case is read from the folder's permissions with test -w, -x and, for a sticky folder, -O, so nothing is written there before the user answers. --- lib/platform/linux/desktop_integration.dart | 34 ++++++++++++ lib/ui/add_to_applications_dialog.dart | 34 +++++++++--- lib/ui/desktop_integration_commands.dart | 12 ++++- specs/linux_appimage.md | 16 +++++- .../linux/desktop_integration_test.dart | 52 +++++++++++++++++++ test/ui/add_to_applications_dialog_test.dart | 18 +++++++ .../ui/desktop_integration_commands_test.dart | 18 +++++++ widgetbook/use_cases/start.dart | 10 ++++ 8 files changed, 185 insertions(+), 9 deletions(-) diff --git a/lib/platform/linux/desktop_integration.dart b/lib/platform/linux/desktop_integration.dart index 7be170f..ae4e241 100644 --- a/lib/platform/linux/desktop_integration.dart +++ b/lib/platform/linux/desktop_integration.dart @@ -173,6 +173,40 @@ class DesktopIntegration { return folder; } + /// Whether [add] has to copy the AppImage and leave the original where it + /// is: App Studio may not take the file out of its folder (a root-owned + /// `/opt`, a read-only file system, or a shared sticky folder such as + /// `/tmp` with someone else's file). The question then says so rather + /// than promising a move. + /// + /// Asked of the permissions, without writing anything: nothing outside + /// App Studio's own folders is touched before the user answers. An + /// immutable file (`chattr +i`) is not detected; Add still copies it, and + /// only the wording is off. + Future keepsOriginal() async { + final folder = await currentFolder(); + final appImage = _appImage; + if (folder == null || appImage == null) return false; + try { + // Taking a file out of a folder needs write and search permission on + // the folder and, in a sticky one, owning the file or the folder, or + // being root. + final result = await Process.run('/bin/sh', [ + '-c', + r'[ -w "$1" ] && [ -x "$1" ] && ' + r'{ [ ! -k "$1" ] || [ -O "$1" ] || [ -O "$2" ] || ' + r'[ "$(id -u)" = 0 ]; }', + 'sh', + folder, + appImage, + ]); + return result.exitCode != 0; + } on ProcessException { + // No shell to ask: say it moves, as before. + return false; + } + } + /// Whether [add] would replace another file at [addedAppImagePath]: a copy /// left there after Remove, or after its entry was deleted by hand. It may /// be a newer build, so the question says so. diff --git a/lib/ui/add_to_applications_dialog.dart b/lib/ui/add_to_applications_dialog.dart index 25ddb38..bd59c22 100644 --- a/lib/ui/add_to_applications_dialog.dart +++ b/lib/ui/add_to_applications_dialog.dart @@ -29,6 +29,7 @@ class AddToApplicationsDialog extends StatefulWidget { super.key, required this.onAdd, this.currentFolder, + this.keepsOriginal = false, this.replacedFile, this.offerDontAskAgain = true, }); @@ -40,6 +41,10 @@ class AddToApplicationsDialog extends StatefulWidget { /// it. Null when it is already in `~/AppImages`. final String? currentFolder; + /// Add can only copy the file out of [currentFolder] (a folder App Studio + /// cannot take it out of), so the original stays and the text says so. + final bool keepsOriginal; + /// Another file at the path Add moves this one to, left there by an /// earlier Add. It may be a newer build, so the question says Add replaces /// it. Null when there is none. @@ -103,10 +108,16 @@ class _AddToApplicationsDialogState extends State { title: const Text('Add App Studio to your applications?'), description: Text( [ - folder == null - ? 'App Studio will appear in your app menu.' - : 'App Studio will appear in your app menu, and the file moves ' - 'from ${prettyPath(folder)} to ~/AppImages.', + switch ((folder, widget.keepsOriginal)) { + (null, _) => 'App Studio will appear in your app menu.', + (final folder?, false) => + 'App Studio will appear in your app menu, and the file moves ' + 'from ${prettyPath(folder)} to ~/AppImages.', + (final folder?, true) => + 'App Studio will appear in your app menu, with a copy of the ' + 'file in ~/AppImages. The one in ${prettyPath(folder)} ' + 'stays, since App Studio cannot move it from there.', + }, if (widget.replacedFile case final replaced?) 'It replaces the App Studio already at ${prettyPath(replaced)}.', ].join(' '), @@ -180,6 +191,7 @@ class ReplaceAddedCopyDialog extends StatefulWidget { required this.added, required this.onReplace, this.currentFolder, + this.keepsOriginal = false, }); final AppVersion running; @@ -190,6 +202,10 @@ class ReplaceAddedCopyDialog extends StatefulWidget { /// is in `~/AppImages` already. final String? currentFolder; + /// Replace can only copy this file out of [currentFolder], so it stays + /// there and the text says so. + final bool keepsOriginal; + @override State createState() => _ReplaceAddedCopyDialogState(); } @@ -225,9 +241,13 @@ class _ReplaceAddedCopyDialogState extends State { title: Text('Replace App Studio $added with this version?'), description: Text( 'This copy is App Studio $running, newer than the $added in your app ' - 'menu. ${folder == null ? 'Replace puts it' : 'Replace moves it from ' - '${prettyPath(folder)} to ~/AppImages,'} in place of the older ' - 'one.', + 'menu. ${switch ((folder, widget.keepsOriginal)) { + (null, _) => 'Replace puts it', + (final folder?, false) => 'Replace moves it from ' + '${prettyPath(folder)} to ~/AppImages,', + (final folder?, true) => 'Replace puts a copy of it from ' + '${prettyPath(folder)} into ~/AppImages,', + }} in place of the older one.', ), actions: [ ShadButton.outline( diff --git a/lib/ui/desktop_integration_commands.dart b/lib/ui/desktop_integration_commands.dart index 0dd8da9..2a8d516 100644 --- a/lib/ui/desktop_integration_commands.dart +++ b/lib/ui/desktop_integration_commands.dart @@ -68,6 +68,7 @@ Future maybeOfferAddToApplications( final prefs = await SharedPreferences.getInstance(); if (prefs.getBool(kAddToApplicationsDeclinedKey) ?? false) return; final folder = await integration.integration.currentFolder(); + final keepsOriginal = await integration.integration.keepsOriginal(); final replaced = await integration.integration.replacesAnotherFile() ? integration.integration.addedAppImagePath : null; @@ -77,6 +78,7 @@ Future maybeOfferAddToApplications( integration, fromMenu: false, currentFolder: folder, + keepsOriginal: keepsOriginal, replacedFile: replaced, ); if (answer == AddToApplicationsAnswer.never) { @@ -92,6 +94,7 @@ Future addToApplications( await integration.refresh(); if (integration.status != DesktopIntegrationStatus.notAdded) return; final folder = await integration.integration.currentFolder(); + final keepsOriginal = await integration.integration.keepsOriginal(); final replaced = await integration.integration.replacesAnotherFile() ? integration.integration.addedAppImagePath : null; @@ -101,6 +104,7 @@ Future addToApplications( integration, fromMenu: true, currentFolder: folder, + keepsOriginal: keepsOriginal, replacedFile: replaced, ); } @@ -110,6 +114,7 @@ Future _showAddDialog( DesktopIntegrationController integration, { required bool fromMenu, required String? currentFolder, + required bool keepsOriginal, required String? replacedFile, }) async { final answer = await showAppDialog( @@ -120,6 +125,7 @@ Future _showAddDialog( builder: (context) => AddToApplicationsDialog( onAdd: integration.add, currentFolder: currentFolder, + keepsOriginal: keepsOriginal, replacedFile: replacedFile, offerDontAskAgain: !fromMenu, ), @@ -178,8 +184,11 @@ Future _offerForOtherCopy( }) async { final desktop = integration.integration; final copy = await desktop.otherCopy(); + if (copy == null) return; final folder = await desktop.currentFolder(); - if (copy == null || !context.mounted || !onStartPage()) return; + // Only the Replace question names the folder this copy is in. + final keepsOriginal = copy.runningIsNewer && await desktop.keepsOriginal(); + if (!context.mounted || !onStartPage()) return; final toaster = ShadToaster.maybeOf(context); if (copy.runningIsNewer) { @@ -191,6 +200,7 @@ Future _offerForOtherCopy( added: copy.added, onReplace: integration.add, currentFolder: folder, + keepsOriginal: keepsOriginal, ), ); if (replaced == true) { diff --git a/specs/linux_appimage.md b/specs/linux_appimage.md index 2bdeb4c..b2a11a0 100644 --- a/specs/linux_appimage.md +++ b/specs/linux_appimage.md @@ -118,6 +118,17 @@ another file is at `~/AppImages/AppStudio-x86_64.AppImage` already (a copy left there by Remove, or whose entry was deleted by hand), the question adds "It replaces the App Studio already at ~/AppImages/AppStudio-x86_64.AppImage.", since that copy may be newer. + +When App Studio may not take the file out of its folder (a root-owned +`/opt`, a read-only file system, or a shared sticky folder such as `/tmp` +holding someone else's file), Add copies it and the original stays, so the +sentence reads "App Studio will appear in your app menu, with a copy of the +file in ~/AppImages. The one in /opt/as stays, since App Studio cannot move +it from there." This is read from the folder's permissions (`test -w`, `-x`, +and for a sticky folder `-O`, or root), without writing anything there +before the user answers. An immutable file (`chattr +i`) is not detected: Add still +copies it, and only the wording is off. + **Not now** asks again on the next start; with the box ticked it never asks again on start. @@ -232,7 +243,10 @@ number, which orders releases: ``` When the copy is in `~/AppImages` already, the second sentence reads - "Replace puts it in place of the older one." Replace runs Add, so + "Replace puts it in place of the older one." Where the file can only be + copied out of its folder (as for the question above), it reads "Replace + puts a copy of it from /opt/as into ~/AppImages, in place of the older + one." Replace runs Add, so everything above applies: the file is renamed over the old one, and the entry is rewritten with the new version. Once the move has happened the older copy is gone; if a later step fails, the existing entry and icons diff --git a/test/platform/linux/desktop_integration_test.dart b/test/platform/linux/desktop_integration_test.dart index 9bd632a..d9c8b44 100644 --- a/test/platform/linux/desktop_integration_test.dart +++ b/test/platform/linux/desktop_integration_test.dart @@ -525,6 +525,58 @@ Exec=appstudio --extra ); }); + // The sticky-folder rule (a shared folder such as /tmp holding someone + // else's file) needs a second user to set up, so only the write + // permission is tested here. + group('a folder the file cannot be taken out of', () { + test( + 'is said up front, where Add can only copy', + () async { + final uid = await Process.run('id', ['-u']); + if ('${uid.stdout}'.trim() == '0') { + markTestSkipped('root can take files out of any folder'); + return; + } + final folder = p.dirname(appImage); + expect(await integration().keepsOriginal(), isFalse); + + await Process.run('chmod', ['555', folder]); + addTearDown(() => Process.run('chmod', ['755', folder])); + + expect(await integration().keepsOriginal(), isTrue); + }, + tags: 'process', + testOn: 'linux', + ); + + test( + 'writes nothing to the folder it asks about', + () async { + final folder = Directory(p.dirname(appImage)); + final backdated = await Process.run('touch', [ + '-t', + '200001010000', + folder.path, + ]); + expect(backdated.exitCode, 0); + + await integration().keepsOriginal(); + + expect((await folder.stat()).modified.year, 2000); + expect(await folder.list().map((e) => p.basename(e.path)).toList(), [ + p.basename(appImage), + ]); + }, + tags: 'process', + testOn: '!windows', + ); + + test('is not a question for a file in ~/AppImages already', () async { + await integration().add(); + expect(await integration().keepsOriginal(), isFalse); + }); + }); + group('a file already at the target', () { test('is named when Add would replace it', () async { await File(target()).create(recursive: true); diff --git a/test/ui/add_to_applications_dialog_test.dart b/test/ui/add_to_applications_dialog_test.dart index ea26895..6eae30a 100644 --- a/test/ui/add_to_applications_dialog_test.dart +++ b/test/ui/add_to_applications_dialog_test.dart @@ -160,6 +160,24 @@ void main() { expect(result(), isTrue); }); + testWidgets('Replace says it copies where it cannot move', (tester) async { + await show( + tester, + ReplaceAddedCopyDialog( + running: newer, + added: older, + currentFolder: '/opt/as', + keepsOriginal: true, + onReplace: () async {}, + ), + ); + + expect( + find.textContaining('Replace puts a copy of it from /opt/as into'), + findsOneWidget, + ); + }); + testWidgets('an older copy offers to open the newer one', (tester) async { final result = await show( tester, diff --git a/test/ui/desktop_integration_commands_test.dart b/test/ui/desktop_integration_commands_test.dart index 9939fe3..a5a8199 100644 --- a/test/ui/desktop_integration_commands_test.dart +++ b/test/ui/desktop_integration_commands_test.dart @@ -107,6 +107,20 @@ void main() { expect(await declined(), isTrue); }); + testWidgets('says the original stays where Add can only copy it', ( + tester, + ) async { + desktop.keeps = true; + await offer(tester); + + expect(find.textContaining('with a copy of the file in'), findsOneWidget); + expect( + find.textContaining('stays, since App Studio cannot move it'), + findsOneWidget, + ); + expect(find.textContaining('the file moves'), findsNothing); + }); + testWidgets('a file already at the target is named', (tester) async { desktop.replaces = true; await offer(tester); @@ -224,6 +238,7 @@ class _FakeIntegration extends DesktopIntegration { DesktopIntegrationStatus current = DesktopIntegrationStatus.notAdded; bool removeFails = false; bool replaces = false; + bool keeps = false; bool openFails = false; OtherCopy? copy; int added = 0; @@ -242,6 +257,9 @@ class _FakeIntegration extends DesktopIntegration { String get addedAppImagePath => '/home/alex/AppImages/AppStudio-x86_64.AppImage'; + @override + Future keepsOriginal() async => keeps; + @override Future replacesAnotherFile() async => replaces; diff --git a/widgetbook/use_cases/start.dart b/widgetbook/use_cases/start.dart index 94908e8..e61ea0e 100644 --- a/widgetbook/use_cases/start.dart +++ b/widgetbook/use_cases/start.dart @@ -170,6 +170,16 @@ final startFolder = WidgetbookFolder( builder: (_) => _overStartPage(AddToApplicationsDialog(onAdd: () async {})), ), + WidgetbookUseCase( + name: 'From a folder it can only copy from', + builder: (_) => _overStartPage( + AddToApplicationsDialog( + onAdd: () async {}, + currentFolder: '/opt/as', + keepsOriginal: true, + ), + ), + ), WidgetbookUseCase( name: 'Replacing a copy left in ~/AppImages', builder: (_) => _overStartPage(