Compare commits

...
Author SHA1 Message Date
2a85ac9bbf Move Astar Hub links to astar76.com
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-02 16:26:00 -06:00
2caff86bf1 Handoff and status after 0.1.1 release
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 07:59:55 -06:00
4f5d07d0fe S050: partial results, test file, PROGRESS
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-27 07:52:16 -06:00
6d56d3f58e S050: tray speed uses the held value; dialog height drift no longer repaints every frame
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-27 07:52:11 -06:00
ff1b1a06a9 S050: connector flood test fires in parallel so the limit shows
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-27 07:51:02 -06:00
2d79478ffc S050: bug hunt plan
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 07:50:26 -06:00
3dc4b04abe 0.1.1: release notes complete, package sums
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 07:48:57 -06:00
f560275327 S049: take focus on niri over IPC when a download arrives
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-27 07:44:25 -06:00
62147e743a S047: close to tray on Wayland: window reopens, hidden runs tested, tools/tray-check
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 07:33:47 -06:00
451f153925 S047: the app outlives its window; close to tray reopens through run_native_ext with one context
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 07:08:05 -06:00
fa00568641 Package sums for the quit fix build; handoff at weekly 89 %
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:15:52 -06:00
02d37f61a7 Ctrl+Q quits even with close to tray; on Wayland closing quits (no hiding there) until S047
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:12:18 -06:00
7d017c96ae package.sh pins the tar.gz sum it builds in PKGBUILD and .SRCINFO
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:28:57 -06:00
b057c86abc Enable egui clipboard: copy and paste in every text field and Ctrl+V on the list
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:20:30 -06:00
0d5b4a89d5 S049: plan for focus on niri through its IPC
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:07:00 -06:00
e6b089b609 Handoff: S048 done, open items
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 17:37:01 -06:00
4d95d6d98c S048: test file, release notes, packaging fixes, progress
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 17:36:34 -06:00
3500a4c25b S048: farm rule only over HTTP (FTP keeps mtime as proof of change); http test builds
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:28:22 -06:00
9f38019b14 S048: prove until the triggering version is sure; parts check counts three starts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:17:46 -06:00
fc7f04ac03 S048: per-version proof against a known sample, farm tests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:13:53 -06:00
ed2f7c67e5 S048: farms with differing validators: byte proof, no If-Range, stored flag; testserver farm and liar modes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:58:03 -06:00
f6c8a5c57a S048: plan for server farms with differing validators (romsgames.net)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:52:23 -06:00
63f0046965 S046: tick plan boxes; handoff for the next session
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:18:32 -06:00
cfa789dce8 S046: packages, results, progress
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 13:18:00 -06:00
7d0587e424 S046: version 0.1.1, settings row key fix, release notes, test file
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 13:05:38 -06:00
7831445a6c S047: plan for close to tray on Wayland
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:51:01 -06:00
fdbb007f53 S046: snail test 2026-11-26 12:46:13 -06:00
6f06b10792 S046: readable speed, one-bar setting, snail button and 8 kB cap 2026-11-26 12:44:21 -06:00
8ffed89259 S046: tests fixed 2026-11-26 12:35:50 -06:00
a8c38788e1 S046: placeholder names give way to the server's, raise on arrival, copy in fields 2026-11-26 12:34:22 -06:00
51dc36f519 S046: plan for 0.1.1 fixes (server names, raise on arrival, copy in fields)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:32:46 -06:00
67 changed files with 1754 additions and 205 deletions

View file

@ -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 <name> <driver> [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 [email protected] 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.

108
Cargo.lock generated
View file

@ -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",

View file

@ -3,7 +3,7 @@ members = ["crates/*"]
resolver = "3"
[workspace.package]
version = "0.1.0"
version = "0.1.1"
edition = "2024"
license = "MIT"

View file

@ -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.

View file

@ -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.

View file

@ -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 = `"<size hex>-<mtime hex>"`). `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.

View file

@ -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.

View file

@ -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.

View file

@ -66,6 +66,11 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
## 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)

View file

@ -1,7 +1,7 @@
# 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.0 is the first release.
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)
@ -23,21 +23,21 @@ The full list and its state: [docs/FEATURES.md](docs/FEATURES.md) and [docs/FEAT
Needs a Linux x86_64 desktop with Wayland or X11, and glibc 2.44 or newer (see "Requirements").
**AppImage:** `chmod +x Medlar-0.1.0-x86_64.AppImage && ./Medlar-0.1.0-x86_64.AppImage`
**AppImage:** `chmod +x Medlar-0.1.1-x86_64.AppImage && ./Medlar-0.1.1-x86_64.AppImage`
**tar.gz:** `tar xzf Medlar-0.1.0-Linux-x86_64.tar.gz && cd medlar-0.1.0 && ./install.sh`
**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.0-Linux-x86_64.tar.gz` (or with no file: it uses a tar.gz or AppImage beside it).
**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.0-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.0-Linux-x86_64.tar.gz makepkg -si`.
**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.0`: `sha256sum -c SHA256SUMS-0.1.0`.
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=<dir>` sets the folder directly and wins over both.
@ -63,7 +63,7 @@ Requests with a web `Origin` or a foreign `Host` are refused, and no CORS header
## Limits and known gaps
Honest state of 0.1.0. The engine is tested hard (unit, integration, fuzz, a 20-minute fault soak with 606 files and no
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

View file

@ -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"

View file

@ -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<Do> {
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<Do> {
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<String>) -> 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<String>) -> 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<dyn eframe::App>)
};
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 {

View file

@ -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::<u8>().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<Event>, 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"] {

View file

@ -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;

90
crates/app/src/niri.rs Normal file
View file

@ -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<u64> {
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<String> {
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<u64> {
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();
}
}

View file

@ -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<Do>,
shown: Option<TrayState>,
/// 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));
}
}

View file

@ -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();
}

View file

@ -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;

View file

@ -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::<f64>() / 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::<Calm>(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]);

114
crates/app/src/ui/snail.rs Normal file
View file

@ -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<Pos2> = (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:?}");
}
}
}

Some files were not shown because too many files have changed in this diff Show more