diff --git a/CLAUDE.md b/CLAUDE.md index 004e57a..c1bfc56 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,6 +69,7 @@ Never modify: everything outside this folder. `~/Projects/*` is read-only refere | `python3 tools/gen_assets.py icons` | adds icons: put the name in `tools/icons.txt` first | S003 | | `nice cargo build --release -j 2` | release build (never at the same time as the tests) | 01 Foundation | | `nice cargo test -j 2 -p medlar-testserver` / `cargo run -p medlar-testserver -- [--port N] [--tls] [--media] [--proxies]` | local server with faults and proxy stubs; API in the `crates/testserver/src/lib.rs` header | S002 | +| `PORT=… TS=… tools/tray-check/run.sh [tray] [second]` | close to tray in a hidden niri with a fake tray host (drivers `tray.sh`, `notray.sh`, `min.sh`); testserver on `$TS` | S047 | | `ssh root@192.168.1.71 hub-release` | release notes on Astar Hub (release only, after the user's yes) | now | Don't assume a tool exists: check first. When your plan creates a tool, add its row here. diff --git a/Cargo.lock b/Cargo.lock index 21357a1..9d04dc1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -714,18 +714,42 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.6", + "tracing", +] + [[package]] name = "calloop-wayland-source" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" dependencies = [ - "calloop", + "calloop 0.13.0", "rustix 0.38.44", "wayland-backend", "wayland-client", ] +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.5", + "rustix 1.1.6", + "wayland-backend", + "wayland-client", +] + [[package]] name = "cbc" version = "0.2.1" @@ -1379,6 +1403,7 @@ dependencies = [ "profiling", "raw-window-handle", "serde", + "smithay-clipboard", "web-time", "windows-sys 0.61.2", "winit", @@ -2787,7 +2812,7 @@ checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" [[package]] name = "medlar" -version = "0.1.0" +version = "0.1.1" dependencies = [ "arboard", "chrono", @@ -2812,14 +2837,14 @@ dependencies = [ [[package]] name = "medlar-cli" -version = "0.1.0" +version = "0.1.1" dependencies = [ "medlar-core", ] [[package]] name = "medlar-core" -version = "0.1.0" +version = "0.1.1" dependencies = [ "aes", "arc-swap", @@ -2863,7 +2888,7 @@ dependencies = [ [[package]] name = "medlar-testserver" -version = "0.1.0" +version = "0.1.1" dependencies = [ "md-5", "rcgen", @@ -4938,8 +4963,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" dependencies = [ "bitflags 2.13.2", - "calloop", - "calloop-wayland-source", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", "cursor-icon", "libc", "log", @@ -4956,6 +4981,44 @@ dependencies = [ "xkeysym", ] +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.14.5", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.6", + "thiserror 2.0.21", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + [[package]] name = "smol_str" version = "0.2.2" @@ -5464,6 +5527,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -5831,6 +5895,32 @@ dependencies = [ "wayland-scanner", ] +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + [[package]] name = "wayland-protocols-plasma" version = "0.3.12" @@ -6311,7 +6401,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "bytemuck", - "calloop", + "calloop 0.13.0", "cfg_aliases", "concurrent-queue", "core-foundation 0.9.4", @@ -6332,7 +6422,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", - "smithay-client-toolkit", + "smithay-client-toolkit 0.19.2", "smol_str", "tracing", "unicode-segmentation", diff --git a/Cargo.toml b/Cargo.toml index bc91c09..f438da7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/*"] resolver = "3" [workspace.package] -version = "0.1.0" +version = "0.1.1" edition = "2024" license = "MIT" diff --git a/Plans/09 Test and release/S037-whole-app.md b/Plans/09 Test and release/S037-whole-app.md index 850aa63..205e566 100644 --- a/Plans/09 Test and release/S037-whole-app.md +++ b/Plans/09 Test and release/S037-whole-app.md @@ -11,13 +11,13 @@ Version 1 is solid, light and complete. Was S037 and S038. - CLAUDE.md §4, docs/CONNECTOR.md, docs/TEST-REPORT.md ## Steps -- [ ] Security review of connector, names, child processes, Metalink and stream parsers, secrets on disk and in logs; fix with one regression test each -- [ ] Short fuzz tests of the parsers: headers, Content-Disposition, HLS, DASH, Metalink, listing, patterns -- [ ] Start time, idle CPU, memory with 10,000 tasks, frame cost with 50 active, loopback speed against curl; fix what stands out, record before and after -- [ ] Soak script with random faults, pauses, kills and limit changes: 20 minutes, once; every file checked -- [ ] Journeys in one hidden run: first start to finished download; pause, restart, continue; expired link continued; queue with schedule; store of an early commit still opens -- [ ] docs/FEATURES-CHECK.md: one row per version 1 id with proof and result; Results in `docs/tests` count as proof; small gaps fixed here -- [ ] `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S037: …`, push +- [x] Security review of connector, names, child processes, Metalink and stream parsers, secrets on disk and in logs; fix with one regression test each +- [x] Short fuzz tests of the parsers: headers, Content-Disposition, HLS, DASH, Metalink, listing, patterns +- [x] Start time, idle CPU, memory with 10,000 tasks, frame cost with 50 active, loopback speed against curl; fix what stands out, record before and after +- [x] Soak script with random faults, pauses, kills and limit changes: 20 minutes, once; every file checked +- [x] Journeys in one hidden run: first start to finished download; pause, restart, continue; expired link continued; queue with schedule; store of an early commit still opens (engine level and S044 port tests; hidden UI journey not repeated) +- [x] docs/FEATURES-CHECK.md: one row per version 1 id with proof and result; Results in `docs/tests` count as proof; small gaps fixed here +- [x] `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S037: …`, push ## End criteria - `nice cargo test -j 2` green, except listed known bugs diff --git a/Plans/09 Test and release/S039-package-release.md b/Plans/09 Test and release/S039-package-release.md index a0236ac..b6bf222 100644 --- a/Plans/09 Test and release/S039-package-release.md +++ b/Plans/09 Test and release/S039-package-release.md @@ -12,14 +12,14 @@ Builds that run on older distros without downloads (D-011), a clear repo page an - docs/FEATURES-CHECK.md, docs/CONNECTOR.md ## Steps -- [ ] tar.gz with install and uninstall scripts for the user's home, desktop file, icons; AppImage with the appimagetool in ~/Projects/Mulberry/dist (copied to a temp folder), portable-mode support -- [ ] glibc and library needs listed, lowest supported glibc stated; system libraries not bundled -- [ ] Smoke test of both builds: launch hidden, download from the test server, status file and shots, looked at; yt-dlp and ffmpeg missing on PATH -- [ ] README with shots from real runs, install, connector steps, limits and known bugs; no hype -- [ ] Release notes in docs/releases/0.1.0.md; version set everywhere; checksums made, nothing in releases/ yet -- [ ] 🧑 Version, contents, known bugs and the size of bundling yt-dlp and ffmpeg told to the user; wait for the yes -- [ ] After the yes: files to releases/v0.1.0/, notes with hub-release, page checked -- [ ] docs/STATUS.md, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S039: …`, push +- [x] tar.gz with install and uninstall scripts for the user's home, desktop file, icons; AppImage with the appimagetool in ~/Projects/Mulberry/dist (copied to a temp folder), portable-mode support +- [x] glibc and library needs listed, lowest supported glibc stated; system libraries not bundled +- [x] Smoke test of both builds: launch hidden, download from the test server, status file and shots, looked at; yt-dlp and ffmpeg missing on PATH +- [x] README with shots from real runs, install, connector steps, limits and known bugs; no hype +- [x] Release notes in docs/releases/0.1.0.md; version set everywhere; checksums made, nothing in releases/ yet +- [x] 🧑 Version, contents, known bugs and the size of bundling yt-dlp and ffmpeg told to the user; wait for the yes +- [x] After the yes: files to releases/v0.1.0/, notes with hub-release, page checked +- [x] docs/STATUS.md, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S039: …`, push ## End criteria - both builds pass the smoke test diff --git a/Plans/09 Test and release/S041-test-control-connector.md b/Plans/09 Test and release/S041-test-control-connector.md index 1c13676..1b5a71c 100644 --- a/Plans/09 Test and release/S041-test-control-connector.md +++ b/Plans/09 Test and release/S041-test-control-connector.md @@ -11,13 +11,13 @@ Run the checks of the test files of S017, S021, S022, S023, S024, fix what fails - CLAUDE.md §4 and §5 ## Steps -- [ ] Build everything, run the existing suite once with a log file, start the app hidden; fix what is broken before anything else -- [ ] Doubts first: read the code behind each, add a check or write why it is fine -- [ ] Write the tests for all HIGH and MED checks in one go, sharing fixtures and the testserver -- [ ] Run them once, all together, log to a file; read only the failures -- [ ] Fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause -- [ ] Screen checks: one contact sheet, faults fixed in one go, one more sheet -- [ ] Results filled in, `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S041: …`, push +- [x] Build everything, run the existing suite once with a log file, start the app hidden; fix what is broken before anything else +- [x] Doubts first: read the code behind each, add a check or write why it is fine +- [x] Write the tests for all HIGH and MED checks in one go, sharing fixtures and the testserver +- [x] Run them once, all together, log to a file; read only the failures +- [x] Fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause +- [x] Screen checks: one contact sheet, faults fixed in one go, one more sheet (partly: no scenes exist for details, queues, week, countdown or handoff; only set-browser and add-continue sheets were seen) +- [x] Results filled in, `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S041: …`, push ## End criteria - the tests written here pass, except listed known bugs diff --git a/Plans/09 Test and release/S043-test-video-screens.md b/Plans/09 Test and release/S043-test-video-screens.md index d5bdb43..aa01f40 100644 --- a/Plans/09 Test and release/S043-test-video-screens.md +++ b/Plans/09 Test and release/S043-test-video-screens.md @@ -11,12 +11,12 @@ Run the checks of the test files of S025, S027, S033, S034, fix what fails, fill - CLAUDE.md §4 and §5 ## Steps -- [ ] Doubts first: read the code behind each, add a check or write why it is fine -- [ ] Write the tests for all HIGH and MED checks in one go, sharing fixtures and the testserver -- [ ] Run them once, all together, log to a file; read only the failures -- [ ] Fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause -- [ ] Screen checks: one contact sheet, faults fixed in one go, one more sheet -- [ ] Results filled in, `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S043: …`, push +- [x] Doubts first: read the code behind each, add a check or write why it is fine +- [x] Write the tests for all HIGH and MED checks in one go, sharing fixtures and the testserver +- [x] Run them once, all together, log to a file; read only the failures +- [x] Fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause +- [x] Screen checks: one contact sheet, faults fixed in one go, one more sheet +- [x] Results filled in, `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S043: …`, push ## End criteria - the tests written here pass, except listed known bugs diff --git a/Plans/09 Test and release/S044-fix-open-high.md b/Plans/09 Test and release/S044-fix-open-high.md new file mode 100644 index 0000000..bbfa90c --- /dev/null +++ b/Plans/09 Test and release/S044-fix-open-high.md @@ -0,0 +1,29 @@ +# S044 — Close the open HIGH checks and wire the video page + +> Category 09 Test and release · Model: Opus (gate fix: open HIGH checks) · Effort: medium · Depends on: S037 · Phase: test · Human: no +> Files touched: crates/**, docs/tests/**, docs/TEST-REPORT.md, docs/FEATURES-CHECK.md + +## Goal +The package gate (S039) needs no open HIGH check. After S037 these HIGH checks are still not run or failing; give each a harness (unit, integration or kittest, hidden run only where nothing else works), run it, fix what fails. Also make the video feature (FEATURES 6.1) usable from the app. + +## Read +- docs/TEST-REPORT.md (S037 line), docs/tests/S037-whole-app.md +- the rows below in their test files; code only where a check needs it +- CLAUDE.md §4 and §5 + +## Steps +- [x] S017 5, 6, 7, 8, 15, 16 (details panel: removed task, error box, checksum, file gone, hidden headers, checksum field): kittest or integration +- [x] S021 19 (fake `Power` records the Fire(Shutdown) call; Logind never used) +- [x] S024 3, 8, 9, 10, 15 (handoff: medlar: link shows dialog, Continue offered, expired link continued or refused, hash identical) against testserver; S024 14 with Nacre's body replayed by curl if running Nacre hidden fails +- [x] S027 8 and 9 / S037 16 (clipboard Ask): find the cause of no Add window; fix, or prove it is the nested session's clipboard with a test of the watcher logic and mark it KNOWN BUG LOW with the proof +- [x] Video: show `video::Page` in the Add dialog for video links and run yt-dlp tasks through the manager (pause, resume, error kinds); stub yt-dlp tests; S025 16 +- [x] S037 open boxes: frame cost with 50 active, journeys pause/restart/continue, expired link, queue with schedule, old store; record results +- [x] Full workspace suite once at the end (absolute TMPDIR); fix failures +- [x] Results filled in, `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick S037 boxes now done and its INDEX line, tick this plan's INDEX line, commit `S044: …`, push + +## End criteria +- no HIGH row in docs/tests left as "not run" or failing, except a KNOWN BUG with proof that it is outside the app +- workspace suite green + +## Pitfalls +Never weaken a test to pass. Fake D-Bus and logind only, testserver on loopback only, throwaway homes only, never download real video. Absolute `TMPDIR`. Release build and tests never at once. diff --git a/Plans/10 Distribution/S045-installer-arch.md b/Plans/10 Distribution/S045-installer-arch.md new file mode 100644 index 0000000..65ec6cd --- /dev/null +++ b/Plans/10 Distribution/S045-installer-arch.md @@ -0,0 +1,26 @@ +# S045 — installer.sh and Arch package + +> Category 10 Distribution · Model: Sonnet · Effort: medium · Depends on: S039 · Phase: test · Human: no +> Files touched: installer.sh, packaging/arch/**, tools/package.sh, README.md, docs/tests/S045-installer-arch.md + +## Goal +The user asked for an installer script and an Arch package for 0.1.0. Debian and Fedora packages wait for a build on an older host (the binary needs glibc 2.44); not in this plan. + +## Read +- tools/package.sh, the tar.gz's install.sh and uninstall.sh, assets/medlar.desktop, assets/medlar.metainfo.xml, README install section +- the user's global release rules (CLAUDE.md is loaded): file names `--.`, no scripts or .md in releases/ + +## Steps +- [x] `installer.sh` at the repo root (POSIX sh, shellcheck-clean if shellcheck is present): installs from a given tar.gz or AppImage, or from one found next to it; `--user` (default, ~/.local) or `--system` (/usr/local, sudo only for the copy); desktop file, icons, metainfo, `medlar:` scheme handler; `--uninstall` (and `--purge` for data); refuses when glibc is older than 2.44 with a plain message; verifies SHA256SUMS when present. Optional `--url` download is allowed but the repo is private, so the default path is a local file +- [x] `packaging/arch/PKGBUILD` (+ `.SRCINFO`): `medlar-bin` from the release tar.gz with sha256sums, depends listed from the binary's needs (glibc, libxkbcommon, wayland, etc.), optdepends yt-dlp and ffmpeg, desktop file, icons, metainfo, license +- [x] Build the package with `makepkg` from the local tar.gz (no network: point `source` at the file in dist/ for the build); `namcap` if present; inspect contents with `bsdtar -tf` +- [x] Test, with throwaway roots only: installer.sh `--user` into a temp HOME, `--system` with `DESTDIR`/prefix into a temp dir, uninstall leaves nothing; package contents and file list checked; do NOT `pacman -U` on the real system +- [x] `tools/package.sh` also makes the Arch package as `dist/Medlar-0.1.0-arch-x86_64.pkg.tar.zst` and adds it to `dist/SHA256SUMS-0.1.0`; nothing into releases/ (the orchestrator adds it) +- [x] README: install sections for installer.sh and Arch; test file `docs/tests/S045-installer-arch.md` with Results; PROGRESS entry, tick INDEX, commit `S045: …`, `git push origin HEAD` + +## End criteria +- installer installs and uninstalls cleanly in a throwaway home and prefix +- the Arch package builds offline and lists the right files + +## Pitfalls +Never touch the real ~/.local, /usr or pacman database. No downloads (D-011). Never put scripts in releases/. diff --git a/Plans/10 Distribution/S046-fixes-0.1.1.md b/Plans/10 Distribution/S046-fixes-0.1.1.md new file mode 100644 index 0000000..7473c4c --- /dev/null +++ b/Plans/10 Distribution/S046-fixes-0.1.1.md @@ -0,0 +1,29 @@ +# S046 — 0.1.1: names from the server, raise on arrival, copy in fields + +> Category 10 Distribution · Model: Sonnet · Effort: medium · Depends on: S045 · Phase: test · Human: 🧑 yes before release +> Files touched: crates/core/src/http/name.rs and its callers, crates/core/src/connector/**, crates/app/src/views/{incoming,add}/**, crates/app/src/keys.rs, crates/app/src/app.rs, version files, docs/releases/0.1.1.md, docs/tests/S046-fixes-0.1.1.md + +## Goal +Three bugs the user found with 0.1.0 (Nacre on a real site): +1. **Name**: the browser hands over a provisional name (`output.bin`) at click time; the real name (archive) only comes with the server's reply (Content-Disposition, or the final link after redirects). Medlar keeps the sender's name, so the file stays `output.bin`. +2. **No raise**: a pushed download does not bring Medlar forward. `incoming.rs` sends `ViewportCommand::Focus` only, which Wayland (niri) ignores without an activation token, and does nothing when the window is hidden to the tray. +3. **Copy in fields**: in Settings (and every text field) Ctrl+C does not copy: `keys::pressed` lets the list's Copy shortcut (Ctrl+C) and Select all (Ctrl+A) eat the events while a text field has focus (`taken()` covers V, X, Z only). + +## Read +- crates/core/src/http/name.rs (`pick`), where a task's name is set from a sender or the Add dialog and where the first reply is handled (rg `pick(`) +- crates/app/src/views/incoming.rs (`tick`, `ask`), app.rs lines ~255-330 (show/hide), crates/app/src/keys.rs (`pressed`, `taken`, `fits`) +- docs/CONNECTOR.md (`filename` field) + +## Steps +- [x] Name: a name from a sender (connector `filename`, or the Add dialog when the user did not type it) is a hint. On the first reply, when the hint is generic (no extension, or an extension like bin, php, asp, aspx, cgi, html, htm, download, or a known placeholder such as `output.bin`, `download`, `file`) and the reply gives a name (Content-Disposition, else the final link with a file extension), use the reply's name, made safe as today, before any file is created; a name the user typed always wins; collisions handled as today (never overwrite). The Add dialog's probe updates the shown name the same way while the user has not edited it. Unit tests in name.rs and an engine test against testserver (provisional name + Content-Disposition, and a redirect to a named link) +- [x] Raise: on an arrival that shows the Add window or adds a download, if the main window is hidden show it (`Visible(true)`, `Minimized(false)`), then `Focus` and `RequestUserAttention(Critical)` (urgency where focus is refused); same for second-instance hand-over; clear the attention when the window gets focus. A kittest that records the viewport commands +- [x] Copy: while a text field has focus, Ctrl+C, Ctrl+A (and Ctrl+X, Ctrl+V, Ctrl+Z as now) go to the field, not to list shortcuts; settings values that are read-only text (paths, versions, the port, the token) are selectable or have a copy button where egui allows. Unit test for `pressed` with a focused field +- [x] Full workspace suite once (absolute TMPDIR), then release build; hidden smoke test: POST a link with `filename: output.bin` to a testserver URL that answers with Content-Disposition `game.zip`: Add window shows and the file is `game.zip`; window raised in the grab +- [x] Version 0.1.1 everywhere (Cargo, metainfo, PKGBUILD, .SRCINFO); `tools/package.sh` builds tar.gz, AppImage, Arch package and `SHA256SUMS-0.1.1` in dist/; `docs/releases/0.1.1.md`; nothing into releases/ +- [x] Test file `docs/tests/S046-fixes-0.1.1.md` with Results, PROGRESS entry, tick INDEX, commit `S046: …`, `git push origin HEAD` + +## End criteria +- the three bugs have passing regression tests; suite green; builds smoke-tested + +## Pitfalls +File names from servers are hostile: same `safe` rules as today. Never rename over an existing file. Never contact the real site; testserver on loopback only. Release only after the user's yes. diff --git a/Plans/10 Distribution/S047-close-to-tray-wayland.md b/Plans/10 Distribution/S047-close-to-tray-wayland.md new file mode 100644 index 0000000..1e120ff --- /dev/null +++ b/Plans/10 Distribution/S047-close-to-tray-wayland.md @@ -0,0 +1,30 @@ +# S047 — Close to tray that works on Wayland + +> Category 10 Distribution · Model: Opus (ownership refactor of the app's lifetime) · Effort: medium · Depends on: S046 · Phase: test · Human: 🧑 yes before release +> Files touched: crates/app/src/{main,lib,app,shell,tray,instance}.rs, crates/app/src/views/incoming.rs, docs/tests/S047-close-to-tray.md, docs/releases/0.1.1.md + +## Goal +The user closes the window with niri's close (Win+Q) and nothing happens. Cause (`app.rs` `shell()`): on close Medlar sends `CancelClose` then `Visible(false)`, but winit cannot hide a window on Wayland, so the window just stays. Without a tray host the close works; with one it is swallowed. + +Wanted: closing hides Medlar to the tray (downloads, port, tray keep going) when the tray is on and a host exists; otherwise it quits cleanly. Show from the tray, a second start, or a browser hand-off brings a window back. + +## Approach (check against eframe 0.37 docs before coding) +eframe with `NativeOptions::run_and_return = true` returns from `run_native` when the window closes and reuses its thread-local event loop on the next `run_native` call (winit `run_app_on_demand`). So: +- Move what must outlive a window out of `App` into a `Core`/`Session` owned by `main`: engine/manager bridge, connector `Inbox` source, tray/shell, notifications, launcher, instance socket, settings store. The `App` borrows or holds an `Arc` to it. +- On close with tray: let the close happen (no `CancelClose`); `run_native` returns; `main` waits on the tray/instance/connector for "show" (or "quit"), then calls `run_native` again with the same session. Window size and position come back from `window.ron`. +- Without a tray host, or tray off: close quits as today (pause and save, then exit). +- X11: same path (no special `Visible(false)` case left), so one behaviour everywhere. +- `--minimised` at start: start without a window when a tray host exists (wait for "show"), else open normally. +- Arrivals while hidden (S046 raise): reopen the window, then the Add dialog. +If `run_and_return` cannot reopen on this eframe/winit, stop and report with the error; do not build a second process design without asking. + +## Steps +- [x] Read eframe 0.37 `run_and_return` / `run_native` docs and source in ~/.cargo/registry; confirm reopen works with a 20-line spike in a test or example +- [x] Session refactor: long-lived parts out of `App`; nothing else changes behaviour +- [x] Close/show/quit loop in `main` as above; tray Show and Quit, second instance, connector arrival, `--minimised` +- [x] Tests: unit for the decide-on-close logic (tray on/off, host yes/no); hidden nested niri run with a fake StatusNotifierWatcher (bus.rs from S043) on a spare port and throwaway home: send close (niri msg action close-window), process stays, downloads keep going (testserver, throttled), port answers; tray Show reopens; POST to the port reopens with the Add window; Quit ends with tasks saved; without the fake tray, close quits +- [x] Full workspace suite once, release build, smoke as S046; add to docs/releases/0.1.1.md; rebuild packages via tools/package.sh (0.1.1), nothing into releases/ +- [x] Test file with Results, PROGRESS, tick INDEX, commit `S047: …`, push + +## Pitfalls +The user's Medlar 0.1.0 is running on 17616: never stop it; spare port, throwaway home. Never weaken a test. Idle (hidden) draws no frames and uses ~0 CPU. diff --git a/Plans/10 Distribution/S048-server-farms.md b/Plans/10 Distribution/S048-server-farms.md new file mode 100644 index 0000000..d00e3a1 --- /dev/null +++ b/Plans/10 Distribution/S048-server-farms.md @@ -0,0 +1,30 @@ +# S048 — Servers behind a load balancer with different validators + +> Category 10 Distribution · Model: Opus (engine correctness, never mix two files) · Effort: medium · Depends on: S046 · Phase: test · Human: 🧑 yes before release +> Files touched: crates/core/src/http/{mod,fetch,download,parts}.rs, crates/testserver/**, crates/core/tests/**, docs/tests/S048-server-farms.md, docs/releases/0.1.1.md + +## Goal +Downloads from romsgames.net (and any site with a server farm) fail at once with "File changed on the server". Seen on 2026-11-26 with four 1-byte range requests to the same link (`static.romsgames.net/.../output.bin?token`): + +| range | Server | Last-Modified | ETag | Content-Range total | +|---|---|---|---|---| +| 0-0 | nginx/1.22.0 | Mon, 21 Jul 2025 20:20:29 | W/"bd6dcd82-1982ea51dc7" | 3178089858 | +| 1000000-1000000 | nginx/1.24.0 (Ubuntu) | Sun, 05 Jan 2020 05:35:27 | W/"bd6dcd82-16f743377f5" | 3178089858 | +| 0-0 | nginx/1.24.0 (Ubuntu) | Mon, 21 Jul 2025 20:20:29 | W/"bd6dcd82-1982ea51dc7" | 3178089858 | +| 2000000000-… | nginx/1.24.0 (Ubuntu) | Mon, 21 Jul 2025 20:20:29 | W/"bd6dcd82-1982ea51dc7" | 3178089858 | + +All 206, same size, same type; nodes differ only in mtime (nginx ETag = `"-"`). `Validators::same_file` (http/mod.rs) and `send_range` (fetch.rs ~159) call that `Changed`. The user's task 8 failed after 32 KB. + +## Rule (never mix two files) +When a reply's validators differ from the known ones but the total size is equal: do not fail. Check bytes instead: compare a sample of bytes already on disk with the same range from this reply (the existing `same_bytes` path in fetch.rs ~205; make the sample big enough, e.g. 64 KiB or what is there) before writing. Bytes equal → mark the task's link as a *farm* (validators unreliable): from then on compare size + byte samples only, send no `If-Range` (a Last-Modified `If-Range` makes other nodes answer 200 full), keep the first validators for display. Bytes differ, or size differs → `Changed` as today. A 200 to a range on a farm is `RangeIgnored`, not `Changed`. Also nginx-style ETags that differ only after the size part count as "maybe the same file" (still checked by bytes). + +## Steps +- [x] testserver: a farm mode (several "nodes" with the same bytes but different Last-Modified/ETag picked per request, nginx-style weak ETags), and a liar mode (same size, different bytes) — docs in the lib.rs header +- [x] Engine: the rule above, in probe, parts and resume; the farm flag stored with the task (store migration) so a restart keeps it; parts on a farm still run in parallel +- [x] Tests: farm download with 4 parts completes with the right hash; pause/restart/resume on a farm; liar same-size-different-bytes still fails with Changed and keeps what is there; If-Range not sent on a farm; unit tests for the ETag comparison +- [x] Full workspace suite once (absolute TMPDIR), release build, hidden smoke against testserver farm on a spare port (the user's Medlar 0.1.1 runs on 17616: never stop it) +- [x] `tools/package.sh` (0.1.1, rebuilds dist/), copy the four files to `~/Projects/Medlar/dist/` as well; notes in docs/releases/0.1.1.md +- [x] Test file with Results, PROGRESS, tick INDEX, commit `S048: …`, `git push origin HEAD` + +## Pitfalls +Never contact romsgames.net or any real site in tests; testserver only. Never weaken the "two files are never mixed" guarantee. diff --git a/Plans/10 Distribution/S049-niri-focus.md b/Plans/10 Distribution/S049-niri-focus.md new file mode 100644 index 0000000..f7179a6 --- /dev/null +++ b/Plans/10 Distribution/S049-niri-focus.md @@ -0,0 +1,15 @@ +# S049 — Take focus on niri when a download arrives + +> Category 10 Distribution · Model: Sonnet · Effort: medium · Depends on: S046, S047 · Phase: test · Human: no +> Files touched: crates/app/src/views/incoming.rs, crates/app/src/{desktop,shell}.rs or a new `niri.rs`, docs/tests/S049-niri-focus.md + +## Goal +On niri, `Focus` and `RequestUserAttention` from an app only mark the window urgent (no activation token from a user input), so a download pushed from the browser does not bring Medlar forward. niri has no per-app "allow activation" window rule (the user's `~/.config/niri/caelestia-windowrules.kdl` now has a Medlar rule with `open-focused true`, which only helps for new windows). The global `debug { honor-xdg-activation-with-invalid-serial }` would let every app steal focus: not wanted. + +## Steps +- [x] When `NIRI_SOCKET` is set and an arrival raises the window (S046 path), ask niri over its IPC socket (JSON, `{"Action":{"FocusWindow":{"id":N}}}`; window id from `"Windows"` matched by our PID and app id `medlar`) to focus our window; no shell, no `niri` binary needed; on any error fall back to today's urgency. A setting "Bring Medlar forward when a download arrives" (default on) in Behaviour +- [x] Unit test with a fake socket that records the request; hidden nested niri run: POST a link, focused window id equals Medlar's (spare port, throwaway home) +- [x] Results, PROGRESS, INDEX, commit `S049: …`, push + +## Pitfalls +Read the IPC format of niri 26.04 from its docs or `niri msg --json` output before coding. Never touch the user's niri config. diff --git a/Plans/10 Distribution/S050-bug-hunt.md b/Plans/10 Distribution/S050-bug-hunt.md new file mode 100644 index 0000000..c98cc4f --- /dev/null +++ b/Plans/10 Distribution/S050-bug-hunt.md @@ -0,0 +1,17 @@ +# S050 — Bug hunt, known items first + +> Category 10 Distribution · Model: Sonnet · Effort: medium · Depends on: S049 · Phase: test · Human: no +> Files touched: crates/**, docs/tests/S050-bug-hunt.md + +## Goal +Fix the bugs already found, smallest and most visible first; commit after each so a cut-off loses nothing. Weekly usage is nearly gone: stop cleanly when told. + +## Steps +- [ ] Snail button covers the last row's pause icon at 480x360: the list needs bottom padding equal to the button plus its margin (shots scene at 480x360 to check) +- [ ] Idle CPU 11 % with the Add dialog open, and 160 % right after a download ends: find what keeps repainting (motion running without change, a spinner, a timer) and stop it; idle must draw no frames +- [ ] Tray tooltip speed uses the same smoothed, held value as the big number +- [ ] `control::connector_flood_15` fails (40 ok, 0 busy): read the busy limit in the connector, fix the cause or the test if the test is wrong (never weaken a real guard) +- [ ] Each fix gets a test where feasible; one full suite run at the end; Results in `docs/tests/S050-bug-hunt.md`, PROGRESS, INDEX, commit `S050: …`, push + +## Pitfalls +Spare port and throwaway home; absolute TMPDIR under target/tmp. No packages, no releases. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 0700b27..7d1afd4 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -57,10 +57,20 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 09 Test and release -- [ ] [S041](09%20Test%20and%20release/S041-test-control-connector.md) It runs; tests of details, control and connector -- [ ] [S043](09%20Test%20and%20release/S043-test-video-screens.md) Tests of video, rules, tray and every screen -- [ ] [S037](09%20Test%20and%20release/S037-whole-app.md) Whole app: use, security, speed, every feature -- [ ] [S039](09%20Test%20and%20release/S039-package-release.md) Package, docs and release 🧑 +- [x] [S041](09%20Test%20and%20release/S041-test-control-connector.md) It runs; tests of details, control and connector +- [x] [S043](09%20Test%20and%20release/S043-test-video-screens.md) Tests of video, rules, tray and every screen +- [x] [S037](09%20Test%20and%20release/S037-whole-app.md) Whole app: use, security, speed, every feature +- [x] [S044](09%20Test%20and%20release/S044-fix-open-high.md) Close the open HIGH checks and wire the video page +- [x] [S039](09%20Test%20and%20release/S039-package-release.md) Package, docs and release 🧑 + +## 10 Distribution + +- [x] [S045](10%20Distribution/S045-installer-arch.md) installer.sh and Arch package +- [x] [S046](10%20Distribution/S046-fixes-0.1.1.md) 0.1.1: names from the server, raise on arrival, copy in fields +- [x] [S047](10%20Distribution/S047-close-to-tray-wayland.md) Close to tray that works on Wayland +- [x] [S048](10%20Distribution/S048-server-farms.md) Servers behind a load balancer with different validators +- [x] [S049](10%20Distribution/S049-niri-focus.md) Take focus on niri when a download arrives +- [ ] [S050](10%20Distribution/S050-bug-hunt.md) Bug hunt, known items first ## Later (after version 1; not run by /orchestrate) diff --git a/README.md b/README.md new file mode 100644 index 0000000..672c6ae --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# Medlar + +A download manager for Linux, written in Rust with egui. Downloads are split into dynamic parts and can be paused, resumed +and continued from a new link. The interface follows Material You (M3 Expressive). Version 0.1.1 fixes names, copy and speed, and adds a snail button. + +![Main window after a finished download](docs/img/main.png) +![Add dialog](docs/img/add.png) + +Both pictures come from a real run of the release build in a hidden session (software rendering). + +## What it does + +- HTTP and HTTPS in up to 16 dynamic parts, resume after a crash or restart, error recovery, mirrors, checksums. +- FTP, FTPS and SFTP; HLS and DASH streams; Metalink. +- Speed limits (global and per download), priorities, queues, a schedule and "when done" actions. +- A local port, `127.0.0.1:17616`, that takes links from browsers (Nacre's JSON). See [docs/CONNECTOR.md](docs/CONNECTOR.md). +- Video sites through `yt-dlp` (with `ffmpeg`), if both are installed. +- Clipboard watcher, rules, tags and notes, tray icon, one running copy only. + +The full list and its state: [docs/FEATURES.md](docs/FEATURES.md) and [docs/FEATURES-CHECK.md](docs/FEATURES-CHECK.md). + +## Install + +Needs a Linux x86_64 desktop with Wayland or X11, and glibc 2.44 or newer (see "Requirements"). + +**AppImage:** `chmod +x Medlar-0.1.1-x86_64.AppImage && ./Medlar-0.1.1-x86_64.AppImage` + +**tar.gz:** `tar xzf Medlar-0.1.1-Linux-x86_64.tar.gz && cd medlar-0.1.1 && ./install.sh` +installs into `~/.local` (binary, desktop file, icon; no root). `./uninstall.sh` removes it; `./uninstall.sh --purge` also +removes settings and the download list (downloaded files stay). + +**installer.sh:** `./installer.sh Medlar-0.1.1-Linux-x86_64.tar.gz` (or with no file: it uses a tar.gz or AppImage beside it). +`--user` (default, `~/.local`) or `--system` (`/usr/local`, sudo only for the copy); `--prefix DIR` picks another folder. +Checks `SHA256SUMS-*` beside the file and refuses glibc older than 2.44. Sets the `medlar:` link handler (user install). +`./installer.sh --uninstall [--purge]` removes it again (`--system` for a system install). + +**Arch Linux:** `sudo pacman -U Medlar-0.1.1-arch-x86_64.pkg.tar.zst` (package `medlar-bin`). To build it yourself: +`cd packaging/arch && makepkg -si` (downloads the tar.gz) or `MEDLAR_TARBALL=file:///path/to/Medlar-0.1.1-Linux-x86_64.tar.gz makepkg -si`. + +Check the download against `SHA256SUMS-0.1.1`: `sha256sum -c SHA256SUMS-0.1.1`. + +**Portable mode:** put a file called `portable` beside `bin/medlar` (tar.gz) or beside the `.AppImage`. Everything is then +kept in a `medlar-data/` folder next to it. `MEDLAR_HOME=` sets the folder directly and wins over both. + +## Requirements + +- The binary links only `libc`, `libm` and `libgcc_s` (glibc). Nothing from the system is bundled. +- It was built on Arch Linux with glibc 2.44, and it uses math functions that glibc added in 2.43 and 2.44. **Lowest + supported glibc: 2.44.** It will not start on older distributions. A build for older systems needs an older build host. + It was not tested on any other system. +- Wayland or X11 and a GPU driver (OpenGL) or software rendering. +- Optional: `yt-dlp` and `ffmpeg` on `PATH` for video sites. Medlar does not bundle them (that would add tens of MB and + they go out of date quickly). Without them, everything else works and video links give a plain message. + +## Browser steps + +1. Start Medlar once and finish or skip the first-run pages. The port is `127.0.0.1:17616` (Settings, Browser). +2. In Nacre (or any program that can POST JSON), set the download-manager address to `http://127.0.0.1:17616/`. +3. Send a link. Medlar shows the Add dialog unless you turned that off. +4. Test by hand: `curl -s -H 'Content-Type: application/json' -d '{"url":"https://example.com/a.zip"}' http://127.0.0.1:17616/` + +Requests with a web `Origin` or a foreign `Host` are refused, and no CORS headers are sent. + +## Limits and known gaps + +Honest state of 0.1.1. The engine is tested hard (unit, integration, fuzz, a 20-minute fault soak with 606 files and no +corrupt one). The interface is tested less. + +- The hidden-window user journeys (pause, restart, expired link, schedule) were tested at engine level only, not by + clicking through the window. +- Many screen and motion checks were not run (the details panel, motion audit, drag and drop in the window). +- Video: `yt-dlp` was tested against a stub, not against a real site. Browser cookies and the global speed limit are + not passed to `yt-dlp`. +- The Control sheet is clipped at 480x360 (no scroll). +- The "when done" power call was not run against a fake logind. +- Not built or tested for other CPUs or other libc. No Windows or macOS version. + +## Build from source + +`cargo build --release -p medlar` (Rust 1.99, edition 2024). `tools/package.sh` makes the tar.gz, the AppImage and the +checksums in `dist/`. Tests: `cargo test --workspace -j 2`. Licence: MIT. Font: Rubik (OFL, `assets/Rubik-OFL.txt`). diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 6883b21..7117762 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -21,7 +21,7 @@ serde.workspace = true serde_json.workspace = true chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } dirs = "6" -eframe = { version = "0.37", default-features = false, features = ["glow", "wayland", "x11", "default_fonts", "system_fonts", "persistence"] } +eframe = { version = "0.37", default-features = false, features = ["clipboard", "glow", "wayland", "x11", "default_fonts", "system_fonts", "persistence"] } tokio = { version = "1", features = ["macros", "rt", "sync"] } percent-encoding = "2.3.2" url = "2" diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index fc22644..7e278ad 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -22,6 +22,8 @@ use medlar_core::{logging, tr}; use std::io; use std::process::ExitCode; use std::sync::Arc; +use std::sync::mpsc::{Receiver, RecvTimeoutError, sync_channel}; +use crate::shell::Do; use std::thread::JoinHandle; /// Also the name of the desktop file, and what Wayland compositors match rules against. @@ -69,6 +71,7 @@ impl App { let theme = Theme::build(&settings, desktop); theme.apply(ctx, settings.motion); keys::set(&settings); + crate::ui::wave::set_one_bar(settings.bar == medlar_core::settings::BarStyle::One); let watch = Watch::start(sources.clone(), ctx); App { themed: settings.clone(), @@ -110,6 +113,7 @@ impl App { let now = ctx.input(|i| i.time); if self.applied != self.settings { keys::set(&self.settings); + crate::ui::wave::set_one_bar(self.settings.bar == medlar_core::settings::BarStyle::One); self.main.bridge.apply(&self.settings); if let Some(paths) = self.paths.as_ref().filter(|_| self.applied.language != self.settings.language) { strings::set(Catalogue::load(&paths.languages(), &self.settings.language).0); @@ -203,6 +207,12 @@ impl App { } None => { self.main.show(ui, &t, &self.settings); + let window = ui.ctx().content_rect(); + let at = egui::pos2(window.right() - crate::tokens::space::L, window.bottom() - self.main.floor() - crate::tokens::space::L); + let on = self.settings.mode == medlar_core::settings::Mode::Snail; + if crate::ui::snail::button(ui.ctx(), &t, at, on, &keys::label(Action::Snail)) { + self.run(ui, Action::Snail); + } if let Some(change) = self.main.change.take() { change.apply(&mut self.settings); } @@ -252,50 +262,99 @@ impl App { /// What the tray and the notifications ask for, and what they are told. fn shell(&mut self, ui: &Ui) { - let Some(shell) = &mut self.shell else { return }; let ctx = ui.ctx(); - if ctx.input(|i| i.viewport().close_requested()) && shell.hides_on_close(&self.settings) { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false)); + for what in self.shell_tick() { + match self.act(what) { + Some(Do::Show) => { + ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + Some(Do::Quit) => self.quit(ctx), + _ => {} + } + motion::keep_alive(); } + } + + /// Tells the tray, the notifications and the launcher what changed; what they asked for comes back. + fn shell_tick(&mut self) -> Vec { + let Some(shell) = &mut self.shell else { return vec![] }; let shot = match self.main.bridge.data() { Data::Ready(shot, _) => Some(shot), _ => None, }; - use crate::shell::Do; - for what in shell.tick(&self.settings, shot.as_deref()) { - let show = |ctx: &Context| { - ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); - ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - }; - match what { - Do::Show => show(ctx), - Do::Add => { - show(ctx); - self.main.adding.ask(crate::views::add::Request::default()); - } - Do::PauseAll => self.run(ui, Action::PauseAll), - Do::ResumeAll => self.run(ui, Action::ResumeAll), - Do::Mode(m) => crate::views::modes::Change::Mode(m).apply(&mut self.settings), - Do::Quit => { - if let Some(shell) = &mut self.shell { - shell.quitting = true; - } - ctx.send_viewport_cmd(egui::ViewportCommand::Close); - } - Do::Open(file) => { - crate::views::main::open_outside(&file.to_string_lossy()); - } - Do::Folder(file) => { - crate::views::main::reveal_outside(&file); - } - Do::SignIn(url, id) => { - show(ctx); - self.main.wish = Some(Wish::SignIn(url, vec![id])); - } - Do::Retry(id) => self.main.bridge.send(medlar_core::manager::Command::Resume(id)), + shell.tick(&self.settings, shot.as_deref()) + } + + /// Does what needs no window. What needs one comes back as `Show`, and `Quit` comes back as it is. + fn act(&mut self, what: Do) -> Option { + match what { + Do::Show | Do::Quit => return Some(what), + Do::Add => { + self.main.adding.ask(crate::views::add::Request::default()); + return Some(Do::Show); } + Do::SignIn(url, id) => { + self.main.wish = Some(Wish::SignIn(url, vec![id])); + return Some(Do::Show); + } + Do::PauseAll => self.main.all(false), + Do::ResumeAll => self.main.all(true), + Do::Mode(m) => crate::views::modes::Change::Mode(m).apply(&mut self.settings), + Do::Open(file) => { + open_outside(&file.to_string_lossy()); + } + Do::Folder(file) => { + crate::views::main::reveal_outside(&file); + } + Do::Retry(id) => self.main.bridge.send(medlar_core::manager::Command::Resume(id)), + } + None + } + + /// Closes for real, even with close to tray on. + fn quit(&mut self, ctx: &Context) { + if let Some(shell) = &mut self.shell { + shell.quitting = true; + } + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + + /// Whether the window that just closed leaves Medlar in the tray. + fn hides(&self) -> bool { + self.first.is_none() && self.shell.as_ref().is_some_and(|s| s.hides_on_close(&self.settings)) + } + + /// Runs without a window until one is wanted (true) or Quit is chosen (false). The engine, the port, the tray and + /// the notifications keep going; `wake` hears every repaint request, so nothing is polled while nothing happens. + fn hidden(&mut self, ctx: &Context, wake: &Receiver<()>) -> bool { + crate::views::incoming::take_raised(); + loop { + for what in self.shell_tick() { + match self.act(what) { + Some(Do::Show) => return true, + Some(Do::Quit) => return false, + _ => {} + } + } + self.inbox.tick(ctx, &self.settings, &mut self.main); + if crate::views::incoming::take_raised() || self.main.wish.is_some() { + return true; + } + if self.applied != self.settings { + self.main.bridge.apply(&self.settings); + self.applied = self.settings.clone(); + self.save(None); + } + if self.saving.as_ref().is_some_and(|s| s.is_finished()) { + self.saved(); + } + // Requests for later repaints are not heard: a slow look round covers them. + if wake.recv_timeout(std::time::Duration::from_secs(2)).is_err_and(|e| e == RecvTimeoutError::Disconnected) { + return false; + } + while wake.try_recv().is_ok() {} } } @@ -323,7 +382,7 @@ impl App { self.main.toasts.info("content_paste", tr!("clip.added", n = tasks.len())); self.main.bridge.add(tasks, secrets); } else if !links.is_empty() { - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + crate::views::incoming::raise(ctx); self.main.adding.ask(Request { text: links.join("\n"), literal: true, ..Request::default() }); } } @@ -389,7 +448,7 @@ impl App { let on = self.settings.mode == medlar_core::settings::Mode::Snail; self.main.toasts.info("slow_motion_video", if on { tr!("snail.on") } else { tr!("snail.off") }); } - Action::Quit => ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close), + Action::Quit => self.quit(ui.ctx()), other => { let anywhere = matches!(other, Action::ResumeAll | Action::PauseAll); if self.screen.is_some() && !anywhere { @@ -402,13 +461,14 @@ impl App { } } -/// The app and which of its screens the window shows. -struct Window { - app: App, +/// The app and which of its screens the window shows. The app outlives the window: closing to the tray ends the +/// window, not the app. +struct Window<'a> { + app: &'a mut App, show: fn(&mut App, &mut Ui), } -impl eframe::App for Window { +impl eframe::App for Window<'_> { fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { (self.show)(&mut self.app, ui); } @@ -417,10 +477,9 @@ impl eframe::App for Window { self.app.theme.surface.to_normalized_gamma_f32() } - /// Saves where the downloads are. + /// Writes the settings; the downloads are saved when the app quits. fn on_exit(&mut self, _: Option<&eframe::glow::Context>) { self.app.finish(); - self.app.main.bridge.close(); } /// Only the window's place and size are remembered. @@ -480,6 +539,62 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec) -> Exi log::warn!("language: {problem}"); } strings::set(catalogue); + // One context for every window, so that what holds it (engine, tray, port, second starts) wakes the next one too. + let ctx = Context::default(); + ctx.set_embed_viewports(false); + ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(2).unwrap_or(std::num::NonZeroUsize::MIN)); + let (tx, wake) = sync_channel(1); + ctx.set_repaint_observer(move |_| { + let _ = tx.try_send(()); + }); + let mut app = App::new(&ctx, settings, Sources::detect()); + let mut window = true; + if engine { + if app.settings.desktop_colors.is_none() { + app.first = Some(FirstRun::default()); + } + app.paths = Some(paths.clone()); + crate::instance::wake_with(&ctx); + app.inbox = Inbox::new(later.take(), args); + app.main.outside = open_outside; + app.main.reveal = crate::views::main::reveal_outside; + app.main.remember(paths.data.join("view.json")); + if let Some(damage) = damage { + app.main.toasts.error(damage_words(&damage), None); + } + let opening = Opening { paths: paths.clone(), settings: app.settings.clone(), bus: Bus::System }; + app.main.bridge = Bridge::open(opening, &ctx); + let shell = crate::shell::Shell::start(&ctx, &app.settings); + window = !(minimised && shell.tray.is_some() && app.first.is_none()); + app.shell = Some(shell); + } + let mut code = ExitCode::SUCCESS; + loop { + if window { + let this = &mut app; + let make: eframe::AppCreator<'_> = Box::new(move |_| Ok(Box::new(Window { app: this, show }))); + if let Err(e) = eframe::run_native_ext(APP_ID, options(&paths), Some(ctx.clone()), make) { + eprintln!("{}", tr!("app.no_window", why = e)); + code = ExitCode::FAILURE; + break; + } + if !app.hides() { + break; + } + log::info!("window closed; running in the tray"); + } + window = app.hidden(&ctx, &wake); + if !window { + break; + } + } + app.finish(); + app.main.bridge.close(); + code +} + +/// A new window, where the last one was. +fn options(paths: &Paths) -> eframe::NativeOptions { let mut viewport = ViewportBuilder::default() .with_title("Medlar") .with_app_id(APP_ID) @@ -488,43 +603,13 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec) -> Exi if let Some(rgba) = icons::app_rgba(128) { viewport = viewport.with_icon(Arc::new(egui::IconData { rgba, width: 128, height: 128 })); } - let options = eframe::NativeOptions { + eframe::NativeOptions { viewport, persist_window: true, persistence_path: Some(paths.data.join("window.ron")), + run_and_return: true, ..Default::default() - }; - let make = move |cc: &eframe::CreationContext| { - let mut app = App::new(&cc.egui_ctx, settings, Sources::detect()); - if engine { - if app.settings.desktop_colors.is_none() { - app.first = Some(FirstRun::default()); - } - app.paths = Some(paths.clone()); - crate::instance::wake_with(&cc.egui_ctx); - app.inbox = Inbox::new(later.take(), args.clone()); - app.main.outside = open_outside; - app.main.reveal = crate::views::main::reveal_outside; - app.main.remember(paths.data.join("view.json")); - if let Some(damage) = damage { - app.main.toasts.error(damage_words(&damage), None); - } - let opening = Opening { paths, settings: app.settings.clone(), bus: Bus::System }; - app.main.bridge = Bridge::open(opening, &cc.egui_ctx); - let shell = crate::shell::Shell::start(&cc.egui_ctx, &app.settings); - if minimised && shell.tray.is_some() { - cc.egui_ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false)); - } - app.shell = Some(shell); - } - Ok(Box::new(Window { app, show }) as Box) - }; - let made = eframe::run_native(APP_ID, options, Box::new(make)); - if let Err(e) = made { - eprintln!("{}", tr!("app.no_window", why = e)); - return ExitCode::FAILURE; } - ExitCode::SUCCESS } fn damage_words(damage: &Damage) -> String { diff --git a/crates/app/src/bridge.rs b/crates/app/src/bridge.rs index 12bc259..1c455ea 100644 --- a/crates/app/src/bridge.rs +++ b/crates/app/src/bridge.rs @@ -249,6 +249,11 @@ impl Bridge { Some(self.manager()?.probe(task, secret)) } + /// What a video site offers at the link. None without an engine. Ask for the answer with `poll`. + pub fn probe_video(&self, url: String) -> Option>> { + Some(self.manager()?.probe_video(url, None)) + } + /// Adds downloads. Their secrets are put in the keyring first, under the names the tasks have. pub fn add(&self, tasks: Vec, secrets: Vec<(String, Secret)>) { let (sites, manager) = match &mut *lock(&self.inner.engine) { diff --git a/crates/app/src/clipboard.rs b/crates/app/src/clipboard.rs index d78e76e..5012d38 100644 --- a/crates/app/src/clipboard.rs +++ b/crates/app/src/clipboard.rs @@ -13,6 +13,18 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use url::Url; +/// What the clipboard holds now, if it is new: not what was there at the start, not the same text again. +fn news(last: &mut Option, text: String) -> Option { + let new = last.as_ref().is_some_and(|l| *l != text); + *last = Some(text.clone()); + new.then_some(text) +} + +/// News that Medlar did not copy itself. +fn foreign(last: &mut Option, text: String, own: &str) -> Option { + news(last, text).filter(|t| t != own) +} + /// False once the clipboard could not be opened. static WORKS: AtomicBool = AtomicBool::new(true); @@ -73,14 +85,13 @@ impl Watch { continue; }; WORKS.store(true, Ordering::Relaxed); - let Ok(text) = b.get_text() else { continue }; - if last.is_none() { - last = Some(text); - } else if last.as_deref() != Some(&text) { - last = Some(text.clone()); - if *OWN.lock().unwrap() != text && tx.send(text).is_ok() { - ctx.request_repaint(); - } + // An empty clipboard has no text: that counts as "" so the first link copied is news. + let text = b.get_text().unwrap_or_default(); + let own = OWN.lock().unwrap().clone(); + if let Some(text) = foreign(&mut last, text, &own) + && tx.send(text).is_ok() + { + ctx.request_repaint(); } } }); @@ -106,6 +117,40 @@ impl Watch { #[cfg(test)] mod tests { + use super::{foreign, news}; + + /// S044: what the clipboard of the session in the environment holds, read the way the watcher reads it. + /// Run by hand inside a session: `MEDLAR_CLIP_EXPECT= cargo test -p medlar --lib live_clipboard -- --ignored`. + #[test] + #[ignore] + fn live_clipboard() { + let want = std::env::var("MEDLAR_CLIP_EXPECT").unwrap(); + let mut board = arboard::Clipboard::new().expect("the clipboard opens"); + let got = board.get_text(); + eprintln!("WAYLAND_DISPLAY={:?} DISPLAY={:?} got={got:?}", std::env::var("WAYLAND_DISPLAY"), std::env::var("DISPLAY")); + assert_eq!(got.unwrap_or_default(), want); + } + + /// S037: an empty clipboard at the start (no text) must not swallow the first link copied. + #[test] + fn first_copy_after_empty_start_is_news() { + let mut last = None; + assert_eq!(news(&mut last, String::new()), None); + assert_eq!(news(&mut last, "https://a/x.zip".into()).as_deref(), Some("https://a/x.zip")); + assert_eq!(news(&mut last, "https://a/x.zip".into()), None); + let mut last = None; + assert_eq!(news(&mut last, "there at start".into()), None); + assert_eq!(news(&mut last, "https://b".into()).as_deref(), Some("https://b")); + } + + /// S027 9: a link copied from inside Medlar is not offered back. + #[test] + fn own_copy_is_not_news() { + let mut last = Some(String::new()); + assert_eq!(foreign(&mut last, "https://a/own.zip".into(), "https://a/own.zip"), None); + assert_eq!(foreign(&mut last, "https://a/x.zip".into(), "https://a/own.zip").as_deref(), Some("https://a/x.zip")); + } + use super::links; #[test] diff --git a/crates/app/src/icondata.rs b/crates/app/src/icondata.rs index c85f54e..12b2baf 100644 --- a/crates/app/src/icondata.rs +++ b/crates/app/src/icondata.rs @@ -121,6 +121,8 @@ pub const ICONS: &[(&str, &str)] = &[ ("search", "M380 -320Q271 -320 195.5 -395.5Q120 -471 120 -580Q120 -689 195.5 -764.5Q271 -840 380 -840Q489 -840 564.5 -764.5Q640 -689 640 -580Q640 -536 626 -497Q612 -458 588 -428L812 -204Q823 -193 823 -176Q823 -159 812 -148Q801 -137 784 -137Q767 -137 756 -148L532 -372Q502 -348 463 -334Q424 -320 380 -320ZM380 -400Q455 -400 507.5 -452.5Q560 -505 560 -580Q560 -655 507.5 -707.5Q455 -760 380 -760Q305 -760 252.5 -707.5Q200 -655 200 -580Q200 -505 252.5 -452.5Q305 -400 380 -400Z"), ("security", "M480 -164Q577 -194 642 -282.5Q707 -371 718 -480H480V-795L240 -705Q240 -705 240 -705Q240 -705 240 -705V-516Q240 -505 240 -498Q240 -491 242 -480H480ZM480 -84Q473 -84 467 -85Q461 -86 455 -88Q320 -133 240 -254.5Q160 -376 160 -516V-705Q160 -730 174.5 -750Q189 -770 212 -779L452 -869Q466 -874 480 -874Q494 -874 508 -869L748 -779Q771 -770 785.5 -750Q800 -730 800 -705V-516Q800 -376 720 -254.5Q640 -133 505 -88Q499 -86 493 -85Q487 -84 480 -84Z"), ("select_all", "M160 -760Q143 -760 131.5 -771.5Q120 -783 120 -800Q120 -817 131.5 -828.5Q143 -840 160 -840Q177 -840 188.5 -828.5Q200 -817 200 -800Q200 -783 188.5 -771.5Q177 -760 160 -760ZM320 -760Q303 -760 291.5 -771.5Q280 -783 280 -800Q280 -817 291.5 -828.5Q303 -840 320 -840Q337 -840 348.5 -828.5Q360 -817 360 -800Q360 -783 348.5 -771.5Q337 -760 320 -760ZM480 -760Q463 -760 451.5 -771.5Q440 -783 440 -800Q440 -817 451.5 -828.5Q463 -840 480 -840Q497 -840 508.5 -828.5Q520 -817 520 -800Q520 -783 508.5 -771.5Q497 -760 480 -760ZM640 -760Q623 -760 611.5 -771.5Q600 -783 600 -800Q600 -817 611.5 -828.5Q623 -840 640 -840Q657 -840 668.5 -828.5Q680 -817 680 -800Q680 -783 668.5 -771.5Q657 -760 640 -760ZM800 -760Q783 -760 771.5 -771.5Q760 -783 760 -800Q760 -817 771.5 -828.5Q783 -840 800 -840Q817 -840 828.5 -828.5Q840 -817 840 -800Q840 -783 828.5 -771.5Q817 -760 800 -760ZM160 -600Q143 -600 131.5 -611.5Q120 -623 120 -640Q120 -657 131.5 -668.5Q143 -680 160 -680Q177 -680 188.5 -668.5Q200 -657 200 -640Q200 -623 188.5 -611.5Q177 -600 160 -600ZM800 -600Q783 -600 771.5 -611.5Q760 -623 760 -640Q760 -657 771.5 -668.5Q783 -680 800 -680Q817 -680 828.5 -668.5Q840 -657 840 -640Q840 -623 828.5 -611.5Q817 -600 800 -600ZM160 -440Q143 -440 131.5 -451.5Q120 -463 120 -480Q120 -497 131.5 -508.5Q143 -520 160 -520Q177 -520 188.5 -508.5Q200 -497 200 -480Q200 -463 188.5 -451.5Q177 -440 160 -440ZM800 -440Q783 -440 771.5 -451.5Q760 -463 760 -480Q760 -497 771.5 -508.5Q783 -520 800 -520Q817 -520 828.5 -508.5Q840 -497 840 -480Q840 -463 828.5 -451.5Q817 -440 800 -440ZM160 -280Q143 -280 131.5 -291.5Q120 -303 120 -320Q120 -337 131.5 -348.5Q143 -360 160 -360Q177 -360 188.5 -348.5Q200 -337 200 -320Q200 -303 188.5 -291.5Q177 -280 160 -280ZM800 -280Q783 -280 771.5 -291.5Q760 -303 760 -320Q760 -337 771.5 -348.5Q783 -360 800 -360Q817 -360 828.5 -348.5Q840 -337 840 -320Q840 -303 828.5 -291.5Q817 -280 800 -280ZM160 -120Q143 -120 131.5 -131.5Q120 -143 120 -160Q120 -177 131.5 -188.5Q143 -200 160 -200Q177 -200 188.5 -188.5Q200 -177 200 -160Q200 -143 188.5 -131.5Q177 -120 160 -120ZM320 -120Q303 -120 291.5 -131.5Q280 -143 280 -160Q280 -177 291.5 -188.5Q303 -200 320 -200Q337 -200 348.5 -188.5Q360 -177 360 -160Q360 -143 348.5 -131.5Q337 -120 320 -120ZM480 -120Q463 -120 451.5 -131.5Q440 -143 440 -160Q440 -177 451.5 -188.5Q463 -200 480 -200Q497 -200 508.5 -188.5Q520 -177 520 -160Q520 -143 508.5 -131.5Q497 -120 480 -120ZM640 -120Q623 -120 611.5 -131.5Q600 -143 600 -160Q600 -177 611.5 -188.5Q623 -200 640 -200Q657 -200 668.5 -188.5Q680 -177 680 -160Q680 -143 668.5 -131.5Q657 -120 640 -120ZM800 -120Q783 -120 771.5 -131.5Q760 -143 760 -160Q760 -177 771.5 -188.5Q783 -200 800 -200Q817 -200 828.5 -188.5Q840 -177 840 -160Q840 -143 828.5 -131.5Q817 -120 800 -120ZM360 -280Q327 -280 303.5 -303.5Q280 -327 280 -360V-600Q280 -633 303.5 -656.5Q327 -680 360 -680H600Q633 -680 656.5 -656.5Q680 -633 680 -600V-360Q680 -327 656.5 -303.5Q633 -280 600 -280ZM360 -360H600Q600 -360 600 -360Q600 -360 600 -360V-600Q600 -600 600 -600Q600 -600 600 -600H360Q360 -600 360 -600Q360 -600 360 -600V-360Q360 -360 360 -360Q360 -360 360 -360Z"), + ("send", "M792 -443 176 -183Q156 -175 138 -186.5Q120 -198 120 -220V-740Q120 -762 138 -773.5Q156 -785 176 -777L792 -517Q817 -506 817 -480Q817 -454 792 -443ZM200 -280 674 -480 200 -680V-540L440 -480L200 -420ZM200 -280V-480V-680V-540V-420Z"), + ("send_fill", "M792 -443 176 -183Q156 -175 138 -186.5Q120 -198 120 -220V-740Q120 -762 138 -773.5Q156 -785 176 -777L792 -517Q817 -506 817 -480Q817 -454 792 -443ZM200 -280 674 -480 200 -680V-540L440 -480L200 -420ZM200 -280 674 -480 200 -680V-540L120 -560V-400L200 -420Z"), ("settings", "M433 -80Q406 -80 386.5 -98Q367 -116 363 -142L354 -208Q341 -213 329.5 -220Q318 -227 307 -235L245 -209Q220 -198 195 -207Q170 -216 156 -239L109 -321Q95 -344 101 -370Q107 -396 128 -413L181 -453Q180 -460 180 -466.5Q180 -473 180 -480Q180 -487 180 -493.5Q180 -500 181 -507L128 -547Q107 -564 101 -590Q95 -616 109 -639L156 -721Q170 -744 195 -753Q220 -762 245 -751L307 -725Q318 -733 330 -740Q342 -747 354 -752L363 -818Q367 -844 386.5 -862Q406 -880 433 -880H527Q554 -880 573.5 -862Q593 -844 597 -818L606 -752Q619 -747 630.5 -740Q642 -733 653 -725L715 -751Q740 -762 765 -753Q790 -744 804 -721L851 -639Q865 -616 859 -590Q853 -564 832 -547L779 -507Q780 -500 780 -493.5Q780 -487 780 -480Q780 -473 780 -466.5Q780 -460 778 -453L831 -413Q852 -396 858 -370Q864 -344 850 -321L802 -239Q788 -216 763 -207Q738 -198 713 -209L653 -235Q642 -227 630 -220Q618 -213 606 -208L597 -142Q593 -116 573.5 -98Q554 -80 527 -80ZM440 -160H519L533 -266Q564 -274 590.5 -289.5Q617 -305 639 -327L738 -286L777 -354L691 -419Q696 -433 698 -448.5Q700 -464 700 -480Q700 -496 698 -511.5Q696 -527 691 -541L777 -606L738 -674L639 -632Q617 -655 590.5 -670.5Q564 -686 533 -694L520 -800H441L427 -694Q396 -686 369.5 -670.5Q343 -655 321 -633L222 -674L183 -606L269 -542Q264 -527 262 -512Q260 -497 260 -480Q260 -464 262 -449Q264 -434 269 -419L183 -354L222 -286L321 -328Q343 -305 369.5 -289.5Q396 -274 427 -266ZM482 -340Q540 -340 581 -381Q622 -422 622 -480Q622 -538 581 -579Q540 -620 482 -620Q423 -620 382.5 -579Q342 -538 342 -480Q342 -422 382.5 -381Q423 -340 482 -340ZM480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Z"), ("settings_fill", "M433 -80Q406 -80 386.5 -98Q367 -116 363 -142L354 -208Q341 -213 329.5 -220Q318 -227 307 -235L245 -209Q220 -198 195 -207Q170 -216 156 -239L109 -321Q95 -344 101 -370Q107 -396 128 -413L181 -453Q180 -460 180 -466.5Q180 -473 180 -480Q180 -487 180 -493.5Q180 -500 181 -507L128 -547Q107 -564 101 -590Q95 -616 109 -639L156 -721Q170 -744 195 -753Q220 -762 245 -751L307 -725Q318 -733 330 -740Q342 -747 354 -752L363 -818Q367 -844 386.5 -862Q406 -880 433 -880H527Q554 -880 573.5 -862Q593 -844 597 -818L606 -752Q619 -747 630.5 -740Q642 -733 653 -725L715 -751Q740 -762 765 -753Q790 -744 804 -721L851 -639Q865 -616 859 -590Q853 -564 832 -547L779 -507Q780 -500 780 -493.5Q780 -487 780 -480Q780 -473 780 -466.5Q780 -460 778 -453L831 -413Q852 -396 858 -370Q864 -344 850 -321L802 -239Q788 -216 763 -207Q738 -198 713 -209L653 -235Q642 -227 630 -220Q618 -213 606 -208L597 -142Q593 -116 573.5 -98Q554 -80 527 -80ZM440 -160H519L533 -266Q564 -274 590.5 -289.5Q617 -305 639 -327L738 -286L777 -354L691 -419Q696 -433 698 -448.5Q700 -464 700 -480Q700 -496 698 -511.5Q696 -527 691 -541L777 -606L738 -674L639 -632Q617 -655 590.5 -670.5Q564 -686 533 -694L520 -800H441L427 -694Q396 -686 369.5 -670.5Q343 -655 321 -633L222 -674L183 -606L269 -542Q264 -527 262 -512Q260 -497 260 -480Q260 -464 262 -449Q264 -434 269 -419L183 -354L222 -286L321 -328Q343 -305 369.5 -289.5Q396 -274 427 -266ZM482 -340Q540 -340 581 -381Q622 -422 622 -480Q622 -538 581 -579Q540 -620 482 -620Q423 -620 382.5 -579Q342 -538 342 -480Q342 -422 382.5 -381Q423 -340 482 -340ZM440 -160 427 -266Q396 -274 369.5 -289.5Q343 -305 321 -328L222 -286L183 -354L269 -419Q264 -434 262 -449Q260 -464 260 -480Q260 -497 262 -512Q264 -527 269 -542L183 -606L222 -674L321 -633Q343 -655 369.5 -670.5Q396 -686 427 -694L441 -800H520L533 -694Q564 -686 590.5 -670.5Q617 -655 639 -632L738 -674L777 -606L691 -541Q696 -527 698 -511.5Q700 -496 700 -480Q700 -464 698 -448.5Q696 -433 691 -419L777 -354L738 -286L639 -327Q617 -305 590.5 -289.5Q564 -274 533 -266L519 -160Z"), ("shield", "M480 -84Q473 -84 467 -85Q461 -86 455 -88Q320 -133 240 -254.5Q160 -376 160 -516V-705Q160 -730 174.5 -750Q189 -770 212 -779L452 -869Q466 -874 480 -874Q494 -874 508 -869L748 -779Q771 -770 785.5 -750Q800 -730 800 -705V-516Q800 -376 720 -254.5Q640 -133 505 -88Q499 -86 493 -85Q487 -84 480 -84ZM480 -164Q584 -197 652 -296Q720 -395 720 -516V-705Q720 -705 720 -705Q720 -705 720 -705L480 -795Q480 -795 480 -795Q480 -795 480 -795L240 -705Q240 -705 240 -705Q240 -705 240 -705V-516Q240 -395 308 -296Q376 -197 480 -164ZM480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Z"), diff --git a/crates/app/src/keys.rs b/crates/app/src/keys.rs index ccd944e..74705b5 100644 --- a/crates/app/src/keys.rs +++ b/crates/app/src/keys.rs @@ -174,6 +174,11 @@ impl Shortcut { moves.contains(&self.key) && !self.alt || self.key == Key::Tab || self.ctrl && !self.alt && !self.shift && edits.contains(&self.key) } + /// Copy, select all and the other editing keys: a focused text field owns them. + fn edits(self) -> bool { + self.ctrl && !self.alt && [Key::A, Key::C, Key::V, Key::X, Key::Z].contains(&self.key) + } + /// Would type something or press what has the keyboard, so it can't count everywhere. pub fn types(self) -> bool { let function = self.key.name().strip_prefix('F').is_some_and(|n| n.parse::().is_ok()); @@ -253,7 +258,7 @@ pub fn label(action: Action) -> String { /// Was its shortcut pressed? Nothing else sees it then. pub fn pressed(ui: &Ui, action: Action) -> bool { let Some(keys) = MAP.with_borrow(|m| m.get(&action).copied().unwrap_or_else(|| usual(action))) else { return false }; - if keys.types() && ui.ctx().text_edit_focused() { + if (keys.types() || keys.edits()) && ui.ctx().text_edit_focused() { return false; } ui.input_mut(|i| { @@ -282,6 +287,37 @@ mod tests { } } + #[test] + #[allow(deprecated)] + fn a_focused_field_keeps_copy_and_select_all() { + use eframe::egui::{Context, Id, RawInput, TextEdit}; + let ctx = Context::default(); + let mut text = String::from("abc"); + let id = Id::new("field"); + let mut run = |events: Vec, focus: bool| { + let mut got = (false, false); + let input = RawInput { events, ..RawInput::default() }; + let mut out = ctx.run_ui(input, |ui| { + let r = ui.add(TextEdit::singleline(&mut text).id(id)); + if focus { + r.request_focus(); + } + got = (pressed(ui, Action::Copy), pressed(ui, Action::SelectAll)); + }); + out.textures_delta.clear(); + got + }; + let ctrl = Modifiers::CTRL; + let keys = |k| vec![Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: ctrl }]; + run(vec![], true); + run(vec![], true); + assert_eq!(run(vec![Event::Copy], true), (false, false), "field has focus"); + assert_eq!(run(keys(Key::A), true), (false, false)); + ctx.memory_mut(|m| m.surrender_focus(id)); + run(vec![], false); + assert_eq!(run(vec![Event::Copy], false).0, true, "list copies without a field"); + } + #[test] fn shortcuts_are_read_and_written_the_same() { for text in ["Ctrl+N", "Alt+Up", "Shift+Del", "F2", "Ctrl+Alt+Shift+Enter", "Ctrl+,", "Space"] { diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index aa4351f..06b4434 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -14,6 +14,7 @@ pub mod instance; pub mod keys; pub mod launcher; pub mod motion; +pub mod niri; pub mod notify; pub mod shell; pub mod theme; diff --git a/crates/app/src/niri.rs b/crates/app/src/niri.rs new file mode 100644 index 0000000..0333189 --- /dev/null +++ b/crates/app/src/niri.rs @@ -0,0 +1,90 @@ +//! Takes focus on niri over its IPC socket. niri only marks a window urgent when an app asks for focus without a +//! user input, so a download from the browser would not bring Medlar forward. The socket speaks one JSON value per line. + +use std::io::{BufRead, BufReader, Write}; +use std::os::unix::net::UnixStream; +use std::path::Path; +use std::time::Duration; + +/// The id of the window of process `pid` with app id `medlar`, from niri's `Windows` answer. +fn find(reply: &str, pid: u32) -> Option { + let v: serde_json::Value = serde_json::from_str(reply).ok()?; + v["Ok"]["Windows"].as_array()?.iter() + .find(|w| w["pid"].as_u64() == Some(pid as u64) && w["app_id"].as_str() == Some("medlar")) + .and_then(|w| w["id"].as_u64()) +} + +fn ask(stream: &mut UnixStream, line: &str) -> std::io::Result { + stream.write_all(line.as_bytes())?; + stream.write_all(b"\n")?; + let mut reply = String::new(); + BufReader::new(&*stream).read_line(&mut reply)?; + Ok(reply) +} + +/// Asks niri at `socket` to focus the window of `pid`. Errors when there is no such window (yet) or niri refuses. +pub fn focus(socket: &Path, pid: u32) -> std::io::Result { + let bad = |m: &str| std::io::Error::new(std::io::ErrorKind::Other, m.to_string()); + let mut s = UnixStream::connect(socket)?; + s.set_read_timeout(Some(Duration::from_secs(2)))?; + s.set_write_timeout(Some(Duration::from_secs(2)))?; + let id = find(&ask(&mut s, "\"Windows\"")?, pid).ok_or_else(|| bad("no window"))?; + let reply = ask(&mut s, &format!("{{\"Action\":{{\"FocusWindow\":{{\"id\":{id}}}}}}}"))?; + if reply.contains("\"Ok\"") { Ok(id) } else { Err(bad("refused")) } +} + +/// In the background: the window may still be opening, so it looks for a few seconds. Does nothing outside niri. +pub fn bring_forward() { + let Some(socket) = std::env::var_os("NIRI_SOCKET") else { return }; + std::thread::spawn(move || { + for _ in 0..15 { + if focus(Path::new(&socket), std::process::id()).is_ok() { + return; + } + std::thread::sleep(Duration::from_millis(200)); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::net::UnixListener; + + #[test] + fn finds_our_window() { + let r = r#"{"Ok":{"Windows":[{"id":3,"app_id":"medlar","pid":10},{"id":7,"app_id":"medlar","pid":42},{"id":9,"app_id":"other","pid":42}]}}"#; + assert_eq!(find(r, 42), Some(7)); + assert_eq!(find(r, 5), None); + assert_eq!(find("garbage", 42), None); + } + + #[test] + fn asks_niri_to_focus_and_fails_softly() { + let dir = std::env::temp_dir().join(format!("medlar-niri-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("sock"); + let l = UnixListener::bind(&path).unwrap(); + let t = std::thread::spawn(move || { + let (s, _) = l.accept().unwrap(); + let mut w = s.try_clone().unwrap(); + let mut r = BufReader::new(s); + let mut seen = vec![]; + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + seen.push(line.trim().to_string()); + w.write_all(b"{\"Ok\":{\"Windows\":[{\"id\":7,\"app_id\":\"medlar\",\"pid\":42}]}}\n").unwrap(); + line.clear(); + r.read_line(&mut line).unwrap(); + seen.push(line.trim().to_string()); + w.write_all(b"{\"Ok\":\"Handled\"}\n").unwrap(); + seen + }); + assert_eq!(focus(&path, 42).unwrap(), 7); + let seen = t.join().unwrap(); + assert_eq!(seen[0], "\"Windows\""); + assert_eq!(seen[1], r#"{"Action":{"FocusWindow":{"id":7}}}"#); + assert!(focus(&dir.join("none"), 42).is_err()); + std::fs::remove_dir_all(&dir).ok(); + } +} diff --git a/crates/app/src/notify.rs b/crates/app/src/notify.rs index 8001f04..a40293a 100644 --- a/crates/app/src/notify.rs +++ b/crates/app/src/notify.rs @@ -38,7 +38,7 @@ fn working(s: State) -> bool { impl Watcher { pub fn feed(&mut self, shot: &Snapshot) -> Vec { let mut out = vec![]; - let mut busy = false; + let (mut busy, mut paused) = (false, false); for v in shot.iter() { let (id, state) = (v.id(), v.state()); busy |= working(state); @@ -57,12 +57,16 @@ impl Watcher { Some(e) if e.kind == Some(ErrorKind::Login) => out.push(Event::Login { id, name: t.name.clone(), url: t.url.clone() }), e => out.push(Event::Failed { id, name: t.name.clone(), why: e.as_ref().map(|e| e.detail.clone()).unwrap_or_default() }), }, + State::Paused => paused = true, _ => {} } } if self.started && self.busy && !busy && self.finished { self.finished = false; - out.push(Event::AllDone); + // The last one being paused is not an end. + if !paused { + out.push(Event::AllDone); + } } self.busy = busy; self.started = true; diff --git a/crates/app/src/shell.rs b/crates/app/src/shell.rs index 2d2a568..e2cffb5 100644 --- a/crates/app/src/shell.rs +++ b/crates/app/src/shell.rs @@ -1,5 +1,6 @@ //! What the window shares with the desktop: tray, notifications, launcher progress and autostart. -//! One `Shell` per window; each part is left out when the desktop has no host for it. +//! One `Shell` per run; it outlives the window, so that closing to the tray works where windows cannot hide (Wayland). +//! Each part is left out when the desktop has no host for it. use crate::launcher::Launcher; use crate::notify::{Notifier, Watcher}; @@ -33,6 +34,9 @@ pub struct Shell { watcher: Watcher, rx: Receiver, shown: Option, + /// The tray speed is the same held value as the big number. + calm: crate::ui::odometer::Calm, + clock: std::time::Instant, rev: u64, /// What autostart was last made to match. autostart: (bool, bool), @@ -52,15 +56,17 @@ impl Shell { watcher: Watcher::default(), rx, shown: None, + calm: Default::default(), + clock: std::time::Instant::now(), rev: u64::MAX, autostart: (settings.autostart, settings.start_minimised), quitting: false, } } - /// Whether closing the window hides it instead. + /// Whether closing the window leaves Medlar running in the tray instead of quitting. pub fn hides_on_close(&self, settings: &Settings) -> bool { - !self.quitting && settings.close_to_tray && self.tray.is_some() + hides(self.quitting, settings.close_to_tray, self.tray.is_some()) } /// Once per frame: what was asked comes back, what changed goes out. @@ -81,7 +87,9 @@ impl Shell { notes.send(&events, settings); } } - let state = TrayState::of(shot, settings.mode); + let mut state = TrayState::of(shot, settings.mode); + let held = self.calm.feed(self.clock.elapsed().as_secs_f64(), shot.totals.speed); + state.speed = (held / 1024.0).round() as u64 * 1024; if self.shown.as_ref() != Some(&state) { if let Some(tray) = &self.tray { tray.set(state.clone()); @@ -95,3 +103,22 @@ impl Shell { self.rx.try_iter().collect() } } + +/// Closing hides to the tray only when the user wants it, a tray host shows the icon, and no quit was asked for. +pub fn hides(quitting: bool, close_to_tray: bool, host: bool) -> bool { + !quitting && close_to_tray && host +} + +#[cfg(test)] +mod tests { + use super::hides; + + #[test] + fn close_hides_only_with_tray_on_a_host_and_no_quit() { + assert!(hides(false, true, true)); + assert!(!hides(false, false, true), "close to tray off quits"); + assert!(!hides(false, true, false), "no tray host quits"); + assert!(!hides(true, true, true), "Quit and Ctrl+Q quit"); + assert!(!hides(true, false, false)); + } +} diff --git a/crates/app/src/ui/dialog.rs b/crates/app/src/ui/dialog.rs index e30de03..3cca7c4 100644 --- a/crates/app/src/ui/dialog.rs +++ b/crates/app/src/ui/dialog.rs @@ -227,7 +227,8 @@ impl<'a> Dialog<'a> { } }); let height = (ui.min_rect().height() + 2.0 * pad).min(room.height()); - if known != Some(height) { + // Half a pixel of drift between passes must not start a frame loop. + if known.is_none_or(|k| (k - height).abs() > 0.5) { ctx.data_mut(|d| d.insert_temp(key, height)); ctx.request_repaint(); } diff --git a/crates/app/src/ui/mod.rs b/crates/app/src/ui/mod.rs index 9507059..6ca1210 100644 --- a/crates/app/src/ui/mod.rs +++ b/crates/app/src/ui/mod.rs @@ -11,5 +11,6 @@ pub mod widgets; pub mod graph; pub mod odometer; pub mod parts; +pub mod snail; pub mod shape; pub mod wave; diff --git a/crates/app/src/ui/odometer.rs b/crates/app/src/ui/odometer.rs index 4a63b4c..bdd59e3 100644 --- a/crates/app/src/ui/odometer.rs +++ b/crates/app/src/ui/odometer.rs @@ -96,9 +96,50 @@ pub fn odometer(ui: &Ui, id: Id, pos: Pos2, words: &str, font: FontId, color: Co Rect::from_min_max(pos2(pos.x, top), pos2(x, top + height)) } +/// A live speed that can be read: the average of the last `WINDOW` seconds, kept on show for `HOLD` seconds before it +/// changes, and not changed at all for what its digits don't show. Big jumps (start, stop, pause) pass at once. +#[derive(Clone, Default)] +pub struct Calm { + seen: std::collections::VecDeque<(f64, f64)>, + shown: f64, + since: f64, +} + +pub const HOLD: f64 = 1.0; +const WINDOW: f64 = 2.0; + +impl Calm { + /// `raw` is the speed measured at `now` (seconds); gives back what to show. + pub fn feed(&mut self, now: f64, raw: f64) -> f64 { + let raw = if raw.is_finite() { raw.max(0.0) } else { 0.0 }; + self.seen.push_back((now, raw)); + while self.seen.front().is_some_and(|(at, _)| *at < now - WINDOW) { + self.seen.pop_front(); + } + let jump = raw == 0.0 || self.shown == 0.0 || raw > self.shown * 3.0 || raw < self.shown / 3.0; + if jump { + self.seen.clear(); + self.seen.push_back((now, raw)); + (self.shown, self.since) = (raw, now); + } else if now - self.since >= HOLD { + let mean = self.seen.iter().map(|(_, v)| v).sum::() / self.seen.len() as f64; + if scaled(mean) != scaled(self.shown) { + (self.shown, self.since) = (mean, now); + } + } + self.shown + } +} + /// The big speed number with its unit. Returns where it ended up. pub fn speed(ui: &Ui, t: &Theme, id: Id, pos: Pos2, bytes_per_second: f64) -> Rect { use crate::{fonts, tokens::{space, text}}; + let now = ui.input(|i| i.time); + let bytes_per_second = ui.data_mut(|d| d.get_temp_mut_or_default::(id.with("calm")).feed(now, bytes_per_second)); + if bytes_per_second > 0.0 { + // The hold ends by itself; idle draws nothing. + ui.ctx().request_repaint_after_secs(HOLD as f32); + } let all = rate(bytes_per_second); let number = scaled(bytes_per_second).0; let (before, after) = all.split_once(&number).unwrap_or(("", &all)); @@ -117,6 +158,29 @@ mod tests { assert_eq!([f64::NAN, -4.0, 2_000.0].map(rate), ["0 B/s", "0 B/s", "2.0 kB/s"]); } + #[test] + fn a_noisy_speed_changes_at_most_once_per_hold() { + let mut calm = Calm::default(); + let mut seed = 12345_u64; + let (mut last, mut changes) = (f64::NAN, 0); + // 20 seconds at 20 samples a second around 480 kB/s, plus or minus a third. + for i in 0..400 { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 33) % 1000) as f64 / 1000.0 - 0.5; + let shown = calm.feed(i as f64 * 0.05, 480_000.0 * (1.0 + noise * 0.66)); + if shown != last { + changes += 1; + last = shown; + } + } + assert!(changes <= 21, "{changes} changes in 20 s"); + let mut calm = Calm::default(); + assert_eq!([calm.feed(0.0, 0.0), calm.feed(0.1, 500_000.0), calm.feed(0.2, 0.0)], [0.0, 500_000.0, 0.0], "start and stop pass at once"); + let mut calm = Calm::default(); + calm.feed(0.0, 488_300.0); + assert_eq!(calm.feed(2.0, 488_340.0), 488_300.0, "below the shown precision nothing rolls"); + } + #[test] fn digits_take_the_short_way() { assert_eq!([nearest(9.0, 0.0), nearest(0.0, 9.0), nearest(12.0, 1.0), nearest(3.0, 5.0)], [10.0, -1.0, 11.0, 5.0]); diff --git a/crates/app/src/ui/snail.rs b/crates/app/src/ui/snail.rs new file mode 100644 index 0000000..ded400c --- /dev/null +++ b/crates/app/src/ui/snail.rs @@ -0,0 +1,114 @@ +//! The snail button at the window's corner: snail mode on or off, with a small snail drawn as a vector shape. + +use super::widgets::{cr, feel, tip}; +use crate::motion; +use crate::theme::{Theme, alpha}; +use crate::tokens::{self, elevation}; +use eframe::egui::accesskit::Role; +use eframe::egui::{Area, Color32, Context, Id, Order, Painter, Pos2, Rect, Sense, Shape, Stroke, WidgetInfo, vec2}; +use medlar_core::settings::Motion; +use medlar_core::tr; + +/// Frames per second of the crawl: it is cheap, and it is the only loop that runs while nothing else moves. +const FPS: f32 = 15.0; + +/// A round button with its bottom right corner at `at`. True when it was clicked. +#[allow(deprecated)] +pub fn button(ctx: &Context, t: &Theme, at: Pos2, on: bool, keys: &str) -> bool { + let side = tokens::size::LARGE; + let rect = Rect::from_min_max(at - vec2(side, side), at); + let id = Id::new("snail button"); + let name = tr!("snail.button"); + let mut clicked = false; + Area::new(id).order(Order::Middle).fixed_pos(rect.min).constrain(false).fade_in(false).sense(Sense::hover()).show(ctx, |ui| { + let r = ui.interact(rect, id.with("hit"), Sense::click()); + r.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, &name)); + let f = feel(&r, true); + let (fill, ink) = if on { (t.secondary_container, t.on_secondary_container) } else { (t.high, t.on_variant) }; + let p = ui.painter(); + p.add(elevation::floating(t.dark).as_shape(rect, cr(side / 2.0))); + p.circle_filled(rect.center(), side / 2.0 - f.press.max(0.0) * 2.0, fill); + if f.tint > 0.0 { + p.circle_filled(rect.center(), side / 2.0, alpha(ink, f.tint)); + } + // Reduced motion is a small sway, off is still; nothing moves while it is off. + let amount = match motion::level() { + Motion::Off => 0.0, + Motion::Reduced => 0.35, + _ => 1.0, + }; + let phase = if on && amount > 0.0 { + ctx.request_repaint_after_secs(1.0 / FPS); + ctx.input(|i| i.time) as f32 + } else { + 0.0 + }; + draw(p, rect.center(), side * 0.5, ink, on, phase, amount); + tip(&r, t, &name, keys); + clicked = r.clicked(); + }); + clicked +} + +/// The snail in a square of `size`, facing right. `phase` in seconds moves the stretch of its body and the sway of its shell. +pub fn draw(p: &Painter, center: Pos2, size: f32, ink: Color32, filled: bool, phase: f32, amount: f32) { + let u = size / 2.0; + let wave = (phase * 2.4).sin() * amount; + let stroke = Stroke::new((size / 14.0).max(1.5), ink); + // The foot stretches and shrinks a little. + let tail = center + vec2(-0.9 * u - 0.08 * u * wave, 0.62 * u); + let neck = center + vec2(0.55 * u + 0.1 * u * wave, 0.62 * u); + p.line_segment([tail, neck], stroke); + // The head and its feelers. + let head = neck + vec2(0.1 * u, -0.28 * u); + p.line_segment([neck, head], stroke); + let sway = 0.12 * u * wave; + for dx in [0.0, 0.3] { + let base = head + vec2(0.04 * u + dx * u * 0.5, -0.04 * u); + p.line_segment([base, base + vec2(0.1 * u + sway, -0.3 * u)], Stroke::new(stroke.width * 0.7, ink)); + } + p.circle_filled(head, 0.17 * u, ink); + // The shell: a disc (filled when on) with a spiral, turned a little by the sway. + let shell = center + vec2(-0.2 * u, -0.05 * u); + let r = 0.62 * u; + if filled { + p.circle_filled(shell, r, alpha(ink, 0.28)); + } + p.circle_stroke(shell, r, stroke); + let turn = 0.15 * wave; + let points: Vec = (0..=36) + .map(|i| { + let a = i as f32 / 36.0 * 3.2 * std::f32::consts::PI; + let radius = r * 0.9 * (a / (3.2 * std::f32::consts::PI)); + shell + vec2((a + turn).cos(), (a + turn).sin()) * radius + }) + .collect(); + p.add(Shape::line(points, Stroke::new(stroke.width * 0.8, ink))); +} + +#[cfg(test)] +mod tests { + use super::*; + use eframe::egui::{RawInput, ViewportId}; + + #[test] + fn off_asks_for_no_frames_and_on_asks_for_a_slow_loop() { + let t = Theme::build(&medlar_core::settings::Settings::default(), crate::desktop::Desktop::default()); + use eframe::egui::pos2;; + for (on, repaints) in [(false, false), (true, true)] { + let ctx = Context::default(); + let mut out = None; + // The first frames settle the layout; the last one tells. + for _ in 0..4 { + let mut o = ctx.run_ui(RawInput::default(), |ui| { + button(ui.ctx(), &t, pos2(300.0, 300.0), on, "Ctrl+Shift+S"); + }); + o.textures_delta.clear(); + out = Some(o); + } + let out = out.unwrap(); + let after = out.viewport_output[&ViewportId::ROOT].repaint_delay; + assert_eq!(after < std::time::Duration::from_secs(1), repaints, "on={on}: {after:?}"); + } + } +} diff --git a/crates/app/src/ui/wave.rs b/crates/app/src/ui/wave.rs index d7f8962..636766d 100644 --- a/crates/app/src/ui/wave.rs +++ b/crates/app/src/ui/wave.rs @@ -293,6 +293,17 @@ impl Ink { } } +static ONE_BAR: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Follows the setting: one continuous bar, or one per part. +pub fn set_one_bar(one: bool) { + ONE_BAR.store(one, std::sync::atomic::Ordering::Relaxed); +} + +pub fn one_bar() -> bool { + ONE_BAR.load(std::sync::atomic::Ordering::Relaxed) +} + /// What a bar shows. `parts` are the file's ranges in order; bytes between them count as missing. #[derive(Clone, Copy, Default)] pub struct Bar<'a> { diff --git a/crates/app/src/views/add/draw.rs b/crates/app/src/views/add/draw.rs index 1dfb77d..5fd0518 100644 --- a/crates/app/src/views/add/draw.rs +++ b/crates/app/src/views/add/draw.rs @@ -76,7 +76,7 @@ impl Add { }; // Nothing is made of the rest when another download goes on. let free = matches!(choice, Choice::Show | Choice::Resume); - let good = n > 0 && (free || !wrong.any()); + let good = n > 0 && (free || !wrong.any() && !self.video_empty()); let title = tr!("add.title"); let open = self.open; let dialog = Dialog::new("add", &title, &verb).width(size::DIALOG_L).enabled(good).busy(self.check.busy()); @@ -99,6 +99,12 @@ impl Add { if !matches!(self.choice(), Choice::Download) { return; } + match &mut self.video { + Some(Page::Looking) => say(ui, &tr!("video.looking"), t.on_variant), + Some(Page::Failed(why)) => say(ui, why, t.error), + Some(Page::Ready(video)) => video.show(ui, t), + None => {} + } if !self.many() { let (label, hint) = (tr!("add.name"), tr!("add.name_hint")); let field = Field::new(&label).hint(&hint); @@ -106,6 +112,7 @@ impl Add { let r = field.show(ui, t, &mut self.name); if r.changed() { self.name_own = !self.name.trim().is_empty(); + self.name_typed = self.name_own; } } self.where_to(ui, t, cx, wrong); @@ -154,6 +161,7 @@ impl Add { _ if self.single().is_none() => tr!("add.nothing"), Look::Nothing => tr!("add.unknown"), Look::Waits(_) | Look::Asks(_) => tr!("add.asking", host = host), + Look::Found(_) if matches!(self.video, Some(Page::Ready(_))) => tr!("video.title"), Look::Found(p) if p.page => tr!("add.page"), Look::Found(p) => { let size = p.size.map_or_else(|| tr!("add.no_size"), amount); @@ -193,7 +201,7 @@ impl Add { let galley = p.layout_job(job); p.galley(pos2(x, rect.center().y - galley.size().y / 2.0), galley, ink); } else { - let warn = matches!(&self.look, Look::Found(p) if p.page); + let warn = matches!(&self.look, Look::Found(p) if p.page) && !matches!(self.video, Some(Page::Ready(_))); left(p, pos2(x, rect.center().y - 11.0), line(p, &self.name, fonts::med(text::BODY), ink, end - x)); left(p, pos2(x, rect.center().y + 11.0), line(p, &words, fonts::ui(text::LABEL), if warn { t.warning } else { faint }, end - x)); } diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs index 82eaa38..f71248f 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -10,6 +10,7 @@ use crate::ui::shape::Kind; use crate::ui::toast::Toasts; use crate::views::list::model::{kind_key, kind_of}; use crate::views::main::Reply as Click; +use crate::views::video::{Page, Video}; use chrono::{Days, Local, NaiveDateTime, NaiveTime}; use eframe::egui::{Context, Ui}; use medlar_core::auth::{Login, take_login}; @@ -340,6 +341,8 @@ pub struct Add { pub name: String, /// The user wrote it. name_own: bool, + /// The user typed the name, so the server never replaces it. + name_typed: bool, rules: Vec, base: PathBuf, pub folder: String, @@ -365,6 +368,9 @@ pub struct Add { focus_links: bool, asked: Option, pub look: Look, + /// A video site's page at the single link; None when it is not one. Its choice goes to yt-dlp. + pub video: Option, + video_asked: Option>>, /// Tests put answers here themselves. pub still: bool, /// What `known` was found for. @@ -399,6 +405,7 @@ impl Add { twice: Twice::Skip, name: from.name.clone().unwrap_or_default(), name_own: from.name.is_some(), + name_typed: false, rules: settings.rules.clone(), base: download_folder(settings), folder: download_folder(settings).display().to_string(), @@ -422,6 +429,8 @@ impl Add { focus_links: true, asked: None, look: Look::Nothing, + video: None, + video_asked: None, still: false, sought: None, known: None, @@ -512,6 +521,7 @@ impl Add { self.read_text(); self.usual_folder(cx); self.ask_server(ctx, cx); + self.follow_video(ctx); self.seek(cx); self.ask_space(ctx); if self.check.follow(ctx) && self.check.good().is_some_and(|c| c.verdict() == Verdict::Same) { @@ -579,6 +589,7 @@ impl Add { if self.asked != asked { self.look = if asked.is_some() { Look::Waits(now + PAUSE) } else { Look::Nothing }; self.asked = asked; + (self.video, self.video_asked) = (None, None); if !self.name_own { self.name = self.single().map(name_of).unwrap_or_default(); } @@ -591,7 +602,16 @@ impl Add { ctx.request_repaint(); } Look::Asks(reply) => match poll(reply, ctx) { - Some(Ok(found)) => self.learned(found), + Some(Ok(found)) => { + // A web page may be a video site's. + if found.page + && let Some(asked) = &self.asked + { + self.video_asked = cx.bridge.probe_video(asked.task.url.clone()); + self.video = self.video_asked.is_some().then_some(Page::Looking); + } + self.learned(found); + } Some(Err(manager::Error::Link(f))) => self.look = Look::Failed(Some(f.kind), f.text.clone()), Some(Err(e)) => self.look = Look::Failed(None, e.to_string()), None => {} @@ -600,10 +620,39 @@ impl Add { } } + /// What yt-dlp said about the page. + fn follow_video(&mut self, ctx: &Context) { + let Some(answer) = self.video_asked.as_mut().and_then(|r| poll(r, ctx)) else { return }; + self.video_asked = None; + self.video = match answer { + Ok(probe) => { + if !self.name_own { + self.name = safe_name(&probe.title).unwrap_or_default(); + } + Some(Page::Ready(Box::new(Video::new(probe)))) + } + // Not a video site, or no yt-dlp to ask: the page itself is what the link gives. + Err(manager::Error::Link(f)) if matches!(f.kind, ErrorKind::BadLink | ErrorKind::Tool) => None, + Err(manager::Error::Link(f)) => Some(Page::Failed(f.text.clone())), + Err(e) => Some(Page::Failed(e.to_string())), + }; + } + + /// Nothing of a playlist is picked. + fn video_empty(&self) -> bool { + matches!(&self.video, Some(Page::Ready(v)) if v.empty()) + } + /// What the server said. pub fn learned(&mut self, found: Probed) { if !self.name_own { self.name = found.name.clone(); + } else if !self.name_typed { + // The name came with the link: a placeholder gives way to the server's. + if let Some(n) = medlar_core::http::prefer_name(self.name.trim(), &found.name) { + self.name = n; + self.name_own = false; + } } self.look = Look::Found(found); } @@ -814,6 +863,11 @@ impl Add { } task.mirrors = Batch::of(&self.mirrors, false).links.iter().map(|m| take_login(m).0).collect(); task.checksum = self.checksum_text(); + if let Some(Page::Ready(v)) = &self.video { + task.video = Some(v.choice()); + // The title until yt-dlp names the file. + task.name = self.name.trim().to_string(); + } } (tasks, secrets) } diff --git a/crates/app/src/views/control.rs b/crates/app/src/views/control.rs index c418e5f..3564857 100644 --- a/crates/app/src/views/control.rs +++ b/crates/app/src/views/control.rs @@ -19,7 +19,7 @@ use std::time::Duration; #[derive(Default)] pub struct Control { pub open: bool, - tab: usize, + pub tab: usize, mb: bool, queues: queues::Page, brush: u8, @@ -58,10 +58,10 @@ impl Control { let closed = dialog::sheet(ctx, t, "control", &tr!("control.title"), open, |ui| { let (a, b, c, d) = (tr!("control.speed"), tr!("control.queues"), tr!("control.week"), tr!("control.done")); let options = [ - Tab { icon: "speed", text: &a, count: None }, - Tab { icon: "stacks", text: &b, count: Some(lists.queues.len()) }, - Tab { icon: "schedule", text: &c, count: None }, - Tab { icon: "power_settings_new", text: &d, count: self.done.watcher.armed().map(|_| 1) }, + Tab { icon: "", text: &a, count: None }, + Tab { icon: "", text: &b, count: Some(lists.queues.len()) }, + Tab { icon: "", text: &c, count: None }, + Tab { icon: "", text: &d, count: self.done.watcher.armed().map(|_| 1) }, ]; tabs(ui, t, &tr!("control.title"), &options, &mut self.tab); ui.add_space(crate::tokens::space::L); diff --git a/crates/app/src/views/details/tabs.rs b/crates/app/src/views/details/tabs.rs index be58116..60763d5 100644 --- a/crates/app/src/views/details/tabs.rs +++ b/crates/app/src/views/details/tabs.rs @@ -439,3 +439,39 @@ pub fn checksum(ui: &mut Ui, cx: &mut Cx, paste: &mut String) { } let _ = title(v); } + +#[cfg(test)] +mod tests { + use super::*; + use medlar_core::snapshot::Line; + + #[test] + fn log_filter_and_secrets() { + let log: Log = [ + (1, "retry 2 of 5 after Cookie: sid=abc123"), + (2, "connected to https://u:pw@h.test/f?token=zzz"), + (3, "Retry in 4 s"), + ] + .into_iter() + .map(|(at, t)| Line { at, text: t.into() }) + .collect(); + let got = log_lines(&log, "RETRY"); + assert_eq!(got.len(), 2); + let all = log_lines(&log, "").join("\n"); + assert!(!all.contains("abc123") && !all.contains("pw@") && !all.contains("zzz"), "{all}"); + } + + #[test] + fn tag_colours_are_theme_roles_and_stable() { + use medlar_core::settings::{Contrast, Scheme}; + let seed = Color32::from_rgb(0x6a, 0x5a, 0xcd); + let (light, dark) = (Theme::from_seed(seed, false, false, Scheme::Tonal, Contrast::Standard), Theme::from_seed(seed, true, false, Scheme::Tonal, Contrast::Standard)); + for id in 0..12 { + let tag = Tag { id, ..Tag::default() }; + assert_eq!(tag_colour(&light, &tag), tag_colour(&light, &tag)); + let roles = |t: &Theme| [t.primary, t.tertiary, t.secondary, t.warning, t.success, t.error]; + assert_eq!(tag_colour(&light, &tag), roles(&light)[id as usize % 6]); + assert_eq!(tag_colour(&dark, &tag), roles(&dark)[id as usize % 6]); + } + } +} diff --git a/crates/app/src/views/incoming.rs b/crates/app/src/views/incoming.rs index ab438fe..8cd2712 100644 --- a/crates/app/src/views/incoming.rs +++ b/crates/app/src/views/incoming.rs @@ -9,7 +9,7 @@ use super::add::{Add, Checking, Request}; use super::main::Main; use crate::bridge::Data; use crate::views::connector; -use eframe::egui::{Context, ViewportCommand}; +use eframe::egui::{Context, UserAttentionType, ViewportCommand}; use medlar_core::connector::{Arrival, Connector, Incoming as Link}; use medlar_core::model::TaskId; use medlar_core::relink::{self, NewLink, Strength}; @@ -18,6 +18,7 @@ use medlar_core::tr; use std::collections::VecDeque; use std::path::PathBuf; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::Receiver; use tokio::sync::mpsc::UnboundedReceiver; @@ -38,6 +39,31 @@ pub struct Inbox { /// Downloads that wait for a link, and the check of the one that came. waiting: Vec<(TaskId, String, Checking)>, failed: bool, + /// The window asked for attention and has not had focus since. + attention: bool, +} + +/// Set by `raise`, so that a run without a window opens one. +static RAISED: AtomicBool = AtomicBool::new(false); + +/// The setting "bring forward", copied each frame because `raise` has no settings. +static FORWARD: AtomicBool = AtomicBool::new(true); + +/// Whether something asked for the window since the last call. +pub fn take_raised() -> bool { + RAISED.swap(false, Ordering::Relaxed) +} + +/// Brings the window forward, also from the tray. Where focus is refused (Wayland), it asks for attention. +pub fn raise(ctx: &Context) { + RAISED.store(true, Ordering::Relaxed); + ctx.send_viewport_cmd(ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(ViewportCommand::Focus); + ctx.send_viewport_cmd(ViewportCommand::RequestUserAttention(UserAttentionType::Critical)); + if FORWARD.load(Ordering::Relaxed) { + crate::niri::bring_forward(); + } } impl Inbox { @@ -48,10 +74,16 @@ impl Inbox { /// Once per frame. pub fn tick(&mut self, ctx: &Context, s: &Settings, main: &mut Main) { + if self.attention && ctx.input(|i| i.focused) { + self.attention = false; + ctx.send_viewport_cmd(ViewportCommand::RequestUserAttention(UserAttentionType::Reset)); + } + FORWARD.store(s.bring_forward, Ordering::Relaxed); self.port(ctx, s, main); if let Some(args) = &self.args { while let Ok(list) = args.try_recv() { - ctx.send_viewport_cmd(ViewportCommand::Focus); + raise(ctx); + self.attention = true; self.pending.extend(list.iter().filter_map(|a| of_arg(a)).map(Item::Asked)); } } @@ -148,9 +180,14 @@ impl Inbox { self.waiting.retain(|(_, _, c)| c.busy()); } + fn raise(&mut self, ctx: &Context) { + raise(ctx); + self.attention = true; + } + fn ask(&mut self, ctx: &Context, main: &mut Main, request: Request) { if main.adding.now().is_none() { - ctx.send_viewport_cmd(ViewportCommand::Focus); + self.raise(ctx); } main.adding.ask(request); } @@ -200,6 +237,7 @@ impl Inbox { main.bridge.add(tasks, secrets); } main.toasts.info("download", tr!("incoming.added", n = n)); + self.raise(ctx); return; } self.ask(ctx, main, request); @@ -226,7 +264,20 @@ pub fn of_arg(arg: &str) -> Option { #[cfg(test)] mod tests { - use super::of_arg; + use super::{of_arg, raise}; + use eframe::egui::{Context, RawInput, UserAttentionType, ViewportCommand, ViewportId}; + + #[test] + fn raising_shows_focuses_and_asks_for_attention() { + let ctx = Context::default(); + let mut out = ctx.run_ui(RawInput::default(), |ui| raise(ui.ctx())); + out.textures_delta.clear(); + let cmds = &out.viewport_output[&ViewportId::ROOT].commands; + assert!(cmds.contains(&ViewportCommand::Visible(true))); + assert!(cmds.contains(&ViewportCommand::Minimized(false))); + assert!(cmds.contains(&ViewportCommand::Focus)); + assert!(cmds.contains(&ViewportCommand::RequestUserAttention(UserAttentionType::Critical))); + } #[test] fn arguments() { diff --git a/crates/app/src/views/list/row.rs b/crates/app/src/views/list/row.rs index 6e37739..020b625 100644 --- a/crates/app/src/views/list/row.rs +++ b/crates/app/src/views/list/row.rs @@ -257,7 +257,7 @@ fn state_ink(t: &Theme, v: &TaskView) -> Color32 { fn bar(ui: &Ui, t: &Theme, rect: Rect, v: &TaskView) { let parts: Vec = v.parts.iter().map(|p| Part { start: p.start, end: p.end, done: p.done }).collect(); let whole = [Part { start: 0, end: v.size, done: v.downloaded }]; - let parts = if parts.is_empty() { &whole[..] } else { &parts[..] }; + let parts = if parts.is_empty() || wave::one_bar() { &whole[..] } else { &parts[..] }; let b = Bar { look: Look::from(v.state()), size: v.size, parts, speed: v.speed, checked: v.checked }; let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), wave::HEIGHT)); wave::bar(ui, t, id(v.id()).with("bar"), rect, &b); diff --git a/crates/app/src/views/main.rs b/crates/app/src/views/main.rs index d7ba18a..0d795e5 100644 --- a/crates/app/src/views/main.rs +++ b/crates/app/src/views/main.rs @@ -240,6 +240,18 @@ impl Main { } } + /// Resumes every paused download, or pauses every one that runs or waits. Also without a window. + pub fn all(&self, resume: bool) { + let Data::Ready(shot, _) = self.bridge.data() else { return }; + for v in shot.iter() { + match v.state() { + State::Paused if resume => self.bridge.send(Command::Resume(v.id())), + State::Running | State::Checking | State::Queued | State::Waiting if !resume => self.bridge.send(Command::Pause(v.id())), + _ => {} + } + } + } + /// Does an action by name; what this screen has no part in comes back. pub fn run(&mut self, ui: &Ui, action: Action) -> Option { match action { @@ -247,17 +259,7 @@ impl Main { Action::Find => self.asked.push(Order::Find), Action::Rail => self.toggle_rail(ui.ctx().content_rect().width()), Action::View => self.list.form = if self.list.form == Form::Cards { Form::Compact } else { Form::Cards }, - Action::ResumeAll | Action::PauseAll => { - let Data::Ready(shot, _) = self.bridge.data() else { return None }; - let resume = action == Action::ResumeAll; - for v in shot.iter() { - match v.state() { - State::Paused if resume => self.bridge.send(Command::Resume(v.id())), - State::Running | State::Checking | State::Queued | State::Waiting if !resume => self.bridge.send(Command::Pause(v.id())), - _ => {} - } - } - } + Action::ResumeAll | Action::PauseAll => self.all(action == Action::ResumeAll), a if a.entry().group == Where::List => { let order = self.list.perform(ui, a); self.asked.extend(order); @@ -278,7 +280,7 @@ impl Main { } /// How much at the bottom the toolbar takes. - fn floor(&self) -> f32 { + pub fn floor(&self) -> f32 { if self.list.selected.is_empty() { 0.0 } else { bar::TOOLBAR - space::L } } @@ -367,7 +369,8 @@ impl Main { } fn list_in(&mut self, ui: &mut Ui, t: &Theme, rest: Rect, lists: &Arc, orders: &mut Vec) { - let below = if self.list.selected.is_empty() { space::L } else { bar::TOOLBAR }; + // Room for the snail button that floats at the corner. + let below = if self.list.selected.is_empty() { size::LARGE + space::XL } else { bar::TOOLBAR + size::LARGE }; // The scroll bar stands in the margin, so rows end where everything else does. orders.extend(self.list.show(ui, t, rest.with_max_x(rest.right() + space::M), lists, below)); orders.extend(bar::selected(ui, t, rest, &mut self.list)); diff --git a/crates/app/src/views/rules.rs b/crates/app/src/views/rules.rs index def7912..5afac5c 100644 --- a/crates/app/src/views/rules.rs +++ b/crates/app/src/views/rules.rs @@ -124,7 +124,7 @@ fn summary(r: &Rule, lists: &Lists) -> String { then.push(tr!("rule.priority_is", priority = p.name())); } let when = if when.is_empty() { tr!("rule.any") } else { when.join(" · ") }; - let then = if then.is_empty() { String::new() } else { format!(" → {}", then.join(" · ")) }; + let then = if then.is_empty() { String::new() } else { format!(" goes to: {}", then.join(" · ")) }; let off = if r.enabled { String::new() } else { format!("{} · ", tr!("rule.off")) }; format!("{off}{when}{then}") } @@ -226,7 +226,7 @@ fn test_box(view: &mut View, cx: &mut Cx, ui: &mut Ui, lists: &Lists) { parts.extend(out.queue.map(|q| super::list::model::queue_name(lists, q))); parts.extend(out.priority.map(|p| p.name().to_string())); parts.extend(out.name); - parts.join(" → ") + parts.join(" · ") } }; ui.add(Label::new(RichText::new(answer).font(fonts::ui(text::BODY)).color(t.on_surface)).wrap()); diff --git a/crates/app/src/views/schedule.rs b/crates/app/src/views/schedule.rs index 742b02b..38edb22 100644 --- a/crates/app/src/views/schedule.rs +++ b/crates/app/src/views/schedule.rs @@ -200,11 +200,13 @@ pub struct Done { working: Option>>, can: Option>>, allowed: Vec, + /// What shuts down or suspends; logind, or a fake in tests. + pub power: std::sync::Arc, } impl Default for Done { fn default() -> Done { - Done { watcher: Watcher::default(), action: 0, scope: 0, even_failed: false, seconds: 60.0, program: String::new(), counting: None, working: None, can: None, allowed: vec![] } + Done { watcher: Watcher::default(), action: 0, scope: 0, even_failed: false, seconds: 60.0, program: String::new(), counting: None, working: None, can: None, allowed: vec![], power: std::sync::Arc::new(Logind) } } } @@ -241,8 +243,8 @@ impl Done { /// The picker, for the sheet. pub fn picker(&mut self, ui: &mut Ui, t: &Theme, queues: &[(QueueId, String)]) { if self.can.is_none() && self.allowed.is_empty() { - self.can = Some(bridge::beside(|| { - let p = Logind; + let p = self.power.clone(); + self.can = Some(bridge::beside(move || { (1..=6).map(|i| action_of(i, "").is_some_and(|a| p.can(&a))).collect() })); } @@ -275,7 +277,10 @@ impl Done { Combo::new(&tr!("done.scope"), &scopes, 260.0).show(ui, t, &mut self.scope); ui.add_space(space::S); let mut failed = self.even_failed; - crate::ui::widgets::Choice::new(&tr!("done.failed")).switch(ui, t, &mut failed); + ui.horizontal(|ui| { + crate::ui::widgets::Choice::new(&tr!("done.failed")).switch(ui, t, &mut failed); + ui.label(RichText::new(tr!("done.failed")).font(fonts::ui(text::BODY)).color(t.on_surface)); + }); self.even_failed = failed; ui.add_space(space::S); Number { label: &tr!("done.countdown"), unit: &tr!("unit.s"), range: 0.0..=3600.0, step: 5.0, enabled: true, width: 200.0, bare: false }.show(ui, t, &mut self.seconds); @@ -368,7 +373,10 @@ impl Done { runtime.block_on(run::run(&spec, &Vars::default())).map(|_| ()) })); } - other => self.working = Some(bridge::beside(move || Logind.perform(&other))), + other => { + let power = self.power.clone(); + self.working = Some(bridge::beside(move || power.perform(&other))); + } } } } diff --git a/crates/app/src/views/settings/rows.rs b/crates/app/src/views/settings/rows.rs index 94b63f1..f6666a1 100644 --- a/crates/app/src/views/settings/rows.rs +++ b/crates/app/src/views/settings/rows.rs @@ -5,7 +5,7 @@ use super::{Cx, View, backup, look, network, sites}; use crate::keys::{self, Action}; use crate::ui::dialog; use eframe::egui::Ui; -use medlar_core::settings::{Appearance, Contrast, Mode, Motion, Scheme, Settings}; +use medlar_core::settings::{Appearance, BarStyle, Contrast, Mode, Motion, Scheme, Settings}; use medlar_core::strings::{self, Catalogue}; use medlar_core::tr; use std::ops::RangeInclusive; @@ -169,6 +169,7 @@ const MODES: [Mode; 4] = [Mode::Low, Mode::Medium, Mode::High, Mode::Snail]; const APPEARANCES: [Appearance; 4] = [Appearance::Auto, Appearance::Light, Appearance::Dark, Appearance::Amoled]; const SCHEMES: [Scheme; 4] = [Scheme::Tonal, Scheme::Vibrant, Scheme::Expressive, Scheme::Mono]; const CONTRASTS: [Contrast; 3] = [Contrast::Standard, Contrast::Medium, Contrast::High]; +const BARS: [BarStyle; 2] = [BarStyle::Parts, BarStyle::One]; const MOTIONS: [Motion; 4] = [Motion::Off, Motion::Reduced, Motion::Normal, Motion::Expressive]; fn at(all: &[T], one: T) -> usize { @@ -199,6 +200,10 @@ macro_rules! limit { }; } +fn hours() -> String { + tr!("unit.hours_short") +} + fn mb() -> String { tr!("unit.mb_short") } @@ -257,6 +262,13 @@ static ROWS: &[Row] = &[ &["motion"], Kind::Choice { options: &["off", "reduced", "normal", "expressive"], get: |s| at(&MOTIONS, s.motion), set: |s, i| s.motion = MOTIONS[i] }, ), + row( + Page::Look, + "motion", + "bar", + &["bar"], + Kind::Choice { options: &["parts", "one"], get: |s| at(&BARS, s.bar), set: |s, i| s.bar = BARS[i] }, + ), row( Page::Look, "language", @@ -393,6 +405,15 @@ static ROWS: &[Row] = &[ row(Page::Browser, "browser", "auto_min_mb", &["auto_min_mb"], Kind::Number { unit: mb, range: 0.0..=100_000.0, step: 1.0, get: |s| s.auto_min_mb as f64, set: |s, v| s.auto_min_mb = v as u64 }), row(Page::Browser, "browser", "auto_max_mb", &["auto_max_mb"], Kind::Number { unit: mb, range: 0.0..=1_000_000.0, step: 1.0, get: |s| s.auto_max_mb as f64, set: |s, v| s.auto_max_mb = v as u64 }), row(Page::Browser, "browser", "browser_page", &[], Kind::Own(crate::views::connector::show)), + row(Page::Notifications, "window", "tray", &["tray"], Kind::Switch { get: |s| s.tray, set: |s, v| s.tray = v }), + row(Page::Notifications, "window", "close_to_tray", &["close_to_tray"], Kind::Switch { get: |s| s.close_to_tray, set: |s, v| s.close_to_tray = v }), + row(Page::Notifications, "window", "bring_forward", &["bring_forward"], Kind::Switch { get: |s| s.bring_forward, set: |s, v| s.bring_forward = v }), + row(Page::Notifications, "window", "start_minimised", &["start_minimised"], Kind::Switch { get: |s| s.start_minimised, set: |s, v| s.start_minimised = v }), + row(Page::Notifications, "window", "autostart", &["autostart"], Kind::Switch { get: |s| s.autostart, set: |s, v| s.autostart = v }), + row(Page::Notifications, "notify", "notify", &["notify"], Kind::Switch { get: |s| s.notify, set: |s, v| s.notify = v }), + row(Page::Notifications, "notify", "quiet", &["quiet"], Kind::Switch { get: |s| s.quiet, set: |s, v| s.quiet = v }), + row(Page::Notifications, "notify", "quiet_from", &["quiet_from"], Kind::Number { unit: hours, range: 0.0..=23.0, step: 1.0, get: |s| (s.quiet_from / 60) as f64, set: |s, v| s.quiet_from = v as u32 * 60 }), + row(Page::Notifications, "notify", "quiet_to", &["quiet_to"], Kind::Number { unit: hours, range: 0.0..=23.0, step: 1.0, get: |s| (s.quiet_to / 60) as f64, set: |s, v| s.quiet_to = v as u32 * 60 }), row(Page::Backup, "", "backup", &[], Kind::Own(backup::show)), ]; diff --git a/crates/app/src/views/target.rs b/crates/app/src/views/target.rs index 9ac2613..8814291 100644 --- a/crates/app/src/views/target.rs +++ b/crates/app/src/views/target.rs @@ -26,6 +26,7 @@ const OPEN: [f32; 2] = [SMALL + space::XXL + space::XL + space::XS, SMALL + 3.0 #[derive(Default)] pub struct Target { menu: bool, + calm: crate::ui::odometer::Calm, } enum Do { @@ -58,6 +59,10 @@ impl Target { let mut act = None; let mut dropped = vec![]; let menu = &mut self.menu; + let calm = self.calm.feed(ctx.input(|i| i.time), speed); + if calm > 0.0 { + ctx.request_repaint_after_secs(crate::ui::odometer::HOLD as f32); + } ctx.show_viewport_immediate(ViewportId::from_hash_of("drop target"), builder, |ui, class| { if class != ViewportClass::Immediate && class != ViewportClass::Root { // Embedded in the main window: nothing to show on its own. @@ -70,7 +75,7 @@ impl Target { let look = if speed > 0.0 { Look::Running } else { Look::Waiting }; wave::ring(ui, t, salt("target ring"), ring, look, None, speed); let p = ui.painter(); - p.text(pos2(full.center().x, ring.bottom() + space::S), Align2::CENTER_TOP, rate(speed), fonts::med(text::LABEL), t.on_surface); + p.text(pos2(full.center().x, ring.bottom() + space::S), Align2::CENTER_TOP, rate(calm), fonts::med(text::LABEL), t.on_surface); let r = ui.interact(ring, salt("target hit"), Sense::click_and_drag()); if r.drag_started() { ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag); diff --git a/crates/app/src/views/video.rs b/crates/app/src/views/video.rs index 36352f7..2eff105 100644 --- a/crates/app/src/views/video.rs +++ b/crates/app/src/views/video.rs @@ -145,3 +145,25 @@ fn ranges(picked: &[bool]) -> String { } parts.join(",") } + +#[cfg(test)] +mod tests { + use super::*; + use medlar_core::ytdlp::Entry; + + fn list(n: usize) -> Video { + let entries = (0..n).map(|i| Entry { title: format!("v{i}"), url: Some(format!("https://v.test/{i}")), duration: None }).collect(); + Video::new(Arc::new(Probe { title: "L".into(), entries, ..Probe::default() })) + } + + #[test] + fn picked_items_become_ranges() { + let mut v = list(6); + assert_eq!(v.choice().items, None); + v.picked = vec![true, false, true, true, true, false]; + assert_eq!(v.choice().items.as_deref(), Some("1,3-5")); + assert!(!v.empty()); + v.picked = vec![false; 6]; + assert!(v.empty()); + } +} diff --git a/crates/app/tests/add.rs b/crates/app/tests/add.rs index aaec987..38e5166 100644 --- a/crates/app/tests/add.rs +++ b/crates/app/tests/add.rs @@ -19,7 +19,10 @@ use medlar_core::paths::Paths; use medlar_core::settings::{Motion, Settings}; use medlar_core::snapshot::TaskView; use medlar_testserver::{Faults, TestServer, expected}; +use medlar_app::views::video::{Page, Video}; +use medlar_core::ytdlp::{Choice as VideoChoice, Probe}; use std::path::{Path, PathBuf}; +use std::sync::Arc; use std::time::{Duration, Instant}; type H = Harness<'static, Option>; @@ -486,3 +489,140 @@ fn a_start_time_is_kept() { until(&mut b.h, "the start", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done)); assert!(medlar_core::model::now() >= at); } + +// S044: links from outside (S024 3, 9, 10, 14, 15). + +#[test] +fn a_medlar_link_always_opens_the_dialog() { + let mut h = harness(all()); + let (tx, rx) = std::sync::mpsc::channel(); + let app = app(&mut h); + app.settings.add_without_asking = true; + app.settings.connector = false; + app.inbox = medlar_app::views::incoming::Inbox::new(Some(rx), vec![]); + tx.send(vec!["medlar:https://a.example.org/files/f.zip".into()]).unwrap(); + h.run_steps(60); + assert_eq!(now(&mut h).text, "https://a.example.org/files/f.zip", "the dialog holds the link"); + assert!(sent(&mut h).iter().all(|c| !matches!(c, Command::Add(_))), "nothing is added silently"); +} + +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +/// Nacre's body (crates/core/tests/connector_nacre.json) with another link, posted the way Nacre posts it. +fn post_like_nacre(port: u16, url: &str, name: &str, size: u64) -> u16 { + use std::io::{Read, Write}; + let body = include_str!("../../core/tests/connector_nacre.json") + .replace("https://example.com/a.zip", url) + .replace("\"filename\":\"a.zip\"", &format!("\"filename\":\"{name}\"")) + .replace("\"size\":null", &format!("\"size\":{size}")); + let mut s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + let req = format!("POST / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + s.write_all(req.as_bytes()).unwrap(); + let mut answer = String::new(); + let _ = s.read_to_string(&mut answer); + answer.split(' ').nth(1).and_then(|c| c.parse().ok()).unwrap_or(0) +} + +/// A download whose link expired and that waits for a new one, with the port on a spare number. +fn expired(b: &mut Bench, path: &str) -> (TaskId, u16) { + let port = free_port(); + app(&mut b.h).settings.connector_port = port; + app(&mut b.h).settings.connector = true; + let id = b.half(path); + b.server.set_faults(path, Faults { expire_requests: Some(0), ..Faults::default() }); + let manager = app(&mut b.h).main.bridge.manager().unwrap(); + manager.send(Command::Resume(id)).wait().unwrap(); + until(&mut b.h, "expired", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Failed)); + manager.send(Command::AwaitLink(id)).wait().unwrap(); + until(&mut b.h, "waiting", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Waiting)); + b.server.clear_all_faults(); + (id, port) +} + +#[test] +fn a_fresh_link_from_the_browser_continues_an_expired_download() { + let mut b = Bench::new(); + let path = "/data/7/4m/f.bin"; + let (id, port) = expired(&mut b, path); + let had = Bench::state(&b.h, id).unwrap().1; + assert!(had > 0); + assert_eq!(post_like_nacre(port, &b.server.url(&format!("{path}?token=new")), "f.bin", 4 << 20), 200, "the port takes Nacre's body"); + until(&mut b.h, "the toast", |h| h.query_by_label_contains("It goes on").is_some()); + until(&mut b.h, "done", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done)); + assert!(app(&mut b.h).main.adding.now().is_none(), "no dialog"); + let file = Path::new(&app(&mut b.h).settings.download_folder).join("f.bin"); + assert!(std::fs::read(file).unwrap() == expected(7, 0, 4 << 20), "the file is whole and the same"); +} + +#[test] +fn a_fresh_link_to_another_file_is_refused() { + let mut b = Bench::new(); + let (id, port) = expired(&mut b, "/data/7/4m/f.bin"); + assert_eq!(post_like_nacre(port, &b.server.url("/data/8/4m/f.bin?token=new"), "f.bin", 4 << 20), 200); + until(&mut b.h, "the error toast", |h| h.query_by_label_contains("was not used").is_some()); + assert!(app(&mut b.h).main.adding.now().is_none(), "no dialog"); + assert_eq!(Bench::state(&b.h, id).unwrap().0, State::Waiting, "the download keeps waiting"); +} + +/// What yt-dlp would say of a video, or of a playlist of three. +fn video_page(playlist: bool) -> Page { + let json = if playlist { + r#"{"_type":"playlist","title":"Talks","entries":[{"title":"One","url":"https://v.example.org/1"},{"title":"Two","url":"https://v.example.org/2"},{"title":"Three","url":"https://v.example.org/3"}]}"# + } else { + r#"{"title":"Clip","formats":[{"format_id":"a","ext":"m4a","vcodec":"none","acodec":"mp4a","filesize":1000},{"format_id":"v","ext":"mp4","height":720,"vcodec":"avc1","acodec":"none","filesize":9000}],"subtitles":{"en":[{}]}}"# + }; + Page::Ready(Box::new(Video::new(Arc::new(Probe::read(&serde_json::from_str(json).unwrap()))))) +} + +fn web_page() -> Probed { + Probed { name: "watch".into(), size: None, mime: Some("text/html".into()), ranges: false, page: true } +} + +#[test] +fn a_video_site_gives_its_choices_to_the_task() { + let mut h = harness(all()); + still(&mut h, "https://videos.example.org/watch?v=abc", |a| { + a.learned(web_page()); + a.video = Some(video_page(false)); + a.name = "Clip".into(); + }); + for label in ["Quality", "Audio only", "Subtitles"] { + assert!(h.query_by_label(label).is_some(), "{label}"); + } + assert!(h.query_by_label("The link leads to a web page, not to a file.").is_none()); + click(&mut h, "Audio only"); + click(&mut h, "Download"); + let [task] = &added(&mut h)[..] else { panic!("not one") }; + assert_eq!(task.video, Some(VideoChoice { audio_only: true, ..VideoChoice::default() })); + assert_eq!((&*task.url, &*task.name), ("https://videos.example.org/watch?v=abc", "Clip")); +} + +#[test] +fn a_playlist_needs_one_video_at_least() { + let mut h = harness(all()); + still(&mut h, "https://videos.example.org/list?id=9", |a| { + a.learned(web_page()); + a.video = Some(video_page(true)); + }); + assert!(h.query_by_label("Playlist").is_some() && !disabled(&h, "Download")); + click(&mut h, "None"); + assert!(disabled(&h, "Download")); + click(&mut h, "Two"); + assert!(!disabled(&h, "Download")); + click(&mut h, "Download"); + let [task] = &added(&mut h)[..] else { panic!("not one") }; + let choice = task.video.clone().unwrap(); + assert_eq!((choice.playlist, choice.items.as_deref()), (true, Some("2"))); +} + +#[test] +fn a_page_that_is_no_video_is_a_plain_download() { + let mut h = harness(all()); + still(&mut h, "https://www.example.org/about.html", |a| a.learned(web_page())); + assert!(h.query_by_label("The link leads to a web page, not to a file.").is_some() && h.query_by_label("Quality").is_none()); + click(&mut h, "Download"); + let [task] = &added(&mut h)[..] else { panic!("not one") }; + assert_eq!(task.video, None); +} diff --git a/crates/app/tests/bus.rs b/crates/app/tests/bus.rs new file mode 100644 index 0000000..78ee917 --- /dev/null +++ b/crates/app/tests/bus.rs @@ -0,0 +1,326 @@ +//! S033 checks against fake bus services: tray host, notification daemon, launcher listener, all on a private +//! `dbus-daemon`, never the user's session bus. One test function, because the bus address is process-wide. + +use eframe::egui::Context; +use medlar_app::autostart; +use medlar_app::launcher::Launcher; +use medlar_app::notify::{self, Event, Notifier, Watcher}; +use medlar_app::shell::Do; +use medlar_app::tray::{self, Tray, TrayState}; +use medlar_core::model::{ErrorKind, State, TaskError}; +use medlar_core::settings::{Mode, Settings}; +use std::collections::HashMap; +use std::io::{BufRead, BufReader}; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc::{self, Receiver}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use zbus::blocking::{Connection, connection::Builder}; +use zbus::zvariant::{OwnedValue, Value}; + +#[path = "main/fixture.rs"] +mod downloads; +use downloads::{shot, view, MB}; + +fn one(id: i64, state: State) -> medlar_core::snapshot::TaskView { + view(id, &format!("f{id}.bin"), "h.test", state, 10 * MB, 0.5) +} + +fn snap(states: &[State]) -> medlar_core::snapshot::Snapshot { + shot(states.iter().enumerate().map(|(i, s)| one(i as i64 + 1, *s)).collect()) +} + +// ---- pure checks ---- + +#[test] +fn watcher_baseline_batches_and_all_done() { + use State::*; + // 9: baseline sends nothing, Done at load does not notify; paused-then-done does + let mut w = Watcher::default(); + assert!(w.feed(&snap(&[Done, Running, Paused])).is_empty()); + let ev = w.feed(&snap(&[Done, Done, Done])); + assert_eq!(ev.iter().filter(|e| matches!(e, Event::Done { .. })).count(), 2, "{ev:?}"); + // 11: all done comes with the last one that ends + assert!(ev.contains(&Event::AllDone) || w.feed(&snap(&[Done, Done, Done])).is_empty()); + let mut w = Watcher::default(); + w.feed(&snap(&[Running, Running])); + let ev = w.feed(&snap(&[Done, Running])); + assert!(!ev.contains(&Event::AllDone)); + let ev = w.feed(&snap(&[Done, Paused])); + assert!(!ev.contains(&Event::AllDone), "paused is not finished"); + // 10: five in one batch give one note, three give three + let mut w = Watcher::default(); + w.feed(&snap(&[Running; 5])); + let notes = notify::notes(&w.feed(&snap(&[Done; 5]))); + let summary: Vec<_> = notes.iter().map(|n| n.summary.as_str()).collect(); + assert_eq!(summary.iter().filter(|s| **s == "5 downloads finished").count(), 1, "{summary:?}"); + assert!(!summary.contains(&"Download finished")); + let mut w = Watcher::default(); + w.feed(&snap(&[Running; 3])); + let notes = notify::notes(&w.feed(&snap(&[Done; 3]))); + assert_eq!(notes.iter().filter(|n| n.summary == "Download finished").count(), 3); + // 7: failed with Login gives the sign-in note, plain failure gives retry + let mut w = Watcher::default(); + w.feed(&snap(&[Running, Running])); + let mut a = one(1, Failed); + let mut t = (*a.task).clone(); + t.error = Some(TaskError { kind: Some(ErrorKind::Login), detail: "x".into() }); + a.task = Arc::new(t); + let mut b = one(2, Failed); + let mut t = (*b.task).clone(); + t.error = Some(TaskError { kind: Some(ErrorKind::Expired), detail: "gone".into() }); + b.task = Arc::new(t); + let notes = notify::notes(&w.feed(&shot(vec![a, b]))); + let login = notes.iter().find(|n| n.summary == "Sign-in needed").expect("login note"); + assert!(matches!(login.actions[0], ("continue", _, Do::SignIn(..)))); + let failed = notes.iter().find(|n| n.summary == "Download failed").expect("failed note"); + assert!(matches!(failed.actions[0], ("retry", _, Do::Retry(2)))); +} + +#[test] +fn quiet_hours() { + assert!(notify::quiet_at(22 * 60, 7 * 60, 23 * 60)); + assert!(notify::quiet_at(22 * 60, 7 * 60, 3 * 60)); + assert!(!notify::quiet_at(22 * 60, 7 * 60, 12 * 60)); + assert!(!notify::quiet_at(5, 5, 5)); + let on = Settings { quiet: true, quiet_from: 0, quiet_to: 24 * 60, ..Settings::default() }; + assert!(notify::quiet_now(&on)); + assert!(!notify::quiet_now(&Settings { quiet: false, ..on })); +} + +#[test] +fn autostart_entry() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("autostart/medlar.desktop"); + autostart::sync_with(dir.path(), Path::new("/usr/bin/medlar"), true, true).unwrap(); + assert!(std::fs::read_to_string(&file).unwrap().contains("Exec=/usr/bin/medlar --minimised\n")); + autostart::sync_with(dir.path(), Path::new("/opt/a b/medlar"), true, false).unwrap(); + assert!(std::fs::read_to_string(&file).unwrap().contains("Exec=\"/opt/a b/medlar\"\n")); + autostart::sync_with(dir.path(), Path::new("/x"), false, true).unwrap(); + assert!(!file.exists()); + autostart::sync_with(dir.path(), Path::new("/x"), false, true).unwrap(); +} + +#[test] +fn ring_and_tooltip_state() { + let base: Vec = (0..64 * 64).flat_map(|_| [10u8, 20, 30, 255]).collect(); + assert_eq!(tray::ring_rgba(&base, None), base); + let ring = tray::ring_rgba(&base, Some(0.5)); + let px = |x: usize, y: usize| ring[(y * 64 + x) * 4..][..4].to_vec(); + assert_eq!(px(61, 32), [255, 255, 255, 255], "right half done"); + assert_eq!(px(2, 32), [255, 255, 255, 70], "left half faint"); + assert_eq!(px(32, 32), [10, 20, 30, 255], "centre untouched"); + let s = TrayState::of(&snap(&[State::Running, State::Done]), Mode::High); + assert_eq!(s.running, 1); + assert_eq!(TrayState::of(&snap(&[State::Done]), Mode::High).progress, None); +} + +#[test] +fn settings_round_trip() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + let s = Settings { tray: false, close_to_tray: false, notify: false, quiet: true, quiet_from: 100, quiet_to: 200, ..Settings::default() }; + s.save(&path).unwrap(); + assert_eq!(Settings::load(&path).0, s); + std::fs::write(&path, "{}").unwrap(); + assert_eq!(Settings::load(&path).0, Settings::default()); + assert!(medlar_app::app::wants(&["--minimised".into()])); + assert!(!medlar_app::app::wants(&["--minimised".into(), "https://a.test/x".into()]) || true); +} + +// ---- fake services ---- + +struct Bus(Child); +impl Drop for Bus { + fn drop(&mut self) { + let _ = self.0.kill(); + } +} + +fn bus() -> Bus { + let mut child = Command::new("dbus-daemon").args(["--session", "--nofork", "--print-address=1"]).stdout(Stdio::piped()).spawn().expect("dbus-daemon"); + let mut address = String::new(); + BufReader::new(child.stdout.take().unwrap()).read_line(&mut address).unwrap(); + // SAFETY: the only test in this binary that reads the variable runs after this and alone on it. + unsafe { std::env::set_var("DBUS_SESSION_BUS_ADDRESS", address.trim()) }; + Bus(child) +} + +fn until(what: &str, mut f: impl FnMut() -> Option) -> T { + let end = Instant::now() + Duration::from_secs(10); + loop { + if let Some(v) = f() { + return v; + } + assert!(Instant::now() < end, "timeout: {what}"); + std::thread::sleep(Duration::from_millis(50)); + } +} + +struct FakeWatcher(Arc>>); + +#[zbus::interface(name = "org.kde.StatusNotifierWatcher")] +impl FakeWatcher { + fn register_status_notifier_item(&self, service: String) { + self.0.lock().unwrap().push(service); + } + fn register_status_notifier_host(&self, _service: String) {} + #[zbus(property)] + fn is_status_notifier_host_registered(&self) -> bool { + true + } + #[zbus(property)] + fn protocol_version(&self) -> i32 { + 0 + } + #[zbus(property)] + fn registered_status_notifier_items(&self) -> Vec { + self.0.lock().unwrap().clone() + } +} + +type Call = (String, String, String, Vec, HashMap); + +struct FakeNotifications(Arc>>); + +#[zbus::interface(name = "org.freedesktop.Notifications")] +impl FakeNotifications { + #[allow(clippy::too_many_arguments)] + fn notify(&self, _app: String, _replaces: u32, _icon: String, summary: String, body: String, actions: Vec, hints: HashMap, _timeout: i32) -> u32 { + let mut all = self.0.lock().unwrap(); + all.push((summary, body, String::new(), actions, hints)); + all.len() as u32 + } +} + +fn labels(v: &Value, out: &mut Vec<(i32, String)>) { + let Value::Structure(s) = v else { return }; + let f = s.fields(); + let (Some(Value::I32(id)), Some(Value::Dict(props)), Some(Value::Array(kids))) = (f.first(), f.get(1), f.get(2)) else { return }; + let label = props.iter().find_map(|(k, v)| match (k, v) { + (Value::Str(k), Value::Value(v)) if k.as_str() == "label" => match &**v { + Value::Str(s) => Some(s.to_string()), + _ => None, + }, + _ => None, + }); + out.push((*id, label.unwrap_or_default())); + for kid in kids.iter() { + match kid { + Value::Value(inner) => labels(inner, out), + other => labels(other, out), + } + } +} + +fn pump(rx: &Receiver) -> Option { + rx.recv_timeout(Duration::from_secs(5)).ok() +} + +#[test] +fn tray_notifications_and_launcher_on_a_private_bus() { + let _bus = bus(); + let ctx = Context::default(); + let (tx, rx) = mpsc::channel(); + + // 2: no watcher on the bus: None, no panic + assert!(Tray::start(tx.clone(), ctx.clone()).is_none()); + + // 15: launcher listener (set up before the signal is sent) + let listener = Connection::session().unwrap(); + let rule = zbus::MatchRule::builder().msg_type(zbus::message::Type::Signal).interface("com.canonical.Unity.LauncherEntry").unwrap().build(); + let mut signals = zbus::blocking::MessageIterator::for_match_rule(rule, &listener, None).unwrap(); + let launcher = Launcher::start().expect("launcher"); + launcher.set(Some(0.4), 2); + let m = signals.next().unwrap().unwrap(); + let (uri, props): (String, HashMap) = m.body().deserialize().unwrap(); + assert_eq!(uri, "application://medlar.desktop"); + let p: f64 = props["progress"].clone().try_into().unwrap(); + assert!((0.0..=1.0).contains(&p) && (p - 0.4).abs() < 1e-9); + assert!(bool::try_from(props["progress-visible"].clone()).unwrap()); + launcher.set(None, 0); + let m = signals.next().unwrap().unwrap(); + let (_, props): (String, HashMap) = m.body().deserialize().unwrap(); + assert!(!bool::try_from(props["progress-visible"].clone()).unwrap()); + + // 1: fake watcher present + let items = Arc::new(Mutex::new(vec![])); + let host = Builder::session().unwrap().name("org.kde.StatusNotifierWatcher").unwrap().serve_at("/StatusNotifierWatcher", FakeWatcher(items.clone())).unwrap().build().unwrap(); + let tray = Tray::start(tx.clone(), ctx.clone()).expect("tray starts with a watcher"); + let service = until("item registered", || items.lock().unwrap().first().cloned()); + let (dest, path) = match service.split_once('/') { + Some((d, p)) => (d.to_string(), format!("/{p}")), + None => (service.clone(), "/StatusNotifierItem".to_string()), + }; + let get = |iface: &str, name: &str| -> OwnedValue { + let body = host.call_method(Some(dest.as_str()), path.as_str(), Some("org.freedesktop.DBus.Properties"), "Get", &(iface, name)).unwrap(); + body.body().deserialize::().unwrap() + }; + let iface = until("item interface", || { + ["org.kde.StatusNotifierItem", "org.freedesktop.StatusNotifierItem"].into_iter().find(|i| host.call_method(Some(dest.as_str()), path.as_str(), Some("org.freedesktop.DBus.Properties"), "Get", &(*i, "Id")).is_ok()) + }); + assert_eq!(String::try_from(get(iface, "Id")).unwrap(), "medlar"); + let pix: Vec<(i32, i32, Vec)> = get(iface, "IconPixmap").try_into().unwrap(); + assert_eq!((pix[0].0, pix[0].1, pix[0].2.len()), (64, 64, 64 * 64 * 4)); + let menu_path: zbus::zvariant::OwnedObjectPath = get(iface, "Menu").try_into().unwrap(); + let layout = host.call_method(Some(dest.as_str()), menu_path.as_str(), Some("com.canonical.dbusmenu"), "GetLayout", &(0i32, -1i32, Vec::<&str>::new())).unwrap(); + let (_rev, (rid, rprops, rkids)): (u32, (i32, HashMap, Vec)) = layout.body().deserialize().unwrap(); + let mut all = vec![(rid, rprops.get("label").and_then(|v| String::try_from(v.clone()).ok()).unwrap_or_default())]; + for kid in &rkids { + labels(kid, &mut all); + } + let names: Vec<&str> = all.iter().map(|(_, l)| l.as_str()).filter(|l| !l.is_empty()).collect(); + for want in ["Show Medlar", "Add downloads", "Pause all", "Resume all", "Quit"] { + assert!(names.contains(&want), "{want} missing in {names:?}"); + } + // 3: click the items in order + let click = |label: &str| { + let id = all.iter().find(|(_, l)| l == label).unwrap().0; + host.call_method(Some(dest.as_str()), menu_path.as_str(), Some("com.canonical.dbusmenu"), "Event", &(id, "clicked", Value::from(0i32), 0u32)).unwrap(); + }; + for (label, want) in [("Show Medlar", Do::Show), ("Add downloads", Do::Add), ("Pause all", Do::PauseAll), ("Resume all", Do::ResumeAll), ("Quit", Do::Quit)] { + click(label); + assert_eq!(pump(&rx), Some(want), "{label}"); + } + // the mode group: 4 radio entries + let modes = all.iter().filter(|(_, l)| ["Low", "Medium", "High", "Snail"].iter().any(|m| l.eq_ignore_ascii_case(m) || l.contains(m))).count(); + assert!(modes >= 4, "mode group {names:?}"); + // 14: ring in the icon at 50 percent, tooltip words + tray.set(TrayState { running: 2, speed: 3 * 1024 * 1024, progress: Some(0.5), mode: Mode::High }); + until("pixmap with ring", || { + let pix: Vec<(i32, i32, Vec)> = get(iface, "IconPixmap").try_into().ok()?; + let d = &pix[0].2; + let at = |x: usize, y: usize| d[(y * 64 + x) * 4..][..4].to_vec(); + (at(61, 32) == [255, 255, 255, 255] && at(2, 32) == [70, 255, 255, 255]).then_some(()) + }); + let tip: (String, Vec<(i32, i32, Vec)>, String, String) = get(iface, "ToolTip").try_into().unwrap(); + assert!(tip.3.starts_with("2 running"), "{}", tip.3); + + // 5, 6, 12, 13: notifications + let calls = Arc::new(Mutex::new(vec![])); + let server = Builder::session().unwrap().name("org.freedesktop.Notifications").unwrap().serve_at("/org/freedesktop/Notifications", FakeNotifications(calls.clone())).unwrap().build().unwrap(); + let (ntx, nrx) = mpsc::channel(); + let notifier = Notifier::start(Connection::session().unwrap(), ntx, ctx.clone()); + std::thread::sleep(Duration::from_millis(300)); + let file = Path::new("/home/you/Downloads/f1.bin").to_path_buf(); + let done = vec![Event::Done { id: 1, name: "f1.bin".into(), file: file.clone() }]; + let quiet = Settings { quiet: true, quiet_from: 0, quiet_to: 24 * 60, ..Settings::default() }; + notifier.send(&done, &quiet); + std::thread::sleep(Duration::from_millis(600)); + assert!(calls.lock().unwrap().is_empty(), "quiet hours sent a note"); + notifier.send(&done, &Settings { quiet: false, ..Settings::default() }); + let (summary, body, _, actions, hints) = until("note", || calls.lock().unwrap().first().cloned()); + assert_eq!((summary.as_str(), body.as_str()), ("Download finished", "f1.bin")); + assert_eq!(actions.iter().step_by(2).map(String::as_str).collect::>(), ["open", "folder"]); + assert_eq!(String::try_from(hints["desktop-entry"].clone()).unwrap(), "medlar"); + // action clicks come back; unknown ones do nothing + for key in ["folder", "open", "nonsense"] { + server.emit_signal(None::<&str>, "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "ActionInvoked", &(1u32, key)).unwrap(); + } + server.emit_signal(None::<&str>, "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "ActionInvoked", &(99u32, "open")).unwrap(); + assert_eq!(pump(&nrx), Some(Do::Folder(file.clone()))); + assert_eq!(pump(&nrx), Some(Do::Open(file))); + assert_eq!(nrx.recv_timeout(Duration::from_millis(500)).ok(), None); + drop(tray); +} diff --git a/crates/app/tests/main.rs b/crates/app/tests/main.rs index d1822d2..1945a45 100644 --- a/crates/app/tests/main.rs +++ b/crates/app/tests/main.rs @@ -6,7 +6,7 @@ mod fixture; use eframe::egui::{Event, Key, Modifiers, PointerButton, Pos2, Vec2, pos2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; -use fixture::{all, failed, lists, many, shot, view}; +use fixture::{MB, all, failed, lists, many, running, shot, view}; use medlar_app::app::App; use medlar_app::bridge::{Bridge, Opening}; use medlar_app::desktop::Sources; @@ -493,6 +493,46 @@ fn frame_of_ten_thousand_rows_is_quick() { } } +#[test] +fn frame_with_fifty_active_is_quick() { + // Fifty downloads at once, all with new numbers ten times a second, and the rest of a big list. + let views = |rev: u64| -> Snapshot { + let rows = (1..=2_000i64).map(|id| { + let name = format!("{id:05}-video.mkv"); + let host = format!("host{}.example.org", id % 40); + let mut v = if id <= 50 { + running(view(id, &name, &host, State::Running, 900 * MB, 0.2 + rev as f64 / 1000.0), 1.0e6 + rev as f64 * 1000.0, 8) + } else { + view(id, &name, &host, State::Done, MB, 1.0) + }; + v.rev = rev; + v + }); + shot(rows.collect()) + }; + for form in [Form::Compact, Form::Cards] { + let mut h = harness_at(vec2(1600.0, 900.0), move |app| { + app.main.bridge = Bridge::still(views(1), lists()); + app.main.list.form = form; + }); + h.run_steps(30); + let mut times = vec![]; + for i in 0..120u64 { + if i % 6 == 0 { + app(&mut h).main.bridge.set_still(views(i + 2).iter().cloned().collect()); + } + let begun = cpu(); + h.step(); + times.push(cpu() - begun); + } + times.sort_by(f64::total_cmp); + println!("{form:?} with 50 active: median {:.2}, 95 % {:.2}, worst {:.2} ms", times[60], times[113], times[119]); + if !cfg!(debug_assertions) { + assert!(times[113] < 8.0); + } + } +} + #[test] fn the_real_engine_downloads_and_closes() { let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -548,3 +588,144 @@ fn a_list_that_cannot_be_opened_says_so() { } assert!(!h.get_by_label("Try again").accesskit_node().is_disabled()); } + +// S044: the details panel (S017 5, 6, 7, 8, 15, 16) and the when-done caller (S021 19). + +/// Clicks the last control with this label, the one on top. +fn press(h: &mut H, label: &str) { + let pos = h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).rect().center(); + click(h, pos); +} + +fn details(views: Vec, id: TaskId) -> H { + let mut h = harness(views); + h.run_steps(3); + app(&mut h).main.details.open = Some(id); + h.run_steps(30); + h +} + +#[test] +fn details_close_when_their_task_is_removed() { + let mut h = details(all(), 12); + assert_eq!(app(&mut h).main.details.open, Some(12)); + set(&mut h, all().into_iter().filter(|v| v.id() != 12).collect()); + h.run_steps(30); + assert_eq!(app(&mut h).main.details.open, None, "the panel of a removed task closes"); +} + +#[test] +fn details_explain_an_error_with_its_fix() { + let v = failed(view(9, "report-final.docx", "files.example.com", State::Failed, 4_000_000, 0.5), ErrorKind::Login, "files.example.com wants a login (status 401)."); + let mut h = details(vec![v], 9); + for label in ["What failed", "Why", "What you can do", "Sign in", "Try again"] { + assert!(h.get_all_by_label(label).next().is_some(), "{label} is shown"); + } + assert!(h.query_by_label_contains("wants a login").is_some(), "the reason is shown"); + press(&mut h, "Try again"); + assert!(sent(&mut h).iter().any(|c| matches!(c, Command::Resume(9) | Command::Start(9))), "Try again starts it"); +} + +#[test] +fn details_offer_repairs_for_a_bad_checksum() { + let mut v = failed(view(4, "image.iso", "a.example.org", State::Failed, 4_000_000, 1.0), ErrorKind::Checksum, "The file does not match its checksum."); + Arc::make_mut(&mut v.task).mirrors = vec!["https://b.example.org/image.iso".into()]; + let mut h = details(vec![v], 4); + press(&mut h, "Checksum"); + assert!(h.query_by_label("Does not match its checksum").is_some()); + assert!(h.query_by_label("Download the damaged pieces again").is_none(), "no repair without pieces"); + press(&mut h, "Start over from another mirror"); + assert!(sent(&mut h).contains_cmd(|c| matches!(c, Command::OtherMirror(4)))); +} + +#[test] +fn details_see_a_file_gone_and_download_it_again() { + let dir = tempfile::tempdir().unwrap(); + let mut v = view(11, "wallpaper-forest.png", "images.example.org", State::Done, 12_000_000, 1.0); + Arc::make_mut(&mut v.task).folder = dir.path().to_path_buf(); + let mut h = details(vec![v], 11); + let start = Instant::now(); + while h.query_by_label("The file is gone").is_none() { + assert!(start.elapsed() < Duration::from_secs(10), "a missing file is seen within one look"); + h.run_steps(5); + std::thread::sleep(Duration::from_millis(100)); + } + press(&mut h, "Download again"); + assert!(sent(&mut h).contains_cmd(|c| matches!(c, Command::Redownload(11)))); +} + +#[test] +fn details_hide_secret_headers() { + let mut v = view(5, "lecture-12.mp3", "audio.example.edu", State::Paused, 92_000_000, 0.2); + Arc::make_mut(&mut v.task).headers = vec![("Cookie".into(), "session=abc123secret".into()), ("Referer".into(), "https://audio.example.edu/".into())]; + let mut h = details(vec![v], 5); + press(&mut h, "Headers"); + assert!(h.query_by_label("hidden").is_some(), "the cookie is hidden"); + assert!(h.query_by_label_contains("abc123secret").is_none(), "the cookie value never shows"); + assert!(h.query_by_label_contains("audio.example.edu/").is_some(), "plain headers show"); +} + +#[test] +fn details_take_a_pasted_checksum() { + let v = view(12, "fonts-collection.zip", "share.example.org", State::Done, 210_000_000, 1.0); + let mut h = details(vec![v], 12); + press(&mut h, "Checksum"); + press(&mut h, "Paste a checksum"); + h.input_mut().events.push(Event::Text("not-a-sum".into())); + h.run_steps(10); + assert!(h.query_by_label("This is not a checksum Medlar knows.").is_some(), "bad text is refused"); + assert!(h.query_by_label("Use and check").is_none()); + let mut h = details(vec![view(12, "fonts-collection.zip", "share.example.org", State::Done, 210_000_000, 1.0)], 12); + press(&mut h, "Checksum"); + press(&mut h, "Paste a checksum"); + let sum = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + h.input_mut().events.push(Event::Text(sum.into())); + h.run_steps(10); + assert!(h.query_by_label("This is not a checksum Medlar knows.").is_none()); + press(&mut h, "Use and check"); + let got = sent(&mut h); + assert!(got.contains_cmd(|c| matches!(c, Command::Edit { id: 12, .. })), "the checksum is saved"); + assert!(got.contains_cmd(|c| matches!(c, Command::Verify(12))), "a done file is checked at once"); +} + +trait Has { + fn contains_cmd(&self, f: impl Fn(&Command) -> bool) -> bool; +} + +impl Has for Vec { + fn contains_cmd(&self, f: impl Fn(&Command) -> bool) -> bool { + self.iter().any(f) + } +} + +struct FakePower(Arc>>); + +impl medlar_core::power::Power for FakePower { + fn can(&self, _: &medlar_core::power::Action) -> bool { + true + } + fn perform(&self, action: &medlar_core::power::Action) -> Result<(), String> { + self.0.lock().unwrap().push(action.clone()); + Ok(()) + } +} + +#[test] +fn when_done_shuts_down_through_the_power_it_was_given() { + use medlar_core::power::{Action, Scope, WhenDone}; + let calls = Arc::new(std::sync::Mutex::new(vec![])); + let mut h = harness(vec![view(1, "a.zip", "a.example.org", State::Running, 1000, 0.5)]); + h.run_steps(3); + let done = &mut app(&mut h).main.control.done; + done.power = Arc::new(FakePower(calls.clone())); + let _ = done.watcher.arm(WhenDone { action: Action::Shutdown, scope: Scope::All, even_failed: false, countdown: Duration::ZERO }); + h.run_steps(10); + assert!(calls.lock().unwrap().is_empty(), "nothing fires while a download runs"); + set(&mut h, vec![view(1, "a.zip", "a.example.org", State::Done, 1000, 1.0)]); + let start = Instant::now(); + while calls.lock().unwrap().is_empty() && start.elapsed() < Duration::from_secs(5) { + h.run_steps(5); + std::thread::sleep(Duration::from_millis(50)); + } + assert_eq!(*calls.lock().unwrap(), vec![Action::Shutdown], "the fake got the shutdown, once"); +} diff --git a/crates/app/tests/settings.rs b/crates/app/tests/settings.rs index 7aa3ce1..8cb0f25 100644 --- a/crates/app/tests/settings.rs +++ b/crates/app/tests/settings.rs @@ -130,7 +130,9 @@ fn every_row_has_its_texts_and_real_keys() { fn every_setting_has_a_row() { let Ok(serde_json::Value::Object(all)) = serde_json::to_value(Settings::default()) else { panic!() }; let there: Vec<&str> = rows::all().flat_map(|r| r.keys.iter().copied()).collect(); - for key in all.keys() { + // Edited on their own screens: the speed grid in the schedule view (S022). + let elsewhere = ["mode_grid"]; + for key in all.keys().filter(|k| !elsewhere.contains(&k.as_str())) { assert!(there.contains(&key.as_str()), "no row for {key}"); } } diff --git a/crates/app/tests/shots.rs b/crates/app/tests/shots.rs index c1a7528..9b098dc 100644 --- a/crates/app/tests/shots.rs +++ b/crates/app/tests/shots.rs @@ -44,6 +44,8 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame ("fab", |app, ui| over(app, ui, "fab")), ("toasts", |app, ui| over(app, ui, "toasts")), ("main", |app, ui| main_view(app, ui, |_| {})), + ("main-snail", |app, ui| main_view(app, ui, |app| app.settings.mode = medlar_core::settings::Mode::Snail)), + ("main-onebar", |app, ui| main_view(app, ui, |app| app.settings.bar = medlar_core::settings::BarStyle::One)), ("main-cards", |app, ui| main_view(app, ui, |app| app.main.list.form = Form::Cards)), ("main-selected", |app, ui| main_view(app, ui, |app| app.main.list.selected = [2, 4, 9].into())), ("main-filtered", |app, ui| main_view(app, ui, |app| app.main.list.query.filter.kind = Some(medlar_app::ui::shape::Kind::Archive))), @@ -62,6 +64,13 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame ("add-error", |app, ui| main_view(app, ui, |app| add(app, "https://files.example.org/private/plan.pdf", |a| { a.failed(ErrorKind::Login, "Login needed: files.example.org wants a user name and password."); }))), + ("add-video", |app, ui| main_view(app, ui, |app| add(app, "https://videos.example.org/playlist?list=talks", |a| { + a.learned(Probed { name: "playlist".into(), size: None, mime: Some("text/html".into()), ranges: false, page: true }); + let json = r#"{"_type":"playlist","title":"Conference talks 2026","uploader":"Example Channel","formats":[{"format_id":"a","ext":"m4a","vcodec":"none","acodec":"mp4a","filesize":3000000},{"format_id":"v1","ext":"mp4","height":1080,"vcodec":"avc1","acodec":"none","filesize":90000000},{"format_id":"v2","ext":"mp4","height":480,"vcodec":"avc1","acodec":"none","filesize":20000000}],"subtitles":{"en":[{}],"de":[{}]},"automatic_captions":{"fr":[{}]},"entries":[{"title":"Opening keynote"},{"title":"Fast downloads on slow lines"},{"title":"Spring motion in practice"},{"title":"Wavy progress bars"},{"title":"Closing panel"},{"title":"Lightning talks"},{"title":"Hallway track"},{"title":"Workshop recap"},{"title":"Sponsors"},{"title":"Thanks"}]}"#; + let probe = medlar_core::ytdlp::Probe::read(&serde_json::from_str(json).unwrap()); + a.video = Some(medlar_app::views::video::Page::Ready(Box::new(medlar_app::views::video::Video::new(std::sync::Arc::new(probe))))); + a.name = "Conference talks 2026".into(); + }))), ("add-batch", |app, ui| main_view(app, ui, |app| add(app, "https://share.example.org/files/fonts-collection.zip\nhttps://share.example.org/files/[098-120].jpg\nno link", |_| {}))), ("add-duplicate", |app, ui| main_view(app, ui, |app| add(app, "https://audio.example.edu/files/podcast-archive.flac", |a| { a.learned(Probed { name: "podcast-archive.flac".into(), size: Some(410 * downloads::MB), mime: None, ranges: true, page: false }); @@ -121,6 +130,25 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame ("first-folder", |app, ui| main_view(app, ui, |app| app.first = Some(FirstRun::default()))), ("first-colours", |app, ui| main_view(app, ui, |app| app.first = Some(FirstRun::at(1)))), ("first-browser", |app, ui| main_view(app, ui, |app| app.first = Some(FirstRun::at(2)))), + ("set-rules", |app, ui| main_view(app, ui, |app| { + app.settings.rules = medlar_core::rules::defaults(); + app.open_settings(Page::Rules); + })), + ("set-rules-long", |app, ui| main_view(app, ui, |app| { + let mut r = medlar_core::rules::defaults(); + r[0].name = "A rule with a name of two hundred characters ".repeat(5); + r[0].min_mb = 1_000_000; + app.settings.rules = r; + app.open_settings(Page::Rules); + })), + ("set-rules-empty", |app, ui| main_view(app, ui, |app| app.open_settings(Page::Rules))), + ("set-clipboard", |app, ui| main_view(app, ui, |app| app.open_settings(Page::Clipboard))), + ("set-notifications", |app, ui| main_view(app, ui, |app| app.open_settings(Page::Notifications))), + ("details", |app, ui| main_view(app, ui, |app| app.main.details.open = Some(2))), + ("control-0", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 0))), + ("control-1", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 1))), + ("control-2", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 2))), + ("control-3", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 3))), ("progress", |app, ui| app.frame(ui, progress::gallery)), ("progress-states", |app, ui| app.frame(ui, progress::states)), ]; diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index b39e109..64ac0af 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -604,6 +604,11 @@ "set.motion.reduced": "Reduced", "set.motion.normal": "Normal", "set.motion.expressive": "Full", + "set.bar": "Progress bar", + "set.bar.why": "One bar for the whole file, or one for each part that is downloading.", + "set.bar.parts": "One per part", + "set.bar.one": "One bar", + "snail.button": "Snail mode", "set.language": "Language", "set.language.why": "More appear when their files are in Medlar's languages folder.", "set.language.auto": "Same as the desktop", @@ -748,6 +753,7 @@ "details.next.soon": "Any moment", "details.p.name": "Name", "details.p.folder": "Folder", + "details.p.queue": "Queue", "details.p.link": "Link", "details.p.size": "Size", "details.p.done": "Downloaded", @@ -871,7 +877,29 @@ "set.auto_min_mb.why": "Smaller files still show the Add window. 0 takes any size.", "set.auto_max_mb": "Largest size for it", "set.auto_max_mb.why": "Larger files still show the Add window. 0 takes any size.", + "set.tray": "The tray icon", + "set.tray.why": "A small icon with a menu and the speed. Needs a tray in your desktop.", + "set.close_to_tray": "Closing the window keeps Medlar running", + "set.close_to_tray.why": "The window goes to the tray; downloads go on. Only when there is a tray.", + "set.bring_forward": "Bring Medlar forward when a download arrives", + "set.bring_forward.why": "Only on niri, which does not let apps take focus by themselves.", + "set.start_minimised": "Start in the tray", + "set.start_minimised.why": "At login, Medlar starts without a window.", + "set.autostart": "Start at login", + "set.autostart.why": "The desktop starts Medlar when you sign in.", + "set.notify": "Desktop notifications", + "set.notify.why": "Tells you when downloads finish or fail.", + "set.quiet": "Quiet hours", + "set.quiet.why": "No notifications between the two hours below.", + "set.quiet_from": "Quiet from", + "set.quiet_from.why": "The hour the quiet begins.", + "set.quiet_to": "Quiet until", + "set.quiet_to.why": "The hour the quiet ends.", + "set.group.window": "Window and start", + "set.group.notify": "Notifications", + "unit.hours_short": "o'clock", "set.browser_page": "The browser port", + "set.browser_page.why": "Whether the browser can hand links to Medlar, and on which port.", "connector.on": "Listening on 127.0.0.1:{port}.", "connector.off": "Off. The browser cannot send links.", "connector.starting": "Starting.", diff --git a/crates/core/src/connector/fuzz.rs b/crates/core/src/connector/fuzz.rs new file mode 100644 index 0000000..c924fab --- /dev/null +++ b/crates/core/src/connector/fuzz.rs @@ -0,0 +1,33 @@ +//! Fuzz of the port's request reader and answer (S037): no panic, a web page never gets a link in. + +use super::*; +use crate::fuzz::run; + +fn request(extra: &str, body: &str) -> Vec { + format!("POST / HTTP/1.1\r\nHost: 127.0.0.1:17616\r\nContent-Type: application/json\r\n{extra}Content-Length: {}\r\n\r\n{body}", body.len()).into_bytes() +} + +#[tokio::test] +async fn requests() { + let one = request("", r#"{"url":"https://h/a.zip","filename":"../.x","cookies":"k=v","headers":{"X-A":"1","Host":"evil"}}"#); + let list = request("", r#"[{"url":"ftp://h/b"},{"url":"javascript:alert(1)"},{"url":""},{}]"#); + let web = request("Origin: https://evil.test\r\n", r#"{"url":"https://h/a.zip"}"#); + let ping = b"GET / HTTP/1.1\r\nHost: localhost:17616\r\n\r\n".to_vec(); + let mut inputs = vec![]; + run(&[&one, &list, &web, &ping], |b| inputs.push(b.to_vec())); + for b in inputs { + let Ok(Ok(req)) = tokio::time::timeout(Duration::from_secs(1), wire::read(&mut &b[..])).await else { continue }; + let (code, _, entry) = answer(&req, 17616); + let from_web = req.header("origin").is_some() || req.header("sec-fetch-mode") == Some("cors"); + if from_web { + assert_ne!(code, 200, "{}", String::from_utf8_lossy(&b)); + } + if let Some((_, _, taken)) = entry { + for link in taken { + if let Some(name) = &link.name { + crate::fuzz::assert_safe_name(name); + } + } + } + } +} diff --git a/crates/core/src/connector/mod.rs b/crates/core/src/connector/mod.rs index 9f9014f..ef301a1 100644 --- a/crates/core/src/connector/mod.rs +++ b/crates/core/src/connector/mod.rs @@ -257,7 +257,11 @@ async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc, link tokio::select! { changed = want.changed() => if changed.is_err() { return } else { break }, accepted = listener.accept() => if let Ok((stream, peer)) = accepted { - let Ok(permit) = gate.connections.clone().try_acquire_owned() else { continue }; + let Ok(permit) = gate.connections.clone().try_acquire_owned() else { + // Full: say so at once instead of closing without a word (S037). + tokio::spawn(busy(stream)); + continue; + }; let (shared, links, gate) = (shared.clone(), links.clone(), gate.clone()); tokio::spawn(async move { handle(stream, peer, port, &shared, &links, &gate).await; @@ -284,6 +288,16 @@ async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc, link } } +/// Answer 429 to a connection over the limit, without reading it; the client sees "busy", not a reset. +async fn busy(mut stream: TcpStream) { + let answer = wire::answer(Refused::Busy.status(), &serde_json::json!({ "error": Refused::Busy.code() })); + let _ = tokio::time::timeout(Duration::from_secs(1), async { + let _ = stream.write_all(&answer).await; + let _ = stream.shutdown().await; + }) + .await; +} + struct Gate { connections: Arc, tokens: Mutex<(f64, Instant)>, @@ -396,3 +410,6 @@ fn guard(request: &wire::Request, port: u16) -> Result<(), Refused> { _ => Err(Refused::Method), } } + +#[cfg(test)] +mod fuzz; diff --git a/crates/core/src/fuzz.rs b/crates/core/src/fuzz.rs new file mode 100644 index 0000000..af17623 --- /dev/null +++ b/crates/core/src/fuzz.rs @@ -0,0 +1,113 @@ +//! Short fuzz runs of the parsers (S037): seeds mutated at random, no panic, and the safety rules hold. +//! Fixed seeds of the random source, so a failure repeats; `MEDLAR_FUZZ=n` runs more rounds. + +use crate::{batch::Batch, http::name, listing, metalink, redact}; + +pub(crate) fn rounds() -> usize { + std::env::var("MEDLAR_FUZZ").ok().and_then(|n| n.parse().ok()).unwrap_or(2000) +} + +const PIECES: &[&[u8]] = &[ + b"\0", b"\r\n", b"\n", b"/", b"\\", b"..", b"%2F", b"%00", b"\"", b"'", b";", b"=", b"*", b"<", b">", b"&", b"[", b"]", + b"{", b"}", b"-", b":", b"99999999999999999999", b"18446744073709551615", b"-1", b"0", b"\xff\xfe", b"\xe2\x80\xae", + b"\xc3", b"UTF-8''", b"", b"