diff --git a/CLAUDE.md b/CLAUDE.md index c1bfc56..004e57a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,7 +69,6 @@ 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 9d04dc1..747157c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -714,42 +714,18 @@ 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 0.13.0", + "calloop", "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" @@ -970,15 +946,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-queue" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -1403,7 +1370,6 @@ dependencies = [ "profiling", "raw-window-handle", "serde", - "smithay-clipboard", "web-time", "windows-sys 0.61.2", "winit", @@ -2655,26 +2621,6 @@ dependencies = [ "accesskit_consumer", ] -[[package]] -name = "ksni" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf" -dependencies = [ - "arc-swap", - "async-executor", - "async-io", - "async-lock", - "crossbeam-queue", - "futures-channel", - "futures-lite", - "futures-util", - "pastey", - "serde", - "task-local", - "zbus", -] - [[package]] name = "kurbo" version = "0.11.3" @@ -2812,15 +2758,13 @@ checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" [[package]] name = "medlar" -version = "0.1.1" +version = "0.1.0" dependencies = [ - "arboard", "chrono", "dirs", "eframe", "egui_kittest", "image", - "ksni", "log", "medlar-cli", "medlar-core", @@ -2832,19 +2776,18 @@ dependencies = [ "tempfile", "tokio", "url", - "zbus", ] [[package]] name = "medlar-cli" -version = "0.1.1" +version = "0.1.0" dependencies = [ "medlar-core", ] [[package]] name = "medlar-core" -version = "0.1.1" +version = "0.1.0" dependencies = [ "aes", "arc-swap", @@ -2888,7 +2831,7 @@ dependencies = [ [[package]] name = "medlar-testserver" -version = "0.1.1" +version = "0.1.0" dependencies = [ "md-5", "rcgen", @@ -3662,12 +3605,6 @@ dependencies = [ "phc", ] -[[package]] -name = "pastey" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" - [[package]] name = "pbkdf2" version = "0.13.0" @@ -4963,8 +4900,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" dependencies = [ "bitflags 2.13.2", - "calloop 0.13.0", - "calloop-wayland-source 0.3.0", + "calloop", + "calloop-wayland-source", "cursor-icon", "libc", "log", @@ -4981,44 +4918,6 @@ 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" @@ -5231,15 +5130,6 @@ dependencies = [ "libc", ] -[[package]] -name = "task-local" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" -dependencies = [ - "pin-project-lite", -] - [[package]] name = "tempfile" version = "3.27.0" @@ -5527,7 +5417,6 @@ 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", @@ -5895,32 +5784,6 @@ 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" @@ -6401,7 +6264,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "bytemuck", - "calloop 0.13.0", + "calloop", "cfg_aliases", "concurrent-queue", "core-foundation 0.9.4", @@ -6422,7 +6285,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", - "smithay-client-toolkit 0.19.2", + "smithay-client-toolkit", "smol_str", "tracing", "unicode-segmentation", diff --git a/Cargo.toml b/Cargo.toml index f438da7..bc91c09 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/*"] resolver = "3" [workspace.package] -version = "0.1.1" +version = "0.1.0" edition = "2024" license = "MIT" diff --git a/Plans/06 Media/S025-video-sites.md b/Plans/06 Media/S025-video-sites.md index 87fe03d..bb49b0e 100644 --- a/Plans/06 Media/S025-video-sites.md +++ b/Plans/06 Media/S025-video-sites.md @@ -12,13 +12,13 @@ FEATURES 6.1 with the system's yt-dlp (D-011). - `yt-dlp --help` (format, output, progress parts) ## Steps -- [x] Finder and version check, missing and too-old states in plain words -- [x] Probe to JSON: formats, audio, subtitles, chapters, playlists; cached and cancellable -- [x] Add dialog page: quality choice with sizes, audio only, subtitles, playlist picker -- [x] Run as a task: progress template parsed to parts and speed, pause by stop and resume, limits passed on, cookies through a private temp file -- [x] Errors mapped to kinds: private, removed, region, login, unsupported, too many requests; DRM refused -- [x] Test file `docs/tests/S025-video-sites.md`, with the checks below -- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S025: …`, push +- [ ] Finder and version check, missing and too-old states in plain words +- [ ] Probe to JSON: formats, audio, subtitles, chapters, playlists; cached and cancellable +- [ ] Add dialog page: quality choice with sizes, audio only, subtitles, playlist picker +- [ ] Run as a task: progress template parsed to parts and speed, pause by stop and resume, limits passed on, cookies through a private temp file +- [ ] Errors mapped to kinds: private, removed, region, login, unsupported, too many requests; DRM refused +- [ ] Test file `docs/tests/S025-video-sites.md`, with the checks below +- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S025: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/07 Library and tools/S027-rules-clipboard-drop.md b/Plans/07 Library and tools/S027-rules-clipboard-drop.md index 8268666..fbcf4c7 100644 --- a/Plans/07 Library and tools/S027-rules-clipboard-drop.md +++ b/Plans/07 Library and tools/S027-rules-clipboard-drop.md @@ -12,14 +12,14 @@ FEATURES 3.3, 3.4, 3.9. - ~/Projects/Nacre/Cargo.toml (arboard line) ## Steps -- [x] Rules engine: conditions (extension, MIME, host, size, name pattern) to folder, queue, tags, priority, name template; order, test box, default rule set by type -- [x] Name templates with safe placeholders and collision handling -- [x] Clipboard watcher: off, ask, add; filters; ignores our own copies; privacy note; Wayland limits stated honestly -- [x] Drop links, text, lists and `.metalink` on the window with a full-window drop state -- [x] Floating drop target: small wavy ring with speed, own always-on-top window where the compositor allows, else a compact window; accepts drops; context menu -- [x] Rules and clipboard pages -- [x] Test file `docs/tests/S027-rules-clipboard-drop.md`, with the checks below -- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S027: …`, push +- [ ] Rules engine: conditions (extension, MIME, host, size, name pattern) to folder, queue, tags, priority, name template; order, test box, default rule set by type +- [ ] Name templates with safe placeholders and collision handling +- [ ] Clipboard watcher: off, ask, add; filters; ignores our own copies; privacy note; Wayland limits stated honestly +- [ ] Drop links, text, lists and `.metalink` on the window with a full-window drop state +- [ ] Floating drop target: small wavy ring with speed, own always-on-top window where the compositor allows, else a compact window; accepts drops; context menu +- [ ] Rules and clipboard pages +- [ ] Test file `docs/tests/S027-rules-clipboard-drop.md`, with the checks below +- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S027: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/07 Library and tools/S033-tray-notify.md b/Plans/07 Library and tools/S033-tray-notify.md index b233162..57f87f7 100644 --- a/Plans/07 Library and tools/S033-tray-notify.md +++ b/Plans/07 Library and tools/S033-tray-notify.md @@ -12,13 +12,13 @@ FEATURES 8.1, 8.4. - ksni docs ## Steps -- [x] Tray icon with progress ring and speed tooltip; menu: modes, pause all, resume all, add, show, quit -- [x] Close to tray, start minimised, autostart file; works without a tray host -- [x] Notifications: done, failed, needs login, all done, with actions (open, show folder, continue, retry); grouped, quiet hours -- [x] Launcher progress through the Unity D-Bus signal -- [x] Desktop file, metainfo, MIME and scheme entries checked by their validators when present -- [x] Test file `docs/tests/S033-tray-notify.md`, with the checks below -- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S033: …`, push +- [ ] Tray icon with progress ring and speed tooltip; menu: modes, pause all, resume all, add, show, quit +- [ ] Close to tray, start minimised, autostart file; works without a tray host +- [ ] Notifications: done, failed, needs login, all done, with actions (open, show folder, continue, retry); grouped, quiet hours +- [ ] Launcher progress through the Unity D-Bus signal +- [ ] Desktop file, metainfo, MIME and scheme entries checked by their validators when present +- [ ] Test file `docs/tests/S033-tray-notify.md`, with the checks below +- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S033: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/08 Motion and polish/S034-motion-audit.md b/Plans/08 Motion and polish/S034-motion-audit.md index dcc4446..f190f87 100644 --- a/Plans/08 Motion and polish/S034-motion-audit.md +++ b/Plans/08 Motion and polish/S034-motion-audit.md @@ -11,13 +11,13 @@ One look and feel, and motion that earns its place (D-008, FEATURES 9.7). Was S0 - crates/app/src/{motion,tokens}*, then the views by `rg` hits only ## Steps -- [x] One list of faults across all screens, by leverage: motion, edges, grid, radii, sizes, states, copy, focus; drop what is by design -- [x] Fix every high and medium motion fault -- [x] Fix every high and medium look fault; no literal colours or radii outside tokens -- [x] Hide every setting, menu entry and tab of a feature that is Later (PLAN.md), so nothing on screen does nothing -- [x] Copy, empty states, AccessKit names, focus and 32 px hit targets -- [x] Test file `docs/tests/S034-motion-audit.md`: each fixed motion with normal, reduced and off; keyboard only; sizes 480, 900, 1600, 3440; light, dark, AMOLED; long names and big numbers -- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S034: …`, push +- [ ] One list of faults across all screens, by leverage: motion, edges, grid, radii, sizes, states, copy, focus; drop what is by design +- [ ] Fix every high and medium motion fault +- [ ] Fix every high and medium look fault; no literal colours or radii outside tokens +- [ ] Hide every setting, menu entry and tab of a feature that is Later (PLAN.md), so nothing on screen does nothing +- [ ] Copy, empty states, AccessKit names, focus and 32 px hit targets +- [ ] Test file `docs/tests/S034-motion-audit.md`: each fixed motion with normal, reduced and off; keyboard only; sizes 480, 900, 1600, 3440; light, dark, AMOLED; long names and big numbers +- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S034: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/09 Test and release/S037-whole-app.md b/Plans/09 Test and release/S037-whole-app.md index 205e566..850aa63 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 -- [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 +- [ ] 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 ## 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 b6bf222..a0236ac 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 -- [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 +- [ ] 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 ## 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 1b5a71c..1c13676 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 -- [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 +- [ ] 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 ## 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 aa01f40..d5bdb43 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 -- [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 +- [ ] 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 ## 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 deleted file mode 100644 index bbfa90c..0000000 --- a/Plans/09 Test and release/S044-fix-open-high.md +++ /dev/null @@ -1,29 +0,0 @@ -# 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 deleted file mode 100644 index 65ec6cd..0000000 --- a/Plans/10 Distribution/S045-installer-arch.md +++ /dev/null @@ -1,26 +0,0 @@ -# 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 deleted file mode 100644 index 7473c4c..0000000 --- a/Plans/10 Distribution/S046-fixes-0.1.1.md +++ /dev/null @@ -1,29 +0,0 @@ -# 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 deleted file mode 100644 index 1e120ff..0000000 --- a/Plans/10 Distribution/S047-close-to-tray-wayland.md +++ /dev/null @@ -1,30 +0,0 @@ -# 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 deleted file mode 100644 index d00e3a1..0000000 --- a/Plans/10 Distribution/S048-server-farms.md +++ /dev/null @@ -1,30 +0,0 @@ -# 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 deleted file mode 100644 index f7179a6..0000000 --- a/Plans/10 Distribution/S049-niri-focus.md +++ /dev/null @@ -1,15 +0,0 @@ -# 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 deleted file mode 100644 index c98cc4f..0000000 --- a/Plans/10 Distribution/S050-bug-hunt.md +++ /dev/null @@ -1,17 +0,0 @@ -# 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 7d1afd4..00e2ee1 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -44,33 +44,23 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 06 Media -- [x] [S025](06%20Media/S025-video-sites.md) Video sites through yt-dlp +- [ ] [S025](06%20Media/S025-video-sites.md) Video sites through yt-dlp ## 07 Library and tools -- [x] [S027](07%20Library%20and%20tools/S027-rules-clipboard-drop.md) Rules, clipboard, drag and drop, drop target -- [x] [S033](07%20Library%20and%20tools/S033-tray-notify.md) Tray, notifications and autostart +- [ ] [S027](07%20Library%20and%20tools/S027-rules-clipboard-drop.md) Rules, clipboard, drag and drop, drop target +- [ ] [S033](07%20Library%20and%20tools/S033-tray-notify.md) Tray, notifications and autostart ## 08 Motion and polish -- [x] [S034](08%20Motion%20and%20polish/S034-motion-audit.md) Motion and look pass +- [ ] [S034](08%20Motion%20and%20polish/S034-motion-audit.md) Motion and look pass ## 09 Test 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 +- [ ] [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 🧑 ## Later (after version 1; not run by /orchestrate) diff --git a/README.md b/README.md deleted file mode 100644 index 672c6ae..0000000 --- a/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# 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/assets/medlar.desktop b/assets/medlar.desktop index f003c67..f97ea63 100644 --- a/assets/medlar.desktop +++ b/assets/medlar.desktop @@ -8,5 +8,3 @@ Terminal=false Categories=Network;FileTransfer; StartupWMClass=medlar MimeType=x-scheme-handler/medlar;application/metalink+xml;application/metalink4+xml; -Keywords=download;manager;torrent;video; -X-GNOME-UsesNotifications=true diff --git a/assets/medlar.metainfo.xml b/assets/medlar.metainfo.xml deleted file mode 100644 index 155e3bf..0000000 --- a/assets/medlar.metainfo.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - medlar - Medlar - A download manager - CC0-1.0 - MIT - medlar.desktop - -

Medlar splits downloads into dynamic parts, with limits, priorities, queues, video sites and a local port that takes downloads from browsers.

-
- - medlar - - - Network - FileTransfer - -
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 7117762..b7d8bd8 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -21,14 +21,11 @@ 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 = ["clipboard", "glow", "wayland", "x11", "default_fonts", "system_fonts", "persistence"] } +eframe = { version = "0.37", default-features = false, features = ["glow", "wayland", "x11", "default_fonts", "system_fonts", "persistence"] } tokio = { version = "1", features = ["macros", "rt", "sync"] } percent-encoding = "2.3.2" url = "2" resvg = { version = "0.45", default-features = false } -ksni = { version = "0.3", default-features = false, features = ["async-io", "blocking"] } -zbus = "5" -arboard = { version = "3.6", default-features = false, features = ["wayland-data-control"] } [dev-dependencies] egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 7e278ad..971c896 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -22,8 +22,6 @@ 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. @@ -48,10 +46,6 @@ pub struct App { pub desktop: Desktop, sources: Sources, watch: Watch, - clip: Option, - target: crate::views::target::Target, - /// Tray, notifications and the launcher; only with an engine. - shell: Option, /// What `theme` was made from; a change in settings rebuilds it. themed: Settings, /// What the engine and the shortcuts know. @@ -71,7 +65,6 @@ 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(), @@ -88,9 +81,6 @@ impl App { desktop, sources, watch, - clip: None, - target: Default::default(), - shell: None, save_at: None, saving: None, } @@ -113,7 +103,6 @@ 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); @@ -207,21 +196,13 @@ 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); } } } if self.first.is_none() { - self.shell(ui); self.inbox.tick(ui.ctx(), &self.settings, &mut self.main); - self.extras(ui.ctx(), &t); } let bridge = &self.main.bridge; if let Some(ask) = &mut self.sign_in { @@ -260,140 +241,6 @@ impl App { } } - /// What the tray and the notifications ask for, and what they are told. - fn shell(&mut self, ui: &Ui) { - let ctx = ui.ctx(); - 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, - }; - 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() {} - } - } - - /// The clipboard watcher, the drop target and the full-window drop state. - fn extras(&mut self, ctx: &Context, t: &Theme) { - use crate::bridge::Data; - use crate::views::add::Request; - if self.settings.clipboard != "off" && self.clip.is_none() { - self.clip = Some(crate::clipboard::Watch::start(ctx.clone())); - } - let shot = match self.main.bridge.data() { - Data::Ready(shot, _) => Some(shot), - _ => None, - }; - if let Some(clip) = &self.clip { - let mut links = clip.tick(&self.settings.clipboard, &self.settings.clip_types, &self.settings.clip_skip); - if let Some(shot) = shot.as_ref().filter(|_| !links.is_empty()) { - let known = medlar_core::duplicate::Known::new(shot.iter().map(|v| &*v.task)); - links.retain(|l| known.find(&medlar_core::duplicate::New { url: l, ..Default::default() }).is_none()); - if !links.is_empty() && self.settings.clipboard == "add" { - let request = Request { text: links.join("\n"), literal: true, ..Request::default() }; - let mut add = crate::views::add::Add::new(request, &self.settings); - add.read_text(); - let (tasks, secrets) = add.tasks(); - self.main.toasts.info("content_paste", tr!("clip.added", n = tasks.len())); - self.main.bridge.add(tasks, secrets); - } else if !links.is_empty() { - crate::views::incoming::raise(ctx); - self.main.adding.ask(Request { text: links.join("\n"), literal: true, ..Request::default() }); - } - } - } - let speed = shot.as_ref().map_or(0.0, |s| s.iter().map(|v| v.speed).sum()); - self.target.show(ctx, t, &mut self.settings, &mut self.main, speed); - if self.screen.is_none() { - crate::drop::overlay(ctx, t); - } - } - fn settings_screen(&mut self, ui: &mut Ui, t: &Theme, screen: &mut View) -> bool { let main = &mut self.main; let mut cx = Cx { t, s: &mut self.settings, desktop: self.desktop, bridge: &main.bridge, toasts: &mut main.toasts, paths: self.paths.as_ref() }; @@ -448,7 +295,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 => self.quit(ui.ctx()), + Action::Quit => ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close), other => { let anywhere = matches!(other, Action::ResumeAll | Action::PauseAll); if self.screen.is_some() && !anywhere { @@ -461,14 +308,13 @@ impl 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, +/// The app and which of its screens the window shows. +struct Window { + app: 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); } @@ -477,9 +323,10 @@ impl eframe::App for Window<'_> { self.app.theme.surface.to_normalized_gamma_f32() } - /// Writes the settings; the downloads are saved when the app quits. + /// Saves where the downloads are. 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. @@ -495,12 +342,9 @@ pub fn run() -> ExitCode { /// Whether the arguments are for a window: links of the `medlar:` scheme and link lists, as a desktop hands them over. pub fn wants(args: &[String]) -> bool { - !args.is_empty() && args.iter().all(|a| a == MINIMISED || of_arg(a).is_some()) + !args.is_empty() && args.iter().all(|a| of_arg(a).is_some()) } -/// Starts in the tray when there is one (what autostart passes). -pub const MINIMISED: &str = "--minimised"; - /// Opens the window with something to add, or hands it to the Medlar that runs and returns. pub fn run_with(args: Vec) -> ExitCode { open(true, App::show, args) @@ -512,9 +356,7 @@ pub fn run_gallery() -> ExitCode { } /// `engine`: with the downloads, else only the window. -fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec) -> ExitCode { - let minimised = args.iter().any(|a| a == MINIMISED); - args.retain(|a| a != MINIMISED); +fn open(engine: bool, show: fn(&mut App, &mut Ui), args: Vec) -> ExitCode { let paths = Paths::detect(); if let Err(e) = paths.create() { eprintln!("{}: {e}", paths.config.display()); @@ -539,62 +381,6 @@ 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) @@ -603,13 +389,38 @@ fn options(paths: &Paths) -> eframe::NativeOptions { if let Some(rgba) = icons::app_rgba(128) { viewport = viewport.with_icon(Arc::new(egui::IconData { rgba, width: 128, height: 128 })); } - eframe::NativeOptions { + let options = 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); + } + 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/autostart.rs b/crates/app/src/autostart.rs deleted file mode 100644 index 96115df..0000000 --- a/crates/app/src/autostart.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! The autostart entry: `/autostart/medlar.desktop`. Callers pass the config folder, so that tests use a -//! throwaway one. - -use std::io; -use std::path::{Path, PathBuf}; - -pub const FILE: &str = "medlar.desktop"; - -/// The entry's text. `exe` is the AppImage when there is one, else this program. -pub fn entry(exe: &Path, minimised: bool) -> String { - let exe = exe.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\""); - let quoted = if exe.contains([' ', '\t']) { format!("\"{exe}\"") } else { exe }; - let flag = if minimised { " --minimised" } else { "" }; - format!( - "[Desktop Entry]\nType=Application\nName=Medlar\nComment=Download manager\nExec={quoted}{flag}\nIcon=medlar\nTerminal=false\nX-GNOME-Autostart-enabled=true\n" - ) -} - -fn program() -> PathBuf { - std::env::var_os("APPIMAGE").map(PathBuf::from).or_else(|| std::env::current_exe().ok()).unwrap_or_else(|| "medlar".into()) -} - -/// Makes the entry exist (`on`) or not. Without a config folder nothing is done. -pub fn sync(config: Option, on: bool, minimised: bool) -> io::Result<()> { - let Some(config) = config else { return Ok(()) }; - sync_with(&config, &program(), on, minimised) -} - -pub fn sync_with(config: &Path, exe: &Path, on: bool, minimised: bool) -> io::Result<()> { - let file = config.join("autostart").join(FILE); - if !on { - return match std::fs::remove_file(&file) { - Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), - _ => Ok(()), - }; - } - std::fs::create_dir_all(file.parent().unwrap_or(config))?; - std::fs::write(file, entry(exe, minimised)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn writes_and_removes() { - let dir = tempfile::tempdir().unwrap(); - sync_with(dir.path(), Path::new("/opt/My Apps/medlar"), true, true).unwrap(); - let text = std::fs::read_to_string(dir.path().join("autostart").join(FILE)).unwrap(); - assert!(text.contains("Exec=\"/opt/My Apps/medlar\" --minimised\n")); - sync_with(dir.path(), Path::new("medlar"), false, false).unwrap(); - assert!(!dir.path().join("autostart").join(FILE).exists()); - sync_with(dir.path(), Path::new("medlar"), false, false).unwrap(); - } -} diff --git a/crates/app/src/bridge.rs b/crates/app/src/bridge.rs index 1c455ea..12bc259 100644 --- a/crates/app/src/bridge.rs +++ b/crates/app/src/bridge.rs @@ -249,11 +249,6 @@ 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 deleted file mode 100644 index 5012d38..0000000 --- a/crates/app/src/clipboard.rs +++ /dev/null @@ -1,165 +0,0 @@ -//! Links that are copied (FEATURES 3.4). A thread looks at the clipboard once a second while the setting is on and -//! hands over what is new. What was there at the start, what the same text again and what Medlar copied itself are -//! left alone. -//! -//! On Wayland a program may read the clipboard only through the data-control protocol, which some compositors do not -//! offer; then nothing is seen and the page says so. X11 and XWayland work as they are. - -use medlar_core::batch::Batch; -use medlar_core::site::Pattern; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{Receiver, channel}; -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); - -pub fn works() -> bool { - WORKS.load(Ordering::Relaxed) -} - -/// What Medlar put on the clipboard last. -static OWN: Mutex = Mutex::new(String::new()); - -/// Copies for the user and remembers that they are ours. -pub fn copy(ctx: &eframe::egui::Context, text: String) { - *OWN.lock().unwrap() = text.clone(); - ctx.copy_text(text); -} - -/// The links in a copied text that the filters let through. -pub fn links(text: &str, types: &[String], skip: &[String]) -> Vec { - let skip: Vec = skip.iter().map(|s| Pattern::new(s)).collect(); - Batch::of(text, false) - .links - .into_iter() - .filter(|l| { - let Ok(url) = Url::parse(l) else { return false }; - let path = url.path().to_ascii_lowercase(); - let ext = path.rsplit_once('.').map(|(_, e)| e).unwrap_or_default(); - (types.is_empty() || types.iter().any(|t| t.trim_start_matches('.').eq_ignore_ascii_case(ext))) && !skip.iter().any(|p| p.fits(&url)) - }) - .collect() -} - -/// The thread that looks. -pub struct Watch { - on: Arc, - found: Receiver, -} - -impl Watch { - pub fn start(ctx: eframe::egui::Context) -> Watch { - let (tx, found) = channel(); - let on = Arc::new(AtomicBool::new(false)); - let flag = on.clone(); - let spawned = std::thread::Builder::new().name("clipboard".into()).spawn(move || { - let mut board = None; - let mut last: Option = None; - loop { - std::thread::sleep(Duration::from_secs(1)); - if !flag.load(Ordering::Relaxed) { - // What is copied while it is off is not news when it goes on. - last = None; - continue; - } - if board.is_none() { - board = arboard::Clipboard::new().map_err(|e| log::info!("clipboard: {e}")).ok(); - } - let Some(b) = &mut board else { - WORKS.store(false, Ordering::Relaxed); - continue; - }; - WORKS.store(true, Ordering::Relaxed); - // 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(); - } - } - }); - if let Err(e) = spawned { - log::warn!("clipboard: {e}"); - WORKS.store(false, Ordering::Relaxed); - } - Watch { on, found } - } - - /// Follows the setting. Returns the new links, if any. - pub fn tick(&self, mode: &str, types: &[String], skip: &[String]) -> Vec { - self.on.store(mode == "ask" || mode == "add", Ordering::Relaxed); - let mut out = vec![]; - while let Ok(text) = self.found.try_recv() { - if mode != "off" { - out.extend(links(&text, types, skip)); - } - } - out - } -} - -#[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] - fn filters() { - let text = "see https://a.test/x.zip and https://b.test/y.iso and https://a.test/page"; - assert_eq!(links(text, &[], &[]).len(), 3); - assert_eq!(links(text, &["zip".into(), ".iso".into()], &[]).len(), 2); - assert_eq!(links(text, &[], &["*.test".into()]).len(), 0); - assert_eq!(links(text, &[], &["b.test".into()]).len(), 2); - assert!(links("no links here", &[], &[]).is_empty()); - } -} diff --git a/crates/app/src/drop.rs b/crates/app/src/drop.rs deleted file mode 100644 index 558956f..0000000 --- a/crates/app/src/drop.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! Things let go over a window (FEATURES 3.9): files (lists of links, `.metalink`) and, where the windowing system -//! passes them on as a path, links. The toolkit hands over no dropped text, so a link dragged from a browser's address -//! bar arrives only where the browser makes a file or `://` path of it; paste into the Add window otherwise. A full-window state shows while something is over the window. - -use crate::fonts; -use crate::theme::{Theme, alpha}; -use crate::tokens::{radius, size, space, spring, text}; -use crate::views::add::Request; -use crate::ui::widgets::cr; -use eframe::egui::{Align2, Context, Id, LayerId, Order, Stroke, StrokeKind}; -use medlar_core::tr; - -#[allow(deprecated)] -fn id() -> Id { - Id::new("drop overlay") -} - -/// What was dropped, as asks for the Add window. Text counts when it holds links. -pub fn requests(ctx: &Context) -> Vec { - let files = ctx.input(|i| i.raw.dropped_files.clone()); - let mut out = vec![]; - let mut texts: Vec = vec![]; - for f in files { - let path = f.path().to_path_buf(); - let shown = path.to_string_lossy(); - // Some sources hand a link over as if it were a file. - if shown.contains("://") { - texts.push(shown.into_owned()); - } else { - out.push(Request { list: Some(path), ..Request::default() }); - } - } - if !texts.is_empty() { - out.push(Request { text: texts.join("\n"), ..Request::default() }); - } - out -} - -/// Something is over the window. -pub fn hovering(ctx: &Context) -> bool { - ctx.input(|i| !i.raw.hovered_files.is_empty()) -} - -/// How much the window dims under the drop state. -const DIM: f32 = 0.86; - -/// The full-window state: the window dims, a frame and a line say what happens. It fades in and out. -pub fn overlay(ctx: &Context, t: &Theme) { - let shown = crate::motion::spring(id().with("shown"), f32::from(hovering(ctx)), spring::EFFECT).clamp(0.0, 1.0); - if shown <= 0.0 { - return; - } - let rect = ctx.content_rect(); - let p = ctx.layer_painter(LayerId::new(Order::Foreground, id())); - p.rect_filled(rect, 0.0, alpha(t.surface, DIM * shown)); - let frame = rect.shrink(space::L); - p.rect_stroke(frame, cr(radius::L), Stroke::new(size::FOCUS_RING, alpha(t.primary, shown)), StrokeKind::Inside); - p.text(frame.center(), Align2::CENTER_CENTER, tr!("drop.here"), fonts::med(text::TITLE), alpha(t.on_surface, shown)); - let below = frame.center() + eframe::egui::vec2(0.0, text::TITLE + space::M); - p.text(below, Align2::CENTER_CENTER, tr!("drop.what"), fonts::ui(text::BODY), alpha(t.on_variant, shown)); -} diff --git a/crates/app/src/icondata.rs b/crates/app/src/icondata.rs index 12b2baf..c85f54e 100644 --- a/crates/app/src/icondata.rs +++ b/crates/app/src/icondata.rs @@ -121,8 +121,6 @@ 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 74705b5..ccd944e 100644 --- a/crates/app/src/keys.rs +++ b/crates/app/src/keys.rs @@ -174,11 +174,6 @@ 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()); @@ -258,7 +253,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() || keys.edits()) && ui.ctx().text_edit_focused() { + if keys.types() && ui.ctx().text_edit_focused() { return false; } ui.input_mut(|i| { @@ -287,37 +282,6 @@ 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/launcher.rs b/crates/app/src/launcher.rs deleted file mode 100644 index a870bb5..0000000 --- a/crates/app/src/launcher.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Progress on the dock or launcher icon, through the Unity launcher entry signal that KDE, GNOME's dash-to-dock and -//! others read. Nothing happens when there is no session bus. - -use std::collections::HashMap; -use zbus::blocking::Connection; -use zbus::zvariant::Value; - -const URI: &str = "application://medlar.desktop"; - -pub struct Launcher { - conn: Connection, -} - -impl Launcher { - pub fn start() -> Option { - Connection::session().ok().map(|conn| Launcher { conn }) - } - - /// `progress` 0 to 1, None to hide the bar; `count` shows as the badge when above 0. - pub fn set(&self, progress: Option, count: usize) { - let mut props: HashMap<&str, Value> = HashMap::new(); - props.insert("progress", Value::from(progress.unwrap_or(0.0))); - props.insert("progress-visible", Value::from(progress.is_some())); - props.insert("count", Value::from(count as i64)); - props.insert("count-visible", Value::from(count > 0)); - let sent = self.conn.emit_signal(None::<&str>, "/com/canonical/unity/launcherentry/medlar", "com.canonical.Unity.LauncherEntry", "Update", &(URI, props)); - if let Err(e) = sent { - log::debug!("launcher: {e}"); - } - } -} diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 06b4434..47a9907 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -1,10 +1,7 @@ //! Medlar's window: theme, motion, widgets and views. pub mod app; -pub mod autostart; pub mod bridge; -pub mod clipboard; -pub mod drop; pub mod desktop; pub mod fonts; #[rustfmt::skip] @@ -12,14 +9,9 @@ mod icondata; pub mod icons; pub mod instance; pub mod keys; -pub mod launcher; pub mod motion; -pub mod niri; -pub mod notify; -pub mod shell; pub mod theme; pub mod tokens; -pub mod tray; pub mod ui; pub mod views; diff --git a/crates/app/src/niri.rs b/crates/app/src/niri.rs deleted file mode 100644 index 0333189..0000000 --- a/crates/app/src/niri.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! 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 deleted file mode 100644 index a40293a..0000000 --- a/crates/app/src/notify.rs +++ /dev/null @@ -1,238 +0,0 @@ -//! Desktop notifications (org.freedesktop.Notifications): done, failed, needs a login, all done. Actions come back as -//! `Do`. A batch of many of one kind becomes one summary; quiet hours send nothing. - -use crate::shell::Do; -use eframe::egui::Context; -use medlar_core::model::{ErrorKind, State, TaskId}; -use medlar_core::settings::Settings; -use medlar_core::snapshot::Snapshot; -use medlar_core::tr; -use std::collections::HashMap; -use std::path::PathBuf; -use std::sync::mpsc::Sender; -use std::sync::{Arc, Mutex}; -use zbus::blocking::Connection; -use zbus::zvariant::Value; - -#[derive(Debug, Clone, PartialEq)] -pub enum Event { - Done { id: TaskId, name: String, file: PathBuf }, - Failed { id: TaskId, name: String, why: String }, - Login { id: TaskId, name: String, url: String }, - AllDone, -} - -/// Sees what changed between snapshots. The first one only sets the baseline. -#[derive(Default)] -pub struct Watcher { - seen: HashMap, - started: bool, - busy: bool, - finished: bool, -} - -fn working(s: State) -> bool { - matches!(s, State::Queued | State::Waiting | State::Running | State::Checking | State::Finishing) -} - -impl Watcher { - pub fn feed(&mut self, shot: &Snapshot) -> Vec { - let mut out = vec![]; - let (mut busy, mut paused) = (false, false); - for v in shot.iter() { - let (id, state) = (v.id(), v.state()); - busy |= working(state); - let before = self.seen.insert(id, state); - let Some(before) = before.filter(|_| self.started) else { continue }; - if before == state || !working(before) && before != State::Paused { - continue; - } - let t = &v.task; - match state { - State::Done => { - self.finished = true; - out.push(Event::Done { id, name: t.name.clone(), file: t.folder.join(&t.name) }); - } - State::Failed => match &t.error { - 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; - // The last one being paused is not an end. - if !paused { - out.push(Event::AllDone); - } - } - self.busy = busy; - self.started = true; - out - } -} - -/// Minutes since midnight in the quiet span, which may wrap past midnight. Equal ends mean no span. -pub fn quiet_at(from: u32, to: u32, now: u32) -> bool { - match from.cmp(&to) { - std::cmp::Ordering::Equal => false, - std::cmp::Ordering::Less => (from..to).contains(&now), - std::cmp::Ordering::Greater => now >= from || now < to, - } -} - -pub fn quiet_now(s: &Settings) -> bool { - use chrono::Timelike; - let now = chrono::Local::now(); - s.quiet && quiet_at(s.quiet_from, s.quiet_to, now.hour() * 60 + now.minute()) -} - -/// One notification to show. -#[derive(Debug, Clone, PartialEq)] -pub struct Note { - pub summary: String, - pub body: String, - /// `transfer.complete`, `transfer.error` or `network`. - pub category: &'static str, - /// (key, label, what it does). - pub actions: Vec<(&'static str, String, Do)>, -} - -/// More than this many of one kind in one batch are a summary. -const MOST: usize = 3; - -pub fn notes(events: &[Event]) -> Vec { - let done: Vec<_> = events.iter().filter(|e| matches!(e, Event::Done { .. })).collect(); - let failed: Vec<_> = events.iter().filter(|e| matches!(e, Event::Failed { .. })).collect(); - let mut out = vec![]; - if done.len() > MOST { - out.push(Note { summary: tr!("notify.many_done", n = done.len()), body: String::new(), category: "transfer.complete", actions: vec![("show", tr!("notify.show"), Do::Show)] }); - } - if failed.len() > MOST { - out.push(Note { summary: tr!("notify.many_failed", n = failed.len()), body: String::new(), category: "transfer.error", actions: vec![("show", tr!("notify.show"), Do::Show)] }); - } - for e in events { - match e { - Event::Done { name, file, .. } if done.len() <= MOST => out.push(Note { - summary: tr!("notify.done"), - body: name.clone(), - category: "transfer.complete", - actions: vec![("open", tr!("notify.open"), Do::Open(file.clone())), ("folder", tr!("notify.folder"), Do::Folder(file.clone()))], - }), - Event::Failed { id, name, why } if failed.len() <= MOST => out.push(Note { - summary: tr!("notify.failed"), - body: if why.is_empty() { name.clone() } else { format!("{name}\n{why}") }, - category: "transfer.error", - actions: vec![("retry", tr!("notify.retry"), Do::Retry(*id))], - }), - Event::Login { id, name, url } => out.push(Note { - summary: tr!("notify.login"), - body: name.clone(), - category: "network", - actions: vec![("continue", tr!("notify.continue"), Do::SignIn(url.clone(), *id))], - }), - Event::AllDone => out.push(Note { summary: tr!("notify.all_done"), body: String::new(), category: "transfer.complete", actions: vec![("show", tr!("notify.show"), Do::Show)] }), - _ => {} - } - } - out -} - -type Shown = Arc>>>; - -/// Sends notes through a bus connection and turns clicks on their buttons into `Do`. -pub struct Notifier { - conn: Connection, - shown: Shown, -} - -impl Notifier { - pub fn start(conn: Connection, tx: Sender, ctx: Context) -> Notifier { - let shown: Shown = Arc::default(); - let (listen, map) = (conn.clone(), shown.clone()); - std::thread::spawn(move || listen_for_actions(listen, map, tx, ctx)); - Notifier { conn, shown } - } - - /// Shows what the events call for, unless it is quiet. Never blocks the window: it is sent from a thread. - pub fn send(&self, events: &[Event], settings: &Settings) { - if events.is_empty() || quiet_now(settings) { - return; - } - let list = notes(events); - let (conn, shown) = (self.conn.clone(), self.shown.clone()); - std::thread::spawn(move || { - for note in list { - match show(&conn, ¬e) { - Ok(id) => { - shown.lock().unwrap_or_else(|e| e.into_inner()).insert(id, note.actions.into_iter().map(|(k, _, d)| (k, d)).collect()); - } - Err(e) => log::debug!("notification: {e}"), - } - } - }); - } -} - -fn show(conn: &Connection, note: &Note) -> zbus::Result { - let mut actions: Vec<&str> = vec![]; - for (key, label, _) in ¬e.actions { - actions.extend([*key, label.as_str()]); - } - let mut hints: HashMap<&str, Value> = HashMap::new(); - hints.insert("desktop-entry", Value::from("medlar")); - hints.insert("category", Value::from(note.category)); - let reply = conn.call_method( - Some("org.freedesktop.Notifications"), - "/org/freedesktop/Notifications", - Some("org.freedesktop.Notifications"), - "Notify", - &("Medlar", 0u32, "medlar", note.summary.as_str(), note.body.as_str(), actions, hints, -1i32), - )?; - reply.body().deserialize::() -} - -fn listen_for_actions(conn: Connection, shown: Shown, tx: Sender, ctx: Context) { - let Ok(rule) = zbus::MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .interface("org.freedesktop.Notifications") - .and_then(|b| b.member("ActionInvoked")) - .map(|b| b.build()) - else { - return; - }; - let Ok(messages) = zbus::blocking::MessageIterator::for_match_rule(rule, &conn, None) else { return }; - for message in messages.flatten() { - let Ok((id, key)) = message.body().deserialize::<(u32, String)>() else { continue }; - let what = shown.lock().unwrap_or_else(|e| e.into_inner()).get(&id).and_then(|a| a.iter().find(|(k, _)| *k == key).map(|(_, d)| d.clone())); - if let Some(what) = what { - // Opening and showing a folder need no window, but the window is the one that does them. - let _ = tx.send(what); - ctx.request_repaint(); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn quiet_span_wraps_midnight() { - assert!(quiet_at(22 * 60, 7 * 60, 23 * 60)); - assert!(quiet_at(22 * 60, 7 * 60, 3 * 60)); - assert!(!quiet_at(22 * 60, 7 * 60, 12 * 60)); - assert!(quiet_at(9 * 60, 17 * 60, 10 * 60)); - assert!(!quiet_at(9 * 60, 9 * 60, 9 * 60)); - } - - #[test] - fn many_of_a_kind_become_one() { - let done = |i| Event::Done { id: i, name: format!("f{i}"), file: PathBuf::from("/x") }; - assert_eq!(notes(&[done(1), done(2)]).len(), 2); - let many: Vec<_> = (1..=5).map(done).collect(); - assert_eq!(notes(&many).len(), 1); - } -} diff --git a/crates/app/src/shell.rs b/crates/app/src/shell.rs deleted file mode 100644 index e2cffb5..0000000 --- a/crates/app/src/shell.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! What the window shares with the desktop: tray, notifications, launcher progress and autostart. -//! 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}; -use crate::tray::{Tray, TrayState}; -use eframe::egui::Context; -use medlar_core::model::TaskId; -use medlar_core::settings::{Mode, Settings}; -use medlar_core::snapshot::Snapshot; -use std::path::PathBuf; -use std::sync::mpsc::{Receiver, Sender, channel}; - -/// What the tray or a notification asks the window to do. -#[derive(Debug, Clone, PartialEq)] -pub enum Do { - Show, - Add, - PauseAll, - ResumeAll, - Mode(Mode), - Quit, - Open(PathBuf), - Folder(PathBuf), - SignIn(String, TaskId), - Retry(TaskId), -} - -pub struct Shell { - pub tray: Option, - notes: Option, - launcher: Option, - 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), - /// Set by `Do::Quit`, so that closing really closes. - pub quitting: bool, -} - -impl Shell { - pub fn start(ctx: &Context, settings: &Settings) -> Shell { - let (tx, rx): (Sender, Receiver) = channel(); - let tray = settings.tray.then(|| Tray::start(tx.clone(), ctx.clone())).flatten(); - let notes = zbus::blocking::Connection::session().ok().map(|c| Notifier::start(c, tx, ctx.clone())); - Shell { - tray, - notes, - launcher: Launcher::start(), - 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 leaves Medlar running in the tray instead of quitting. - pub fn hides_on_close(&self, settings: &Settings) -> bool { - hides(self.quitting, settings.close_to_tray, self.tray.is_some()) - } - - /// Once per frame: what was asked comes back, what changed goes out. - pub fn tick(&mut self, settings: &Settings, shot: Option<&Snapshot>) -> Vec { - let want = (settings.autostart, settings.start_minimised); - if want != self.autostart { - self.autostart = want; - if let Err(e) = crate::autostart::sync(dirs::config_dir(), want.0, want.1) { - log::warn!("autostart: {e}"); - } - } - if let Some(shot) = shot { - let fresh = shot.rev != self.rev; - self.rev = shot.rev; - if fresh { - let events = self.watcher.feed(shot); - if let Some(notes) = self.notes.as_ref().filter(|_| settings.notify) { - notes.send(&events, settings); - } - } - 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()); - } - if let Some(launcher) = &self.launcher { - launcher.set(state.progress, state.running); - } - self.shown = Some(state); - } - } - 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/tray.rs b/crates/app/src/tray.rs deleted file mode 100644 index 20b90f4..0000000 --- a/crates/app/src/tray.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! The tray icon (StatusNotifierItem): a progress ring around the app icon, the speed as tooltip and a menu. -//! Without a StatusNotifierWatcher on the bus `start` gives None, and the window closes as usual. - -use crate::shell::Do; -use crate::ui::odometer::rate; -use eframe::egui::Context; -use ksni::blocking::{Handle, TrayMethods}; -use medlar_core::model::State; -use medlar_core::settings::Mode; -use medlar_core::snapshot::Snapshot; -use medlar_core::tr; -use std::sync::mpsc::Sender; - -const SIZE: u32 = 64; - -/// What the tray shows; sent only when it changes. -#[derive(Debug, Clone, PartialEq)] -pub struct TrayState { - pub running: usize, - /// Bytes per second. - pub speed: u64, - /// Share done of the downloads that run, None when none do. - pub progress: Option, - pub mode: Mode, -} - -impl TrayState { - pub fn of(shot: &Snapshot, mode: Mode) -> TrayState { - let (mut size, mut done, mut running) = (0u64, 0u64, 0usize); - for v in shot.iter().filter(|v| matches!(v.state(), State::Running | State::Checking | State::Finishing)) { - running += 1; - size += v.size.unwrap_or(0); - done += v.downloaded.min(v.size.unwrap_or(0)); - } - let progress = (running > 0 && size > 0).then(|| (done as f64 / size as f64).clamp(0.0, 1.0)); - // Whole percents and 1 KiB/s steps, so that a changing speed doesn't rebuild the icon every frame. - let progress = progress.map(|p| (p * 100.0).round() / 100.0); - TrayState { running, speed: (shot.totals.speed / 1024.0).round() as u64 * 1024, progress, mode } - } -} - -/// The app icon (straight RGBA, `SIZE` square) with a ring around it: a faint track, and the done part from the top. -pub fn ring_rgba(base: &[u8], progress: Option) -> Vec { - let mut out = base.to_vec(); - let Some(p) = progress else { return out }; - let c = SIZE as f32 / 2.0; - let (outer, inner) = (c - 0.5, c - 7.0); - for y in 0..SIZE { - for x in 0..SIZE { - let (dx, dy) = (x as f32 + 0.5 - c, y as f32 + 0.5 - c); - let d = (dx * dx + dy * dy).sqrt(); - if d < inner || d > outer { - continue; - } - // Clockwise from the top, in 0..1. - let turn = (dx.atan2(-dy) / std::f32::consts::TAU).rem_euclid(1.0); - let px = &mut out[((y * SIZE + x) * 4) as usize..][..4]; - let colour = if (turn as f64) <= p { [255, 255, 255, 255] } else { [255, 255, 255, 70] }; - px.copy_from_slice(&colour); - } - } - out -} - -/// SNI wants ARGB32 in network byte order. -pub fn argb(rgba: &[u8]) -> Vec { - rgba.chunks_exact(4).flat_map(|p| [p[3], p[0], p[1], p[2]]).collect() -} - -struct Item { - tx: Sender, - ctx: Context, - base: Vec, - state: Option, -} - -impl Item { - fn send(&self, what: Do) { - let _ = self.tx.send(what); - self.ctx.request_repaint(); - } - - fn icon(&self) -> ksni::Icon { - let rgba = ring_rgba(&self.base, self.state.as_ref().and_then(|s| s.progress)); - ksni::Icon { width: SIZE as i32, height: SIZE as i32, data: argb(&rgba) } - } -} - -const MODES: [Mode; 4] = [Mode::Low, Mode::Medium, Mode::High, Mode::Snail]; - -impl ksni::Tray for Item { - fn id(&self) -> String { - "medlar".into() - } - - fn title(&self) -> String { - "Medlar".into() - } - - fn icon_name(&self) -> String { - String::new() - } - - fn icon_pixmap(&self) -> Vec { - vec![self.icon()] - } - - fn tool_tip(&self) -> ksni::ToolTip { - let description = match &self.state { - Some(s) if s.running > 0 => tr!("tray.tip_running", n = s.running, speed = rate(s.speed as f64)), - _ => tr!("tray.tip_idle"), - }; - ksni::ToolTip { icon_name: String::new(), icon_pixmap: vec![self.icon()], title: "Medlar".into(), description } - } - - fn activate(&mut self, _x: i32, _y: i32) { - self.send(Do::Show); - } - - fn menu(&self) -> Vec> { - use ksni::menu::*; - let item = |label: String, icon: &str, what: Do| -> ksni::MenuItem { - StandardItem { label, icon_name: icon.into(), activate: Box::new(move |t: &mut Self| t.send(what.clone())), ..Default::default() }.into() - }; - let mode = self.state.as_ref().map_or(Mode::High, |s| s.mode); - let modes = RadioGroup { - selected: MODES.iter().position(|m| *m == mode).unwrap_or(2), - select: Box::new(|t: &mut Self, i| t.send(Do::Mode(MODES[i]))), - options: MODES.iter().map(|m| RadioItem { label: crate::views::modes::label(*m), ..Default::default() }).collect(), - }; - vec![ - item(tr!("tray.show"), "window", Do::Show), - item(tr!("tray.add"), "list-add", Do::Add), - MenuItem::Separator, - modes.into(), - MenuItem::Separator, - item(tr!("tray.pause_all"), "media-playback-pause", Do::PauseAll), - item(tr!("tray.resume_all"), "media-playback-start", Do::ResumeAll), - MenuItem::Separator, - item(tr!("tray.quit"), "application-exit", Do::Quit), - ] - } -} - -pub struct Tray { - handle: Handle, -} - -impl Tray { - /// None when the desktop has no tray host (or the bus is out of reach). - pub fn start(tx: Sender, ctx: Context) -> Option { - let base = crate::icons::app_rgba(SIZE)?; - match (Item { tx, ctx, base, state: None }).spawn() { - Ok(handle) => Some(Tray { handle }), - Err(e) => { - log::info!("tray: {e}"); - None - } - } - } - - pub fn set(&self, state: TrayState) { - let _ = self.handle.update(move |t: &mut Item| t.state = Some(state)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ring_is_only_drawn_with_progress() { - let base = vec![0u8; (SIZE * SIZE * 4) as usize]; - assert_eq!(ring_rgba(&base, None), base); - let half = ring_rgba(&base, Some(0.5)); - let at = |x: u32, y: u32| half[((y * SIZE + x) * 4 + 3) as usize]; - // Right of centre, on the ring: done. Left: only the track. - assert_eq!(at(SIZE - 3, SIZE / 2), 255); - assert_eq!(at(2, SIZE / 2), 70); - assert_eq!(at(SIZE / 2, SIZE / 2), 0); - } - - #[test] - fn argb_moves_alpha_first() { - assert_eq!(argb(&[1, 2, 3, 4]), vec![4, 1, 2, 3]); - } -} diff --git a/crates/app/src/ui/dialog.rs b/crates/app/src/ui/dialog.rs index 3cca7c4..e30de03 100644 --- a/crates/app/src/ui/dialog.rs +++ b/crates/app/src/ui/dialog.rs @@ -227,8 +227,7 @@ impl<'a> Dialog<'a> { } }); let height = (ui.min_rect().height() + 2.0 * pad).min(room.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) { + if known != Some(height) { 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 6ca1210..9507059 100644 --- a/crates/app/src/ui/mod.rs +++ b/crates/app/src/ui/mod.rs @@ -11,6 +11,5 @@ 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 bdd59e3..4a63b4c 100644 --- a/crates/app/src/ui/odometer.rs +++ b/crates/app/src/ui/odometer.rs @@ -96,50 +96,9 @@ 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)); @@ -158,29 +117,6 @@ 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 deleted file mode 100644 index ded400c..0000000 --- a/crates/app/src/ui/snail.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! 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 636766d..d7f8962 100644 --- a/crates/app/src/ui/wave.rs +++ b/crates/app/src/ui/wave.rs @@ -293,17 +293,6 @@ 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 5fd0518..1dfb77d 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() && !self.video_empty()); + let good = n > 0 && (free || !wrong.any()); 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,12 +99,6 @@ 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); @@ -112,7 +106,6 @@ 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); @@ -161,7 +154,6 @@ 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); @@ -201,7 +193,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) && !matches!(self.video, Some(Page::Ready(_))); + let warn = matches!(&self.look, Look::Found(p) if p.page); 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 f71248f..de4c8ed 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -10,7 +10,6 @@ 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}; @@ -341,10 +340,6 @@ 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, folder_own: bool, pub queue: QueueId, @@ -368,9 +363,6 @@ 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. @@ -405,9 +397,6 @@ 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(), folder_own: false, queue: medlar_core::model::MAIN_QUEUE, @@ -429,8 +418,6 @@ impl Add { focus_links: true, asked: None, look: Look::Nothing, - video: None, - video_asked: None, still: false, sought: None, known: None, @@ -521,7 +508,6 @@ 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) { @@ -589,7 +575,6 @@ 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(); } @@ -602,16 +587,7 @@ impl Add { ctx.request_repaint(); } Look::Asks(reply) => match poll(reply, ctx) { - 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(Ok(found)) => 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 => {} @@ -620,39 +596,10 @@ 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); } @@ -816,8 +763,6 @@ impl Add { // One item for each site and login. Others can't use it: it has a home. let mut names: HashMap<(String, Option<(String, String)>), String> = HashMap::new(); let (mut tasks, mut secrets) = (vec![], vec![]); - let mut used = std::collections::HashSet::new(); - let mut templated: Vec = vec![]; // What was typed is for the site of the first link. let home = links.first().and_then(|l| place(l)); for link in links { @@ -832,42 +777,13 @@ impl Add { }) }); let secret = name.map(|n| n.clone()); - let mut task = Task { url, secret, ..common.clone() }; - // The rules fill in what the user left as it was. - let own = if single.is_some() { self.name.trim().to_string() } else { String::new() }; - let item = medlar_core::rules::Item { url: &task.url, name: &own, mime: self.from.mime.as_deref(), size: self.from.size }; - let o = medlar_core::rules::apply(&self.rules, &item, &self.base, Local::now().date_naive()); - if let Some(f) = o.folder.filter(|_| !self.folder_own) { - task.folder = f; - } - if let Some(q) = o.queue.filter(|_| self.queue == medlar_core::model::MAIN_QUEUE) { - task.queue = q; - } - if let Some(p) = o.priority.filter(|_| self.priority == Priority::Normal) { - task.priority = p; - } - task.tags = o.tags; - if let Some(n) = o.name { - task.name = medlar_core::rules::free_name(&n, &task.folder, &mut used); - templated.push(task.name.clone()); - } else { - templated.push(String::new()); - } - tasks.push(task); + tasks.push(Task { url, secret, ..common.clone() }); } if let ([task], Some(_)) = (&mut tasks[..], single) { // Without one the server names it. task.name = if self.name_own { self.name.trim().to_string() } else { String::new() }; - if let Some(n) = templated.first().filter(|n| !n.is_empty()) { - task.name = n.clone(); - } 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 3564857..c418e5f 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, - pub tab: usize, + 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: "", 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) }, + 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) }, ]; 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 60763d5..ea046b2 100644 --- a/crates/app/src/views/details/tabs.rs +++ b/crates/app/src/views/details/tabs.rs @@ -84,7 +84,7 @@ fn props(ui: &mut Ui, t: &Theme, id: &str, rows: &[(String, String)]) { ui.label(RichText::new(name).font(fonts::ui(text::LABEL)).color(t.on_variant)); let r = ui.add(Label::new(RichText::new(value).font(fonts::ui(text::BODY)).color(t.on_surface)).wrap().sense(Sense::click())); if r.clicked() { - crate::clipboard::copy(ui.ctx(), value.clone()); + ui.ctx().copy_text(value.clone()); } r.on_hover_text(tr!("details.copy")); ui.end_row(); @@ -349,7 +349,7 @@ pub fn log(ui: &mut Ui, cx: &mut Cx, filter: &mut String) { ui.horizontal(|ui| { Field::new(&label).width((ui.available_width() - size::CONTROL - space::S).max(80.0)).show(ui, t, filter); if Button::icon("content_copy", &tr!("details.log.copy")).show(ui, t).clicked() { - crate::clipboard::copy(ui.ctx(), log_lines(&v.log, filter).join("\n")); + ui.ctx().copy_text(log_lines(&v.log, filter).join("\n")); } }); let lines = log_lines(&v.log, filter); @@ -439,39 +439,3 @@ 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 8cd2712..ab438fe 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, UserAttentionType, ViewportCommand}; +use eframe::egui::{Context, ViewportCommand}; use medlar_core::connector::{Arrival, Connector, Incoming as Link}; use medlar_core::model::TaskId; use medlar_core::relink::{self, NewLink, Strength}; @@ -18,7 +18,6 @@ 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; @@ -39,31 +38,6 @@ 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 { @@ -74,16 +48,10 @@ 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() { - raise(ctx); - self.attention = true; + ctx.send_viewport_cmd(ViewportCommand::Focus); self.pending.extend(list.iter().filter_map(|a| of_arg(a)).map(Item::Asked)); } } @@ -180,14 +148,9 @@ 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() { - self.raise(ctx); + ctx.send_viewport_cmd(ViewportCommand::Focus); } main.adding.ask(request); } @@ -237,7 +200,6 @@ 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); @@ -264,20 +226,7 @@ pub fn of_arg(arg: &str) -> Option { #[cfg(test)] mod tests { - 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))); - } + use super::of_arg; #[test] fn arguments() { diff --git a/crates/app/src/views/list/row.rs b/crates/app/src/views/list/row.rs index 020b625..6e37739 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() || wave::one_bar() { &whole[..] } else { &parts[..] }; + let parts = if parts.is_empty() { &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 0d795e5..75e1ce9 100644 --- a/crates/app/src/views/main.rs +++ b/crates/app/src/views/main.rs @@ -240,18 +240,6 @@ 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 { @@ -259,7 +247,17 @@ 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 => self.all(action == Action::ResumeAll), + 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())), + _ => {} + } + } + } a if a.entry().group == Where::List => { let order = self.list.perform(ui, a); self.asked.extend(order); @@ -280,7 +278,7 @@ impl Main { } /// How much at the bottom the toolbar takes. - pub fn floor(&self) -> f32 { + fn floor(&self) -> f32 { if self.list.selected.is_empty() { 0.0 } else { bar::TOOLBAR - space::L } } @@ -369,8 +367,7 @@ impl Main { } fn list_in(&mut self, ui: &mut Ui, t: &Theme, rest: Rect, lists: &Arc, orders: &mut Vec) { - // 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 }; + let below = if self.list.selected.is_empty() { space::L } else { bar::TOOLBAR }; // 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)); @@ -384,8 +381,8 @@ impl Main { /// Files let go over the window: lists of links. fn dropped(&mut self, ui: &Ui) { - for request in crate::drop::requests(ui.ctx()) { - self.adding.ask(request); + for file in ui.input(|i| i.raw.dropped_files.clone()) { + self.adding.ask(Request { list: Some(file.path().to_path_buf()), ..Request::default() }); } } @@ -546,7 +543,7 @@ impl Main { } Act::Copy => { let all: Vec<&str> = views.iter().map(|v| v.task.url.as_str()).collect(); - crate::clipboard::copy(ui.ctx(), all.join("\n")); + ui.ctx().copy_text(all.join("\n")); self.toasts.info("content_copy", tr!("toast.copied", n = views.len())); } Act::OpenPage => { diff --git a/crates/app/src/views/mod.rs b/crates/app/src/views/mod.rs index 0374784..a6ee3da 100644 --- a/crates/app/src/views/mod.rs +++ b/crates/app/src/views/mod.rs @@ -13,8 +13,5 @@ pub mod modes; pub mod palette; pub mod queues; pub mod rail; -pub mod rules; pub mod schedule; pub mod settings; -pub mod target; -pub mod video; diff --git a/crates/app/src/views/queues.rs b/crates/app/src/views/queues.rs index 3c9b0ce..c96a78a 100644 --- a/crates/app/src/views/queues.rs +++ b/crates/app/src/views/queues.rs @@ -4,14 +4,12 @@ use super::list::model::queue_name; use super::schedule::{self, Level}; use crate::bridge::{Bridge, Lists}; use crate::fonts; -use crate::theme::{Theme, mix}; +use crate::theme::Theme; use crate::tokens::{radius, size, space, text}; use crate::ui::field::{Field, Number}; use crate::ui::widgets::{Button, Choice, Kind, cr, left, line}; use crate::icons; -use crate::motion::{self, spring, spring_from}; -use crate::tokens::spring::{DEFAULT, EFFECT}; -use eframe::egui::{CursorIcon, Layout, Align, Id, Rect, RichText, Sense, Ui, UiBuilder, pos2, vec2}; +use eframe::egui::{Layout, Align, Id, Rect, RichText, Sense, Ui, UiBuilder, pos2, vec2}; use medlar_core::manager::Command; use medlar_core::model::{MAIN_QUEUE, Queue, QueueId, State, TaskId}; use medlar_core::snapshot::Snapshot; @@ -71,22 +69,11 @@ impl Page { let width = ui.available_width(); let mut cards = vec![]; let mut released = None; - // Places are measured from the top of the list, so scrolling moves cards 1:1 and only a new order glides. - let top = ui.cursor().top(); for (i, q) in order.iter().enumerate() { let (slot, _) = ui.allocate_exact_size(vec2(width, CARD), Sense::hover()); ui.add_space(space::S); - let key = ("queue card", q.id); - let y = match self.grab.filter(|(id, _)| *id == q.id) { - // In hand: under the pointer, and the spring starts from here when it is let go. - Some((_, dy)) => { - motion::forget(key); - let y = slot.top() - top + dy; - spring_from(key, y, y, DEFAULT) - } - None => spring(key, slot.top() - top, DEFAULT), - }; - let rect = slot.translate(vec2(0.0, y + top - slot.top())); + let pulled = self.grab.filter(|(id, _)| *id == q.id).map_or(0.0, |(_, dy)| dy); + let rect = slot.translate(vec2(0.0, pulled)); cards.push(rect); let n = totals(shot, q.id); let mut moved = None; @@ -128,15 +115,11 @@ impl Page { #[allow(clippy::too_many_arguments)] fn card(&mut self, ui: &mut Ui, t: &Theme, rect: Rect, q: &Queue, lists: &Lists, n: Totals, i: usize, count: usize, selected: &[TaskId], bridge: &Bridge, moved: &mut Option, released: &mut Option) { let held = self.grab.is_some_and(|(id, _)| id == q.id); - let lift = spring(("queue lift", q.id), f32::from(held), EFFECT); - ui.painter().rect_filled(rect, cr(radius::L), mix(t.container, t.highest, lift)); + ui.painter().rect_filled(rect, cr(radius::L), if held { t.highest } else { t.container }); let inner = rect.shrink(space::M); let handle = Rect::from_min_size(inner.min, vec2(size::HIT, size::HIT)); let r = ui.interact(handle, Id::unique(("queue handle", q.id)), Sense::drag()); icons::paint(ui.painter(), handle.center(), crate::tokens::icon::M, "drag_indicator", t.on_variant); - if r.hovered() || r.dragged() { - ui.ctx().set_cursor_icon(if r.dragged() { CursorIcon::Grabbing } else { CursorIcon::Grab }); - } if r.dragged() { let dy = self.grab.filter(|(id, _)| *id == q.id).map_or(0.0, |(_, d)| d) + r.drag_delta().y; self.grab = Some((q.id, dy)); diff --git a/crates/app/src/views/rules.rs b/crates/app/src/views/rules.rs deleted file mode 100644 index 5afac5c..0000000 --- a/crates/app/src/views/rules.rs +++ /dev/null @@ -1,299 +0,0 @@ -//! The rules page (FEATURES 3.3): the list in order, an editor for one rule, the default set and a test box. -//! The clipboard page's privacy note lives here too, as the two pages share the way of drawing. - -use super::settings::{Cx, View, plate, small}; -use crate::bridge::{Data, Lists}; -use crate::theme::Theme; -use crate::tokens::{icon, size, space, text}; -use crate::ui::dialog::{Answer, Dialog}; -use crate::ui::field::{Combo, Field, Number}; -use crate::ui::widgets::{Button, Kind, left, line}; -use crate::{fonts, icons}; -use eframe::egui::{Label, Rect, RichText, Sense, Ui, UiBuilder, Vec2, pos2, vec2}; -use medlar_core::model::Priority; -use medlar_core::rules::{self, Item, Rule}; -use medlar_core::tr; - -const ROW: f32 = 60.0; -const NUMBER: f32 = size::CONTROL + 2.0 * (space::L + space::XS); - -#[derive(Default)] -pub struct State { - edit: Option, - /// The test box. - sample: String, -} - -struct Edit { - at: Option, - open: bool, - name: String, - on: bool, - extensions: String, - mime: String, - host: String, - min: f64, - max: f64, - pattern: String, - folder: String, - /// 0 for none, then the queues in order. - queue: usize, - priority: usize, - tags: String, - template: String, -} - -fn words(list: &[String]) -> String { - list.join(", ") -} - -fn split(text: &str) -> Vec { - text.split([',', ' ', '\n']).map(|p| p.trim().trim_start_matches('.').to_ascii_lowercase()).filter(|p| !p.is_empty()).collect() -} - -impl Edit { - fn new(at: Option, r: &Rule, lists: &Lists) -> Edit { - Edit { - at, - open: true, - name: r.name.clone(), - on: at.is_none() || r.enabled, - extensions: words(&r.extensions), - mime: words(&r.mime), - host: r.host.clone(), - min: r.min_mb as f64, - max: r.max_mb as f64, - pattern: r.pattern.clone(), - folder: r.folder.clone(), - queue: r.queue.and_then(|q| lists.queues.iter().position(|x| x.id == q)).map_or(0, |i| i + 1), - priority: r.priority.and_then(|p| Priority::ALL.iter().position(|x| *x == p)).map_or(0, |i| i + 1), - tags: r.tags.iter().filter_map(|id| lists.tags.iter().find(|t| t.id == *id)).map(|t| t.name.clone()).collect::>().join(", "), - template: r.template.clone(), - } - } - - fn rule(&self, lists: &Lists) -> Rule { - let tags = self.tags.split(',').map(str::trim).filter_map(|n| lists.tags.iter().find(|t| t.name.eq_ignore_ascii_case(n))).map(|t| t.id).collect(); - Rule { - name: self.name.trim().to_string(), - enabled: self.on, - extensions: split(&self.extensions), - mime: split(&self.mime.replace(',', " ")).into_iter().map(|m| m.trim_start_matches('.').to_string()).collect(), - host: self.host.trim().to_string(), - min_mb: self.min as u64, - max_mb: self.max as u64, - pattern: self.pattern.trim().to_string(), - folder: self.folder.trim().to_string(), - queue: self.queue.checked_sub(1).and_then(|i| lists.queues.get(i)).map(|q| q.id), - tags, - priority: self.priority.checked_sub(1).and_then(|i| Priority::ALL.get(i)).copied(), - template: self.template.trim().to_string(), - } - } - - /// Tag names that don't exist. - fn tag_error(&self, lists: &Lists) -> Option { - let missing: Vec<&str> = self.tags.split(',').map(str::trim).filter(|n| !n.is_empty() && !lists.tags.iter().any(|t| t.name.eq_ignore_ascii_case(n))).collect(); - (!missing.is_empty()).then(|| tr!("rule.no_tag", tag = missing.join(", "))) - } -} - -/// What a rule does, in a line. -fn summary(r: &Rule, lists: &Lists) -> String { - let mut when = vec![]; - if !r.extensions.is_empty() { - when.push(words(&r.extensions)); - } - if !r.mime.is_empty() { - when.push(words(&r.mime)); - } - if !r.host.is_empty() { - when.push(r.host.clone()); - } - if !r.pattern.is_empty() { - when.push(r.pattern.clone()); - } - let mut then = vec![]; - if !r.folder.is_empty() { - then.push(r.folder.clone()); - } - if let Some(q) = r.queue { - then.push(super::list::model::queue_name(lists, q)); - } - if let Some(p) = r.priority { - 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!(" goes to: {}", then.join(" · ")) }; - let off = if r.enabled { String::new() } else { format!("{} · ", tr!("rule.off")) }; - format!("{off}{when}{then}") -} - -fn lists(cx: &Cx) -> Lists { - match cx.bridge.data() { - Data::Ready(_, l) => (*l).clone(), - _ => Lists { queues: vec![], tags: vec![] }, - } -} - -/// The page: rules, buttons, test box. -pub fn list(view: &mut View, cx: &mut Cx, ui: &mut Ui) { - let t = cx.t; - let lists = lists(cx); - let mut moved: Option<(usize, i32)> = None; - let mut gone = None; - let mut flip = None; - if cx.s.rules.is_empty() { - ui.label(RichText::new(tr!("rule.none")).font(fonts::ui(text::BODY)).color(t.on_variant)); - ui.add_space(space::S); - } - for (i, r) in cx.s.rules.iter().enumerate() { - let name = if r.name.is_empty() { tr!("rule.unnamed") } else { r.name.clone() }; - let (rect, resp) = plate(ui, t, ROW, &tr!("rule.change", rule = name)); - let p = ui.painter(); - let x = rect.left() + space::M; - icons::paint(p, pos2(x + icon::M / 2.0, rect.center().y), icon::M, if r.enabled { "check_circle" } else { "visibility_off" }, t.on_variant); - let x = x + icon::M + space::M; - let room = rect.right() - x - 4.0 * size::HIT - space::M; - left(p, pos2(x, rect.center().y - 9.0), line(p, &name, fonts::med(text::BODY), if r.enabled { t.on_surface } else { t.on_variant }, room)); - left(p, pos2(x, rect.center().y + 10.0), line(p, &summary(r, &lists), fonts::ui(text::LABEL), t.on_variant, room)); - let mut hit = true; - for (k, (icon, label)) in [("delete", tr!("rule.remove", rule = name)), ("arrow_downward", tr!("rule.down", rule = name)), ("arrow_upward", tr!("rule.up", rule = name)), (if r.enabled { "visibility" } else { "visibility_off" }, tr!("rule.toggle", rule = name))].into_iter().enumerate() { - let place = Rect::from_center_size(pos2(rect.right() - space::S - size::HIT * (k as f32 + 0.5), rect.center().y), Vec2::splat(size::HIT)); - let mut child = ui.new_child(UiBuilder::new().max_rect(place).id_salt(("rule button", i, k))); - if small(&mut child, t, icon, &label) { - hit = false; - match k { - 0 => gone = Some(i), - 1 => moved = Some((i, 1)), - 2 => moved = Some((i, -1)), - _ => flip = Some(i), - } - } - } - if hit && resp.clicked() { - view.rules.edit = Some(Edit::new(Some(i), r, &lists)); - } - } - if let Some((i, d)) = moved { - let j = i as i32 + d; - if j >= 0 && (j as usize) < cx.s.rules.len() { - cx.s.rules.swap(i, j as usize); - } - } - if let Some(i) = flip { - cx.s.rules[i].enabled = !cx.s.rules[i].enabled; - } - if let Some(i) = gone { - let before = cx.s.clone(); - let r = cx.s.rules.remove(i); - let name = if r.name.is_empty() { tr!("rule.unnamed") } else { r.name }; - cx.toasts.undo("delete", tr!("rule.removed", rule = name), crate::views::main::Reply::Settings(Box::new(before))); - } - ui.horizontal(|ui| { - if Button::new(&tr!("rule.add")).with_icon("add").kind(Kind::Tonal).show(ui, t).clicked() { - view.rules.edit = Some(Edit::new(None, &Rule::default(), &lists)); - } - if Button::new(&tr!("rule.defaults")).kind(Kind::Text).show(ui, t).clicked() { - let before = cx.s.clone(); - let have: Vec = cx.s.rules.iter().map(|r| r.name.to_lowercase()).collect(); - // Names are the user's words; the set is in English until a language file says otherwise. - cx.s.rules.extend(rules::defaults().into_iter().filter(|r| !have.contains(&r.name.to_lowercase()))); - cx.toasts.undo("add", tr!("rule.defaults_added"), crate::views::main::Reply::Settings(Box::new(before))); - } - }); - ui.add_space(space::M); - test_box(view, cx, ui, &lists); -} - -/// A link or a name, and the rule it meets. -fn test_box(view: &mut View, cx: &mut Cx, ui: &mut Ui, lists: &Lists) { - let t = cx.t; - Field::new(&tr!("rule.test")).hint("https://example.com/video.mp4").help(&tr!("rule.test_help")).show(ui, t, &mut view.rules.sample); - let sample = view.rules.sample.trim(); - if sample.is_empty() { - return; - } - let (url, name) = if sample.contains("://") { (sample, String::new()) } else { ("", sample.to_string()) }; - let item = Item { url, name: &name, ..Item::default() }; - let base = crate::bridge::download_folder(cx.s); - let out = rules::apply(&cx.s.rules, &item, &base, chrono::Local::now().date_naive()); - let answer = match out.rule { - None => tr!("rule.test_none"), - Some(i) => { - let mut parts = vec![tr!("rule.test_rule", rule = cx.s.rules[i].name)]; - parts.extend(out.folder.map(|f| f.display().to_string())); - 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(" · ") - } - }; - ui.add(Label::new(RichText::new(answer).font(fonts::ui(text::BODY)).color(t.on_surface)).wrap()); -} - -/// The clipboard page's note about what is read and what is not. -pub fn clip_note(_: &mut View, cx: &mut Cx, ui: &mut Ui) { - let t: &Theme = cx.t; - for key in [tr!("clip.privacy"), tr!("clip.wayland")] { - ui.add(Label::new(RichText::new(key).font(fonts::ui(text::LABEL)).color(t.on_variant)).wrap()); - ui.add_space(space::S); - } - if !crate::clipboard::works() { - ui.add(Label::new(RichText::new(tr!("clip.broken")).font(fonts::ui(text::LABEL)).color(t.error)).wrap()); - } -} - -impl State { - /// The editor of one rule. - pub fn dialog(&mut self, ui: &Ui, cx: &mut Cx) { - let Some(e) = &mut self.edit else { return }; - let t = cx.t; - let lists = lists(cx); - let queues: Vec = std::iter::once(tr!("rule.keep")).chain(lists.queues.iter().map(|q| super::list::model::queue_name(&lists, q.id))).collect(); - let priorities: Vec = std::iter::once(tr!("rule.keep")).chain(Priority::ALL.iter().map(|p| strings_priority(*p))).collect(); - let bad_tags = e.tag_error(&lists); - let bad_folder: Option = None; - let good = !e.name.trim().is_empty() && bad_tags.is_none() && bad_folder.is_none(); - let title = if e.at.is_some() { tr!("rule.edit_title") } else { tr!("rule.add_title") }; - let open = e.open; - let answer = Dialog::new("rule", &title, &tr!("rule.save")).width(size::DIALOG_M).enabled(good).show(ui.ctx(), t, open, |ui| { - let r = Field::new(&tr!("rule.name")).show(ui, t, &mut e.name); - if ui.memory(|m| m.focused().is_none()) { - r.request_focus(); - } - Field::new(&tr!("rule.extensions")).hint("zip, iso, mp4").show(ui, t, &mut e.extensions); - Field::new(&tr!("rule.mime")).hint("video/, application/pdf").show(ui, t, &mut e.mime); - Field::new(&tr!("rule.host")).hint("*.example.com").show(ui, t, &mut e.host); - let side = ((ui.available_width() - space::S) / 2.0).floor(); - let (both, _) = ui.allocate_exact_size(vec2(ui.available_width(), NUMBER), Sense::hover()); - let mut half = |x: f32, salt: &str| ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size(pos2(x, both.top()), vec2(side, NUMBER))).id_salt(salt)); - let mut first = half(both.left(), "min"); - Number { label: &tr!("rule.min"), unit: &tr!("unit.mb_short"), range: 0.0..=1_000_000.0, step: 1.0, enabled: true, width: side, bare: false }.show(&mut first, t, &mut e.min); - let mut second = half(both.right() - side, "max"); - Number { label: &tr!("rule.max"), unit: &tr!("unit.mb_short"), range: 0.0..=1_000_000.0, step: 1.0, enabled: true, width: side, bare: false }.show(&mut second, t, &mut e.max); - Field::new(&tr!("rule.pattern")).hint("*-setup-*.exe").show(ui, t, &mut e.pattern); - Field::new(&tr!("rule.folder")).hint("Video").help(&tr!("rule.folder_help")).error(bad_folder.as_deref()).show(ui, t, &mut e.folder); - ui.horizontal_top(|ui| { - Combo::new(&tr!("rule.queue"), &queues, side).show(ui, t, &mut e.queue); - Combo::new(&tr!("rule.priority"), &priorities, side).show(ui, t, &mut e.priority); - }); - Field::new(&tr!("rule.tags")).error(bad_tags.as_deref()).show(ui, t, &mut e.tags); - Field::new(&tr!("rule.template")).hint("{date} {stem}.{ext}").help(&tr!("rule.template_help")).show(ui, t, &mut e.template); - }); - let Some(answer) = answer else { return }; - e.open = false; - if answer == Answer::Cancel { - return; - } - let rule = e.rule(&lists); - match e.at.filter(|i| *i < cx.s.rules.len()) { - Some(i) => cx.s.rules[i] = rule, - None => cx.s.rules.push(rule), - } - } -} - -fn strings_priority(p: Priority) -> String { - medlar_core::strings::text(&format!("priority.{}", p.name()), &[]) -} diff --git a/crates/app/src/views/schedule.rs b/crates/app/src/views/schedule.rs index 38edb22..742b02b 100644 --- a/crates/app/src/views/schedule.rs +++ b/crates/app/src/views/schedule.rs @@ -200,13 +200,11 @@ 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![], power: std::sync::Arc::new(Logind) } + 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![] } } } @@ -243,8 +241,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() { - let p = self.power.clone(); - self.can = Some(bridge::beside(move || { + self.can = Some(bridge::beside(|| { + let p = Logind; (1..=6).map(|i| action_of(i, "").is_some_and(|a| p.can(&a))).collect() })); } @@ -277,10 +275,7 @@ 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; - 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)); - }); + crate::ui::widgets::Choice::new(&tr!("done.failed")).switch(ui, t, &mut failed); 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); @@ -373,10 +368,7 @@ impl Done { runtime.block_on(run::run(&spec, &Vars::default())).map(|_| ()) })); } - other => { - let power = self.power.clone(); - self.working = Some(bridge::beside(move || power.perform(&other))); - } + other => self.working = Some(bridge::beside(move || Logind.perform(&other))), } } } diff --git a/crates/app/src/views/settings/mod.rs b/crates/app/src/views/settings/mod.rs index bf7e7de..99e1bba 100644 --- a/crates/app/src/views/settings/mod.rs +++ b/crates/app/src/views/settings/mod.rs @@ -68,7 +68,6 @@ pub struct View { look: look::State, network: network::State, sites: sites::State, - pub rules: crate::views::rules::State, keys: shortcuts::State, backup: backup::State, focus_search: bool, @@ -206,7 +205,6 @@ impl View { } } self.sites.dialog(ui, cx); - self.rules.dialog(ui, cx); if rows::free(ui) && !self.keys.recording() { let typing = ui.memory(|m| m.focused()).is_some() && ui.ctx().text_edit_focused(); close |= !typing && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)); @@ -445,12 +443,12 @@ fn line_of(ui: &mut Ui, t: &Theme, name: &str, why: &str, control: f32, error } /// A small button at the right of a row that draws itself. -pub(crate) fn small(ui: &mut Ui, t: &Theme, icon: &str, name: &str) -> bool { +fn small(ui: &mut Ui, t: &Theme, icon: &str, name: &str) -> bool { Button::icon(icon, name).size(Size::S).show(ui, t).clicked() } /// A row that can be clicked as a whole. Gives back its place too. -pub(crate) fn plate(ui: &mut Ui, t: &Theme, height: f32, name: &str) -> (Rect, eframe::egui::Response) { +fn plate(ui: &mut Ui, t: &Theme, height: f32, name: &str) -> (Rect, eframe::egui::Response) { let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click()); r.widget_info(|| WidgetInfo::labeled(Role::Button, true, name)); let f = feel(&r, true); diff --git a/crates/app/src/views/settings/rows.rs b/crates/app/src/views/settings/rows.rs index f6666a1..5c394f2 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, BarStyle, Contrast, Mode, Motion, Scheme, Settings}; +use medlar_core::settings::{Appearance, Contrast, Mode, Motion, Scheme, Settings}; use medlar_core::strings::{self, Catalogue}; use medlar_core::tr; use std::ops::RangeInclusive; @@ -18,8 +18,6 @@ pub enum Page { Connections, Network, Sites, - Rules, - Clipboard, Browser, Notifications, Power, @@ -28,14 +26,12 @@ pub enum Page { } impl Page { - pub const ALL: [Page; 12] = [ + pub const ALL: [Page; 10] = [ Page::Look, Page::Downloads, Page::Connections, Page::Network, Page::Sites, - Page::Rules, - Page::Clipboard, Page::Browser, Page::Notifications, Page::Power, @@ -50,8 +46,6 @@ impl Page { Page::Connections => "connections", Page::Network => "network", Page::Sites => "sites", - Page::Rules => "rules", - Page::Clipboard => "clipboard", Page::Browser => "browser", Page::Notifications => "notifications", Page::Power => "power", @@ -67,8 +61,6 @@ impl Page { Page::Connections => "speed", Page::Network => "language", Page::Sites => "key", - Page::Rules => "tune", - Page::Clipboard => "content_paste", Page::Browser => "public", Page::Notifications => "notifications", Page::Power => "power_settings_new", @@ -169,7 +161,6 @@ 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 { @@ -200,10 +191,6 @@ macro_rules! limit { }; } -fn hours() -> String { - tr!("unit.hours_short") -} - fn mb() -> String { tr!("unit.mb_short") } @@ -262,13 +249,6 @@ 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", @@ -347,40 +327,6 @@ static ROWS: &[Row] = &[ }, ), row(Page::Sites, "", "sites", &["sites"], Kind::Own(sites::list)), - row(Page::Rules, "", "rules", &["rules"], Kind::Own(crate::views::rules::list)), - row( - Page::Clipboard, - "clipboard", - "clipboard", - &["clipboard"], - Kind::Choice { options: &["off", "ask", "add"], get: |s| ["off", "ask", "add"].iter().position(|m| *m == s.clipboard).unwrap_or(0), set: |s, i| s.clipboard = ["off", "ask", "add"][i].into() }, - ), - row( - Page::Clipboard, - "clipboard", - "clip_types", - &["clip_types"], - Kind::Text { - hint: |_| "zip, iso, mp4".into(), - check: |_| None, - get: |s| s.clip_types.join(", "), - set: |s, v| s.clip_types = v.split([',', ' ', '\n']).map(|p| p.trim().trim_start_matches('.').to_ascii_lowercase()).filter(|p| !p.is_empty()).collect(), - }, - ), - row( - Page::Clipboard, - "clipboard", - "clip_skip", - &["clip_skip"], - Kind::Text { - hint: |_| "*.example.com".into(), - check: |_| None, - get: |s| s.clip_skip.join(", "), - set: |s, v| s.clip_skip = v.split([',', ' ', '\n']).map(str::trim).filter(|p| !p.is_empty()).map(String::from).collect(), - }, - ), - row(Page::Clipboard, "drop", "drop_target", &["drop_target"], Kind::Switch { get: |s| s.drop_target, set: |s, v| s.drop_target = v }), - row(Page::Clipboard, "", "clip_note", &[], Kind::Own(crate::views::rules::clip_note)), row(Page::Browser, "browser", "connector", &["connector"], Kind::Switch { get: |s| s.connector, set: |s, v| s.connector = v }), row( Page::Browser, @@ -405,15 +351,6 @@ 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 deleted file mode 100644 index 8814291..0000000 --- a/crates/app/src/views/target.rs +++ /dev/null @@ -1,117 +0,0 @@ -//! The drop target (FEATURES 3.9): a small wavy ring with the speed, in a window of its own that takes drops. -//! -//! It asks for "always on top". Wayland has no such thing for ordinary windows, so on niri it is a small window that -//! can be moved and put on a workspace like any other; where the compositor honours the hint (X11, XWayland, some -//! others) it floats. A click brings the main window back; a right click opens the menu. - -use super::add::Request; -use super::main::Main; -use crate::drop; -use crate::theme::Theme; -use crate::tokens::{size, space, text}; -use crate::ui::odometer::rate; -use crate::ui::wave::{self, Look}; -use crate::ui::widgets::{Button, Kind}; -use crate::fonts; -use eframe::egui::{Align2, Context, Id, Sense, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId, pos2, vec2}; -use medlar_core::settings::Settings; -use medlar_core::tr; - -const RING: f32 = 84.0; -const SMALL: f32 = 112.0; -/// The window: the ring and its speed line, and with the menu open room for three text buttons. -const CLOSED: [f32; 2] = [SMALL, SMALL + space::XL - space::XS]; -const OPEN: [f32; 2] = [SMALL + space::XXL + space::XL + space::XS, SMALL + 3.0 * size::CONTROL]; - -#[derive(Default)] -pub struct Target { - menu: bool, - calm: crate::ui::odometer::Calm, -} - -enum Do { - Open, - Add, - Hide, -} - -#[allow(deprecated)] -fn salt(name: &str) -> Id { - Id::new(name) -} - -impl Target { - /// Once per frame, while the setting is on. `speed` is all downloads together, in bytes per second. - pub fn show(&mut self, ctx: &Context, t: &Theme, settings: &mut Settings, main: &mut Main, speed: f64) { - if !settings.drop_target { - self.menu = false; - return; - } - let big = if self.menu { OPEN.into() } else { CLOSED.into() }; - let builder = ViewportBuilder::default() - .with_title("Medlar") - .with_app_id(crate::app::APP_ID) - .with_inner_size(big) - .with_resizable(false) - .with_decorations(false) - .with_always_on_top() - .with_taskbar(false); - 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. - return; - } - ui.ctx().send_viewport_cmd(ViewportCommand::InnerSize(big)); - let full = ui.max_rect(); - ui.painter().rect_filled(full, crate::ui::widgets::cr(size::CONTROL / 2.0), t.container); - let ring = eframe::egui::Rect::from_center_size(pos2(full.center().x, full.top() + space::S + RING / 2.0), vec2(RING, RING)); - 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(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); - } - if r.clicked() { - act = Some(Do::Open); - } - if r.secondary_clicked() { - *menu = !*menu; - } - if *menu { - ui.add_space(RING + 2.0 * space::L + text::LABEL); - for (label, what) in [(tr!("target.open"), Do::Open), (tr!("target.add"), Do::Add), (tr!("target.hide"), Do::Hide)] { - if Button::new(&label).kind(Kind::Text).show(ui, t).clicked() { - act = Some(what); - *menu = false; - } - } - } - dropped = drop::requests(ui.ctx()); - if ui.ctx().input(|i| i.viewport().close_requested()) { - act = Some(Do::Hide); - } - }); - for r in dropped { - main.adding.ask(r); - ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus); - } - match act { - Some(Do::Open) => ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus), - Some(Do::Add) => { - main.adding.ask(Request::default()); - ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus); - } - Some(Do::Hide) => settings.drop_target = false, - None => {} - } - } -} diff --git a/crates/app/src/views/video.rs b/crates/app/src/views/video.rs deleted file mode 100644 index 2eff105..0000000 --- a/crates/app/src/views/video.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! The Add dialog's page for a video site: quality with sizes, audio only, subtitles, the videos of a playlist. -//! It holds what was asked and what was chosen; `choice` gives the core what to run. The dialog owns the probe's task. - -use crate::theme::Theme; -use crate::tokens::{space, text}; -use crate::ui::odometer::amount; -use crate::ui::widgets::Choice as Pick; -use eframe::egui::{RichText, ScrollArea, Ui}; -use medlar_core::ytdlp::{Choice, Probe, Quality}; -use medlar_core::{strings, tr}; -use std::sync::Arc; - -/// Rows of the playlist that are seen at once. -const SEEN: f32 = 220.0; - -/// Where the page is. -pub enum Page { - Looking, - /// In plain words, what failed and why. - Failed(String), - Ready(Box