diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index e65a2854..5d2a42fd 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -375,6 +375,47 @@ jobs: tools/among-tools/target/release/among-tools run-ignored-tests "$RUNNER_TEMP/tool-tests.jsonl" cargo test --locked --no-run --message-format=json > "$RUNNER_TEMP/test-executables.jsonl" tools/among-tools/target/release/among-tools run-ignored-tests "$RUNNER_TEMP/test-executables.jsonl" + - name: Documentation media on the owned display image + if: matrix.runner == 'ubuntu-24.04' + run: | + set -euo pipefail + touch src/build_info.rs + AMONG_BUILD_VERSION=0.2.0 \ + AMONG_BUILD_COMMIT="$(git rev-parse --short HEAD)" \ + AMONG_BUILD_DATE="$(date -u +%F)" \ + cargo test --locked --no-run --message-format=json > "$RUNNER_TEMP/media-tests.jsonl" + app_test="$(jq -sre '[.[] | select(.reason == "compiler-artifact" and .profile.test == true and .target.name == "among" and .target.kind == ["bin"] and .executable != null) | .executable] | unique | if length == 1 then .[0] else error("expected one application test executable") end' "$RUNNER_TEMP/media-tests.jsonl")" + case "$app_test" in "$PWD"/target/debug/deps/*) ;; *) exit 1 ;; esac + test -x "$PWD/target/debug/examples/fake-plugin" + root="$AMONG_CHECK_ROOT/media" + mkdir -p "$root"/{home,config,data,cache,state,out} + chmod 700 "$root" + container_test="/target/${app_test#"$PWD/target/"}" + docker run --rm --network none --user "$(id -u):$(id -g)" \ + --mount type=bind,src="$PWD/target",dst=/target,readonly \ + --mount type=bind,src="$PWD/tools/among-tools/target/release/among-tools",dst=/tools/among-tools,readonly \ + --mount type=bind,src="$PWD",dst=/source,readonly \ + --mount type=bind,src="$root",dst=/run-root \ + --env HOME=/run-root --env XDG_DATA_HOME=/run-root/data --env XDG_CONFIG_HOME=/run-root/config \ + --env XDG_CACHE_HOME=/run-root/cache --env XDG_STATE_HOME=/run-root/state --env XDG_RUNTIME_DIR=/run-root \ + --env AMONG_CHECK_ROOT=/run-root --env AMONG_MEDIA_SOURCE="$(git rev-parse HEAD)" \ + --workdir /source among-installer-enospc:ci \ + /tools/among-tools media all "$container_test" /run-root/out \ + > "$root/media.log" 2>&1 + docker run --rm --network none --user "$(id -u):$(id -g)" \ + --mount type=bind,src="$PWD/tools/among-tools/target/release/among-tools",dst=/tools/among-tools,readonly \ + --mount type=bind,src="$root",dst=/run-root \ + among-installer-enospc:ci \ + /tools/among-tools media verify /run-root/out + cat "$root/media.log" + - name: Keep documentation media evidence + if: ${{ always() && matrix.runner == 'ubuntu-24.04' }} + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: documentation-media + path: ${{ runner.temp }}/among-checks/media + if-no-files-found: warn + retention-days: 7 - name: Real audio through each distribution's declared packages run: | cargo build --locked --example audio-probe --bin among diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c66b3af3..d80c2b5e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -73,6 +73,9 @@ Behaviour that only exists in a running window is verified differently: the application is driven with scripted actions (`AMONG_SCRIPT`) and real key events (`xdotool`), and its state is read back from `AMONG_SELFCHECK`. See [Verification aids](docs/testing.md) for the full list of switches. +Documentation stills and the notification recording come from +[documentation media](docs/media.md); use `among-tools media` instead of a +temporary capture script. A change to layout, focus, or the plugin pipeline is not finished until it has been observed at that boundary. A test that only proves a function returns a diff --git a/docs/media.md b/docs/media.md new file mode 100644 index 00000000..a3ce9dd6 --- /dev/null +++ b/docs/media.md @@ -0,0 +1,185 @@ +# Documentation media + +Screenshots and demo recordings for the site and README come from one +scene. The scene is real application state: a saved session, three named +workspaces, real PTYs, the real Preferences window and a real GNOME +notification. Nothing is assembled by hand. + +The same command produces the files, so a layout change is fixed once instead +of once per page. + +Build the display image once; it carries Xvfb, Xephyr, GNOME Shell, +ImageMagick, ffmpeg and `xsetroot`: + +```sh +docker build -f tools/among-tools/containers/Dockerfile.display -t among-display:media . +``` + +## One command + +Build the application test binary in the pinned Ubuntu image, build +`among-tools`, then run the capture inside the display image: + +```sh +# 0. Prepare the bind mounts and the offline registry cache. +mkdir -p "$HOME/.cache/among/media/cargo" \ + "$HOME/.cache/among/media/build/target" \ + "$HOME/.cache/among/media/run" +cargo fetch --locked + +# 1. Build the application test binary and the plugin fixture. +docker run --rm --network none --user "$(id -u):$(id -g)" \ + --mount type=bind,src="$PWD",dst=/source,readonly \ + --mount type=bind,src="$HOME/.cache/among/media/cargo",dst=/cargo \ + --mount type=bind,src="$HOME/.cargo/registry",dst=/cargo/registry,readonly \ + --mount type=bind,src="$HOME/.cache/among/media/build/target",dst=/target \ + --env HOME=/tmp --env CARGO_HOME=/cargo --env CARGO_TARGET_DIR=/target \ + --env AMONG_BUILD_VERSION=0.2.0 \ + --env AMONG_BUILD_COMMIT="$(git rev-parse --short HEAD)" \ + --env AMONG_BUILD_DATE="$(date -u +%F)" \ + --env CARGO_NET_OFFLINE=true --workdir /source \ + among-managed-resource-gui:1.98.1-ubuntu24-20261025-01 \ + bash -c 'cargo test --locked --offline --bin among --no-run --message-format=json > /target/test.jsonl && cargo build --locked --offline --example fake-plugin' +# Take the last compiler-artifact executable from target/test.jsonl; it is +# usually target/debug/deps/among-. + +# 2. Build the tool. +cargo build --locked --release --manifest-path tools/among-tools/Cargo.toml + +# 3. Capture and prepare everything. +docker run --rm --network none --user "$(id -u):$(id -g)" \ + --mount type=bind,src="$HOME/.cache/among/media/build/target",dst=/target,readonly \ + --mount type=bind,src="$PWD/tools/among-tools/target/release/among-tools",dst=/tools/among-tools,readonly \ + --mount type=bind,src="$PWD",dst=/source,readonly \ + --mount type=bind,src="$HOME/.cache/among/media/run",dst=/run \ + --env HOME=/run --env XDG_DATA_HOME=/run/data --env XDG_CONFIG_HOME=/run/config \ + --env XDG_CACHE_HOME=/run/cache --env XDG_STATE_HOME=/run/state \ + --env XDG_RUNTIME_DIR=/run --env AMONG_CHECK_ROOT=/run \ + --env AMONG_MEDIA_SOURCE="$(git rev-parse HEAD)" \ + --workdir /source among-display:media \ + /tools/among-tools media all /target/debug/deps/among- /run/out + +# 4. Check the published contract inside the image that carries ffprobe. +docker run --rm --network none --user "$(id -u):$(id -g)" \ + --mount type=bind,src="$PWD/tools/among-tools/target/release/among-tools",dst=/tools/among-tools,readonly \ + --mount type=bind,src="$HOME/.cache/among/media/run",dst=/run \ + among-display:media \ + /tools/among-tools media verify /run/out +``` + +CI runs the same `media all` and `media verify` in the x86_64 native job and +keeps the output as the `documentation-media` artifact. + +`among-display:media` is built from +`tools/among-tools/containers/Dockerfile.display`. It contains the owned X11 +and GNOME stack, ImageMagick, ffmpeg and `xsetroot`; the image also owns +`/work`, the synthetic project path that may appear in a notification. + +The captures write below the output directory and create the synthetic +`/work/among` project inside the disposable display image. The scene removes +that project only when its own `.git/among-media-project` marker is present; +a project without the marker is refused. `/work` is sticky and writable by +any runtime uid, so `--user "$(id -u):$(id -g)"` works without uid 1000. +`raw/` contains the untouched captures and stays as evidence. `media.json` +records every published file, its size, dimensions and SHA-256; set +`AMONG_MEDIA_SOURCE` to the source commit or the manifest keeps `source: null` +and prints a warning. + +## Scenarios + +| Command | What it captures | +| --- | --- | +| `media stills` | The restore prompt, the three-pane Workbench, an expanded pane, the Review workspace, the plugin status comparison and the seven Preferences pages including About | +| `media panes` | One pane split to five, divider resizes, a pane dragged to a new position, workspace switching, then a new workspace created and renamed | +| `media notification` | The Review workspace with a status terminal, a real GNOME notification, a pointer click and the focused terminal after it | +| `media all` | All three, in one output directory | + +The stills and panes runs use an owned 1600x1000 Xvfb/Openbox display with the +application maximized, so the product fills the frame. The notification run +uses an owned Xephyr/GNOME Shell display with a private session bus, a private +desktop identity and dark system settings. All use the same project, terminal +colours, font fixture and application build. + +## The published contract + +| Asset | Size | +| --- | --- | +| `main-window.png`, `expanded-pane.png`, `workspaces.png` | 1600x1000 | +| `plugin-off.png`, `plugin-on.png` | 1600x1000 | +| `panes.mp4`, `panes-poster.png` | 1600x1000, H.264, 30 fps, no audio | +| `session-restore.png` | 800x480 | +| Preferences stills | 882 wide, 2 px taller than the window | +| `notification-return.mp4` | 1600x1000, H.264, 30 fps, no audio | +| `notification-return-poster.png` | 1600x1000 | +| `desktop-notification.png` | 640x130 | + +The application fills the 1600x1000 display. Preferences stills are cropped to +the window with a 1 px `#3a414d` border, so no desktop margin remains. The +application is Adwaita dark, the terminal is Gray on black with the Tango +palette, and every PNG has its metadata stripped. `media verify` checks the +exact 18-name set, hashes, sizes, +and the video stream geometry and rate. + +## The notification recording + +The scene queues a bell in the unfocused `status` terminal, focuses a neutral +1x1 window so the application is in the background, and records the real +GNOME banner with `ffmpeg x11grab`. The pointer gesture is visible. GNOME's +X11 stage in this owned session does not deliver synthetic XTest clicks to the +banner, so the scene then calls the same `app.focus-pane` action the +notification's default target names. The payload and the real activation +contract are checked separately by +`among-tools check-desktop-notifications`; the recording is a visual +demonstration, not the notification acceptance test. + +The shell's own startup notifications are suppressed by keeping banners off +until the scene is ready. They are not part of the product story. + +The scene leaves Review for Workbench before recording, so the bell belongs to +the unseen status terminal and the banner click has a visible result. Recording +starts just before the bell, waits until the banner is visible, and captures the +poster from that confirmed frame. The clip contains the ring, the banner and the +return to Review without a hard-coded trim. + +## The panes recording + +The scene starts from a saved single-pane layout, splits to five with +`Ctrl+Shift+N`, drags the root divider twice, drags pane five onto pane two, +then switches to Review, Notes and back to Workbench with `Alt+2`, `Alt+3` and +`Alt+1`, creates a fourth workspace with `Ctrl+Shift+T` and renames it in +place. The project is synthetic; every terminal is real. + +## The plugin comparison + +`plugin-off.png` and `plugin-on.png` come from one stills run. The second image +registers the `github:12/demo-status` managed fixture, which answers the status +request with fixed `CPU 18%`, `MEM 6.2 GB` and `DISK 41%` fragments in the +application header. The fixture is a test executable, not a shipped plugin; the +values are synthetic and the page says so. + +## Publishing + +Copy the verified files into the site repository: + +| Output | Site path | +| --- | --- | +| `main-window.png`, `expanded-pane.png`, `workspaces.png`, `session-restore.png` | `docs/public/media/app/` | +| `plugin-off.png`, `plugin-on.png` | `docs/public/media/app/` | +| `panes.mp4`, `panes-poster.png` | `docs/public/media/app/` | +| `notification-return.mp4`, `notification-return-poster.png`, `desktop-notification.png` | `docs/public/media/app/` | +| `plugins.png`, `plugin-access-review.png`, `notifications.png`, `keyboard.png`, `terminal.png`, `about.png` | `docs/public/media/preferences/` | + +Use the dimensions above in page markup. Run the site's `npm run build` and +`npm run check` after replacing the files. + +## Known limits + +- The notification recording uses the owned GNOME X11 stage; it is not a + Wayland or installed-package recording. +- The example project, plugin catalogue and package sizes are synthetic, as + the site captions say. +- The raw captures are kept below the output directory; delete old output + directories yourself when they are no longer needed. +- This pipeline covers documentation stills and the panes and notification + clips. The promo, action and overview films keep their separate production + tooling. diff --git a/docs/media/among-terminal-action-v5.mp4 b/docs/media/among-terminal-action-v5.mp4 deleted file mode 100644 index 2492a4e1..00000000 Binary files a/docs/media/among-terminal-action-v5.mp4 and /dev/null differ diff --git a/docs/media/among-terminal-action-v5.png b/docs/media/among-terminal-action-v5.png deleted file mode 100644 index f94d5be7..00000000 Binary files a/docs/media/among-terminal-action-v5.png and /dev/null differ diff --git a/docs/testing.md b/docs/testing.md index 6d2e229d..9a76dbb8 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -641,6 +641,15 @@ paths and desktop never appear because the test runs in the owned display with its own `HOME`. The tool runs `/usr/bin/convert` with a cleared environment, the same fixed path the other graphical checks use. +### Site and README media + +The differently framed stills and the notification recording used by the +public site and README come from `among-tools media`; see +[documentation media](media.md). That pipeline starts its own owned X11 and +GNOME displays, writes a manifest and checks the published dimensions. The +Preferences captures above remain the in-repository table until its remaining +states are ported to the same scene. + ## Installer ENOSPC context `among-tools check-installer-enospc-from-cargo CARGO_TEST_RECORDS` selects the diff --git a/examples/fake-plugin.rs b/examples/fake-plugin.rs index 5b2995f0..120924d0 100644 --- a/examples/fake-plugin.rs +++ b/examples/fake-plugin.rs @@ -451,6 +451,21 @@ fn serve_managed_transport(mode: &str) -> std::io::Result<()> { _ => "ok", }; let mut response = json!({"type":"status","session":message["session"],"generation":message["generation"],"request_id":message["request_id"],"fragments":[{"text":text,"style":"success","priority":10}]}); + if mode == "demo-status" { + let slot = message["scope"]["slot"].as_str().unwrap_or_default(); + response["fragments"] = if slot == "app_header" { + json!([ + {"text": "09:41", "style": "default", "priority": 4}, + {"text": "CPU 18%", "style": "accent", "priority": 10}, + {"text": "MEM 6.2 GB", "style": "default", "priority": 11}, + {"text": "DISK 41%", "style": "warning", "priority": 12} + ]) + } else if slot.starts_with("pane_footer") { + json!([{"text": "/work/among", "style": "dim", "priority": 10}]) + } else { + json!([]) + }; + } if mode == "rapid" { response["refresh_ms"] = json!(0); } diff --git a/src/app/plugin_tests/installation.rs b/src/app/plugin_tests/installation.rs index 699cf91e..59039bc3 100644 --- a/src/app/plugin_tests/installation.rs +++ b/src/app/plugin_tests/installation.rs @@ -4,6 +4,7 @@ use std::os::fd::AsRawFd; use std::os::unix::fs::PermissionsExt; mod candidate; +mod doc_media; mod doc_screenshots; mod list; mod local_catalogue; diff --git a/src/app/plugin_tests/installation/doc_media.rs b/src/app/plugin_tests/installation/doc_media.rs new file mode 100644 index 00000000..2972ede4 --- /dev/null +++ b/src/app/plugin_tests/installation/doc_media.rs @@ -0,0 +1,1338 @@ +//! One scene for every documentation still and recording. +//! +//! The scene is built here, not in a shell script, so the workspaces, panes, +//! terminal content and the restore prompt are real application state. The +//! owned display runner supplies the private HOME, X server and window manager; +//! `among-tools media` prepares and checks the files after this process exits. +//! +//! Set `AMONG_MEDIA_OUTPUT` to an absolute directory. The test refuses to run +//! without an owned display and writes only below that directory. + +use super::*; +use crate::plugin::install::listing::tests::{digest, document}; +use crate::plugin::install::source::Inspection; +use crate::plugin::inventory::tests::{fixture_plugin, release_of, source_receipt, Identity}; +use crate::plugin::origin::Origin; +use crate::session::{SavedDirectory, SavedNode, SavedOrientation, SavedWorkspace, Snapshot}; +use crate::tree::PaneId; +use serde_json::json; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Where a still or a raw recording is written. +fn output() -> PathBuf { + let path = PathBuf::from( + std::env::var_os("AMONG_MEDIA_OUTPUT").expect("AMONG_MEDIA_OUTPUT is required"), + ); + assert!(path.is_absolute(), "AMONG_MEDIA_OUTPUT must be absolute"); + fs::create_dir_all(&path).expect("media output directory"); + path +} + +fn shell() -> PathBuf { + let path = PathBuf::from(std::env::var_os("HOME").expect("owned display HOME")).join("shell"); + fs::write( + &path, + b"#!/bin/sh\nexport PS1='\\W $ '\nexport HISTFILE=/dev/null\n\ + exec /bin/bash --noprofile --norc -i\n", + ) + .expect("media shell"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).expect("media shell mode"); + path +} + +/// A deterministic project whose working tree has a reviewable diff. +/// +/// The scene runs in the disposable display image, where `/work` is a fixture +/// directory. It refuses to reuse an existing project instead of deleting one: +/// a stale path means the caller did not start from the expected image. +fn project(_home: &Path) -> PathBuf { + let project = PathBuf::from("/work/among"); + let marker = project.join(".git/among-media-project"); + if project.exists() { + assert!( + marker.is_file(), + "refusing to remove {} without the in-project media marker", + project.display() + ); + fs::remove_dir_all(&project).expect("clean media project"); + } + fs::create_dir_all(project.join("src")).expect("project source"); + fs::create_dir_all(project.join(".demo")).expect("demo scripts"); + fs::write( + project.join("src/review.rs"), + r#"pub fn review(changes: &[Change]) -> Report { + let mut report = Report::default(); + for change in changes { + report.checked += 1; + } + report +} +"#, + ) + .expect("review source"); + fs::write( + project.join("checklist.md"), + r#"# Review checklist + +- [x] Read the changed parser +- [x] Compare the public API +- [ ] Run the integration suite +- [ ] Update the changelog +- [ ] Ask for a second reviewer + +The parser keeps the old shape; only its +error path changes. +"#, + ) + .expect("checklist"); + fs::write( + project.join("notes.md"), + r#"# Notes + +Keep the review small enough to finish +in one sitting. The next step is the +integration suite, not another refactor. +"#, + ) + .expect("notes"); + fs::write( + project.join("Makefile"), + b"check:\n\t@printf 'cargo test --workspace\\n'\n\t@sleep 2\n\t@printf '712 passed\\n'\n", + ) + .expect("Makefile"); + write_scripts(&project); + for args in [ + vec!["init", "-q"], + vec!["config", "user.email", "docs@among.invalid"], + vec!["config", "user.name", "Among Documentation"], + vec!["add", "."], + vec!["commit", "-qm", "Seed the review workspace"], + ] { + let status = Command::new("git") + .current_dir(&project) + .args(args) + .status() + .expect("git fixture"); + assert!(status.success(), "git fixture command failed"); + } + fs::write( + project.join(".git/among-media-project"), + b"among-tools media\n", + ) + .expect("media project marker"); + fs::write( + project.join("src/review.rs"), + r#"pub fn review(changes: &[Change]) -> Report { + let mut report = Report::default(); + for change in changes { + report.checked += 1; + if change.needs_attention() { + report.attention.push(change.id()); + } + } + report +} + +fn summary(report: &Report) -> String { + format!( + "{} checked, {} need attention", + report.checked, + report.attention.len() + ) +} +"#, + ) + .expect("changed source"); + fs::write( + project.join("checklist.md"), + r#"# Review checklist + +- [x] Read the changed parser +- [x] Compare the public API +- [x] Read the patch notes +- [ ] Run the integration suite +- [ ] Update the changelog +- [ ] Ask for a second reviewer + +The parser keeps the old shape; only its +error path changes. +"#, + ) + .expect("changed checklist"); + project +} + +fn script(project: &Path, name: &str, body: &str) { + let path = project.join(".demo").join(name); + fs::write( + &path, + format!("#!/bin/sh\nprintf '\\033[2J\\033[H'\n{body}\n"), + ) + .expect("demo script"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).expect("demo script mode"); +} + +fn write_scripts(project: &Path) { + fs::write( + project.join(".demo/env.sh"), + b"stty -echo 2>/dev/null\nPS1='$ '\n", + ) + .expect("shell environment"); + script( + project, + "diff.sh", + "printf '\\033]0;git diff\\007'\n\ + cd \"/work/among\"\n\ + git --no-pager diff --color=always -- src/review.rs | head -32", + ); + script( + project, + "checklist.sh", + "printf '\\033]0;checklist\\007'\n\ + cd \"/work/among\"\n\ + awk '{ if ($0 ~ /^- \\[x\\]/) printf \"\\033[32m%s\\033[0m\\n\", $0; else if ($0 ~ /^- \\[ \\]/) printf \"\\033[33m%s\\033[0m\\n\", $0; else print }' checklist.md", + ); + script( + project, + "changes.sh", + "printf '\\033]0;changes\\007'\n\ + cd \"/work/among\"\n\ + git --no-pager -c color.ui=always diff --stat\n\ + printf '\\n'\n\ + git --no-pager log --oneline --decorate --color=always -5", + ); + script( + project, + "make.sh", + "printf '\\033]0;make\\007'\n\ + cd \"/work/among\"\n\ + printf 'cargo test --workspace\\n'\n\ + i=1\n\ + while [ $i -le 40 ]; do\n\ + printf 'test parser_case_%02d ... ok\\n' \"$i\"\n\ + i=$((i+1))\n\ + done\n\ + printf '\\n712 passed\\n'", + ); + script( + project, + "status.sh", + "printf '\\033]0;status\\007'\n\ + cd \"/work/among\"\n\ + git status --short", + ); + script( + project, + "notes.sh", + "printf '\\033]0;notes\\007'\n\ + cd \"/work/among\"\n\ + cat notes.md", + ); + script( + project, + "pane.sh", + "printf '\\033]0;terminal %s\\007' \"$1\"\n\ + cd \"/work/among\"\n\ + printf 'pane %s\\n' \"$1\"\n\ + printf '%s\\n' \"$PWD\"\n\ + git --no-pager status --short", + ); + script( + project, + "bell.sh", + "printf '\\033]0;make\\007'\n\ + cd \"/work/among\"\n\ + printf 'cargo test --workspace\\n'\n\ + i=1\n\ + while [ $i -le 40 ]; do\n\ + printf 'test parser_case_%02d ... ok\\n' \"$i\"\n\ + i=$((i+1))\n\ + done\n\ + printf 'media-bell-ready\\n'\n\ + sleep 2\n\ + printf '\\a'\n\ + printf 'test parser_case_41 ... ok\\n'", + ); + script( + project, + "bell-status.sh", + "printf '\\033]0;status\\007'\n\ + cd \"/work/among\"\n\ + git status --short\n\ + sleep 2\n\ + printf '\\a'", + ); +} + +fn pane(cwd: &Path, id: u64) -> SavedDirectory { + SavedDirectory { + pane: id, + cwd: Some(cwd.display().to_string()), + } +} + +fn split( + orientation: SavedOrientation, + ratio: f64, + first: SavedNode, + second: SavedNode, +) -> SavedNode { + SavedNode::Split { + orientation, + ratio, + first: Box::new(first), + second: Box::new(second), + } +} + +fn snapshot(cwd: &Path) -> Snapshot { + Snapshot { + version: 1, + active: 0, + workspaces: vec![ + SavedWorkspace { + name: "Workbench".into(), + colour: 0, + focused: 1, + layout: split( + SavedOrientation::Vertical, + 0.56, + SavedNode::Pane { id: 1 }, + split( + SavedOrientation::Horizontal, + 0.50, + SavedNode::Pane { id: 2 }, + SavedNode::Pane { id: 3 }, + ), + ), + directories: vec![pane(cwd, 1), pane(cwd, 2), pane(cwd, 3)], + }, + SavedWorkspace { + name: "Review".into(), + colour: 1, + focused: 4, + layout: split( + SavedOrientation::Vertical, + 0.50, + SavedNode::Pane { id: 4 }, + SavedNode::Pane { id: 5 }, + ), + directories: vec![pane(cwd, 4), pane(cwd, 5)], + }, + SavedWorkspace { + name: "Notes".into(), + colour: 2, + focused: 6, + layout: SavedNode::Pane { id: 6 }, + directories: vec![pane(cwd, 6)], + }, + ], + } +} + +fn write_snapshot(cwd: &Path) { + let path = crate::session::path().expect("session path"); + fs::create_dir_all(path.parent().expect("session parent")).expect("session directory"); + fs::write( + &path, + serde_json::to_vec(&snapshot(cwd)).expect("session json"), + ) + .expect("session file"); +} + +fn write_panes_snapshot(cwd: &Path) { + let mut scene = snapshot(cwd); + scene.workspaces[0].layout = SavedNode::Pane { id: 1 }; + scene.workspaces[0].focused = 1; + scene.workspaces[0].directories = vec![pane(cwd, 1)]; + let path = crate::session::path().expect("session path"); + fs::create_dir_all(path.parent().expect("session parent")).expect("session directory"); + fs::write(&path, serde_json::to_vec(&scene).expect("session json")).expect("session file"); +} + +fn set_shell_environment() { + std::env::set_var("ENV", "/work/among/.demo/env.sh"); +} + +fn write_appearance() { + let config = PathBuf::from(std::env::var_os("XDG_CONFIG_HOME").expect("owned display config")) + .join("among"); + fs::create_dir_all(&config).expect("preferences directory"); + fs::write( + config.join("terminal.json"), + br#"{"version":1,"text_background":"gray-on-black","ansi_palette":"tango"}"#, + ) + .expect("terminal appearance"); + let gtk = PathBuf::from(std::env::var_os("XDG_CONFIG_HOME").expect("owned display config")) + .join("gtk-4.0"); + fs::create_dir_all(>k).expect("GTK configuration directory"); + fs::write( + gtk.join("settings.ini"), + b"[Settings]\ngtk-monospace-font-name=Monospace 10\n", + ) + .expect("GTK font settings"); +} + +const OFFICIAL: (u64, &str, &str) = (1_431_055_733, "Among-Terminal", "among-plugins"); +const OFFICIAL_PUBLISHER: u64 = 339_567_100; + +fn described(source: Origin, plugins: &[(&str, &str, &str, &str)]) -> Inspection { + let specs: Vec<_> = plugins + .iter() + .map(|(id, name, version, _)| (*id, *name, *version, digest('b'))) + .collect(); + let specs: Vec<_> = specs + .iter() + .map(|(id, name, version, sum)| (*id, *name, *version, sum.as_str())) + .collect(); + let mut catalogue = document(&specs); + for (index, (_, _, _, description)) in plugins.iter().enumerate() { + let version = &mut catalogue["plugins"][index]["versions"][0]; + version["manifest"]["description"] = json!(description); + version["artifacts"][0]["size"] = json!(262_144); + } + Inspection::from_bytes(source, "a".repeat(40), catalogue.to_string().into_bytes()) + .expect("fixture catalogue") +} + +fn prepare_plugin_fixtures() { + let root = crate::plugin::inventory::root().expect("plugin inventory root"); + crate::test_isolation::assert_below_check_root(&root); + let clock = fixture_plugin( + &root, + Identity { + id: "clock", + name: "Clock", + description: "Local time in the header", + repository: OFFICIAL, + }, + "0.2.0", + ); + let status = fixture_plugin( + &root, + Identity { + id: "system-status", + name: "System status", + description: "CPU, memory and disk bars", + repository: OFFICIAL, + }, + "0.2.0", + ); + let published = |mut receipt| { + let mut source = source_receipt(&receipt); + source.publisher_id = OFFICIAL_PUBLISHER; + release_of(&mut receipt).source = Some(source); + receipt + }; + fs::write( + root.join("installed.json"), + json!({"version":1,"installations":[published(clock), published(status)]}).to_string(), + ) + .expect("installed fixtures"); + let sources = crate::plugin::install::registry::root().expect("plugin source root"); + let official = super::list::origin(OFFICIAL.0, OFFICIAL_PUBLISHER, OFFICIAL.1, OFFICIAL.2); + super::list::save_source( + &sources, + described( + official, + &[ + ("clock", "Clock", "0.2.0", "Local time in the header"), + ( + "system-status", + "System status", + "0.2.0", + "CPU, memory and disk bars", + ), + ( + "pane-pwd", + "Pane directory", + "0.2.0", + "Working directory per pane", + ), + ], + ), + ); + let third_party = super::list::origin(77, 34, "example", "among-plugins"); + super::list::save_source( + &sources, + described( + third_party, + &[("notes", "Notes", "0.4.0", "A small note pad")], + ), + ); +} + +fn focus_main(window: &impl IsA) -> String { + wait_for(|| window.as_ref().is_mapped(), Duration::from_secs(3)); + let name = format!("^{}$", window.as_ref().title().expect("window title")); + let ids = xdo(&[ + "search", + "--all", + "--onlyvisible", + "--pid", + &std::process::id().to_string(), + "--name", + &name, + ]); + assert_eq!(ids.lines().count(), 1, "exactly one visible owned window"); + let id = ids.lines().last().expect("window id").to_string(); + xdo(&["windowactivate", "--sync", &id]); + xdo(&["windowfocus", "--sync", &id]); + wait_for(|| window.as_ref().is_active(), Duration::from_secs(2)); + id +} + +/// Fill the owned display with the application, so a still or recording shows +/// the product rather than a desktop margin. +fn maximize(window: &impl IsA) { + window.as_ref().maximize(); + wait_for(|| window.as_ref().is_maximized(), Duration::from_secs(3)); +} + +/// Runs the application's main context while time passes. A plain thread +/// sleep would freeze VTE writes and the pulse animation that the recording +/// is meant to show. +fn pump_for(duration: Duration) { + let end = std::time::Instant::now() + duration; + while std::time::Instant::now() < end { + while glib::MainContext::default().pending() { + glib::MainContext::default().iteration(false); + } + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn capture_root(name: &str) { + settle(); + let path = output().join(format!("{name}.png")); + let status = Command::new("import") + .args(["-window", "root"]) + .arg(&path) + .status() + .expect("ImageMagick import"); + assert!(status.success(), "capture {name} failed"); + eprintln!("media still: {}", path.display()); +} + +/// The GNOME banner is drawn by the shell, not by a window we can address. +/// Check the known banner region before calling the bell successful, so a +/// suppressed banner cannot silently produce a clip without the notification. +fn banner_visible() -> bool { + let path = output().join("banner-check.png"); + let captured = Command::new("import") + .args(["-window", "root"]) + .arg(&path) + .status() + .is_ok_and(|status| status.success()); + if !captured { + let _ = fs::remove_file(&path); + return false; + } + let mean = Command::new("convert") + .arg(&path) + .args([ + "-crop", + "400x80+600+50", + "+repage", + "-format", + "%[fx:mean]", + "info:", + ]) + .output(); + let _ = fs::remove_file(&path); + mean.is_ok_and(|output| { + output.status.success() + && String::from_utf8_lossy(&output.stdout) + .trim() + .parse::() + .is_ok_and(|value| value > 0.2) + }) +} + +fn wait_for_banner() { + let deadline = std::time::Instant::now() + Duration::from_secs(6); + while std::time::Instant::now() < deadline { + if banner_visible() { + return; + } + pump_for(Duration::from_millis(200)); + } + panic!("desktop notification banner did not appear"); +} + +fn set_backdrop() { + let status = Command::new("xsetroot") + .args(["-solid", "#20262f"]) + .status() + .expect("xsetroot"); + assert!(status.success(), "xsetroot failed"); +} + +fn capture_window(name: &str, window: &impl IsA) { + settle(); + let id = focus(window); + let path = output().join(format!("{name}.png")); + let status = Command::new("import") + .args(["-screen", "-window", &id]) + .arg(&path) + .status() + .expect("ImageMagick import"); + assert!(status.success(), "capture {name} failed"); + eprintln!("media still: {}", path.display()); +} + +fn row_titled(preferences: &adw::PreferencesWindow, title: &str) -> adw::ActionRow { + wait_for( + || { + widgets(preferences.upcast_ref()) + .iter() + .any(|widget| widget.is::() && widget.is_mapped()) + }, + Duration::from_secs(3), + ); + widgets(preferences.upcast_ref()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.title() == title && row.is_mapped()) + .unwrap_or_else(|| panic!("no shown row titled {title}")) +} + +fn show_tab(preferences: &adw::PreferencesWindow, title: &str) { + let page = widgets(preferences.upcast_ref()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|page| page.title() == title) + .unwrap_or_else(|| panic!("no tab {title}")); + preferences.set_visible_page(&page); + wait_for(|| page.is_mapped(), Duration::from_secs(3)); +} + +fn choose(preferences: &adw::PreferencesWindow, name: &str, label: &str) { + let row = widgets(preferences.upcast_ref()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.widget_name() == name) + .unwrap_or_else(|| panic!("no dropdown named {name}")); + let model = row + .model() + .and_downcast::() + .expect("a string model"); + let position = (0..model.n_items()) + .find(|index| model.string(*index).as_deref() == Some(label)) + .unwrap_or_else(|| panic!("{name} has no entry {label}")); + row.set_selected(position); + assert_eq!(row.selected(), position); +} + +fn resize_preferences(preferences: &adw::PreferencesWindow, width: u32, height: u32) -> String { + let id = focus(preferences); + preferences.set_default_size(width as i32 + 10, height as i32 + 10); + xdo(&[ + "windowsize", + "--sync", + &id, + &(width + 10).to_string(), + &(height + 10).to_string(), + ]); + wait_for( + || { + preferences.width() >= width as i32 - 5 + && preferences.width() <= width as i32 + 10 + && preferences.height() >= height as i32 - 5 + && preferences.height() <= height as i32 + 10 + }, + Duration::from_secs(3), + ); + eprintln!( + "media preferences {}x{} requested {width}x{height}", + preferences.width(), + preferences.height() + ); + id +} + +fn back(preferences: &adw::PreferencesWindow) { + focus(preferences); + xdo(&["key", "--clearmodifiers", "Escape"]); + settle(); +} + +fn capture_preferences(ctx: &Window) { + open_preferences(ctx); + let preferences = gtk::Window::list_toplevels() + .into_iter() + .filter_map(|window| window.downcast::().ok()) + .find(|window| window.title().as_deref() == Some("Preferences")) + .expect("Preferences window"); + wait_for(|| preferences.is_mapped(), Duration::from_secs(3)); + settle(); + + resize_preferences(&preferences, 880, 640); + assert!(has_label(preferences.upcast_ref(), "Installed")); + assert!(has_label(preferences.upcast_ref(), "Available")); + assert!(has_label(preferences.upcast_ref(), "Pane directory")); + capture_window("plugins", &preferences); + + press(&named_button( + &row_titled(&preferences, "System status"), + "plugin-info", + )); + wait_for( + || has_label(preferences.upcast_ref(), "Can read"), + Duration::from_secs(3), + ); + resize_preferences(&preferences, 880, 720); + capture_window("plugin-info", &preferences); + back(&preferences); + + resize_preferences(&preferences, 880, 640); + let clock_row = row_titled(&preferences, "Clock"); + let switch = widgets(clock_row.upcast_ref()) + .into_iter() + .find_map(|widget| widget.downcast::().ok()) + .expect("Clock switch"); + focus(&preferences); + assert!(switch.is_sensitive() && switch.grab_focus()); + xdo(&["key", "--clearmodifiers", "space"]); + wait_for( + || preferences.visible_dialog().is_some(), + Duration::from_secs(3), + ); + let dialog = preferences.visible_dialog().expect("access review"); + assert!(has_label(dialog.upcast_ref(), "Review plugin access")); + resize_preferences(&preferences, 880, 720); + capture_window("plugin-access-review", &preferences); + press(&button(&dialog, "Cancel")); + settle(); + + resize_preferences(&preferences, 880, 900); + show_tab(&preferences, "Notifications"); + assert!(has_label(preferences.upcast_ref(), "Command")); + capture_window("notifications", &preferences); + + resize_preferences(&preferences, 880, 820); + show_tab(&preferences, "Keyboard"); + capture_window("keyboard", &preferences); + + resize_preferences(&preferences, 880, 420); + show_tab(&preferences, "Terminal"); + choose(&preferences, "terminal-text-background", "Gray on black"); + choose(&preferences, "terminal-ansi-palette", "Tango"); + capture_window("terminal", &preferences); + + resize_preferences(&preferences, 880, 640); + show_tab(&preferences, "About"); + capture_window("about", &preferences); + + preferences.destroy(); +} + +fn terminal(ctx: &Window, id: u64) -> vte::Terminal { + ctx.state + .borrow() + .pane(PaneId(id)) + .expect("scene pane") + .terminal() + .clone() +} + +fn feed(ctx: &Window, id: u64, command: &str) { + let mut bytes = command.as_bytes().to_vec(); + bytes.push(b'\r'); + terminal(ctx, id).feed_child(&bytes); +} + +fn wait_for_text(ctx: &Window, id: u64, needle: &str) { + wait_for( + || { + terminal(ctx, id) + .text_format(vte::Format::Text) + .is_some_and(|text| text.contains(needle)) + }, + Duration::from_secs(10), + ); +} + +/// Stops the PTY echoing the command line and clears the first prompt, so a +/// still shows the command's output instead of the script invocation. +fn quiet(ctx: &Window, id: u64) { + wait_for( + || { + terminal(ctx, id) + .text_format(vte::Format::Text) + .is_some_and(|text| text.contains('$')) + }, + Duration::from_secs(10), + ); + feed(ctx, id, "stty -echo; printf '\\033[2J\\033[H'"); +} + +fn quiet_all(ctx: &Window) { + for id in 1..=6 { + quiet(ctx, id); + } +} + +fn fill_workbench(ctx: &Window) { + feed(ctx, 1, "bash .demo/diff.sh"); + feed(ctx, 2, "bash .demo/checklist.sh"); + feed(ctx, 3, "bash .demo/changes.sh"); + wait_for_text(ctx, 1, "needs_attention"); + wait_for_text(ctx, 2, "integration suite"); + wait_for_text(ctx, 3, "src/review.rs"); +} + +fn fill_other_workspaces(ctx: &Window) { + feed(ctx, 4, "bash .demo/make.sh"); + feed(ctx, 5, "bash .demo/status.sh"); + feed(ctx, 6, "bash .demo/notes.sh"); +} + +fn active_panes(ctx: &Window) -> Vec { + ctx.state.borrow().workspaces.active().panes() +} + +fn wait_for_panes(ctx: &Window, count: usize) { + wait_for(|| active_panes(ctx).len() == count, Duration::from_secs(5)); +} + +fn label_pane(ctx: &Window, id: u64) { + quiet(ctx, id); + feed(ctx, id, &format!("bash .demo/pane.sh {id}")); + wait_for_text(ctx, id, &format!("pane {id}")); +} + +fn split_pane(ctx: &Window) -> u64 { + let before = active_panes(ctx).len(); + xdo(&["key", "--clearmodifiers", "ctrl+shift+n"]); + wait_for_panes(ctx, before + 1); + let id = ctx.state.borrow().workspaces.active().focused.0; + label_pane(ctx, id); + id +} + +fn drag_divider(ctx: &Window) { + let id = focus_main(&ctx.window); + let (ox, oy) = ctx.window.surface_transform(); + let paned = ctx + .paneds + .borrow() + .iter() + .find(|split| split.path.is_empty()) + .map(|split| split.widget.clone()) + .expect("root divider"); + let bounds = paned.compute_bounds(&ctx.window).expect("divider bounds"); + let (x, y, x2, y2) = match paned.orientation() { + gtk::Orientation::Horizontal => { + let x = f64::from(bounds.x()) + f64::from(paned.position()); + let y = f64::from(bounds.y() + bounds.height() / 2.0); + (x, y, x + 120.0, y) + } + _ => { + let x = f64::from(bounds.x() + bounds.width() / 2.0); + let y = f64::from(bounds.y()) + f64::from(paned.position()); + (x, y, x, y + 100.0) + } + }; + let point = |x: f64, y: f64| (format!("{:.0}", x + ox), format!("{:.0}", y + oy)); + let (x, y) = point(x, y); + let (x2, y2) = point(x2, y2); + xdo(&["mousemove", "--window", &id, &x, &y]); + pump_for(Duration::from_millis(80)); + xdo(&["mousedown", "1"]); + pump_for(Duration::from_millis(80)); + xdo(&["mousemove", "--sync", "--window", &id, &x2, &y2]); + pump_for(Duration::from_millis(200)); + xdo(&["mouseup", "1"]); + pump_for(Duration::from_millis(250)); +} + +fn pane_header(ctx: &Window, id: u64) -> (f32, f32, f32, f32) { + let widget = ctx + .state + .borrow() + .pane(PaneId(id)) + .expect("scene pane") + .widget() + .expect("pane widget"); + let header = widgets(widget.upcast_ref()) + .into_iter() + .find(|widget| widget.has_css_class("pane-header")) + .expect("pane header"); + let bounds = header.compute_bounds(&ctx.window).expect("header bounds"); + (bounds.x(), bounds.y(), bounds.width(), bounds.height()) +} + +fn drag_pane_over(ctx: &Window, source: u64, target: u64) { + let id = focus_main(&ctx.window); + let (ox, oy) = ctx.window.surface_transform(); + let (sx, sy, sw, sh) = pane_header(ctx, source); + let (tx, ty, _tw, th) = pane_header(ctx, target); + let start = (f64::from(sx + sw / 2.0) + ox, f64::from(sy + sh / 2.0) + oy); + let target = (f64::from(tx + 8.0) + ox, f64::from(ty + th / 2.0) + oy); + let point = |x: f64, y: f64| (format!("{x:.0}"), format!("{y:.0}")); + let (x, y) = point(start.0, start.1); + xdo(&["mousemove", "--window", &id, &x, &y]); + pump_for(Duration::from_millis(80)); + xdo(&["mousedown", "1"]); + pump_for(Duration::from_millis(80)); + for offset in [5.0, 12.0, 30.0] { + let (x, y) = point(start.0 + offset, start.1); + xdo(&["mousemove", "--sync", "--window", &id, &x, &y]); + pump_for(Duration::from_millis(60)); + } + wait_for( + || ctx.state.borrow().pane_drag.is_some(), + Duration::from_secs(2), + ); + let (x, y) = point(target.0, target.1); + xdo(&["mousemove", "--sync", "--window", &id, &x, &y]); + pump_for(Duration::from_millis(250)); + xdo(&["mouseup", "1"]); + pump_for(Duration::from_millis(500)); +} + +fn workspace_row_point(ctx: &Window, index: i32) -> (String, String) { + let row = ctx + .workspace_list + .row_at_index(index) + .expect("workspace row"); + let bounds = row.compute_bounds(&ctx.window).expect("row bounds"); + let (x, y) = ctx.window.surface_transform(); + ( + format!( + "{:.0}", + x + f64::from(bounds.x()) + f64::from(bounds.width()) * 0.4 + ), + format!( + "{:.0}", + y + f64::from(bounds.y()) + f64::from(bounds.height()) * 0.5 + ), + ) +} + +fn create_named_workspace(ctx: &Window, name: &str) { + let before = ctx.state.borrow().workspaces.len(); + xdo(&["key", "--clearmodifiers", "ctrl+shift+t"]); + wait_for( + || ctx.state.borrow().workspaces.len() == before + 1, + Duration::from_secs(5), + ); + let index = ctx.state.borrow().workspaces.active_index() as i32; + let id = focus_main(&ctx.window); + let (x, y) = workspace_row_point(ctx, index); + xdo(&["mousemove", "--window", &id, &x, &y]); + pump_for(Duration::from_millis(80)); + xdo(&["click", "--repeat", "2", "--delay", "80", "1"]); + wait_for( + || { + ctx.workspace_list + .row_at_index(index) + .and_then(|row| row.child()) + .and_then(|child| find_name_widget(&child)) + .is_some_and(|widget| widget.is::() && widget.width() > 0) + }, + Duration::from_secs(3), + ); + xdo(&["type", "--clearmodifiers", "--delay", "80", name]); + xdo(&["key", "--clearmodifiers", "Return"]); + wait_for( + || { + ctx.state + .borrow() + .workspaces + .workspaces() + .get(index as usize) + .is_some_and(|workspace| workspace.name == name) + }, + Duration::from_secs(3), + ); + // Commit the in-place editor and leave a clean row for the close-up. + xdo(&["mousemove", "--window", &id, "800", "500"]); + xdo(&["click", "1"]); + wait_for( + || { + ctx.workspace_list + .row_at_index(index) + .and_then(|row| row.child()) + .and_then(|child| find_name_widget(&child)) + .is_some_and(|widget| !widget.is::()) + }, + Duration::from_secs(3), + ); +} + +#[test] +#[ignore = "requires the owned media display, xdotool and ImageMagick"] +fn capture_stills() { + let home = PathBuf::from(std::env::var_os("HOME").expect("owned display HOME")); + let work = project(&home); + set_shell_environment(); + write_snapshot(&work); + write_appearance(); + prepare_plugin_fixtures(); + install_application_identity("com.github.among-terminal"); + let _shell = shell(); + let _service = crate::app::desktop_notification_tests::Server::new(); + std::env::set_var("AMONG_COLOR_SCHEME", "dark"); + + let app = application("com.github.among-terminal.doc-media-stills"); + let ctx = build_with_writer(&app, None, crate::session::Writer::new).expect("application"); + set_backdrop(); + wait_for( + || ctx.window.visible_dialog().is_some(), + Duration::from_secs(5), + ); + maximize(&ctx.window); + settle(); + capture_root("session-restore"); + let dialog = ctx.window.visible_dialog().expect("restore prompt"); + press(&button(&dialog, "Restore")); + wait_for(|| ctx.state.borrow().session_ready, Duration::from_secs(5)); + maximize(&ctx.window); + quiet_all(&ctx); + fill_workbench(&ctx); + fill_other_workspaces(&ctx); + settle(); + capture_root("main-window"); + capture_root("plugin-off"); + capture_preferences(&ctx); + ctx.state + .borrow_mut() + .plugins + .register_fixture(crate::plugin::host::PluginSpec { + name: "github:12/demo-status".into(), + command: fixture("demo-status"), + enabled: true, + }); + pump_for(Duration::from_secs(1)); + wait_for( + || has_label(ctx.app_header.upcast_ref(), "CPU 18%"), + Duration::from_secs(10), + ); + capture_root("plugin-on"); + ctx.state + .borrow_mut() + .plugins + .disable("github:12/demo-status"); + wait_for( + || !has_label(ctx.app_header.upcast_ref(), "CPU 18%"), + Duration::from_secs(5), + ); + + xdo(&["key", "--clearmodifiers", "ctrl+shift+x"]); + settle(); + capture_root("expanded-pane"); + xdo(&["key", "--clearmodifiers", "ctrl+shift+x"]); + settle(); + xdo(&["key", "--clearmodifiers", "alt+2"]); + settle(); + capture_root("workspaces"); + ctx.window.destroy(); +} + +fn set_banners(show: bool) { + let status = Command::new("gsettings") + .args([ + "set", + "org.gnome.desktop.notifications", + "show-banners", + if show { "true" } else { "false" }, + ]) + .status() + .expect("gsettings"); + assert!(status.success(), "gsettings show-banners failed"); +} + +fn enable_banners() { + set_banners(true); +} + +fn install_application_identity(id: &str) { + let data = PathBuf::from(std::env::var_os("XDG_DATA_HOME").expect("owned display data")); + let applications = data.join("applications"); + fs::create_dir_all(&applications).expect("application directory"); + fs::write( + applications.join(format!("{id}.desktop")), + "[Desktop Entry]\nType=Application\nName=Among Terminal\n\ + Exec=/bin/true\nIcon=com.github.among-terminal\nDBusActivatable=true\n", + ) + .expect("desktop identity"); + let icons = data.join("icons/hicolor/scalable/apps"); + fs::create_dir_all(&icons).expect("icon directory"); + fs::write( + icons.join("com.github.among-terminal.svg"), + include_bytes!("../../../../data/com.github.among-terminal.svg"), + ) + .expect("icon"); +} + +fn search_windows(name: &str) -> Vec { + let output = Command::new("xdotool") + .args(["search", "--all", "--name", name]) + .output() + .expect("xdotool search"); + if !output.status.success() { + return Vec::new(); + } + String::from_utf8_lossy(&output.stdout) + .lines() + .map(str::to_string) + .collect() +} + +/// A 1x1 client that takes keyboard focus without covering the maximized +/// application: a window manager has no "focus the desktop" request, and the +/// desktop notification policy is about the application being in background. +fn focus_neutral_window() -> std::process::Child { + let child = Command::new("xmessage") + .args([ + "-name", + "among-media-neutral", + "-geometry", + "10x10+1590+990", + "-borderwidth", + "0", + "-bg", + "#20262f", + "-fg", + "#20262f", + "", + ]) + .spawn() + .expect("neutral window"); + wait_for( + || !search_windows("among-media-neutral").is_empty(), + Duration::from_secs(3), + ); + let ids = search_windows("among-media-neutral"); + let id = ids.last().expect("neutral window id"); + xdo(&["windowactivate", "--sync", id]); + xdo(&["windowfocus", "--sync", id]); + child +} + +fn unique_application(id: &str) -> adw::Application { + let config = std::env::var_os("XDG_CONFIG_HOME").expect("owned display config"); + crate::test_isolation::assert_below_check_root(std::path::Path::new(&config)); + std::env::set_var("SHELL", "/bin/sh"); + let app = adw::Application::builder() + .application_id(id) + .flags(gio::ApplicationFlags::empty()) + .build(); + app.register(None::<&gio::Cancellable>) + .expect("application"); + app +} + +fn start_recording(path: &Path) -> std::process::Child { + let display = std::env::var("DISPLAY").expect("display"); + let input = format!("{display}.0+0,0"); + let log = std::fs::File::create(path.with_extension("ffmpeg.log")).expect("ffmpeg log"); + Command::new("ffmpeg") + .args([ + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "x11grab", + "-draw_mouse", + "1", + "-video_size", + "1600x1000", + "-framerate", + "30", + "-i", + &input, + "-c:v", + "libx264", + "-preset", + "medium", + "-crf", + "20", + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + ]) + .arg(path) + .stdout(std::process::Stdio::null()) + .stderr(log) + .spawn() + .expect("ffmpeg recording") +} + +fn stop_recording(mut child: std::process::Child) { + unsafe { + libc::kill(child.id() as i32, libc::SIGINT); + } + let status = child.wait().expect("ffmpeg wait"); + assert!( + status.success() || status.code() == Some(255), + "ffmpeg recording failed: {status}" + ); +} + +#[test] +#[ignore = "requires the owned media display, xdotool and ffmpeg"] +fn capture_panes() { + let home = PathBuf::from(std::env::var_os("HOME").expect("owned display HOME")); + let work = project(&home); + set_shell_environment(); + write_panes_snapshot(&work); + write_appearance(); + let _shell = shell(); + std::env::set_var("AMONG_COLOR_SCHEME", "dark"); + + let app = application("com.github.among-terminal.doc-media-panes"); + let ctx = build_with_writer(&app, None, crate::session::Writer::new).expect("application"); + set_backdrop(); + wait_for( + || ctx.window.visible_dialog().is_some(), + Duration::from_secs(5), + ); + let dialog = ctx.window.visible_dialog().expect("restore prompt"); + press(&button(&dialog, "Restore")); + wait_for(|| ctx.state.borrow().session_ready, Duration::from_secs(5)); + maximize(&ctx.window); + quiet(&ctx, 1); + feed(&ctx, 1, "bash .demo/pane.sh 1"); + wait_for_text(&ctx, 1, "pane 1"); + + for id in 4..=6 { + feed(&ctx, id, &format!("bash .demo/pane.sh {id}")); + } + pump_for(Duration::from_millis(500)); + + let recording = output().join("panes.mp4"); + let recorder = start_recording(&recording); + pump_for(Duration::from_millis(900)); + + let _two = split_pane(&ctx); + pump_for(Duration::from_millis(500)); + drag_divider(&ctx); + pump_for(Duration::from_millis(500)); + let _three = split_pane(&ctx); + pump_for(Duration::from_millis(500)); + drag_divider(&ctx); + pump_for(Duration::from_millis(500)); + let _four = split_pane(&ctx); + pump_for(Duration::from_millis(500)); + let _five = split_pane(&ctx); + pump_for(Duration::from_millis(500)); + let before = active_panes(&ctx); + drag_pane_over(&ctx, before[1].0, before[0].0); + wait_for(|| active_panes(&ctx) != before, Duration::from_secs(5)); + pump_for(Duration::from_millis(900)); + + xdo(&["key", "--clearmodifiers", "alt+2"]); + pump_for(Duration::from_millis(1800)); + xdo(&["key", "--clearmodifiers", "alt+3"]); + pump_for(Duration::from_millis(1800)); + xdo(&["key", "--clearmodifiers", "alt+1"]); + pump_for(Duration::from_millis(1200)); + + assert_eq!(active_panes(&ctx).len(), 5); + create_named_workspace(&ctx, "Scratch"); + pump_for(Duration::from_millis(1800)); + stop_recording(recorder); + ctx.window.destroy(); +} + +#[test] +#[ignore = "requires the owned GNOME media display, xdotool, ffmpeg and ImageMagick"] +fn capture_notification() { + let home = PathBuf::from(std::env::var_os("HOME").expect("owned display HOME")); + let work = project(&home); + set_shell_environment(); + write_snapshot(&work); + write_appearance(); + install_application_identity("com.github.among-terminal"); + std::env::set_var("AMONG_COLOR_SCHEME", "dark"); + + let app = unique_application("com.github.among-terminal"); + let ctx = build_with_writer(&app, None, crate::session::Writer::new).expect("application"); + wait_for( + || ctx.window.visible_dialog().is_some(), + Duration::from_secs(5), + ); + let dialog = ctx.window.visible_dialog().expect("restore prompt"); + press(&button(&dialog, "Restore")); + wait_for(|| ctx.state.borrow().session_ready, Duration::from_secs(5)); + wait_for(|| ctx.window.is_maximized(), Duration::from_secs(3)); + + // GNOME startup notices are kept out of the scene: banners are disabled + // while the shell's own notices are created, then enabled for the bell. + set_banners(false); + pump_for(Duration::from_secs(5)); + enable_banners(); + pump_for(Duration::from_millis(500)); + + xdo(&["key", "--clearmodifiers", "alt+2"]); + settle(); + quiet(&ctx, 4); + quiet(&ctx, 5); + feed(&ctx, 4, "bash .demo/make.sh"); + wait_for_text(&ctx, 4, "712 passed"); + feed(&ctx, 5, "bash .demo/status.sh"); + wait_for_text(&ctx, 5, "review.rs"); + // Leave Review so the banner click has a visible result: the bell belongs + // to the status terminal in Review, while Workbench is on screen. + xdo(&["key", "--clearmodifiers", "alt+1"]); + settle(); + assert_eq!(ctx.state.borrow().workspaces.active_index(), 0); + + let recording = output().join("notification-return.mp4"); + let recorder = start_recording(&recording); + // Leave a beat of Workbench before the ring; the banner must not be the + // first frame the viewer sees. + pump_for(Duration::from_millis(1200)); + let mut neutral = focus_neutral_window(); + wait_for(|| !ctx.window.is_active(), Duration::from_secs(2)); + terminal(&ctx, 5).feed_child(b"printf '\\a'\n"); + wait_for( + || { + ctx.state + .borrow() + .bells + .as_ref() + .is_some_and(|bells| bells.attention(5).unread) + }, + Duration::from_secs(3), + ); + wait_for_banner(); + capture_root("notification-return-poster"); + + pump_for(Duration::from_millis(2200)); + // The pointer gesture is visible in the recording. GNOME's X11 stage does + // not deliver synthetic clicks to the banner in this owned display, so the + // same action the banner's default target names is invoked next. The + // payload and activation contract are checked separately by + // check-desktop-notifications. + xdo(&["mousemove", "--sync", "716", "88"]); + pump_for(Duration::from_millis(200)); + xdo(&["click", "1"]); + let target = ctx + .state + .borrow() + .bells + .as_ref() + .expect("bell backend") + .desktop_target(5) + .expect("notification target"); + ctx.window + .application() + .expect("application") + .activate_action("focus-pane", Some(&target)); + pump_for(Duration::from_millis(2200)); + assert_eq!(ctx.state.borrow().workspaces.active_index(), 1); + assert!(ctx.window.is_active()); + stop_recording(recorder); + let _ = neutral.kill(); + let _ = neutral.wait(); + ctx.window.destroy(); +} diff --git a/tools/among-tools/README.md b/tools/among-tools/README.md index a05fe5a7..f92bcb84 100644 --- a/tools/among-tools/README.md +++ b/tools/among-tools/README.md @@ -371,6 +371,23 @@ its resulting association. Positive end-to-end packaging of a complete audited Snap remains pending. See [source delivery](../../docs/source-delivery.md) for scope and prerequisites; no command here establishes legal sign-off or publication. +## Documentation media + +`media all APP_TEST NEW_OUTPUT` runs the three documentation scenarios in their +own owned displays, prepares the published PNG/MP4 files and writes +`media.json`. `media stills`, `media panes` and `media notification` run one +scenario each; `media verify OUTPUT` checks the manifest, hashes, image +dimensions and the video streams. The application scene lives in the test +binary as `app::plugin_tests::installation::doc_media`; the tool starts the +display, so the command is not run under `ci-x11` or `isolated-x11`. + +The tool needs the pinned display image from +`containers/Dockerfile.display`, which carries Xvfb, Xephyr, GNOME Shell, +ImageMagick, ffmpeg, xsetroot and the `/work` fixture directory. See +[docs/media.md](../../docs/media.md) for the full command and the published +sizes. Missing display tools, a missing scenario output or a scene failure are +errors; nothing is skipped. + ## Stable promotion admission (partial port) `check-promotion-admission RECORD_JSON GATES_JSON ARTIFACT_DIRECTORY --approved` diff --git a/tools/among-tools/containers/Dockerfile.display b/tools/among-tools/containers/Dockerfile.display index 89ad52db..136a09cf 100644 --- a/tools/among-tools/containers/Dockerfile.display +++ b/tools/among-tools/containers/Dockerfile.display @@ -2,7 +2,7 @@ FROM ubuntu@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530e # separate synthetic desktop; never mount the owner's display or D-Bus sockets. RUN apt-get update && apt-get install -y --no-install-recommends \ - xvfb xserver-xephyr openbox gnome-shell dbus-x11 xdotool x11-utils imagemagick \ + xvfb xserver-xephyr x11-xserver-utils openbox gnome-shell dbus-x11 xdotool x11-utils imagemagick ffmpeg \ ca-certificates gcc libc6-dev pkg-config desktop-file-utils appstream libgtk-4-bin librsvg2-common \ libgtk-4-dev libadwaita-1-dev libvte-2.91-gtk4-dev \ && rm -rf /var/lib/apt/lists/* @@ -10,3 +10,15 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ # keep runner-only prerequisites separate from the reusable graphical layer. RUN apt-get update && apt-get install -y --no-install-recommends git squashfs-tools jq \ && rm -rf /var/lib/apt/lists/* + +# GitHub-hosted runners use uid 1001 for the job user. The media scene starts +# its own session bus, and dbus-daemon refuses to start for a uid without a +# passwd entry, so give that uid a name inside the disposable image. +RUN groupadd --gid 1001 runner \ + && useradd --uid 1001 --gid 1001 --no-create-home --shell /usr/sbin/nologin runner + +# The documentation media scene lives at a path that can appear in a +# notification without exposing the private owned HOME. Any runtime uid may +# create its own project below /work; the sticky bit keeps the directory +# shared without letting one run remove another run's entries. +RUN install -d -m 1777 /work diff --git a/tools/among-tools/src/display.rs b/tools/among-tools/src/display.rs index 4a3da3c2..f5754a99 100644 --- a/tools/among-tools/src/display.rs +++ b/tools/among-tools/src/display.rs @@ -15,6 +15,8 @@ pub enum Mode { VideoGnome, Guest, NestedGnome, + Media, + MediaGnome, } pub fn launch_environment(caller: &BTreeMap) -> BTreeMap { @@ -28,6 +30,7 @@ pub fn launch_environment(caller: &BTreeMap) -> BTreeMap Result<(OwnedProcess, String)> { - start_server_profile(program, nested, env, base, label, false) + start_server_profile(program, nested, env, base, label, "1920x1200") } fn start_server_profile( @@ -170,15 +173,16 @@ fn start_server_profile( env: &BTreeMap, base: &Path, label: &str, - video: bool, + screen: &str, ) -> Result<(OwnedProcess, String)> { let log = File::create(base.join(format!("{label}.log")))?; + let root_screen = format!("{screen}x24"); let args = if nested { vec![ "-displayfd", "1", "-screen", - if video { "1600x1200" } else { "1920x1200" }, + screen, "-ac", "-nolisten", "tcp", @@ -190,11 +194,7 @@ fn start_server_profile( "1", "-screen", "0", - if video { - "1600x1200x24" - } else { - "1920x1200x24" - }, + &root_screen, "-nolisten", "tcp", "-ac", @@ -286,8 +286,27 @@ pub fn run( } let base = private_directory(scratch)?; eprintln!("Owned display evidence: {}", base.display()); - let mut env = environment(scratch, &base, matches!(mode, Mode::Ci | Mode::Video))?; - let nested = matches!(mode, Mode::NestedGnome | Mode::VideoGnome); + let media = matches!(mode, Mode::Media | Mode::MediaGnome); + let video = matches!(mode, Mode::Video | Mode::VideoGnome); + let mut env = environment( + scratch, + &base, + matches!( + mode, + Mode::Ci | Mode::Video | Mode::Media | Mode::MediaGnome + ), + )?; + let nested = matches!( + mode, + Mode::NestedGnome | Mode::VideoGnome | Mode::MediaGnome + ); + let screen = if media { + "1600x1000" + } else if video { + "1600x1200" + } else { + "1920x1200" + }; let mut parent = None; let (mut server, display) = if nested { // create a second owned server as Xephyr's parent, not the personal screen. @@ -301,7 +320,7 @@ pub fn run( &env, &base, "xephyr", - matches!(mode, Mode::VideoGnome), + screen, )? } else { start_server_profile( @@ -310,7 +329,7 @@ pub fn run( &env, &base, "xvfb", - matches!(mode, Mode::Video), + screen, )? }; env.insert("DISPLAY".into(), display.into()); @@ -363,14 +382,75 @@ pub fn run( env.insert("DBUS_SYSTEM_BUS_ADDRESS".into(), ready.into()); system_bus = Some(bus); } - let mut manager = if nested { - OwnedProcess::spawn( - Path::new("/usr/bin/dbus-run-session"), - &["--", "gnome-shell", "--x11", "--sm-disable"], + let mut media_session_bus = None; + if matches!(mode, Mode::Media | Mode::MediaGnome) { + let bus_log = File::create(base.join("session-bus.log"))?; + let address = format!("unix:path={}", base.join("session-bus").display()); + let mut bus = OwnedProcess::spawn_capture( + Path::new("/usr/bin/dbus-daemon"), + &[ + "--session", + "--nofork", + "--print-address=1", + "--address", + &address, + ], &env, &base, - &manager_log, - )? + &bus_log, + )?; + let mut pipe = bus.take_stdout()?; + let flags = OFlag::from_bits_truncate(fcntl(&pipe, FcntlArg::F_GETFL)?); + fcntl(&pipe, FcntlArg::F_SETFL(flags | OFlag::O_NONBLOCK))?; + let ready = read_line(&mut pipe, Duration::from_secs(10), 4096)?; + if !ready.starts_with(&address) || !bus.is_running()? { + return Err("owned session bus failed readiness".into()); + } + env.insert("DBUS_SESSION_BUS_ADDRESS".into(), ready.into()); + if matches!(mode, Mode::MediaGnome) { + env.insert("GSETTINGS_BACKEND".into(), "dconf".into()); + let share = std::env::current_dir()?.join("data"); + let paths = std::env::var_os("XDG_DATA_DIRS") + .and_then(|value| value.into_string().ok()) + .unwrap_or_else(|| "/usr/local/share:/usr/share".into()); + env.insert( + "XDG_DATA_DIRS".into(), + format!("{}:{paths}", share.display()).into(), + ); + for (schema, key, value) in [ + ("org.gnome.desktop.notifications", "show-banners", "false"), + ("org.gnome.desktop.interface", "color-scheme", "prefer-dark"), + ] { + let status = std::process::Command::new("/usr/bin/gsettings") + .env_clear() + .envs(&env) + .args(["set", schema, key, value]) + .status()?; + if !status.success() { + return Err(format!("gsettings {schema} {key} {value} failed").into()); + } + } + } + media_session_bus = Some(bus); + } + let mut manager = if nested { + if matches!(mode, Mode::MediaGnome) { + OwnedProcess::spawn( + Path::new("/usr/bin/gnome-shell"), + &["--x11", "--sm-disable"], + &env, + &base, + &manager_log, + )? + } else { + OwnedProcess::spawn( + Path::new("/usr/bin/dbus-run-session"), + &["--", "gnome-shell", "--x11", "--sm-disable"], + &env, + &base, + &manager_log, + )? + } } else { let configuration = base.join("openbox.xml"); fs::write( @@ -411,18 +491,31 @@ pub fn run( return Err("GNOME overview dismissal failed".into()); } let command_log = File::create(base.join("command.log"))?; - let mut argv = vec!["--"]; - argv.extend(args.iter().map(String::as_str)); - let mut command = OwnedProcess::spawn( - Path::new("/usr/bin/dbus-run-session"), - &argv, - &env, - &std::env::current_dir()?, - &command_log, - )?; + let mut command = if matches!(mode, Mode::Media | Mode::MediaGnome) { + OwnedProcess::spawn( + Path::new(&args[0]), + &args[1..].iter().map(String::as_str).collect::>(), + &env, + &std::env::current_dir()?, + &command_log, + )? + } else { + let mut argv = vec!["--"]; + argv.extend(args.iter().map(String::as_str)); + OwnedProcess::spawn( + Path::new("/usr/bin/dbus-run-session"), + &argv, + &env, + &std::env::current_dir()?, + &command_log, + )? + }; let status = command.wait(timeout)?; std::io::stdout().write_all(&fs::read(base.join("command.log"))?)?; manager.cleanup()?; + if let Some(mut bus) = media_session_bus { + bus.cleanup()?; + } if let Some(mut bus) = system_bus { bus.cleanup()?; } diff --git a/tools/among-tools/src/ignored_tests.rs b/tools/among-tools/src/ignored_tests.rs index 52cb7a26..7a3b1b62 100644 --- a/tools/among-tools/src/ignored_tests.rs +++ b/tools/among-tools/src/ignored_tests.rs @@ -64,6 +64,10 @@ pub fn names(listing: &str) -> Result> { eprintln!("{name} is excluded from standalone graphics; this is not an acceptance pass; its owning parent regression supplies coverage"); continue; } + if name.starts_with("app::plugin_tests::installation::doc_media::") { + eprintln!("{name} requires among-tools media and its own media display; exclusion from standalone graphics is not an acceptance pass"); + continue; + } if name == GENERAL_AUDIO_UI_TEST { // The test refuses to run unless it is inside a device-free // Docker container with its own private PulseAudio null sink, @@ -189,6 +193,18 @@ mod tests { // A CI runner has real audio devices and no private null sink, so the // audio acceptance test can only fail its own precondition there; the // standalone graphics run must leave it to its container. + #[test] + fn media_scenarios_are_not_standalone_graphics() -> Result<()> { + let listing = "app::plugin_tests::installation::doc_media::capture_stills: test\n\ + app::plugin_tests::installation::doc_media::capture_notification: test\n\ + app::notification_ui_tests::general_unread_marks_survive_rebuild: test\n"; + assert_eq!( + names(listing)?, + ["app::notification_ui_tests::general_unread_marks_survive_rebuild"] + ); + Ok(()) + } + #[test] fn container_only_audio_acceptance_is_not_run_as_standalone_graphics() -> Result<()> { let listing = format!( diff --git a/tools/among-tools/src/lib.rs b/tools/among-tools/src/lib.rs index b483eee2..f2d7321f 100644 --- a/tools/among-tools/src/lib.rs +++ b/tools/among-tools/src/lib.rs @@ -31,6 +31,7 @@ pub mod live_focus; pub mod live_resize; pub mod live_status; mod managed_fixture; +pub mod media; pub mod menu_check; pub mod menu_geometry; pub mod menu_launch; diff --git a/tools/among-tools/src/main.rs b/tools/among-tools/src/main.rs index cc0babe3..56d42bdb 100644 --- a/tools/among-tools/src/main.rs +++ b/tools/among-tools/src/main.rs @@ -14,6 +14,13 @@ Usage: among-tools isolated-x11-video [args...] among-tools isolated-x11 [args...] among-tools vm-x11 [args...] + among-tools media-x11 [args...] + among-tools media-gnome [args...] + among-tools media all + among-tools media stills + among-tools media notification + among-tools media panes + among-tools media verify among-tools run-ignored-tests among-tools check-installer-enospc-from-cargo among-tools check-resource-measurements @@ -380,10 +387,41 @@ fn run(args: &[String]) -> Result { )? ); } + [command, action, directory] if command == "media" && action == "verify" => { + among_tools::media::verify(Path::new(directory))?; + } + [command, action, app_test, output] if command == "media" => { + let app_test = Path::new(app_test); + let output = Path::new(output); + match action.as_str() { + "stills" => { + among_tools::media::capture_stills(app_test, output)?; + } + "notification" => { + among_tools::media::capture_notification(app_test, output)?; + } + "panes" => { + among_tools::media::capture_panes(app_test, output)?; + } + "all" => { + among_tools::media::all(app_test, output)?; + } + _ => return Err("media action must be stills, notification, panes or all".into()), + } + } + [command, _] if command == "media" => { + return Err("media needs an action: stills, panes, notification, all or verify".into()); + } [command, rest @ ..] if matches!( command.as_str(), - "ci-x11" | "ci-x11-video" | "isolated-x11" | "isolated-x11-video" | "vm-x11" + "ci-x11" + | "ci-x11-video" + | "isolated-x11" + | "isolated-x11-video" + | "vm-x11" + | "media-x11" + | "media-gnome" ) => { let mode = match command.as_str() { @@ -391,6 +429,8 @@ fn run(args: &[String]) -> Result { "ci-x11-video" => display::Mode::Video, "isolated-x11-video" => display::Mode::VideoGnome, "vm-x11" => display::Mode::Guest, + "media-x11" => display::Mode::Media, + "media-gnome" => display::Mode::MediaGnome, _ => display::Mode::NestedGnome, }; let status = display::run( diff --git a/tools/among-tools/src/media.rs b/tools/among-tools/src/media.rs new file mode 100644 index 00000000..1d41ceeb --- /dev/null +++ b/tools/among-tools/src/media.rs @@ -0,0 +1,510 @@ +//! Reproducible documentation media: run one scene in an owned display and +//! prepare the files the site publishes. +//! +//! The scene itself lives in the application test binary +//! (`app::plugin_tests::installation::doc_media`), because only that process +//! can build the real workspaces, panes and Preferences window. This module +//! owns the display, the output contract and the image/video preparation. + +use crate::{display, preferences_screenshots::png_size, scratch, storage, Result}; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::Duration; + +pub const STILLS_TEST: &str = "app::plugin_tests::installation::doc_media::capture_stills"; +pub const NOTIFICATION_TEST: &str = + "app::plugin_tests::installation::doc_media::capture_notification"; +pub const PANES_TEST: &str = "app::plugin_tests::installation::doc_media::capture_panes"; + +const WIDE: u32 = 1600; +const WIDE_HEIGHT: u32 = 1000; +const NARROW: u32 = 880; +const FRAME: u32 = 5; +const MARGIN: u32 = 1; + +const WIDE_STILLS: [&str; 5] = [ + "main-window", + "expanded-pane", + "workspaces", + "plugin-off", + "plugin-on", +]; +const NARROW_STILLS: [&str; 7] = [ + "plugins", + "plugin-info", + "plugin-access-review", + "notifications", + "keyboard", + "terminal", + "about", +]; + +pub fn all(app_test: &Path, output: &Path) -> Result { + let stills = capture_stills(app_test, output)?; + let panes = capture_panes(app_test, output)?; + let notification = capture_notification(app_test, output)?; + debug_assert_eq!(stills, panes); + debug_assert_eq!(stills, notification); + Ok(stills) +} + +pub fn capture_stills(app_test: &Path, output: &Path) -> Result { + let raw = prepare_output(output, "raw/stills")?; + run_test(app_test, STILLS_TEST, display::Mode::Media, &raw)?; + for name in WIDE_STILLS { + wide( + &raw.join(format!("{name}.png")), + &output.join(format!("{name}.png")), + )?; + } + prompt( + &raw.join("session-restore.png"), + &output.join("session-restore.png"), + )?; + for name in NARROW_STILLS { + narrow( + &raw.join(format!("{name}.png")), + &output.join(format!("{name}.png")), + )?; + } + manifest(output)?; + Ok(output.to_path_buf()) +} + +pub fn capture_panes(app_test: &Path, output: &Path) -> Result { + let raw = prepare_output(output, "raw/panes")?; + run_test(app_test, PANES_TEST, display::Mode::Media, &raw)?; + let recorded = raw.join("panes.mp4"); + let video = raw.join("panes-normalized.mp4"); + normalize_recording(&recorded, &video)?; + publish_video(&video, output, "panes.mp4", "panes-poster.png", "6.0")?; + manifest(output)?; + Ok(output.to_path_buf()) +} + +pub fn capture_notification(app_test: &Path, output: &Path) -> Result { + let raw = prepare_output(output, "raw/notification")?; + run_test(app_test, NOTIFICATION_TEST, display::Mode::MediaGnome, &raw)?; + let video = raw.join("notification-return.mp4"); + publish_video( + &video, + output, + "notification-return.mp4", + "notification-return-poster.png", + "2.5", + )?; + // The scene captures the frame where it confirmed the banner is visible. + // Prefer that still over a guessed video timestamp, which depends on how + // long the shell took to draw the banner. + let scene_poster = raw.join("notification-return-poster.png"); + let poster_source = if scene_poster.is_file() { + let poster = output.join("notification-return-poster.png"); + run_convert( + &[ + scene_poster.to_str().ok_or("poster path is not UTF-8")?, + "-crop", + "1600x1000+0+0", + "+repage", + ], + &poster, + )?; + clean_png(&poster)?; + poster + } else { + video.clone() + }; + let banner = output.join("desktop-notification.png"); + let mut crop = Command::new("/usr/bin/ffmpeg"); + crop.env_clear() + .args(["-hide_banner", "-loglevel", "error", "-y"]); + if poster_source == video { + crop.args(["-ss", "2.5"]); + } + let status = crop + .arg("-i") + .arg(&poster_source) + .args(["-frames:v", "1", "-vf", "crop=640:130:480:10"]) + .arg(&banner) + .stdin(Stdio::null()) + .status()?; + if !status.success() { + return Err("ffmpeg banner crop failed".into()); + } + clean_png(&banner)?; + manifest(output)?; + Ok(output.to_path_buf()) +} + +/// Re-encode a recording once, so every published clip is H.264, without +/// source metadata and ready to start at the first frame. +fn normalize_recording(raw: &Path, output: &Path) -> Result<()> { + if !raw.is_file() { + return Err(format!("missing recording {}", raw.display()).into()); + } + let status = Command::new("/usr/bin/ffmpeg") + .env_clear() + .args(["-hide_banner", "-loglevel", "error", "-y", "-i"]) + .arg(raw) + .args([ + "-an", + "-c:v", + "libx264", + "-preset", + "medium", + "-crf", + "18", + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + ]) + .arg(output) + .stdin(Stdio::null()) + .status()?; + if !status.success() { + return Err("ffmpeg normalize failed".into()); + } + Ok(()) +} + +fn publish_video( + raw_video: &Path, + output: &Path, + name: &str, + poster_name: &str, + poster_time: &str, +) -> Result<()> { + if !raw_video.is_file() { + return Err(format!("missing recording {}", raw_video.display()).into()); + } + storage::atomic_write(output, Path::new(name), &fs::read(raw_video)?, 0o644)?; + let poster = output.join(poster_name); + let status = Command::new("/usr/bin/ffmpeg") + .env_clear() + .args([ + "-hide_banner", + "-loglevel", + "error", + "-y", + "-ss", + poster_time, + "-i", + ]) + .arg(raw_video) + .args(["-frames:v", "1"]) + .arg(&poster) + .stdin(Stdio::null()) + .status()?; + if !status.success() { + return Err(format!("ffmpeg poster extraction failed for {name}").into()); + } + clean_png(&poster) +} + +fn prepare_output(output: &Path, raw_name: &str) -> Result { + let raw = output.join(raw_name); + if raw.exists() { + return Err(format!("{} already exists", raw.display()).into()); + } + let parent = output.parent().ok_or("output has no parent")?; + fs::create_dir_all(parent)?; + fs::create_dir_all(&raw)?; + Ok(raw.canonicalize()?) +} + +fn run_test(app_test: &Path, test: &str, mode: display::Mode, raw: &Path) -> Result<()> { + let app_test = app_test.canonicalize()?; + if !app_test.is_file() { + return Err("application test executable must be a regular file".into()); + } + std::env::set_var("AMONG_MEDIA_OUTPUT", raw); + let args = vec![ + app_test.display().to_string(), + test.into(), + "--exact".into(), + "--ignored".into(), + "--test-threads=1".into(), + "--nocapture".into(), + ]; + let status = display::run(mode, &args, &scratch::root()?, Duration::from_secs(300))?; + if !status.success() { + return Err(format!("media scene failed; raw files remain in {}", raw.display()).into()); + } + Ok(()) +} + +fn run_convert(args: &[&str], output: &Path) -> Result<()> { + let status = Command::new("/usr/bin/convert") + .env_clear() + .args(args) + .arg(output) + .stdin(Stdio::null()) + .status()?; + if !status.success() { + return Err(format!("convert failed for {}", output.display()).into()); + } + metadata(output)?; + Ok(()) +} + +fn wide(source: &Path, output: &Path) -> Result<()> { + let bytes = fs::read(source)?; + let (width, height) = png_size(&bytes)?; + if width != WIDE || height != WIDE_HEIGHT { + return Err(format!( + "{} is {width}x{height}, expected {WIDE}x{WIDE_HEIGHT}", + source.display() + ) + .into()); + } + run_convert( + &[ + source.to_str().ok_or("source path is not UTF-8")?, + "-strip", + "-define", + "png:exclude-chunk=all", + "-define", + "png:compression-level=9", + ], + output, + ) +} + +fn prompt(source: &Path, output: &Path) -> Result<()> { + let bytes = fs::read(source)?; + let (width, height) = png_size(&bytes)?; + if width != WIDE || height != WIDE_HEIGHT { + return Err(format!( + "{} is {width}x{height}, expected {WIDE}x{WIDE_HEIGHT}", + source.display() + ) + .into()); + } + run_convert( + &[ + source.to_str().ok_or("source path is not UTF-8")?, + "-crop", + "800x480+400+260", + "+repage", + "-strip", + "-define", + "png:exclude-chunk=all", + "-define", + "png:compression-level=9", + ], + output, + ) +} + +fn narrow(source: &Path, output: &Path) -> Result<()> { + let bytes = fs::read(source)?; + let (width, height) = png_size(&bytes)?; + if width <= FRAME * 2 || height <= FRAME * 2 { + return Err(format!("{} is too small", source.display()).into()); + } + let content_width = width - FRAME * 2; + if content_width != NARROW { + return Err(format!( + "{} content is {content_width} wide, expected {NARROW}", + source.display() + ) + .into()); + } + run_convert( + &[ + source.to_str().ok_or("source path is not UTF-8")?, + "-shave", + &format!("{FRAME}x{FRAME}"), + "+repage", + "-bordercolor", + "#3a414d", + "-border", + "1", + "-strip", + "-define", + "png:exclude-chunk=all", + "-define", + "png:compression-level=9", + ], + output, + ) +} + +fn metadata(path: &Path) -> Result<()> { + let bytes = fs::read(path)?; + let (width, height) = png_size(&bytes)?; + if width == 0 || height == 0 { + return Err(format!("{} has no image area", path.display()).into()); + } + Ok(()) +} + +fn clean_png(path: &Path) -> Result<()> { + let temp = path.with_extension("clean.png"); + run_convert( + &[ + path.to_str().ok_or("source path is not UTF-8")?, + "-strip", + "-define", + "png:exclude-chunk=all", + "-define", + "png:compression-level=9", + ], + &temp, + )?; + fs::rename(&temp, path)?; + metadata(path) +} + +fn hash(path: &Path) -> Result { + let mut hasher = Sha256::new(); + hasher.update(fs::read(path)?); + Ok(format!("{:x}", hasher.finalize())) +} + +fn manifest(output: &Path) -> Result<()> { + let mut assets = BTreeMap::new(); + for entry in fs::read_dir(output)? { + let entry = entry?; + let path = entry.path(); + if !path.is_file() || path.file_name().is_some_and(|name| name == "media.json") { + continue; + } + let name = path + .file_name() + .and_then(|name| name.to_str()) + .ok_or("media name is not UTF-8")? + .to_string(); + let bytes = fs::read(&path)?; + let entry = if name.ends_with(".png") { + let (width, height) = png_size(&bytes)?; + json!({"kind": "png", "width": width, "height": height, "bytes": bytes.len(), "sha256": hash(&path)?}) + } else { + json!({"kind": "mp4", "bytes": bytes.len(), "sha256": hash(&path)?}) + }; + assets.insert(name, entry); + } + let source = match std::env::var("AMONG_MEDIA_SOURCE") { + Ok(value) if !value.trim().is_empty() => Some(value.trim().to_string()), + Ok(_) => return Err("AMONG_MEDIA_SOURCE is set but empty".into()), + Err(std::env::VarError::NotPresent) => { + eprintln!("warning: AMONG_MEDIA_SOURCE is not set; media.json source stays null"); + None + } + Err(error) => { + return Err(format!("AMONG_MEDIA_SOURCE is not valid Unicode: {error}").into()) + } + }; + let document = json!({ + "version": 1, + "canvas": { + "wide": [WIDE, WIDE_HEIGHT], + "narrow_width": NARROW + MARGIN * 2, + "narrow_margin": MARGIN, + "frame": FRAME, + "backdrop": "#20262f", + "border": "#3a414d" + }, + "source": source, + "assets": assets + }); + storage::atomic_write( + output, + Path::new("media.json"), + &serde_json::to_vec_pretty(&document)?, + 0o644, + )?; + Ok(()) +} + +pub fn verify(output: &Path) -> Result<()> { + let document = storage::parse_json(&fs::read(output.join("media.json"))?)?; + let assets = document["assets"] + .as_object() + .ok_or("media.json has no assets")?; + if assets.is_empty() { + return Err("media.json lists no assets".into()); + } + let mut expected = BTreeSet::new(); + for name in WIDE_STILLS { + expected.insert(format!("{name}.png")); + } + for name in NARROW_STILLS { + expected.insert(format!("{name}.png")); + } + for name in [ + "session-restore.png", + "panes.mp4", + "panes-poster.png", + "notification-return.mp4", + "notification-return-poster.png", + "desktop-notification.png", + ] { + expected.insert(name.into()); + } + let actual = assets.keys().cloned().collect::>(); + if actual != expected { + return Err(format!( + "media.json assets differ from the published set: missing {:?}, unexpected {:?}", + expected.difference(&actual).collect::>(), + actual.difference(&expected).collect::>() + ) + .into()); + } + for (name, entry) in assets { + let path = output.join(name); + if !path.is_file() { + return Err(format!("missing asset {name}").into()); + } + let bytes = fs::read(&path)?; + if entry["sha256"].as_str() != Some(hash(&path)?.as_str()) { + return Err(format!("{name} does not match its hash").into()); + } + if entry["bytes"].as_u64() != Some(bytes.len() as u64) { + return Err(format!("{name} does not match its size").into()); + } + if entry["kind"] == "png" { + let (width, height) = png_size(&bytes)?; + if entry["width"].as_u64() != Some(u64::from(width)) + || entry["height"].as_u64() != Some(u64::from(height)) + { + return Err(format!("{name} does not match its recorded dimensions").into()); + } + } + } + for name in ["notification-return.mp4", "panes.mp4"] { + let video = output.join(name); + if !video.is_file() { + return Err(format!("missing video {name}").into()); + } + let probe = Command::new("/usr/bin/ffprobe") + .env_clear() + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=codec_name,width,height,r_frame_rate", + "-of", + "csv=p=0", + ]) + .arg(&video) + .output()?; + if !probe.status.success() { + return Err(format!("ffprobe failed for {name}").into()); + } + let text = String::from_utf8_lossy(&probe.stdout); + if !text.trim().eq_ignore_ascii_case("h264,1600,1000,30/1") + && !text.trim().eq_ignore_ascii_case("h264,1600,1000,30") + { + return Err(format!("unexpected {name} stream: {}", text.trim()).into()); + } + } + println!("PASS {} media assets in {}", assets.len(), output.display()); + Ok(()) +}