diff --git a/assets/MaterialDesignIcons-LICENSE.txt b/assets/MaterialDesignIcons-LICENSE.txt index 86df0710..513edacb 100644 --- a/assets/MaterialDesignIcons-LICENSE.txt +++ b/assets/MaterialDesignIcons-LICENSE.txt @@ -1,6 +1,6 @@ Material Design Icons in Grimoire's Terminess -The 84 icons in assets/TerminessNerdFontMono-Regular.ttf and -Bold.ttf, the code points from +The 86 icons in assets/TerminessNerdFontMono-Regular.ttf and -Bold.ttf, the code points from U+F0001 to U+F1AF0 that assets/terminess-keep.txt lists (the icons the app draws, on its tools, buttons and sheets and as the clefs of music paper, and those its next version plans), are Material Design Icons by Pictogrammers (https://pictogrammers.com/library/mdi/); 52 of them were drawn by diff --git a/assets/README.md b/assets/README.md index 31c633fa..c4429250 100644 --- a/assets/README.md +++ b/assets/README.md @@ -38,7 +38,7 @@ EOF Fonts 3.4.0, its Terminess Nerd Font Mono, a patched build of Terminus TTF 4.49.3; SIL Open Font License 1.1, see `Terminess-OFL-1.1.txt`), cut down to Terminus's text glyphs and the Material Design icons Grimoire draws or plans: exactly the code points `terminess-keep.txt` lists, 1,197 -text and 85 icons. That is about 0.43 MB a weight instead of 2.67 MB. The icons are Material Design +text and 87 icons. That is about 0.43 MB a weight instead of 2.67 MB. The icons are Material Design Icons by Pictogrammers under the Apache License 2.0 (`MaterialDesignIcons-LICENSE.txt`, which says where they come from, and `MaterialDesignIcons-Apache-2.0.txt`); the release ships both notices beside the OFL text, and the share pages serve all three, with the Gothic fonts' OFL texts, as diff --git a/assets/TerminessNerdFontMono-Bold.ttf b/assets/TerminessNerdFontMono-Bold.ttf index 884d3259..43e33f97 100644 Binary files a/assets/TerminessNerdFontMono-Bold.ttf and b/assets/TerminessNerdFontMono-Bold.ttf differ diff --git a/assets/TerminessNerdFontMono-Regular.ttf b/assets/TerminessNerdFontMono-Regular.ttf index 302f8ad8..aa17a951 100644 Binary files a/assets/TerminessNerdFontMono-Regular.ttf and b/assets/TerminessNerdFontMono-Regular.ttf differ diff --git a/assets/terminess-keep.txt b/assets/terminess-keep.txt index 37756c5b..221f0044 100644 --- a/assets/terminess-keep.txt +++ b/assets/terminess-keep.txt @@ -191,7 +191,7 @@ U+2E2C # the replacement character U+FFFD -# Icons: 84 code points +# Icons: 86 code points # Icons: the app's icons (rust/src/ui.rs, the icon table) U+F064F # md-lead_pencil: the Pencil tool U+F0CB6 # md-pencil_outline: the Mechanical pencil tool @@ -224,6 +224,8 @@ U+F0455 # md-rename_box: Rename U+F0252 # md-folder_move: moving to a folder U+F0257 # md-folder_plus: a new folder U+F01DA # md-download: downloads and exports +U+F00EC # md-calculator: the calculator widget +U+F03D7 # md-package_variant_closed: Packages U+F0652 # md-marker: the Highlighter tool U+F00E2 # md-broom: clearing a page U+F00DF # md-brightness_6: the front light @@ -244,7 +246,7 @@ U+F018F # md-content_copy: Copy U+F0339 # md-link_variant: links U+F0119 # md-cast_connected: Live view U+F0297 # md-gamepad_variant: controllers and keys -U+F06B0 # md-update: Updates +U+F06B0 # md-update: Updates and Update all U+F0150 # md-clock_outline: the clock and battery corner U+F0349 # md-magnify: the Index: Go to page or name U+F0208 # md-eye: showing or hiding link areas diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 90e2b65c..877ab15a 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -41,6 +41,11 @@ root/backlinks.ini links between notebooks, turned around ( root/graph-index.ini every notebook's pages, names and links, for the Graph (2.0.0-beta.2; a cache: Library index) root/graph-all.ini the Graph of all notebooks' layout (2.0.0-beta.2; a cache: Library index) root/graph-omit.ini folders left out of the Graph of all notebooks (2.0.0-beta.2; Library index) +root/widgets.ini the open widget windows' places and sizes (2.2, issue #200; Widgets) +root/packages/index.json the installed widget packages (2.2, issue #200; Widget packages) +root/packages/widgets//package.yaml a widget package's manifest and files (2.2, issue #200; Widget packages) +root/packages/widgets//state/settings.json the values of a package's declared settings, written by the host (2.2; Widget packages) +root/packages/widgets/.previous/ the version an update replaced, for a rollback (2.2, issue #200; Widget packages) root/clipboard.qpg the lasso's clipboard: what Copy or Cut took (2.0.0-beta.2; The clipboard) root/shortcuts.ini keyboard and controller mappings the owner edits (2.0; settings.ini) root/controller.ini controller buttons learned in Settings (2.0; settings.ini) @@ -1571,6 +1576,148 @@ critical on purpose. every link is kept exactly, `index` included. A paste that would pass 64 links on the page or 4000 in the notebook, or carries links while links.ini cannot be written, is refused whole. +## `widgets.ini` (2.2, issue #200) + +The editor's open widgets, one line each: an installed package's id (`com.example.timer`). A line +is the widget's id, an `=`, and seven comma-separated numbers: x, y, width, height, minimized (0 +or 1), z-order, and a reserved flag (written as 0). Coordinates are screen pixels, as the panel's +are. A closed widget has no line. Unknown ids and malformed lines are skipped. The file is at most +64 KiB, written atomically. + +``` +# Grimoire widget layout. One line per open widget: +# id=x,y,w,h,minimized,z +com.example.timer=1416,28,220,160,0,0,0 +com.grimoire.calculator=1416,270,340,560,0,1,0 +``` + +## Widget packages (2.2, issue #200) + +Settings → Packages → Widgets installs a widget from a GitHub repository (`user/repo`) or an +HTTPS `.yaml` address; the Widgets popup's **Manage widgets...** row opens the same page. +[WIDGETS.md](WIDGETS.md) is the developer's guide to the manifest, the artifact and publishing. +The manifest is `package.yaml`; unknown keys are ignored. An install is refused before anything is +written if the manifest is invalid, the platform does not match, or the artifact does not match its +size and SHA-256. The artifact is one file under the package's folder; it cannot be `package.yaml` +or anything under `state/`, which belongs to the host and the widget's saved data. + +```yaml +name: Timer +id: com.example.timer # lowercase letters, digits, dots and hyphens +version: 1.0.0 # semantic version (a -prerelease suffix is allowed) +type: widget +author: Jane Doe +description: A small timer widget. +license: MIT # optional; the install page asks you to agree to it first +license_url: https://example.org/timer/LICENSE # optional; without it, the repository's LICENSE, + # LICENSE.md, LICENSE.txt, COPYING or COPYING.md is tried +min_grimoire_version: 2.1.0 # optional +platforms: [all] # or kindle-scribe-2022, kindle-scribe-2024 +repository: https://example.org/timer +capabilities: [editor:overlay, storage:widget-local] +settings: # optional; a Settings... page of up to 32 rows + - key: show_seconds # lowercase letters, digits, . - _ + label: Show seconds + type: toggle # or choice + default: true + - key: layout + label: Layout + type: choice + default: compact + choices: [compact, large] +artifact: + path: timer.bin + sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + size: 4 +releases: # optional per-version artifacts + - version: 1.0.0 + url: https://example.org/timer/1.0.0/timer.bin + sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 +spec: + runtime: wasm # the only runtime; widget code is a WebAssembly module + entry: _start # ignored by the host; `widget_draw` and `widget_tap` are the exports it calls + icon: timer # a Grimoire icon (calculator, clock, timer, music, notebook, pdf, image, ...); + # unknown or omitted: the widget grid + minimizable: true + size: + mode: fixed # or resizable + default: [220, 160] + min: [160, 120] # resizable only + max: [600, 600] # resizable only +``` + +An omitted `platforms` means every supported device; an explicit empty list is refused. A device's +platform is `GRIMOIRE_WIDGET_PLATFORM` when set, otherwise the Kindle model in +`/proc/device-tree/model`. The known values are `all`, `kindle-scribe-2022` and +`kindle-scribe-2024`. The artifact is at most 32 MiB; at most 64 packages are installed. A manifest +is at most 256 KiB. + +`packages/index.json` lists what is installed, and is written atomically after the package's files +are complete: + +```json +{ + "version": 1, + "packages": [ + {"id":"com.example.timer","name":"Timer","version":"1.0.0","author":"Jane Doe", + "description":"A small timer widget.","icon":"timer","path":"packages/widgets/com.example.timer/timer.bin", + "sha":"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + "installed_at":1,"source_url":"https://example.org/timer.yaml"} + ] +} +``` + +A package's detail page shows `Author:` and, when the manifest names one, `License:`, with **View +license** to read its text (from `license_url`, or the repository's license file when the manifest +only names the license). A GitHub package also has **View QR code**, which shows its repository +address as a QR code for a phone. When the manifest declares `settings`, the page also has +**Settings...**: one switch per `toggle` and one cycling row per `choice`, saved as they are tapped, +with **Reset all to defaults** at the end. Its values live in +`packages/widgets//state/settings.json`, as strings keyed by the setting's `key`; a missing or +invalid value reads as its default, and reset removes the file. A license whose files are all +missing does not stop the install when only its name was declared; a `license_url` that does not +answer does. + +**Update all** at the top of the package list checks every installed package that has a +`source_url`, one after another, and installs the newer ones; an up-to-date package costs its +manifest's fetch only. The packages were trusted when they were installed, so the batch does not +ask again for each one. An update keeps the old directory as `.previous` until the new one is in +place, so a failed write can be rolled back. Removing a package closes its widget, deletes its files and its +`widgets.ini` line. A package's own state is kept under `packages/widgets//state/` when the +package is replaced or removed (Remove keeps that folder; nothing else of the package stays). The +host's `settings.json` in that folder is kept too; a package should use another file for its own data. + +`spec.runtime` must be `wasm`: a package ships behavior as a WebAssembly module, and Grimoire carries +no widget implementations of its own. A native runtime or entry is refused. The artifact is size- +and SHA-256-checked at install, then instantiated in the frame when it first draws. + +A module exports `memory`, `widget_draw(width, height, scale_milli)` and +`widget_tap(hit_id)`, and imports from the `grimoire` module: + +```text +rect(x, y, w, h, style) +text(x, y, w, h, ptr, len, px, center) +button(id, x, y, w, h, ptr, len, style) +hit(id, x, y, w, h) +status(ptr, len) +request_redraw(after_ms) +setting(key_ptr, key_len, out_ptr, out_cap) -> i32 +state_get(ptr, cap) -> i32 +state_set(ptr, len) +now() -> i64 +``` + +Coordinates are screen pixels inside the frame body. `style` is `0` normal, `1` selected or `2` +disabled. Strings are UTF-8 in the module's memory. `request_redraw` names the delay before the +host draws the widget again (16 ms to 24 hours), for a clock or a countdown. `setting` returns the bytes written for one of +the package's saved settings (empty when it is missing); `state_get`/`state_set` read and write the +widget's saved state in `packages/widgets//state/runtime.bin`, capped at 64 KiB. `status` sets +the text read back by the editor's `editor.widget.N.status` probe. Each call has a fixed instruction +budget and linear memory is capped at 32 MiB, so a looping or greedy widget stops with an error +instead of freezing the device. + +[WIDGETS.md](WIDGETS.md#the-wasm-abi) is the guide to writing one. + ## `settings.ini` `key=value` lines; `#` starts a comment line. Readers strip one carriage return at the end of a diff --git a/docs/SIM.md b/docs/SIM.md index c0f9ae4d..0d843120 100644 --- a/docs/SIM.md +++ b/docs/SIM.md @@ -174,7 +174,21 @@ v_storage_full.qs leaves with a page that cannot be saved. The editor panel's buttons, by the names `tap panel` and `editor.panel_at.X.Y` use: `grip`, `collapse` and `expand` (the collapsed panel is one `expand` button), `tool-picker` (the tool button, or the grid when its pen is pinned), `tool:NAME` (a pinned pen, NAME as `editor.tool` has it), `eraser`, `undo`, `redo`, `clear`, -`previous`, `pages` (the page chip), `next`, `links` (the Links button), `paper`, `display`, `pen-feel` and `library`. A disabled button +`previous`, `pages` (the page chip), `next`, `links` (the Links button), `widgets`, `paper`, `display`, `pen-feel` and `library`. The +Widgets popup's rows are `widgets.ID` (`widgets.com.example.timer`), and an open frame's parts are +`widget.ID.title`, `.close`, `.min` (or `.minimize`), `.resize` and `.body`. A frame can also be +named by its index in the open list, which is how a scenario reaches the controls a package draws: +`widget.0.hit.N` is the hit region with id N in the first frame's last draw, and +`widget.0.hit.N` stays a valid name only while that region exists. A package's own status text is +read with `editor.widget.0.status`. The Packages page is Settings → Packages +→ Widgets: `settings.cat.5` picks the Packages category and `settings.packages` opens the Widgets +page. Its controls are `packages.close` (the X, which closes Settings), `packages.back` (to +Settings), `packages.row.ID` (or its index, `packages.row.0`), `packages.update-all`, +`packages.install`, `packages.remove`, `packages.remove-yes`, `packages.update`, `packages.trust`, +`packages.license-yes`, `packages.license-view`, `packages.license-prev`, `packages.license-next` and +`packages.qr`; a settings row is `packages.setting.KEY` (or `packages.setting.N`); the repository +address is typed on the regular keyboard (its Done installs, as Done answers every other keyboard). +A disabled button (Undo with nothing to undo, Clear on an empty page, Previous on page 1) has no hit and no name. A scenario that wants a panel button taps it by name, so that it does not break when the panel gains a button; `editor.panel_at.1768.594 is undo` upright with no pins (and the other coordinates of tests/scenarios/ @@ -243,7 +257,7 @@ Settings 1535 95. Its five buttons widen together for a longer word, up to 220 p (the same sideways), so a language with wider top-bar words moves them (docs/TRANSLATING.md). Hosted by KOReader they move left, as Back to KOReader takes the room it needs. Settings is one page (the new Settings menu, #115): its categories are at x 329, y 286 + 136 n (n from 0: General, -Display, Sleep & Clock, Pen, Controls, System), the open category's rows at x 1233, y 371 + 134 n, +Display, Sleep & Clock, Pen, Controls, Packages, System), the open category's rows at x 1233, y 371 + 134 n, and its X at 1735 95; a submenu's Back is at 125 95 and its X at 1735 95. Tap Settings' rows, the Display, Sleep settings and Clock settings pages' rows (`display.NAME`) and the choice lists' rows by name (`library.ui_at.X.Y` lists the names), never by place. Pen feel's tabs are one strip, its @@ -598,6 +612,13 @@ shows what the app holds. | `editor.links_dirty` | `1` while migrated link areas wait to be written to links.ini (after a 2 s pause, or 2 s after a failed write), else `0` | | `editor.paper` | the page's paper as its number in src/paper.h (1 medium rule, 2 wide rule, 3 sheet music, 6 medium rule without a margin, 8 grand staff...), `custom` for a Custom music layout, `none` with no notebook open | | `editor.panel` | `expanded` or `collapsed` | +| `editor.widgets` | the open widget frames: their count, then their ids (`0`, or `1 com.example.timer`) | +| `editor.widgets.open` | `1` while the Widgets popup is up, else `0` | +| `editor.packages`, `editor.packages.open` | the installed widget packages: their count, then their ids and versions (`0`, or `1 com.example.timer 1.0.0`), and `1` while the Packages page is up, else `0` | +| `editor.widget.N.status`, `editor.widget.N.text` | the text the frame's package last passed to its `status` import, and the text it drew, joined by `\|`; empty until its first draw | +| `editor.widget.N.hits`, `editor.widget.N.error` | how many hit regions its last draw registered, and the runtime error that stopped it, empty while it runs | +| `editor.package.ID` | an installed package's version (`1.0.0`), or empty for an id that is not installed | +| `editor.widget.ID.rect`, `editor.widget.ID.state` | an open frame's screen rect (`x y w h`, the minimized square while minimized) and `normal` or `minimized`; ID is its package id or its index in the open list; empty for a frame that is not open | | `editor.hold_eraser` | `1` while a controller's Erase while held is down (from its press to its release), else `0` | | `editor.music` | the Custom music layout on the Custom music sheet while it is open, else the page's if its paper is custom, else empty: the systems per page, a colon, then the parts top to bottom (`treble`, `bass`, `alto`, `tenor`, `drums`, `plain`, `tab4` to `tab7`, `lyrics`), e.g. `4: treble tab6 bass` | | `editor.music_max` | while the editor's Custom music sheet is open, the most systems its layout fits on the page it is for (that page's height), else empty | @@ -629,7 +650,7 @@ shows what the app holds. | `library.gestures.learning` | action being recorded, or `0` | | `library.record` | `0`, `wait`, `pattern touch.N.KIND`, `shape K` (sample count), `checking` or `ready` | | `library.record.line` | record card's progress/refusal line, empty without a card | -| `library.ui_at.X.Y` | semantic name of the Library hit at screen pixel X,Y, empty for none; see recording workflow. The top bar has five buttons (`exit`, `settings`, `share`, `new-folder`, `new`; beta.2's Graph button was taken out again, the owner's ruling of 2026-11-03). A notebook's menu has `more.open`, `more.rename`, `more.move`, `more.pdf`, `more.graph` (Leave out of the Graph, or Show in the Graph) and `more.delete`; a folder's `fmore.rename`, `fmore.move`, `fmore.graph` and `fmore.remove` (Cancel is `done` in both); Move to `move.top`, `move.to.PATH` (a folder by its path, `move.to.School/Math`), `move.new`, `move.prev` and `move.next`. Settings is one page (the new Settings menu, #115): its categories down the left are `settings.cat.N` (0 General, 1 Display, 2 Sleep & Clock, 3 Pen, 4 Controls, 5 System; the page keeps the one picked until Grimoire starts again, so a script taps the category before a row of it: `tap library settings.cat.4`, then `tap library gestures`), and its X is `done`. General's rows are `language`, `updates` and `wifi`; Display's `display`, `theme` (Style), `dark`, `font` (Classic only), `rotate` and `pinch`; Sleep & Clock's `sleep-clock` (Sleep settings) and `clock-settings`; Pen's `pen-feel`, `pen-button`, `eraser-mode` and `calibrate`; Controls' `shortcuts`, `pair-menu` and `gestures`; System's `ko`, `mirror`, `about-device` and `darker-lines` (Darker lines in imported PDFs, 2.2) (tap them by name, never by place). A submenu's Back is `settings.back` (to the page it was opened from) and its X `settings.close` (the whole of Settings closes); a Gestures or Buttons group's Back is `done` (to the list of groups). The Language list has `language.auto` and `language.CODE` (`language.en`, `language.es`, `language.ja`), the pen button's list `pen-button.N` and the eraser's `eraser-mode.N` (N as settings.ini numbers `side_button` and `eraser_mode`), Darker lines' `darker-lines.N` (0 Off, 1 Medium, 2 Strong), each with its Back (`language.back`, `pen-button.back`, `eraser-mode.back`, `darker-lines.back`); About's Back is `about-device.back`. The Display, Sleep settings and Clock settings pages are the Display sheet's (`display.NAME`: `display.back`, `display.done` for its X, `display.brightness`, `display.auto`, `display.warmth`, `display.fit`, `display.newpage`; `display.sleep`, `display.pin`, `display.sleep_after`; `display.time12`, `display.size`, `display.corner`). The Font sheet has `font.terminess`, `font.atkinson`, `font.noto-sans` and `font.literata` (its rows), `font.cancel` (its Back), `font.done` (its X) and `font.add` (Add a font..., 2.2: the font pick over the sheet; no name while it waits for a copy, nor over a notebook's page, where the sheet has no such row); the Shortcuts sheet has `shortcuts.enable`, `shortcuts.device`, `shortcuts.own`, `buttons` and `shortcuts.reload`, the Pair sheet `bluetooth` and `pair`, the Wi-Fi sheet `wifi.radio` (Turn on, Turn off or Retry), `wifi.tab.saved` (the Saved networks button; tapped again it returns to Nearby), `wifi.scan` (Rescan), `wifi.other` (Other..., a hidden network), `wifi.other.open` and `wifi.other.wpa` (its security, after the name), `wifi.other.cancel`, `wifi.net.N` (the Nth saved network row in the list, from 1; drag the list to scroll; the connected row disconnects when tapped), `wifi.delete.N` (that row's trash button), `wifi.near.N` (the Nth scan result row, from 1; its connected row disconnects too) and `done` (a greyed-out row has no name) | +| `library.ui_at.X.Y` | semantic name of the Library hit at screen pixel X,Y, empty for none; see recording workflow. The top bar has five buttons (`exit`, `settings`, `share`, `new-folder`, `new`; beta.2's Graph button was taken out again, the owner's ruling of 2026-11-03). A notebook's menu has `more.open`, `more.rename`, `more.move`, `more.pdf`, `more.graph` (Leave out of the Graph, or Show in the Graph) and `more.delete`; a folder's `fmore.rename`, `fmore.move`, `fmore.graph` and `fmore.remove` (Cancel is `done` in both); Move to `move.top`, `move.to.PATH` (a folder by its path, `move.to.School/Math`), `move.new`, `move.prev` and `move.next`. Settings is one page (the new Settings menu, #115): its categories down the left are `settings.cat.N` (0 General, 1 Display, 2 Sleep & Clock, 3 Pen, 4 Controls, 5 Packages, 6 System; the page keeps the one picked until Grimoire starts again, so a script taps the category before a row of it: `tap library settings.cat.4`, then `tap library gestures`), and its X is `done`. General's rows are `language`, `updates` and `wifi`; Display's `display`, `theme` (Style), `dark`, `font` (Classic only), `rotate` and `pinch`; Sleep & Clock's `sleep-clock` (Sleep settings) and `clock-settings`; Pen's `pen-feel`, `pen-button`, `eraser-mode` and `calibrate`; Controls' `shortcuts`, `pair-menu` and `gestures`; Packages' `packages` (Widgets); System's `ko`, `mirror`, `about-device` and `darker-lines` (Darker lines in imported PDFs, 2.2) (tap them by name, never by place). A submenu's Back is `settings.back` (to the page it was opened from) and its X `settings.close` (the whole of Settings closes); a Gestures or Buttons group's Back is `done` (to the list of groups). The Language list has `language.auto` and `language.CODE` (`language.en`, `language.es`, `language.ja`), the pen button's list `pen-button.N` and the eraser's `eraser-mode.N` (N as settings.ini numbers `side_button` and `eraser_mode`), Darker lines' `darker-lines.N` (0 Off, 1 Medium, 2 Strong), each with its Back (`language.back`, `pen-button.back`, `eraser-mode.back`, `darker-lines.back`); About's Back is `about-device.back`. The Display, Sleep settings and Clock settings pages are the Display sheet's (`display.NAME`: `display.back`, `display.done` for its X, `display.brightness`, `display.auto`, `display.warmth`, `display.fit`, `display.newpage`; `display.sleep`, `display.pin`, `display.sleep_after`; `display.time12`, `display.size`, `display.corner`). The Font sheet has `font.terminess`, `font.atkinson`, `font.noto-sans` and `font.literata` (its rows), `font.cancel` (its Back), `font.done` (its X) and `font.add` (Add a font..., 2.2: the font pick over the sheet; no name while it waits for a copy, nor over a notebook's page, where the sheet has no such row); the Shortcuts sheet has `shortcuts.enable`, `shortcuts.device`, `shortcuts.own`, `buttons` and `shortcuts.reload`, the Pair sheet `bluetooth` and `pair`, the Wi-Fi sheet `wifi.radio` (Turn on, Turn off or Retry), `wifi.tab.saved` (the Saved networks button; tapped again it returns to Nearby), `wifi.scan` (Rescan), `wifi.other` (Other..., a hidden network), `wifi.other.open` and `wifi.other.wpa` (its security, after the name), `wifi.other.cancel`, `wifi.net.N` (the Nth saved network row in the list, from 1; drag the list to scroll; the connected row disconnects when tapped), `wifi.delete.N` (that row's trash button), `wifi.near.N` (the Nth scan result row, from 1; its connected row disconnects too) and `done` (a greyed-out row has no name) | | `library.map`, `library.map.KEY` | the Graph opened from the Library (2.0.0-beta.2: two fingers down over it, or the `index-map` key): `graph` while it shows, else `0`, and every `editor.map.KEY` (below) of it. `library.map.no_notebook` is `1` for it (no notebook open), `library.map.tabs` the tabs drawn (`graph` alone here; `graph list pages` for the editor's). `library.map.picker` is `1` while its notebooks' browser (past the caps) is up, `library.map.keep` `1` while a notebook it opened is in front (Back there comes back to it). `tap library map.NAME` taps its controls (`map.back`, `map.open`, `map.view`), `tap library elsewhere.NAME` its browser's (`elsewhere.folder.PATH`, `elsewhere.book.ID`, `elsewhere.back`), and `tap map-node ID:PID` its nodes | | `library.graph.omitted` | the Library's notebooks the Graph of all notebooks leaves out (by their own Leave out of the Graph or a folder's), by id, sorted, space-separated (2.0.0-beta.2) | | `library.about.view` | What's new while it is open (else empty): `card` (the card hanging from the bat), `list` (Read all's list of every version's notes) or `note` (a version's notes on the sheet) (2.1.0) | diff --git a/docs/TESTING.md b/docs/TESTING.md index 50f966c4..d590d1e8 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -246,7 +246,7 @@ time) and `beside pid` (the second background process). ## 2.0.0-beta.2, the Terminess diet (device checks pending) Automated: rust/tests/test_terminess_keep.rs (the embedded fonts hold exactly -`assets/terminess-keep.txt`'s code points, 1,197 of Terminus's text and 85 Material Design icons; every +`assets/terminess-keep.txt`'s code points, 1,197 of Terminus's text and 87 Material Design icons; every icon the sources draw is listed, is in both weights and draws ink; none of the Nerd Fonts glyphs the diet leaves out is listed), test_koreader.rs's fonts_follow_the_binary (KOReader's `fonts/Grimoire` written again when it differs, left alone when equal, made only while the Terminess patch is applied, nothing diff --git a/docs/WIDGETS.md b/docs/WIDGETS.md new file mode 100644 index 00000000..bab91aea --- /dev/null +++ b/docs/WIDGETS.md @@ -0,0 +1,449 @@ +# Writing and publishing a widget package + +Widgets are small frames over the notebook: the calculator, a timer, anything a package adds. The +editor's **Widgets** button opens the catalog; a tap on a row opens a frame that can be dragged by +its title bar, minimized, resized from its bottom-right grip and closed. Its place and size are kept +in `widgets.ini` at the data root, so it comes back where it was. + +This page is the developer's guide: the repository, the manifest, the artifact, testing and +publishing. The exact field rules and the installed layout are in +[FORMAT.md](FORMAT.md#widget-packages-22-issue-200); this page explains the workflow around them. + +A widget's behavior lives entirely in its package: Grimoire has no widget implementations in its +source tree. The host draws the frame, routes input and saves state; the package supplies a +WebAssembly module that draws its body and answers taps. This page covers that module's ABI as +well as the repository, the manifest, testing and publishing. + +## The repository + +A package is one repository with the manifest at its root: + +``` +my-timer/ +├── package.yaml +├── timer.bin +├── LICENSE +└── README.md +``` + +`package.yaml` is required and must be at the root. `timer.bin` is whatever single file +`artifact.path` names; the name and extension are yours. `LICENSE` and `README.md` are optional. + +An install copies only two files to the Kindle: `package.yaml` and the artifact. The license is not +copied; **View license** reads it from `license_url` or from the repository when the reader asks. +The README never reaches the device. The files a widget writes at runtime belong in +`packages/widgets//state/`, which survives an update and a removal (see +[State](#state)). + +The repository must be reachable without credentials. Grimoire fetches with `curl`; there is no +token, no private-repository support and no zip or tarball distribution. + +## The address + +Settings → Packages → Widgets accepts two forms: + +| address | what is fetched | +|---|---| +| `user/repo` | GitHub: `https://api.github.com/repos/user/repo` gives the default branch, then `https://raw.githubusercontent.com/user/repo//package.yaml` (the fallback when the API cannot be reached is `main`) | +| `https://host/path/package.yaml` | that manifest directly; any HTTPS host works | + +Only `https://` is fetched, and the address may be at most 1024 characters. The GitHub API is +unauthenticated, so a check is subject to GitHub's rate limit. + +The artifact's URL is the manifest's directory plus `artifact.path`, unless `releases` has an entry +for the manifest's version, in which case that entry's `url` is used. This is why a repository can +keep its source and its built artifact in one tree, or attach the artifact to a GitHub release and +point at it. + +An update re-fetches the stored install address (`source_url`). A package installed as +`user/repo` is updated through GitHub; one installed from a full `.yaml` address is updated from +that address. + +## The manifest + +A complete example: + +```yaml +name: Timer +id: com.example.timer +type: widget +version: 1.0.0 +author: Jane Doe +description: A small timer with one countdown. +license: MIT +license_url: https://github.com/janedoe/timer/blob/main/LICENSE +min_grimoire_version: 2.2.0 +platforms: [all] +repository: https://github.com/janedoe/timer +capabilities: [storage:widget-local] +settings: + - key: show_seconds + label: Show seconds + type: toggle + default: true + - key: layout + label: Layout + type: choice + default: compact + choices: [compact, large] +artifact: + path: timer.bin + sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + size: 4 +releases: + - version: 1.0.0 + url: https://github.com/janedoe/timer/releases/download/v1.0.0/timer.bin + sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 +spec: + runtime: wasm + entry: _start + icon: timer + minimizable: true + size: + mode: fixed + default: [220, 160] +``` + +| field | | +|---|---| +| `name` | required; the row and the frame's title | +| `id` | required; the package's permanent identity. Lowercase letters, digits, dots and hyphens only, at most 128, no leading or trailing dot and no `..`. The install, update and remove paths all use it, so never change it between versions | +| `type` | must be `widget` | +| `version` | required; `MAJOR.MINOR.PATCH`, with an optional prerelease suffix. The updater orders `-beta.N` and `-rc.N`; another suffix is accepted but is not ordered as newer. No leading zeroes in a number. An update is installed only when this sorts above the installed version, so bump it for every published change | +| `author` | optional; shown in the detail page and the widget's frame metadata | +| `description` | optional; shown in the list, the detail page and the frame | +| `license` | optional; the SPDX name or a short name. When its text is found, the install page asks the reader to agree before installing | +| `license_url` | optional; an HTTPS page or raw file with the license text. Without it, `LICENSE`, `LICENSE.md`, `LICENSE.txt`, `COPYING` and `COPYING.md` beside the manifest are tried, in that order | +| `min_grimoire_version` | optional; the same `MAJOR.MINOR.PATCH` form, with an optional `-beta.N` or `-rc.N` suffix. The install is refused on an older Grimoire | +| `platforms` | optional; `all` (the default when the key is omitted), `kindle-scribe-2022`, `kindle-scribe-2024`, or a list of them. An explicit empty list is refused. `all` matches every device | +| `repository` | optional; the human-facing project address. A GitHub address also gets **View QR code** in the detail page | +| `capabilities` | optional; only `editor:overlay` and `storage:widget-local` are accepted. Declare only what the widget needs. The ABI itself has no network, filesystem or process access; a module can reach only the frame, its settings and its own state | +| `settings` | optional; up to 32 settings the package declares for its own Settings page. Each has a `key`, a `label`, a `type` (`toggle` or `choice`), and a `default`; a choice also has 2 to 16 `choices`. An optional `icon` names one of the icons above | +| `artifact.path` | required; a safe relative path, at most 240 bytes: no leading `/`, no backslash, no empty, `.` or `..` component, and neither `package.yaml` nor anything under `state/` | +| `artifact.sha256` | required; 64 hexadecimal characters, over the artifact's bytes | +| `artifact.size` | required; the artifact's size in bytes, at least 1 and at most 32 MiB. It is used even when `releases` supplies the URL and digest | +| `releases` | optional; `version`, `url` (use HTTPS) and `sha256` per entry. Only the entry whose `version` equals the manifest's is used | +| `spec.runtime` | required; `wasm`. Any other value is refused | +| `spec.entry` | optional; accepted and ignored. The host calls the exports `widget_draw` and `widget_tap`, not this name | +| `spec.icon` | optional; one of Grimoire's icons: `calculator`, `package`, `clock`, `timer`/`hourglass`, `music`, `notebook`, `pdf`, `image`/`photo`, `files`/`folder`, `search`, `download`, `language`, `gear`/`settings`, `update`, `paper`/`page`, `library`, `link`, `live`, `gamepad`, `eye`. A `md-` prefix is accepted. An unknown or omitted icon is the widget grid | +| `spec.minimizable` | optional, default `true`. Accepted for forward compatibility; this build always draws the frame's minimize button | +| `spec.size.mode` | `fixed` (default) or `resizable` | +| `spec.size.default` | optional; `[width, height]` at 300 dpi, default `[220, 160]` | +| `spec.size.min`, `spec.size.max` | `resizable` only; each side must be at least 120x80 at 300 dpi and at most 70% of the editor canvas either way (about 1302x1736 on a 1860x2480 Scribe). `min` may not exceed `max`. A `fixed` widget uses `default` for all three | + +Unknown top-level keys are ignored, so a newer manifest can carry fields an older Grimoire does not +know; unknown keys inside `spec` are ignored too. Values of the known fields are checked where +they affect the install: a missing name, a bad id, version, path, digest or size, an unknown +platform, capability or runtime is refused. An unknown icon falls back to the widget grid. + +Limits: the manifest may be at most 256 KiB, the artifact at most 32 MiB, at most 64 packages may +be installed, and at most 8 widget frames may be open at once. A `wasm` artifact is one file; a +release asset is a single file, never an archive. + +### Sizes + +`spec.size` values are pixels at 300 dpi, the Scribe's panel. Grimoire scales them by the panel's +dpi when it draws the frame, so the widget is the same physical size on every device. The floor is +120x80 at 300 dpi; the ceiling is 70% of the editor canvas in either direction. A frame is placed +at the top right of the editor, cascading down as more open, and is clamped onto the screen after +a rotation or a window-size change. + +`mode: resizable` gives the bottom-right grip and clamps to `min` and `max`; `mode: fixed` omits the +grip and keeps the frame at `default`. + +### Settings + +A package can declare a Settings page of its own. When `settings` is not empty, the package's +detail page gets a **Settings...** button above **Check for updates**; opening it lists one row per +setting. A `toggle` row has a switch. A `choice` row shows the current value after its label, and +tapping it moves to the next choice. There is no separate Save button: a tap writes the new value +immediately, and **Reset all to defaults** puts every value back. + +```yaml +settings: + - key: show_seconds + label: Show seconds + type: toggle + default: true + icon: timer + - key: accuracy + label: Accuracy + type: choice + default: seconds + choices: [seconds, tenths] +``` + +| setting field | | +|---|---| +| `key` | required; at most 64 characters of lowercase letters, digits, `.`, `-` and `_`; no leading or trailing dot and no `..`. It is the key the widget reads and must be unique within the package | +| `label` | required; the row's text, at most 160 bytes | +| `type` | required; `toggle` or `choice` | +| `default` | optional; `true` or `false` for a toggle (default `true`), or one of the choices for a choice (default the first) | +| `choices` | a choice needs 2 to 16 unique values, each at most 64 bytes; the row shows the chosen value | +| `icon` | optional; an icon name as in `spec.icon`; the gear when omitted | + +Values are saved in `packages/widgets//state/settings.json`, beside the widget's own state, and +an update or a remove that keeps state carries them along. The file holds strings, keyed by the +setting's `key`; a missing or invalid value reads as its default. That path is reserved for the +host: a widget should keep its other data in another file under `state/`. + +The module reads these values through the ABI's `setting(key_ptr, key_len, out_ptr, out_cap)` +import. It returns the number of bytes written, or `0` when the key is missing; the host caps the +copy at `out_cap`. Values are the same strings the Settings page shows (`true`, `false`, or one of +a choice's values). + +A package can use settings however it likes. The test calculator package, for example, chooses the +calculator a new frame opens with and which ones its mode dropdown offers: + +```yaml +settings: + - key: default_calculator + label: Default calculator + type: choice + default: Simple + choices: [Simple, Scientific, Programming] + - key: enable_simple + label: Simple calculator + type: toggle + default: true + - key: enable_scientific + label: Scientific calculator + type: toggle + default: true + - key: enable_programming + label: Programming calculator + type: toggle + default: true +``` + +The package above is ordinary widget code in its own repository, not part of Grimoire. An open +frame reads its settings again after the Settings page saves them; a package decides what a change +means. A new frame reads the saved values on its first draw. + +## The WASM ABI + +The artifact is one WebAssembly module. It exports `memory`, `widget_draw(width, height, +scale_milli)` and `widget_tap(hit_id)`, and may import these functions from the module named +`grimoire`: + +```text +rect(x, y, w, h, style) +text(x, y, w, h, ptr, len, px, center) +button(id, x, y, w, h, ptr, len, style) +hit(id, x, y, w, h) +status(ptr, len) +request_redraw(after_ms) +setting(key_ptr, key_len, out_ptr, out_cap) -> i32 +state_get(ptr, cap) -> i32 +state_set(ptr, len) +now() -> i64 +``` + +`widget_draw` is called for each frame. `width` and `height` are the body's size in screen pixels; +`scale_milli` is the UI scale times 1000 (300 dpi is 1000), so a package can keep dimensions at +300 dpi by multiplying with `scale_milli / 1000.0`. Drawing coordinates are relative to the body's +top-left. + +| import | | +|---|---| +| `rect` | a rectangle in the frame; `style` is `0` normal, `1` selected or `2` disabled | +| `text` | UTF-8 text at `ptr`, `len` in the module's memory, `px` high, centered when `center` is nonzero | +| `button` | a button with its own label; it is also a hit region with `id` | +| `hit` | a hit region with `id`, without drawing anything | +| `status` | the text the editor's `editor.widget.N.status` probe reads, for tests and debugging | +| `request_redraw` | asks for `widget_draw` again after `after_ms` (16 to 86,400,000); a clock calls it once per draw, and a package that never calls it is only drawn when something else repaints | +| `setting` | copies one saved setting's value into `out_ptr` and returns its byte length, or `0`; `out_cap` caps the copy | +| `state_get` | copies the saved state into `ptr` and returns its byte length, or `0`; `cap` caps the copy | +| `state_set` | replaces the saved state with the bytes at `ptr`; at most 64 KiB is kept | +| `now` | Unix time in seconds, when a widget needs a clock | + +`widget_tap` is called with the `id` of the hit region under the tap, or `-1` for a tap elsewhere +in the body. It should update the package's state; the next `widget_draw` shows the result. A +module may call `state_set` during a tap or a draw; the host writes the state file after the call, +at `packages/widgets//state/runtime.bin`. For a timer or a sticky note, that is the whole +persistence model. + +Each call runs with a fixed instruction budget, and a module's linear memory may grow to at most +32 MiB. A module that loops past the budget is stopped and its frame shows the error instead of +freezing Grimoire. Imports outside the `grimoire` module fail to link, and the module has no +filesystem, network or process access. + +A module must be self-contained: the same bytes run on every supported Scribe, so there is nothing +to cross-compile for armv7. A Rust `cdylib` built for `wasm32-unknown-unknown` with `extern "C"` +imports and `#[no_mangle] pub extern "C"` exports is one working toolchain; any language that +produces a plain WebAssembly module works. + +## The artifact + +The installer downloads the artifact (at most 32 MiB, with a 45-second timeout), checks its length +and SHA-256 against the manifest, and only then writes anything. A mismatch refuses the install +with nothing changed. There is no signature and no inspection beyond that check; the module is +first instantiated when its frame opens. + +`tests/fixtures/widgetcalc/` holds a compiled calculator package used by the scenarios; +`tests/fixtures/widgetpkg/` holds a small package used for the install-path checks. Neither is +built by Grimoire's build, and neither adds code to Grimoire itself. + +## Packaging + +Build the artifact first. Then, from a Grimoire checkout: + +```sh +tools/widget-pack.sh path/to/package path/to/built.bin +``` + +The script copies the built file to the manifest's `artifact.path`, writes `artifact.size` and +`artifact.sha256`, and verifies the result. Run it without the second argument to check an existing +pair: + +```sh +tools/widget-pack.sh path/to/package +``` + +In the manifest it only touches those two numbers. Bump `version` yourself, and run it again after +every rebuild. + +The manifest must use the block form of `artifact:` with `path`, `sha256` and `size` present; the +script refuses an inline mapping rather than rewriting YAML it cannot see. + +A release entry has its own `sha256` and URL. The script does not update it: if `releases` has an +entry for the current version, update that entry by hand (or leave it out and let the artifact be +served from the repository tree). The `artifact.size` must still describe the file at the release +URL. + +### Versioning + +`version` is the package's version, not the artifact's. Bump it whenever the artifact or the +manifest changes: an update is installed only when it sorts above the installed version. A +prerelease such as `1.2.0-beta.1` sorts below `1.2.0`. Use `-beta.N` or `-rc.N` for one: another +suffix passes the manifest check but the updater does not order it as newer. + +Tags and GitHub releases are optional. If you use them, the release entry's `url` must be the +artifact file itself, and its `sha256` and the manifest's `artifact.size` must describe that file. +A release page URL is not an artifact URL. + +### License + +Set `license` to the license you actually publish under. When the text is found, the install page +shows it and asks the reader to agree before the download starts. The text is read from +`license_url`, or from one of the conventional file names beside the manifest. If only the name is declared and no file is found, the +install still proceeds; a declared `license_url` that does not answer stops it. Keep the license +file in the repository even when you set `license_url`, so the source tree is self-contained. + +## Testing + +There is no interactive Rust window. The Rust build is exercised by the headless runner, which can +take PNG screenshots of what it drew. The C simulator (`make sim`) predates widgets and does not +have them. The fixtures and scenarios under `tests/` are the working examples: + +- `tests/fixtures/widgetcalc/` is an installed calculator package whose artifact is a WASM module + (`packages/index.json` plus `packages/widgets/com.grimoire.calculator/`). +- `tests/fixtures/widgetpkg/` is a small package, used for the install-path checks. +- `tests/scenarios/z_widgets.qs` opens the catalog, opens the calculator, calculates in all three + modes, opens the unit converter, minimizes, restores, drags and closes it. Its taps name the + package's hit regions (`widget.0.hit.N`), not controls built into Grimoire. +- `tests/scenarios/z_calculator_settings.qs` changes the calculator's default and enabled modes, + then checks the open frame and a newly opened one. +- `tests/scenarios/z_widget_packages.qs` drives install, update, license and remove through the + package manager. + +A scenario can copy a fixture into a fresh data root: + +``` +# copy: tests/fixtures/widgetcalc . +``` + +To try your own package without publishing it, make a fixture with the installed layout and add its +entry to `packages/index.json`: + +```sh +mkdir -p /tmp/mypkg/packages/widgets +cp -r path/to/my-timer /tmp/mypkg/packages/widgets/com.example.timer +# then add the entry to /tmp/mypkg/packages/index.json (see FORMAT.md) +``` + +The entry's `path` is relative to the data root (`packages/widgets//`), `sha` is +the installed artifact's digest, and `source_url` is the address an update should re-fetch. Then +run a scenario with `# copy: /tmp/mypkg .` (or copy it to `GRIMOIRE_ROOT` yourself) and inspect the +shots: + +```sh +make scenarios SCENARIOS="tests/scenarios/z_widgets.qs" SCEN_JOBS=1 +``` + +The runner writes screenshots under `build/shots//`. `make headless` builds the runner. +Useful environment for widget checks: + +| variable | | +|---|---| +| `GRIMOIRE_ROOT=DIR` | the data root (default `./grimoire-data` off the Kindle) | +| `GRIMOIRE_WIDGET_PLATFORM=kindle-scribe-2022` | stands in for a device's model, for `platforms` checks; off the Kindle it is otherwise `unknown` | +| `GRIMOIRE_SCRIPT=FILE` | the scenario to run in a direct `grimoire-headless` invocation | +| `GRIMOIRE_SHOTS=DIR` | where screenshots go in a direct invocation | + +The platform values are `all`, `kindle-scribe-2022` and `kindle-scribe-2024`. On a Kindle the model +comes from `/proc/device-tree/model`; the environment variable is the simulator's and a test's way +to stand in for it. + +The scenario scripts cannot name a row longer than 32 bytes, so `packages.row.com.grimoire.calculator` +is not a valid panel name. The package controls also accept a row's index (`packages.row.0`) and a +setting's index (`packages.setting.0`), or tap the coordinates instead, as `z_widget_packages.qs` +does. + +## Publishing + +1. Put `package.yaml` and the artifact at the repository root and push them to a public + repository. GitHub's default branch is used for `user/repo`; a direct raw URL works on any + branch. +2. Check the install from a clean data root: Settings → Packages → Widgets → **Install from + repository...**, enter `user/repo`, read the trust page and the license, and install. +3. Open the widget from the catalog, move and resize it, close it and reopen it. If it has a + license, check **View license**. On a GitHub package, check **View QR code**. +4. Publish a new version by changing the artifact and `version`, re-running the packaging script, + and pushing. Existing readers use **Check for updates** or **Update all**. +5. Do not move or rewrite a published version. If the artifact was wrong, publish a new version. + +Removal deletes the installed manifest, artifact and frame, and keeps `state/`. An update keeps +the old directory as `.previous` until the new one is in place; a failed write rolls back. + +## State + +A package that needs to remember something across launches writes it through `state_set`; the host +keeps the bytes in `packages/widgets//state/runtime.bin`. That folder is not part of the +artifact and is never overwritten by an update. Removing the package keeps it, so reinstalling +restores the widget's data. Nothing else of the package remains after a removal. + +Keep state small and treat it as the reader's data: it is not backed up, not uploaded, and not +shared between packages. There is no state migration helper; a widget that changes its format must +read the old one and write the new one itself. + +## Trust and safety + +Installing is an explicit trust decision: the trust page names the package and its author, and the +install only starts after it is accepted. Grimoire checks that the manifest is well formed, that +the platform matches, and that the artifact's length and SHA-256 match the manifest, but it does +not review the code and cannot tell a good widget from a malicious one. Install from sources you +trust, and read the manifest before installing. + +The manifest and artifact are fetched over HTTPS. The SHA-256 protects against a truncated or +corrupted download; it is not a signature, and it comes from the same repository as the artifact. +There is no package signing and no revocation list. + +A widget is confined to its frame, its settings and its own state file. The module has no network, +filesystem or process access; the only files the host touches for it are the artifact it was +installed from and `state/runtime.bin`. It still runs with the reader's full screen and can draw +misleading content, so the trust decision remains yours. + +## Checklist + +- [ ] `package.yaml` at the repository root, `type: widget` +- [ ] a stable `id`, a new `version` for this publish +- [ ] an artifact at `artifact.path`, one file, at most 32 MiB +- [ ] `artifact.size` and `artifact.sha256` match it (`tools/widget-pack.sh`) +- [ ] `license` and a license file or `license_url` +- [ ] `spec.runtime: wasm`, and the module exports `memory`, `widget_draw` and `widget_tap` +- [ ] `spec.size` within 120x80 and 70% of the canvas +- [ ] `platforms` correct, `min_grimoire_version` honest +- [ ] any `settings` keys, labels, defaults and choices are final; changing a key loses its saved value +- [ ] tested from a clean data root: install, open, move, close, update, remove; open Settings and toggle each row +- [ ] README says which Grimoire version runs the widget, and what it does diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 00da90b0..0e0b46df 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -122,6 +122,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "euclid" version = "0.22.14" @@ -175,6 +181,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -197,8 +209,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1218dedd5348c1b166ec3b8b3cbca49d2f527bd43b3fa072ea5123c523ed3f" dependencies = [ "bytemuck", - "foldhash", - "hashbrown", + "foldhash 0.2.0", + "hashbrown 0.17.1", "log", "peniko", "png", @@ -216,6 +228,7 @@ dependencies = [ "libc", "png", "skrifa 0.46.2", + "wasmi", ] [[package]] @@ -227,13 +240,22 @@ dependencies = [ "euclid", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "foldhash", + "foldhash 0.2.0", ] [[package]] @@ -341,6 +363,16 @@ dependencies = [ "png", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "kurbo" version = "0.13.1" @@ -359,6 +391,12 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -561,6 +599,35 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "shlex" version = "2.0.1" @@ -605,12 +672,28 @@ version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "string-interner" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0" +dependencies = [ + "hashbrown 0.15.5", + "serde", +] + [[package]] name = "syn" version = "2.0.119" @@ -694,11 +777,61 @@ checksum = "ed1fec424fbba6acf6cbc78bb526447eb77590d95f40419d598870fe37535212" dependencies = [ "bytemuck", "glifo", - "hashbrown", + "hashbrown 0.17.1", "png", "vello_common", ] +[[package]] +name = "wasmi" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8762bb61dfbcfdbe0ab1a783a73d26d5149809cf7d882c9c9b76b7c0fb9417de" +dependencies = [ + "spin", + "wasmi_collections", + "wasmi_core", + "wasmi_ir", + "wasmparser", +] + +[[package]] +name = "wasmi_collections" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e053dad75ea3b41b5a6973af3e923bd7c608e9d3b7415a7cf0018c280c16b3" +dependencies = [ + "string-interner", +] + +[[package]] +name = "wasmi_core" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1709ad297d9dc05a4b109148e1c0908691b1553b1473f6b08f4f5b969c3c81fe" +dependencies = [ + "libm", +] + +[[package]] +name = "wasmi_ir" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "746ed3ae294cf571d06020c9b8f4a3cb2be1ef228f8556279cc354cf6cf01df4" +dependencies = [ + "wasmi_core", +] + +[[package]] +name = "wasmparser" +version = "0.228.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3" +dependencies = [ + "bitflags", + "indexmap", +] + [[package]] name = "yoke" version = "0.8.4" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 9e078436..21971ba4 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -68,6 +68,9 @@ path = "src/bin/mklogo.rs" [dependencies] libc = "0.2" +# Installed widgets are WebAssembly modules. wasmi is a pure-Rust interpreter, so it follows the +# app to the Kindle's armv7 target and needs no C runtime of its own. +wasmi = { version = "2.0.2", default-features = false, features = ["std", "validate"] } # The PDF import (2.1.0-beta.2, DESIGN.md 5): hayro pinned exactly; 0.9.0 is under two weeks old until # 2026-11-16 (D12). `png` is already in its tree (same version), used to encode the pages. hayro = { version = "=0.8.0", default-features = false, features = ["embed-fonts", "embed-cmaps"] } diff --git a/rust/src/app.rs b/rust/src/app.rs index e402d934..5dd5e1a6 100644 --- a/rust/src/app.rs +++ b/rust/src/app.rs @@ -36,6 +36,8 @@ pub struct App { pub dpi: f32, /// mirrors the panel pub screen: Canvas, + /// The Settings → Packages → Widgets page (widgetpkgui.rs), over whatever screen is behind it. + pub pkg: WidgetPkgUi, pub settings: Settings, /// the default shortcuts: shortcuts.ini and controller.ini, which every keyboard and controller uses /// but one with shortcuts of its own diff --git a/rust/src/editor.rs b/rust/src/editor.rs index b35e0de7..74ee04a5 100644 --- a/rust/src/editor.rs +++ b/rust/src/editor.rs @@ -94,13 +94,18 @@ const P_SHAPE_MIN: i32 = 64; const P_SHAPE_CORNER: i32 = 65; const P_SHAPE_DONE: i32 = 30; const P_SETTINGS: i32 = 31; +/// the Widgets button on the toolbar, and its popup's rows +const P_WIDGETS: i32 = 32; +const P_WIDGET_SPAWN: i32 = 33; +/// the popup's Manage widgets... row +const P_WIDGET_MANAGE: i32 = 34; /// the tool picker's Select (Select mode, select.rs) const P_PICK_SELECT: i32 = 66; /// Which input started the current gesture, and what it does. #[repr(i32)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum Owner { +pub(crate) enum Owner { #[default] None = 0, // OWN_NONE Draw = 1, // OWN_DRAW @@ -137,13 +142,18 @@ enum Owner { /// the contact that opened the quick sizes card (a pen button held HOLD_MS), which may slide to a chip, or one /// that began on the card (quicksize.rs) QuickSize = 22, + /// a contact that began on the Widgets popup + Widgets = 23, + /// a contact that began on a widget frame (its title, close, minimize, grip or body) + Widget = 24, } /// The owner's name in grimoire.log and the `editor.owner` probe. fn owner_name(o: Owner) -> &'static str { - const K: [&str; 23] = [ + const K: [&str; 25] = [ "none", "draw", "erase", "panel", "modal", "display", "pages", "tools", "build", "templates", "link", "bar", "outside", "find", "lasso", "card", "linkto", "strip", "map", "pen-drag", "select", "add-pad", "quick-size", + "widgets", "widget", ]; K[o as usize] } @@ -334,6 +344,22 @@ struct ShapeHold { } struct ShapePreview { saved: Canvas, region: Rect, raw_n: usize, stroke: Box } +/// How a widget drag shows its newest place: a dithered border at the frame's new rect over a copy of +/// the screen without the border's old strips, as a selection's drag does (select.rs). The frame itself +/// stays where it was until the lift, so no page or frame content is composed while the contact moves. +#[derive(Default)] +struct WidgetDragView { + /// the frame rect the border was last drawn at + shown: Option, + /// the screen without the border (and without the panel), copied as the first border shows + base: Option, + base_at: Rect, + shown_at: u32, + moved_at: u32, + samples: u32, + samples_at_last_show: u32, +} + #[derive(Default)] pub struct EditorState { /// when the open page's Pages preview was last made from its canvas (save_page), and whether the @@ -428,7 +454,7 @@ pub struct EditorState { page_views: Vec, // Pointer ownership: which input started the current gesture and what it does. - owner: Owner, + pub(crate) owner: Owner, owner_is_pen: bool, /// grimoire.log's contact and link-making lines (diag): their budget, and the link-making state last said diag: DiagBudget, @@ -582,6 +608,18 @@ pub struct EditorState { /// a press on a Smart shapes slider has come over its track: the knob follows it to the lift tools_slider: bool, + // Widgets (widgets.rs): the open frames, the popup beside the panel, and the contact on one of them. + pub(crate) widgets: WidgetHost, + widgets_open: bool, + /// where the popup's top is meant to be: the panel's, as it opened + widgets_y: i32, + widgets_rect: Rect, + widgets_hits: HitList, + widgets_press: Press, + /// the popup's button pressed, shown pressed until the lift + widgets_pressed: Option, + widget_drag: Option, + widget_drag_view: WidgetDragView, /// the Pages view (pagesview.h) pv: PagesView, destination: NotebookPicker, @@ -679,10 +717,10 @@ pub struct EditorState { } // (The C's S, a->ed.) -fn ed(a: &mut App) -> &mut EditorState { +pub(crate) fn ed(a: &mut App) -> &mut EditorState { a.ed.as_deref_mut().unwrap() } -fn ed_ref(a: &App) -> &EditorState { +pub(crate) fn ed_ref(a: &App) -> &EditorState { a.ed.as_deref().unwrap() } @@ -1487,8 +1525,9 @@ fn draw_panel(a: &mut App) { y += btn_h() + gap(); canvas_hline(c, x, x + w, y + div_h() / 2 - ui_px(6.0), ui_px(3.0), 160); y += div_h(); - // Paper, Display, Settings and Library (icons only, like the rest of the panel). - let rest: [(IconKind, i32); 4] = [ + // Widgets, Paper, Display, Settings and Library (icons only, like the rest of the panel). + let rest: [(IconKind, i32); 5] = [ + (IconKind::Grid, P_WIDGETS), (IconKind::Paper, P_PAPER), (IconKind::Brightness, P_DISPLAY), (IconKind::Gear, P_SETTINGS), @@ -1522,7 +1561,7 @@ fn panel_hit_at(s: &EditorState, x: f32, y: f32) -> Option { /// The runner's name for a panel button (`tap panel NAME`, `editor.panel_at.X.Y`): grip, collapse, /// expand, tool-picker, eraser, tool:NAME (a pinned pen, NAME as `editor.tool` names tools), undo, -/// redo, clear, previous, pages (the page chip), next, links, paper, display, pen-feel, library. "" for a +/// redo, clear, previous, pages (the page chip), next, links, widgets, paper, display, pen-feel, library. "" for a /// hit that is not one of the panel's. fn panel_name(h: &Hit) -> String { match h.id { @@ -1543,6 +1582,7 @@ fn panel_name(h: &Hit) -> String { P_PAGES => "pages".into(), P_NEXT => "next".into(), P_LINKS => "links".into(), + P_WIDGETS => "widgets".into(), P_PAPER => "paper".into(), P_DISPLAY => "display".into(), P_PENSET => "pen-feel".into(), @@ -1593,6 +1633,49 @@ pub fn editor_panel_point(a: &mut App, name: &str) -> Option<(f32, f32)> { if let Some(control)=name.strip_prefix("select."){return sel_control_point(s,control);} if let Some(control)=name.strip_prefix("bar."){return linkbar_control_point(&s.lb,control);} if let Some(control)=name.strip_prefix("linkto."){return linkbar_control_point(&s.lt,control);} + // The Widgets popup's rows: `tap panel widgets.com.example.widget` opens or raises one. + if s.widgets_open { + if let Some(id)=name.strip_prefix("widgets.") { + if id == "manage" { + return s.widgets_hits.h.iter().find(|h| h.id == P_WIDGET_MANAGE) + .map(|h| ((h.r.x + h.r.w / 2) as f32, (h.r.y + h.r.h / 2) as f32)); + } + let i = widget_catalog().iter().position(|d| d.id == id)? as i32; + return s.widgets_hits.h.iter().find(|h| h.id == P_WIDGET_SPAWN && h.arg == i) + .map(|h| ((h.r.x + h.r.w / 2) as f32, (h.r.y + h.r.h / 2) as f32)); + } + } + // A widget frame's parts: `tap panel widget.com.example.widget.close` (title, close, minimize, + // resize, body), while it is open and not minimized (a minimized frame has only its title). + if let Some(n)=name.strip_prefix("widget.") { + // A frame may be named by its index (widget.0.hit.12) or by a package id that has dots + // (widget.com.example.widget.close). + let (id, part) = match n.split_once('.') { + Some((num, rest)) if num.parse::().is_ok() => (num, rest), + _ => n.rsplit_once('.')?, + }; + let i = id.parse::().ok().filter(|&i| i < s.widgets.frames.len()).or_else(|| s.widgets.index_of(id))?; + let f = s.widgets.frames.get(i)?; + if f.layout.minimized && part != "title" { return None; } + if let Some(hit) = part.strip_prefix("hit.") { + let hit: i32 = hit.parse().ok()?; + let r = f.runtime.as_ref()?.hit(hit)?; + let body = widget_body(f); + return Some(((body.x + r.x + r.w / 2) as f32, (body.y + r.y + r.h / 2) as f32)); + } + let r = match part { + "title" => f.title_rect(), + "close" => f.close_rect(), + "min" | "minimize" => f.minimize_rect(), + "resize" => f.resize_rect(), + "body" => { + let t = f.title_rect(); + Rect { x: f.rect().x, y: t.y + t.h, w: f.rect().w, h: f.rect().h - t.h } + } + _ => return None, + }; + return Some(((r.x + r.w / 2) as f32, (r.y + r.h / 2) as f32)); + } if s.tools_open { let target=if name=="picker.pin-mode" {Some((P_PIN_MODE,0))} else if name=="picker.select" {Some((P_PICK_SELECT,0))} @@ -2203,6 +2286,136 @@ fn draw_tools(a: &mut App) { } } +/// The canvas widgets sit on: the whole screen under the status corner. +fn widget_area(a: &App) -> Rect { + let top = status_reserved(a); + Rect { x: 0, y: top, w: a.w, h: a.h - top } +} + +/// The Widgets popup: the catalog's rows beside the panel. Its rows open a widget (or raise it); +/// Manage widgets... opens Settings → Packages → Widgets. +fn draw_widgets_popup(a: &mut App) { + let App { screen: c, ed, .. } = a; + let s = ed.as_deref_mut().unwrap(); + if !s.widgets_open { + return; + } + hits_clear(&mut s.widgets_hits); + let defs = widget_catalog(); + let n = defs.len() as i32; + let w = ui_px(560.0); + let pad = ui_px(30.0); + let gap = ui_px(14.0); + let row_h = ui_px(120.0); + let header = ui_px(104.0); + let h = header + n * (row_h + gap) + row_h + pad; + let mut x = s.panel.x - w - ui_px(20.0); + if x < ui_px(10.0) { + x = s.panel.x + s.panel.w + ui_px(20.0); + } + x = clampi(x, ui_px(10.0), (a.w - w - ui_px(10.0)).max(ui_px(10.0))); + let y = clampi(s.widgets_y, ui_px(10.0), (a.h - h - ui_px(10.0)).max(ui_px(10.0))); + s.widgets_rect = Rect { x, y, w, h }; + ui_frame(c, s.widgets_rect, ui_px(22.0), 255, true, 0); + ui_frame(c, s.widgets_rect, ui_px(22.0), 0, false, ui_px(6.0)); + // TRANSLATORS: the widget popup's title, beside the toolbar's Widgets button. + ui_text(c, FontFace::Bold, ui_text_size(), ui_small_size(), Rect { x: x + pad, y, w: w - 2 * pad, h: header }, tr("Widgets"), 2, false, 0); + let mut ry = y + header; + for (i, def) in defs.iter().enumerate() { + let r = Rect { x: x + pad, y: ry, w: w - 2 * pad, h: row_h }; + let open = s.widgets.is_open(def.id); + let row = if open { Row::selected(def.icon, def.name) } else { Row::new(def.icon, def.name) }; + ui_row(c, r, &row); + hits_add(&mut s.widgets_hits, r, P_WIDGET_SPAWN, i as i32); + ry += row_h + gap; + } + // TRANSLATORS: the widget popup's row that opens the Packages page. + let r = Rect { x: x + pad, y: ry, w: w - 2 * pad, h: row_h }; + let manage = Row::new(IconKind::Gear, tr("Manage widgets...")); + ui_row(c, r, &manage); + hits_add(&mut s.widgets_hits, r, P_WIDGET_MANAGE, 0); +} + +/// The widget frames, below the panel and menus and above the page. +fn draw_widgets(a: &mut App, r: Rect) { + let order = ed_ref(a).widgets.draw_order(); + let clip = a.screen.clip; + canvas_set_clip(&mut a.screen, r); + for i in order { + let rect = ed_ref(a).widgets.frames[i].rect(); + if !rect_overlaps(r, rect) { + continue; + } + draw_widget_frame(a, i); + } + a.screen.clip = clip; +} + +fn widget_body(f: &WidgetFrame) -> Rect { + let r = f.rect(); + let title = f.title_rect(); + Rect { x: r.x + ui_px(14.0), y: title.y + title.h + ui_px(8.0), w: r.w - ui_px(28.0), h: r.h - title.h - ui_px(22.0) } +} + +fn draw_widget_frame(a: &mut App, i: usize) { + let App { screen: c, ed, .. } = a; + let s = ed.as_deref_mut().unwrap(); + let Some(f) = s.widgets.frames.get_mut(i) else { return }; + let r = f.rect(); + let title = f.title_rect(); + ui_frame(c, r, ui_px(18.0), 255, true, 0); + ui_frame(c, r, ui_px(18.0), 0, false, ui_px(3.0)); + if f.layout.minimized { + let icon = Rect { x: r.x + (r.w - ui_px(48.0)) / 2, y: r.y + (r.h - ui_px(48.0)) / 2, w: ui_px(48.0), h: ui_px(48.0) }; + ui_icon(c, f.def.icon, icon, 0); + return; + } + // The title bar: icon, title, minimize, close. + canvas_hline(c, r.x + ui_px(8.0), r.x + r.w - ui_px(8.0), title.y + title.h - ui_px(2.0), ui_px(2.0), 0); + let icon = Rect { x: r.x + ui_px(12.0), y: r.y + ui_px(10.0), w: ui_px(44.0), h: ui_px(44.0) }; + ui_icon(c, f.def.icon, icon, 0); + let cr = f.close_rect(); + let mr = f.minimize_rect(); + let tx = icon.x + icon.w + ui_px(10.0); + let tw = (mr.x - tx - ui_px(8.0)).max(0); + ui_text(c, FontFace::Bold, ui_small_size(), ui_small_size() * 0.55, Rect { x: tx, y: r.y, w: tw, h: title.h }, f.def.name, 1, false, 0); + ui_icon(c, IconKind::Close, Rect::new(cr.x + ui_px(14.0), cr.y + ui_px(14.0), cr.w - ui_px(28.0), cr.h - ui_px(28.0)), 0); + ui_icon(c, IconKind::Minus, Rect::new(mr.x + ui_px(14.0), mr.y + ui_px(14.0), mr.w - ui_px(28.0), mr.h - ui_px(28.0)), 0); + // The body is the package's own WASM runtime. A package that cannot start shows why. + let body = widget_body(f); + if body.w > 0 && body.h > 0 { + f.ensure_runtime(); + if let Some(rt) = f.runtime.as_mut() { + rt.draw(c, body); + } + if let Some(err) = f.error() { + let mut text = format!("{}\nv{}", f.def.name, f.def.version); + if !f.def.author.is_empty() { + text.push_str(&format!(" · {}", f.def.author)); + } + text.push('\n'); + text.push_str(err); + ui_text(c, FontFace::Regular, ui_small_size(), ui_small_size(), body, &text, 6, false, 0); + } else if f.runtime.is_none() { + let mut text = f.def.name.to_string(); + if !f.def.version.is_empty() { + text.push_str(&format!(" v{}", f.def.version)); + } + if !f.def.author.is_empty() { + text.push_str(&format!(" · {}", f.def.author)); + } + ui_text(c, FontFace::Bold, ui_small_size(), ui_small_size(), Rect { x: body.x, y: body.y, w: body.w, h: ui_small_size() as i32 + ui_px(6.0) }, &text, 1, false, 0); + if !f.def.description.is_empty() { + ui_text(c, FontFace::Regular, ui_small_size(), ui_small_size(), Rect { x: body.x, y: body.y + ui_small_size() as i32 + ui_px(10.0), w: body.w, h: body.h }, f.def.description, 4, false, 0); + } + } + } + if f.def.resizable { + let gr = f.resize_rect(); + ui_icon(c, IconKind::Expand, Rect::new(gr.x + ui_px(18.0), gr.y + ui_px(18.0), gr.w - ui_px(36.0), gr.h - ui_px(36.0)), 150); + } +} + fn draw_shape_menu(a: &mut App) { let (aw,ah)=(a.w,a.h); let App {screen:c,settings:st,ed,..}=a; @@ -2510,6 +2723,7 @@ fn compose(a: &mut App, r: Rect) { sel_draw_halo(a, r); draw_area_wait(a, r); draw_card_border(a, r); + draw_widgets(a, r); if rect_overlaps(r, ed(a).panel) && !ed(a).live_no_panel { // Only the part of the panel inside r: the page was blitted there alone, and the rest of the panel (and // whatever menu is over it) is on the screen as it was; drawn again, the panel would lay itself over @@ -2551,6 +2765,13 @@ fn draw_menus(a: &mut App, r: Rect) { if s.tools_open && rect_overlaps(r, s.tools_rect) { draw_tools(a); } + let s = ed_ref(a); + if s.widgets_open && rect_overlaps(r, s.widgets_rect) { + let clip = a.screen.clip; + canvas_set_clip(&mut a.screen, r); + draw_widgets_popup(a); + a.screen.clip = clip; + } // The Find sheet's card of rows and keyboard, where r meets them. let s = ed_ref(a); if s.find.open { @@ -2744,7 +2965,7 @@ fn show(a: &mut App, page_rect: Rect, m: RefreshMode) { app_invalidate(a, r, m); } -fn compose_all(a: &mut App, m: RefreshMode) { +pub(crate) fn compose_all(a: &mut App, m: RefreshMode) { compose(a, Rect { x: 0, y: 0, w: a.w, h: a.h , }, ); @@ -4376,6 +4597,7 @@ fn sheet_open(s: &EditorState) -> bool { || s.map.open || s.pv.open || s.tools_open + || s.widgets_open || s.mb.open || s.dm.open || s.paper_open @@ -4397,6 +4619,7 @@ pub fn editor_pen_not_ink(a: &App) -> bool { || s.pb_drag.is_some() || s.sh.preview.is_some() || s.lb.open + || s.widgets_open || s.find.open || s.card.open || s.qs.open @@ -4412,7 +4635,7 @@ pub fn editor_live_style(a: &App, ev: &InEvent, out: &mut LiveStyle) { if crate::library::library_settings_active(a) {return;} let Some(s) = a.ed.as_deref() else { return }; let Some(page) = s.open_page() else { return }; - if !s.open || pb_contact_bound(a, ev) || s.sh.preview.is_some() || page.readonly || sheet_open(s) || s.pinching || s.lm.state != LmState::Off || (s.owner != Owner::None && s.owner != Owner::Draw && s.owner != Owner::Erase) || editor_pen_not_ink(a) { + if !s.open || pb_contact_bound(a, ev) || s.sh.preview.is_some() || page.readonly || sheet_open(s) || s.widgets.hit(ev.x.round_ties_even() as i32, ev.y.round_ties_even() as i32).is_some() || s.pinching || s.lm.state != LmState::Off || (s.owner != Owner::None && s.owner != Owner::Draw && s.owner != Owner::Erase) || editor_pen_not_ink(a) { return; } let st = &a.settings; @@ -7658,6 +7881,439 @@ fn open_shape_menu(a: &mut App) { let r=ed(a).tools_rect;app_invalidate(a,r,RefreshMode::Ui); } +// ---- the Widgets popup ---- + +fn widgets_union(s: &EditorState) -> Rect { + let mut r = s.widgets_rect; + for f in &s.widgets.frames { + r = rect_union(r, f.rect()); + } + r +} + +fn open_widgets(a: &mut App) { + if ed_ref(a).widgets_open { + close_widgets(a); + return; + } + if ed_ref(a).tools_open { + close_tools(a); + } + let s = ed(a); + s.widgets_open = true; + // Beside its toolbar button, as a sidebar tool's hold opens beside it, not at the panel's top. + s.widgets_y = s.hits.h.iter().find(|h| h.id == P_WIDGETS).map_or(s.panel.y, |h| h.r.y); + draw_widgets_popup(a); + let r = ed(a).widgets_rect; + app_invalidate(a, r, RefreshMode::Ui); +} + +fn close_widgets(a: &mut App) { + if !ed_ref(a).widgets_open { + return; + } + let a_rect = ed(a).widgets_rect; + ed(a).widgets_open = false; + ed(a).widgets_hits = HitList::default(); + compose(a, a_rect); + app_invalidate(a, a_rect, RefreshMode::Ui); +} + +fn widgets_spawn(a: &mut App, def: &'static WidgetDef) { + let area = widget_area(a); + let panel = ed(a).panel; + ed(a).widgets.spawn(def, area, panel); + // The popup closes on the choice: the new frame would otherwise start under it, and the first + // tap on the frame should reach the frame. + ed(a).widgets_open = false; + ed(a).widgets_hits = HitList::default(); + let r = widgets_union(ed(a)); + compose(a, r); + app_invalidate(a, r, RefreshMode::Ui); + ed(a).widgets.save(); +} + +fn widgets_tap(a: &mut App, x: f32, y: f32) { + let s = ed(a); + let hit = hits_find(&s.widgets_hits, x, y).copied(); + match hit { + Some(h) if h.id == P_WIDGET_SPAWN => { + if let Some(def) = widget_catalog().get(h.arg as usize) { + widgets_spawn(a, def); + } + } + Some(h) if h.id == P_WIDGET_MANAGE => { + close_widgets(a); + // The package manager is Settings > Packages > Widgets, over the notebook as Settings is. + crate::library::library_settings_from_notebook(a); + packages_ui_open(a); + } + _ => close_widgets(a), + } +} + +fn widgets_pointer(a: &mut App, ph: i32, ev: &InEvent, pen: bool) { + let (x0, y0) = { + let s = ed(a); + press_move(&mut s.widgets_press, ev.x, ev.y); + if ph != 2 { + return; + } + s.owner = Owner::None; + (s.widgets_press.x0, s.widgets_press.y0) + }; + let mut pressed = ed(a).widgets_pressed.take(); + let back = app_press_release(a, &mut pressed); + if !rect_is_empty(back) { + app_invalidate(a, back, RefreshMode::Ui); + } + if touch_cancelled(ev) { + return; + } + widgets_tap(a, x0, y0); + // (pen and finger alike: the popup swallows the contact, and a tap outside closes it) + let _ = pen; +} + +// A widget drag's border, as a selection's: one fast refresh a show, paced by the panel and the pen. +const WIDGET_SHOW_MS: u32 = DRAG_SHOW_MS; +const WIDGET_PAUSE_MS: u32 = 50; +const WIDGET_SHOW_SAMPLES: u32 = 60; + +/// The screen a frame may show on: under the status bar, with the panel's part taken out below. +fn widget_drag_area(a: &App) -> Rect { + rect_intersect(widget_area(a), Rect { x: 0, y: 0, w: a.w, h: a.h }) +} + +/// r cut into the pieces of `widget_drag_area` a border may draw on (the panel draws over the rest). +fn widget_clip_pieces(a: &App, r: Rect) -> Vec { + let r = rect_intersect(r, widget_drag_area(a)); + if rect_is_empty(r) { + return Vec::new(); + } + let hole = ed_ref(a).panel; + if rect_is_empty(hole) || rect_is_empty(rect_intersect(r, hole)) { + return vec![r]; + } + let mut v = Vec::with_capacity(4); + let top_h = hole.y - r.y; + if top_h > 0 { + v.push(Rect { x: r.x, y: r.y, w: r.w, h: top_h }); + } + let bottom_y = hole.y + hole.h; + if bottom_y < r.y + r.h { + v.push(Rect { x: r.x, y: bottom_y, w: r.w, h: r.y + r.h - bottom_y }); + } + let mid_y = hole.y.max(r.y); + let mid_h = (hole.y + hole.h).min(r.y + r.h) - mid_y; + if mid_h > 0 { + let left_w = hole.x - r.x; + if left_w > 0 { + v.push(Rect { x: r.x, y: mid_y, w: left_w, h: mid_h }); + } + let right_x = hole.x + hole.w; + if right_x < r.x + r.w { + v.push(Rect { x: right_x, y: mid_y, w: r.x + r.w - right_x, h: mid_h }); + } + } + v +} + +/// The border's strips at b, cut to where they may draw: what a show refreshes and a later show puts back. +fn widget_preview_strips(a: &App, b: Rect) -> Vec { + let (band, halo) = (link_band(), ui_px(1.0)); + let mut v = Vec::with_capacity(4); + for s in dither_strips(b, band, halo) { + for p in widget_clip_pieces(a, s) { + let q = rect_intersect(s, p); + if !rect_is_empty(q) && !v.contains(&q) { + v.push(q); + } + } + } + v +} + +fn widget_preview_draw(a: &mut App, b: Rect) { + let (band, halo) = (link_band(), ui_px(1.0)); + let clip = a.screen.clip; + for p in widget_clip_pieces(a, b) { + canvas_set_clip(&mut a.screen, p); + canvas_dither_rect(&mut a.screen, b, band, halo); + } + a.screen.clip = clip; +} + +/// Two strips joined only when one rect over both covers no more than they do apart: a short move's +/// old and new border overlap (as a selection drag's strips, select.rs drag_present). +fn widget_join_strips(mut v: Vec) -> Vec { + let area = |r: Rect| if rect_is_empty(r) { 0 } else { r.w as i64 * r.h as i64 }; + loop { + let mut best: Option<(i64, usize, usize)> = None; + for i in 0..v.len() { + for j in i + 1..v.len() { + let waste = area(rect_union(v[i], v[j])) - area(v[i]) - area(v[j]); + if best.is_none_or(|b| waste < b.0) { + best = Some((waste, i, j)); + } + } + } + match best { + Some((waste, i, j)) if waste <= 0 => { + let u = rect_union(v[i], v[j]); + v.swap_remove(j); + v[i] = u; + } + _ => break, + } + } + v +} + +/// A show: the last border's strips put back from the copy of the screen, the border at the newest place +/// drawn, and each changed strip refreshed on its own (one fast DU each, as a selection drag's outline). +fn widget_preview_paint(a: &mut App, old: Option, new: Rect, now: u32) { + let old_strips = old.map(|r| widget_preview_strips(a, r)).unwrap_or_default(); + let new_strips = widget_preview_strips(a, new); + if let Some(old) = old { + let has_base = ed_ref(a).widget_drag_view.base.is_some(); + if has_base { + let App { screen, ed, .. } = a; + let s = ed.as_ref().unwrap(); + let base_at = s.widget_drag_view.base_at; + if let Some(base) = s.widget_drag_view.base.as_ref() { + for r in &old_strips { + let srect = Rect { x: r.x - base_at.x, y: r.y - base_at.y, w: r.w, h: r.h }; + canvas_blit(screen, base, srect, r.x, r.y); + } + } + } else { + // No memory for the copy: the old border comes off by composing both places. + compose(a, rect_union(old, new)); + } + } + widget_preview_draw(a, new); + let mut v = old_strips; + v.extend(new_strips); + v.retain(|r| !rect_is_empty(*r)); + let v = widget_join_strips(v); + if live_on() { + let all = v.iter().fold(RECT_EMPTY, |u, &r| rect_union(u, r)); + if !rect_is_empty(all) { + live_push(&a.screen, all); + } + } + if !rect_is_empty(a.dirty) { + app_flush(a); + } + for r in v { + app_invalidate(a, r, RefreshMode::Fast); + app_flush(a); + } + let s = ed(a); + s.widget_drag_view.shown = Some(new); + s.widget_drag_view.shown_at = now; + s.widget_drag_view.samples_at_last_show = s.widget_drag_view.samples; +} + +fn widget_preview_begin(a: &mut App, now: u32, shown: Rect) { + let at = widget_drag_area(a); + let mut base = Canvas::default(); + let based = !rect_is_empty(at) && canvas_init(&mut base, at.w, at.h) == 0; + if based { + canvas_blit(&mut base, &a.screen, at, 0, 0); + } + let s = ed(a); + s.widget_drag_view.base = based.then_some(base); + s.widget_drag_view.base_at = at; + s.widget_drag_view.shown = None; + s.widget_drag_view.shown_at = now; + s.widget_drag_view.samples_at_last_show = s.widget_drag_view.samples; + widget_preview_paint(a, None, shown, now); +} + +/// editor_tick: a widget's newest place shown once the panel finished the last fast refresh, as a +/// selection's drag is (select.rs drag_tick): never one DU queued behind another. The frame stays where +/// it was, only its border moves; the lift composes the real frame once. +fn widget_tick(a: &mut App, now: u32) { + let s = ed_ref(a); + let Some(d) = s.widget_drag else { return }; + if s.owner != Owner::Widget + || !d.moved + || !matches!(d.part, WidgetPart::Title | WidgetPart::Resize) + || !s.open + || sheet_open(s) + || s.peek.active + || crate::library::library_settings_active(a) + || display_fast_busy() + { + return; + } + let Some(cur) = s.widgets.frames.get(d.index).map(|f| f.rect()) else { return }; + let v = &s.widget_drag_view; + if v.shown.is_none() { + widget_preview_begin(a, now, cur); + return; + } + if v.shown == Some(cur) { + return; + } + let by_samples = v.samples >= v.samples_at_last_show + WIDGET_SHOW_SAMPLES; + let by_time = now.wrapping_sub(v.shown_at) as i32 >= WIDGET_SHOW_MS as i32; + let by_pause = now.wrapping_sub(v.moved_at) as i32 >= WIDGET_PAUSE_MS as i32; + if by_samples || by_time || by_pause { + widget_preview_paint(a, v.shown, cur, now); + } +} + +/// editor_tick: an open package that asked for a later draw (a clock, a countdown) has its frame +/// refreshed then; a package that never asks is only drawn when something else repaints it. +fn widget_runtime_tick(a: &mut App) { + let s = ed_ref(a); + if !s.open || a.asleep || s.owner != Owner::None || s.peek.active || sheet_open(s) || crate::library::library_settings_active(a) { + return; + } + let now = std::time::Instant::now(); + let mut dirty: Option = None; + for f in &s.widgets.frames { + if f.runtime.as_ref().is_some_and(|r| r.redraw_due(now)) { + dirty = Some(dirty.map_or(f.rect(), |r| rect_union(r, f.rect()))); + } + } + if let Some(r) = dirty { + app_invalidate(a, r, RefreshMode::Ui); + } +} + +fn widget_down(a: &mut App, index: usize, part: WidgetPart, ev: &InEvent, pen: bool) { + let s = ed(a); + s.widgets.raise(index); + s.widget_drag_view = WidgetDragView::default(); + let Some((start, close_r, min_r)) = s.widgets.frames.get(index).map(|f| (f.rect(), f.close_rect(), f.minimize_rect())) else { return }; + s.widget_drag = Some(WidgetDrag { + index, + part, + down_x: ev.x.round_ties_even() as i32, + down_y: ev.y.round_ties_even() as i32, + start, + moved: false, + }); + s.owner = Owner::Widget; + s.owner_is_pen = pen; + if part == WidgetPart::Close || part == WidgetPart::Minimize { + let r = if part == WidgetPart::Close { close_r } else { min_r }; + app_press_feedback(a, r); + ed(a).widgets_pressed = Some(r); + } +} + +fn widget_pointer(a: &mut App, ph: i32, ev: &InEvent, pen: bool) { + let dpi = a.dpi; + let Some(mut d) = ed(a).widget_drag.take() else { ed(a).owner = Owner::None; return }; + if ph == 1 { + let dx = ev.x.round_ties_even() as i32 - d.down_x; + let dy = ev.y.round_ties_even() as i32 - d.down_y; + let slop = mm_to_px(TAP_SLOP_MM, dpi) as i32; + if dx.abs() > slop || dy.abs() > slop { + d.moved = true; + } + let area = widget_area(a); + let (old, new) = { + let Some(f) = ed(a).widgets.frames.get_mut(d.index) else { ed(a).owner = Owner::None; return }; + let old = f.rect(); + match d.part { + WidgetPart::Title => { + f.move_to(d.start.x + dx, d.start.y + dy, area); + } + WidgetPart::Resize => { + f.resize_to(d.start.w + dx, d.start.h + dy, area); + } + _ => {} + } + (old, f.rect()) + }; + if old != new { + // Only note the newest place: widget_tick draws a border there, a fast refresh at a time. + let v = &mut ed(a).widget_drag_view; + v.moved_at = now_ms(); + v.samples = v.samples.wrapping_add(1); + } + ed(a).widget_drag = Some(d); + return; + } + // The lift. A close or minimize only acts on a tap; a title tap restores a minimized frame. + let mut pressed = ed(a).widgets_pressed.take(); + let back = app_press_release(a, &mut pressed); + if !rect_is_empty(back) { + app_invalidate(a, back, RefreshMode::Ui); + } + ed(a).owner = Owner::None; + let cancelled = touch_cancelled(ev); + let area = widget_area(a); + let mut redraw = d.start; + if let Some(p) = ed(a).widget_drag_view.shown { + redraw = rect_union(redraw, p); + } + let mut save = false; + let mut close = false; + { + let Some(f) = ed(a).widgets.frames.get_mut(d.index) else { + ed(a).widget_drag_view = WidgetDragView::default(); + return; + }; + redraw = rect_union(redraw, f.rect()); + if !cancelled && !d.moved { + match d.part { + WidgetPart::Close => close = true, + WidgetPart::Minimize => { + f.layout.minimized = !f.layout.minimized; + redraw = rect_union(redraw, f.rect()); + save = true; + } + WidgetPart::Title if f.layout.minimized => { + f.layout.minimized = false; + f.clamp(area); + redraw = rect_union(redraw, f.rect()); + save = true; + } + WidgetPart::Body => { + let body = widget_body(f); + f.ensure_runtime(); + if let Some(rt) = f.runtime.as_mut() { + rt.tap(d.down_x - body.x, d.down_y - body.y); + redraw = rect_union(redraw, body); + } + } + _ => {} + } + } else if d.moved && (d.part == WidgetPart::Title || d.part == WidgetPart::Resize) { + save = true; + } + if cancelled && (d.part == WidgetPart::Title || d.part == WidgetPart::Resize) { + // A cancelled drag goes back where it started, as a panel drag does. + f.layout.x = d.start.x; + f.layout.y = d.start.y; + f.layout.w = d.start.w; + f.layout.h = d.start.h; + redraw = rect_union(redraw, f.rect()); + } + } + if close { + ed(a).widgets.close(d.index); + redraw = rect_union(redraw, widgets_union(ed(a))); + save = true; + } + ed(a).widget_drag = None; + ed(a).widget_drag_view = WidgetDragView::default(); + compose(a, redraw); + app_invalidate(a, redraw, RefreshMode::Ui); + if save { + ed(a).widgets.save(); + } + // (pen is the contact's input, not a choice here: a frame takes both) + let _ = pen; +} + // ---- the Find sheet ---- // Go to page or name: the sheet opens over the page with an empty field (the sheet's own refresh: a Ui of the @@ -8426,6 +9082,7 @@ fn panel_act(a: &mut App, h: Hit) { clear_page(a); } P_SHAPES => open_shape_menu(a), + P_WIDGETS => open_widgets(a), P_PAGES => pages_show(a), // The dedicated toolbar button creates a link; the upward swipe opens the Links bar. P_LINKS => { @@ -8495,6 +9152,9 @@ fn front_menu(s: &EditorState) -> i32 { if s.pv.open { return if (s.pv.unified&&!s.pv.picking)||s.pv.index_tab{SHORTCUT_INDEX_MAP}else{SHORTCUT_PAGES}; } + if s.widgets_open { + return SHORTCUT_CLOSE_MENU; + } if s.tools_open { return SHORTCUT_TOOL_PICKER; } @@ -8556,6 +9216,9 @@ fn close_front(a: &mut App, draw: bool) { return; } let mut r = if s.tools_open { rect_union(s.tools_rect, s.panel) } else { RECT_EMPTY }; + if s.widgets_open { + r = rect_union(r, s.widgets_rect); + } if s.qs.open { r = rect_union(r, s.qs.rect); } @@ -9533,6 +10196,7 @@ pub fn editor_free(a: &mut App) { } close_notebook(a); let s = ed(a); + s.widgets.save(); if let Some(cur) = s.cur.take() { stroke_free(cur); } @@ -9577,6 +10241,7 @@ fn close_sheets(a: &mut App) { s.mb.open = false; s.tools_open = false; s.pin_mode = false; + s.widgets_open = false; tplsheet_close(&mut s.ts); } @@ -9628,9 +10293,20 @@ pub fn editor_enter(a: &mut App) { if let Some(beside_page)=landscape_panel_slot(a,panel_left) {x=beside_page;} } let p = panel_rect_at(a, x, y); + let (aw, ah, top) = (a.w, a.h, status_reserved(a)); let s = ed(a); s.panel = p; s.tools_y = s.panel.y; + s.widgets_y = s.panel.y; + let area = Rect { x: 0, y: top, w: aw, h: ah - top }; + if s.open && !s.widgets.loaded { + // (a package whose files were removed by hand leaves the index before its frames are restored) + crate::widgetpkg::widget_package_repair(); + crate::widgetpkg::widget_catalog_invalidate(); + s.widgets.load(area); + } else if turned && s.widgets.reclamp(area) { + s.widgets.save(); + } s.owner = Owner::None; // The pen in use always has its button on the panel. One that has none (a pin a version without // pins dropped, or one taken out of settings.ini by hand) goes to the tool button. @@ -9988,7 +10664,7 @@ fn fs_can_arm(a: &App, in_links_bar: bool) -> bool { if gesturemap_shapes(&a.gestures).is_empty() && !gesturemap_has_onefinger(&a.gestures) { return false; } - if s.pv.open || s.tools_open || s.mb.open || s.dm.open || s.paper_open || s.ts.open || s.find.open || s.lt.open || s.card.open || s.qs.open + if s.pv.open || s.tools_open || s.widgets_open || s.mb.open || s.dm.open || s.paper_open || s.ts.open || s.find.open || s.lt.open || s.card.open || s.qs.open || s.lm.state != LmState::Off || s.pv.kb.open || s.find.kb.open || s.lm.kb.open || s.card.kb.open || s.add_kb.open { return false; @@ -10799,6 +11475,17 @@ fn editor_event_in(a: &mut App, ev: &InEvent) { pages_event(a, 0, ev); return; } + // The Widgets popup takes every contact while it is up: a row opens or raises, anything else + // closes it with nothing else done (the panel included). + if s.widgets_open { + s.owner = Owner::Widgets; + press_begin(&mut s.widgets_press, ev.x, ev.y, ev.t_ms); + if let Some(h) = hits_find(&s.widgets_hits, ev.x, ev.y).copied() { + app_press_feedback(a, h.r); + ed(a).widgets_pressed = Some(h.r); + } + return; + } if s.tools_open { s.owner = Owner::Tools; s.tools_slider = false; @@ -10861,6 +11548,8 @@ fn editor_event_in(a: &mut App, ev: &InEvent) { settle_now(a); } ui_pointer(a, 0, ev, false); + } else if let Some((index, part)) = s.widgets.hit(ev.x.round_ties_even() as i32, ev.y.round_ties_even() as i32) { + widget_down(a, index, part, ev, pen); } else if s.lm.state == LmState::Off && sel_takes(s, pen, ev.x, ev.y) { // Select mode: the bar, a drag of the selection, or the pen's lasso (never ink). sel_down(a, ev, pen); @@ -11152,6 +11841,8 @@ fn owner_pointer(a: &mut App, ph: i32, ev: &InEvent, pen: bool) { bar_stay(a); } } + Owner::Widgets => widgets_pointer(a, ph, ev, pen), + Owner::Widget => widget_pointer(a, ph, ev, pen), Owner::Tools => { press_move(&mut s.tools_press, ev.x, ev.y); let slider = hits_find(&s.tools_hits, s.tools_press.x0, s.tools_press.y0).filter(|h| shape_slider_id(h.id)).copied(); @@ -11511,6 +12202,10 @@ pub fn editor_tick(a: &mut App, now: u32) { // A pen held still in Select mode: a paste there (select.rs). if ed(a).open { sel_tick(a, now); + widget_runtime_tick(a); + if ed_ref(a).owner == Owner::Widget { + widget_tick(a, now); + } } // A press held on a chip of the Links bar (a finger or the pen): the long-press card for its entry (8.10). let s = ed(a); @@ -11841,6 +12536,77 @@ pub fn editor_probe(a: &mut App, key: &str, out: &mut String, cap: usize) -> i32 } return 0; } + // The widget windows: "N id id...", "widgets.open" 1 while the popup is up, and a frame's place or + // state ("widget.ID.rect" -> "x y w h", "widget.ID.state" -> normal or minimized). + if key == "widgets" { + let s = ed_ref(a); + let mut text = format!("{}", s.widgets.frames.len()); + for f in &s.widgets.frames { + text.push(' '); + text.push_str(f.def.id); + } + csnprintf!(out, cap, "%s", &text); + return 0; + } + if key == "widgets.open" { + csnprintf!(out, cap, "%d", ed_ref(a).widgets_open as i32); + return 0; + } + if let Some(n) = key.strip_prefix("widget.") { + let Some((id, what)) = n.rsplit_once('.') else { return -1 }; + let s = ed_ref(a); + let Some(i) = id.parse::().ok().filter(|&i| i < s.widgets.frames.len()).or_else(|| s.widgets.index_of(id)) else { return -1 }; + let f = &s.widgets.frames[i]; + match what { + "rect" => { + let r = f.rect(); + csnprintf!(out, cap, "%d %d %d %d", r.x, r.y, r.w, r.h); + } + "state" => { csnprintf!(out, cap, "%s", if f.layout.minimized { "minimized" } else { "normal" }); } + "status" => { csnprintf!(out, cap, "%s", f.runtime.as_ref().map_or("", WidgetRuntime::status)); } + "text" => { csnprintf!(out, cap, "%s", f.runtime.as_ref().map_or(String::new(), WidgetRuntime::text).as_str()); } + "hits" => { csnprintf!(out, cap, "%d", f.runtime.as_ref().map_or(0, |r| r.hit_count() as i32)); } + "error" => { csnprintf!(out, cap, "%s", f.error().unwrap_or("")); } + _ => return -1, + } + return 0; + } + // The widget packages: "N id version id version...", packages.open while the page is up, and an + // installed package's version (empty for one that is not installed). + if key == "packages" { + let ui = &a.pkg; + let mut text = format!("{}", ui.items.len()); + for it in &ui.items { + text.push_str(&format!(" {} {}", it.id, it.version)); + } + csnprintf!(out, cap, "%s", &text); + return 0; + } + if key == "packages.open" { + csnprintf!(out, cap, "%d", a.pkg.open as i32); + return 0; + } + if let Some(rest) = key.strip_prefix("package.") { + // package.ID.settings.KEY: a package setting's saved value (the default while there is no file). + if let Some((id, setting)) = rest.split_once(".settings.") { + let id = match id.parse::() { + Ok(i) => match a.pkg.items.get(i) { Some(x) => x.id.as_str(), None => return -1 }, + Err(_) => id, + }; + let Some(m) = crate::widgetpkg::widget_package_installed_manifest(id) else { return -1 }; + let Some(s) = m.settings.iter().find(|s| s.key == setting) else { return -1 }; + let values = crate::widgetpkg::widget_settings_load(id, &m.settings); + csnprintf!(out, cap, "%s", crate::widgetpkg::widget_setting_value(&values, &s.key, &s.default)); + return 0; + } + let ui = &a.pkg; + if let Some(it) = ui.items.iter().find(|x| x.id == rest) { + csnprintf!(out, cap, "%s", &it.version); + } else { + csnprintf!(out, cap, "%s", ""); + } + return 0; + } // panel_at.X.Y: the name of the panel's button at (X, Y), empty for none. A stale panel is settled // first, as a tap would (hence before s is borrowed). if let Some(xy) = key.strip_prefix("panel_at.") { @@ -14148,12 +14914,12 @@ mod tests { assert!(p.x >= 0 && p.x + p.w <= w && p.y >= 0 && p.y + p.h <= h && p.h + 2 * m <= h); assert_eq!(p.h, panel_height(g_fit(), pins as i32)); // The buttons from the top: grip, collapse, the tool button, the pins, the eraser, (undo, - // redo, clear and previous greyed out), the page chip, next, links, paper, display, pen feel, + // redo, clear and previous greyed out), the page chip, next, links, widgets, paper, display, pen feel, // the library, whose gap under it ends the panel but for its last 6 px. let ids: Vec = s.hits.h.iter().map(|h| h.id).collect(); let mut want = vec![P_GRIP, P_COLLAPSE, P_TOOLPICK]; want.extend(std::iter::repeat_n(P_TOOL, pins)); - want.extend([P_TOOL, P_SHAPES, P_PENSET, P_PAGES, P_NEXT, P_LINKS, P_PAPER, P_DISPLAY, P_SETTINGS, P_LIBRARY]); + want.extend([P_TOOL, P_SHAPES, P_PENSET, P_PAGES, P_NEXT, P_LINKS, P_WIDGETS, P_PAPER, P_DISPLAY, P_SETTINGS, P_LIBRARY]); assert_eq!(ids, want); let last = s.hits.h.last().unwrap().r; assert_eq!(last.y + last.h + gap(), p.y + p.h - ui_px(6.0)); diff --git a/rust/src/editor/select.rs b/rust/src/editor/select.rs index 31aec524..e11b5f76 100644 --- a/rust/src/editor/select.rs +++ b/rust/src/editor/select.rs @@ -434,7 +434,7 @@ fn draw_resize_handles(a: &mut App, off: (i32, i32), r: Rect) { /// The four strips canvas_dither_rect(r, thick, halo) paints, apart: the top and the bottom the full width, /// the left and the right between them (linkcard_strips' shape). Together exactly what it paints. -fn dither_strips(r: Rect, thick: i32, halo: i32) -> [Rect; 4] { +pub(super) fn dither_strips(r: Rect, thick: i32, halo: i32) -> [Rect; 4] { let t = thick.min(r.w).min(r.h); let o = rect_inflate(r, halo); let s = t + 2 * halo; diff --git a/rust/src/lib.rs b/rust/src/lib.rs index a6e7cbd8..1a7e3e33 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -133,6 +133,10 @@ pub mod share; pub mod status; // not a port: the clock and battery corner, Rust only (2.0.0-beta.5) pub mod ui; pub mod upload; // Send a PDF from the Share page: the request's rules, the name shown, the temporary file (2.2, #175) +pub mod widgets; // the editor's widget windows and widgets.ini (2.2, issue #200) +pub mod widgetwasm; // the generic WebAssembly widget host (2.2, issue #200) +pub mod widgetpkg; // widget packages: manifests, platforms, installs and the packages index (2.2, #200) +pub mod widgetpkgui; // the Packages page: installed widgets, install from a repository (2.2, #200) // ---- wave 4: the platform and the main loop ---- pub mod display; // display.h: the types; the functions are the build's platform's @@ -235,6 +239,10 @@ pub mod prelude { pub use crate::ui::*; pub use crate::update::*; pub use crate::wifi::*; + pub use crate::widgets::*; + pub use crate::widgetwasm::*; + pub use crate::widgetpkg::*; + pub use crate::widgetpkgui::*; pub use crate::util::*; pub use crate::{buf_printf, cformat, csnprintf, qlog}; } diff --git a/rust/src/library.rs b/rust/src/library.rs index 5d0630b4..2fca827e 100644 --- a/rust/src/library.rs +++ b/rust/src/library.rs @@ -236,6 +236,8 @@ const H_FMORE_HOME: i32 = 210; const H_SET_DARKER: i32 = 250; const H_DARKER_PICK: i32 = 251; const H_DARKER_BACK: i32 = 252; +// Settings > Packages > Widgets (2.2, issue #200): the widget package manager (widgetpkgui.rs). +const H_SET_PACKAGES: i32 = 260; // Settings > Wi-Fi's top controls and lists: Nearby/Saved (arg: 0 or 1), Rescan, Other... (a hidden // network), a saved row's trash (arg: a row), and a network a scan found (arg: an index of // WifiSheet.near). The saved rows keep H_WIFI_NET. @@ -312,7 +314,7 @@ pub struct LibraryState { settings_painting: bool, settings_editor_fit: bool, /// Settings' page: the category whose settings show (0 General, 1 Display, 2 Sleep & Clock, - /// 3 Pen, 4 Controls, 5 System; H_SET_CAT), and the page each of its lists is on (ui_row_page): + /// 3 Pen, 4 Controls, 5 System, 6 Packages; H_SET_CAT), and the page each of its lists is on (ui_row_page): /// the categories, the open category's rows, and the submenu's rows (whose title keys the last, /// so another submenu starts at its first page). settings_cat: i32, @@ -4825,6 +4827,7 @@ fn setting_hit(id: settingsmenu::SettingId) -> i32 { Updates => H_UPDATES, AboutDevice => H_SET_DEVICE, DarkerLines => H_SET_DARKER, + WidgetPackages => H_SET_PACKAGES, } } @@ -6237,6 +6240,11 @@ fn toast_floor(a: &App) -> i32 { } fn redraw(a: &mut App, m: RefreshMode) { + if a.pkg.open { + crate::widgetpkgui::packages_ui_draw(a); + app_invalidate_all(a, m); + return; + } if files_shown(a) { let mut b = std::mem::take(&mut lib(a).files); b.draw(a); @@ -7402,6 +7410,7 @@ fn act(a: &mut App, h: &Hit) { settings_save(&a.settings); redraw(a, RefreshMode::Full); } + H_SET_PACKAGES => crate::widgetpkgui::packages_ui_open(a), H_SET_DISPLAY => { let mut dm = std::mem::take(&mut lib(a).dm); dispmenu_open(&mut dm, a); @@ -8799,6 +8808,13 @@ pub fn library_event(a: &mut App, ev: &InEvent) { } fn library_event_in(a: &mut App, ev: &InEvent) { + if a.pkg.open { + let ph = app_pointer_phase(ev); + if ph >= 0 { + crate::widgetpkgui::packages_ui_pointer(a, ph, ev); + } + return; + } if library_record_active(a) && record_event(a, ev) { return; } @@ -8945,6 +8961,10 @@ fn library_event_in(a: &mut App, ev: &InEvent) { } pub fn library_tick(a: &mut App, now: u32) { + if a.pkg.open { + crate::widgetpkgui::packages_ui_tick(a, now); + return; + } crate::userfonts::userfonts_tick(a, now); // (a font check that ended with no verdict is queued again after its wait) if files_shown(a) { // (not under Exit Grimoire?, asked at a home inside Files: a draw of Files' own would paint over it) @@ -9547,6 +9567,7 @@ pub fn library_probe(a: &mut App, key: &str, out: &mut String, cap: usize) -> i3 H_SET_DARKER => "darker-lines", H_DARKER_PICK => "darker-lines.", H_DARKER_BACK => "darker-lines.back", H_SET_PINCH => "pinch", H_SET_MIRROR => "mirror", H_SET_DEVICE => "about-device", H_DEVICE_BACK => "about-device.back", + H_SET_PACKAGES => "settings.packages", _ => "", }); if hit.id == H_LANG_PICK { @@ -11714,7 +11735,7 @@ mod tests { library_init(&mut a); crate::pdfimport::set_darker(crate::pdfwork::Gamma::Off); lib(&mut a).modal = Modal::Settings; - lib(&mut a).settings_cat = 5; + lib(&mut a).settings_cat = 6; hits_clear(&mut lib(&mut a).hits); draw_settings(&mut a); assert!(a.lib.as_ref().unwrap().hits.h.iter().any(|h| h.id == H_SET_DARKER), "the System row"); @@ -11767,7 +11788,7 @@ mod tests { assert_eq!(canvas_init(&mut a.screen, a.w, a.h), 0); library_init(&mut a); lib(&mut a).modal = Modal::Settings; - lib(&mut a).settings_cat = 5; + lib(&mut a).settings_cat = 6; hits_clear(&mut lib(&mut a).hits); draw_settings(&mut a); assert!( @@ -12195,6 +12216,10 @@ esac /// Resolve a runner tap through the same hit names used by ui_at probes. pub fn library_control_point(a:&mut App,name:&str)->Option<(f32,f32)> { + // Settings > Packages > Widgets: packages.install, packages.row.ID, packages.back, ... + if let Some(n)=name.strip_prefix("packages.") { + return (a.pkg.open).then(||crate::widgetpkgui::packages_ui_control_point(&a.pkg,n)).flatten(); + } if name.starts_with("music.") {return musicbuild_control_point(&a.lib.as_deref()?.mb,name);} if name.starts_with("ui_has.") {return None;} // The file picker: files.back, files.row.N, files.more.N, files.item.NAME, files.prev, files.next, files.card.* @@ -12261,6 +12286,9 @@ fn turn(a: &mut App, next: bool) { /// The Library's open on-screen keyboard (a name being typed), None for none: where a hardware key's /// input goes (app_type_text). pub fn library_keyboard_area(a: &App) -> Option { + if a.pkg.open && a.pkg.kb.open && !rect_is_empty(a.pkg.kb.area) { + return Some(a.pkg.kb.area); + } let s = a.lib.as_deref()?; if s.files.open { // (Files' rename keyboard, 2.2: Files takes every contact while it is up) @@ -12275,3 +12303,8 @@ pub fn library_settings_active(a:&App)->bool { } pub fn library_settings_redraw(a:&mut App) {redraw(a,RefreshMode::Ui);} pub fn library_settings_back(a:&mut App) {close_modal(a);} +/// The Packages page draws itself whole (widgetpkgui.rs); its callers redraw through here so it +/// replaces Settings while it is open and Settings comes back when it closes. +pub(crate) fn packages_redraw(a:&mut App) {redraw(a,RefreshMode::Ui);} +/// The Packages page's X: the whole of Settings closes, as every Settings submenu's X does. +pub(crate) fn packages_closed(a:&mut App) {close_settings(a,RefreshMode::Ui);} diff --git a/rust/src/panel.rs b/rust/src/panel.rs index 91b14688..34062098 100644 --- a/rust/src/panel.rs +++ b/rust/src/panel.rs @@ -1,5 +1,5 @@ //! panel.h: the editor's floating panel's measures, as pure logic (unit-tested on the host by -//! tests/test_panel.c): its 14 buttons and one more for each pen pinned under the tool button, and +//! tests/test_panel.c): its 15 buttons and one more for each pen pinned under the tool button, and //! how they shrink to fit a screen too short for them (the Kindle turned sideways, with pens //! pinned). The panel is sized to leave 12 px free above and below it, though it may be dragged up //! to the screen's very edges. Then the pens on it, which next and previous tool go through, and the @@ -7,8 +7,8 @@ use crate::prelude::*; -/// Tool, eraser, undo, redo, clear, previous, next, links, paper, display, pen feel, settings, library. -pub const PANEL_BUTTONS: i32 = 14; +/// Tool, eraser, undo, redo, clear, previous, next, links, widgets, paper, display, pen feel, settings, library. +pub const PANEL_BUTTONS: i32 = 15; /// px at 300 dpi, the room panel_fit leaves above and below the panel pub const PANEL_MARGIN: i32 = 12; diff --git a/rust/src/settingsmenu.rs b/rust/src/settingsmenu.rs index b8bdc5e1..86ca89df 100644 --- a/rust/src/settingsmenu.rs +++ b/rust/src/settingsmenu.rs @@ -116,6 +116,7 @@ pub enum SettingId { Updates, AboutDevice, DarkerLines, + WidgetPackages, } /// The state a check row shows, or None for a row drawn as text. @@ -228,8 +229,8 @@ pub const DISPLAY_NO_LIGHT: &str = n_("Display"); // (language, updates, Wi-Fi), Display's (front light, theme, dark mode, font, rotation, zoom), Sleep & // Clock's (sleep screen, timer, clock), the Pen's (tool settings, its button, the eraser, calibration), // Controls' -// (shortcuts, pairing, gestures) and System's (KOReader, USB PDF mirroring, about the device, darker lines in -// imported PDFs). +// (shortcuts, pairing, gestures), Packages' (Widgets), and System's (KOReader, USB PDF mirroring, about +// the device, darker lines in imported PDFs). pub static CATEGORIES: &[Category] = &[ Category::new(n_("General"), IconKind::Gear, &[ Item::value(IconKind::Language, Label::Language, SettingId::Language), @@ -269,6 +270,10 @@ pub static CATEGORIES: &[Category] = &[ Item::open(IconKind::Link, n_("Pair"), SettingId::Pair).when(Show::Pairing), Item::open(IconKind::Gestures, n_("Gestures"), SettingId::Gestures), ]), + Category::new(n_("Packages"), IconKind::Package, &[ + // TRANSLATORS: Settings' Packages category row: the widget package manager. + Item::open(IconKind::Download, n_("Widgets"), SettingId::WidgetPackages), + ]), Category::new(n_("System"), IconKind::Grid, &[ Item::open(IconKind::Notebook, n_("KOReader"), SettingId::KOReader).when(Show::KOReader), Item::value_toggle(IconKind::Download, Label::Mirror, SettingId::Mirror, Check::MirrorPdf), @@ -324,30 +329,31 @@ mod tests { #[test] fn the_schema_keeps_the_settings_page_as_it_is() { - assert_eq!(CATEGORIES.len(), 6); + assert_eq!(CATEGORIES.len(), 7); assert_eq!( CATEGORIES.iter().map(|c| c.title).collect::>(), - vec!["General", "Display", "Sleep & Clock", "Pen", "Controls", "System"] + vec!["General", "Display", "Sleep & Clock", "Pen", "Controls", "Packages", "System"] ); assert_eq!(ids(0), vec![SettingId::Language, SettingId::Updates, SettingId::Wifi]); assert_eq!(ids(1), vec![SettingId::Display, SettingId::Theme, SettingId::DarkMode, SettingId::Font, SettingId::Rotate, SettingId::Pinch]); assert_eq!(ids(2), vec![SettingId::SleepSettings, SettingId::ClockSettings]); assert_eq!(ids(3), vec![SettingId::PenFeel, SettingId::SideButton, SettingId::EraserMode, SettingId::Calibration]); assert_eq!(ids(4), vec![SettingId::Shortcuts, SettingId::Pair, SettingId::Gestures]); - assert_eq!(ids(5), vec![SettingId::KOReader, SettingId::Mirror, SettingId::AboutDevice, SettingId::DarkerLines]); - assert_eq!(CATEGORIES.iter().map(|c| c.items.len()).sum::(), 22); + assert_eq!(ids(5), vec![SettingId::WidgetPackages]); + assert_eq!(ids(6), vec![SettingId::KOReader, SettingId::Mirror, SettingId::AboutDevice, SettingId::DarkerLines]); + assert_eq!(CATEGORIES.iter().map(|c| c.items.len()).sum::(), 23); assert_eq!(text(2, 0), "Sleep settings"); assert_eq!(text(2, 1), "Clock settings"); assert_eq!(text(0, 2), "Wi-Fi"); - assert_eq!(text(5, 0), "KOReader"); - assert_eq!(text(5, 2), "About: device and storage"); + assert_eq!(text(6, 0), "KOReader"); + assert_eq!(text(6, 2), "About: device and storage"); assert!(matches!(CATEGORIES[1].items[0].label, Label::Display)); assert!(matches!(CATEGORIES[0].items[1].show, Show::Updates)); assert!(matches!(CATEGORIES[0].items[2].show, Show::Wifi)); assert!(matches!(CATEGORIES[3].items[3].show, Show::Calibration)); assert!(matches!(CATEGORIES[4].items[1].show, Show::Pairing)); - assert!(matches!(CATEGORIES[5].items[0].show, Show::KOReader)); + assert!(matches!(CATEGORIES[6].items[0].show, Show::KOReader)); assert_eq!(text(1, 2), "Dark mode"); assert_eq!(text(1, 4), "Rotation (portrait and landscape)"); assert_eq!(text(1, 5), "Pinch with two fingers to zoom"); @@ -368,10 +374,10 @@ mod tests { assert!(matches!(CATEGORIES[3].items[1].label, Label::SideButton)); assert!(matches!(CATEGORIES[3].items[2].label, Label::Eraser)); assert!(matches!(CATEGORIES[0].items[0].label, Label::Language)); - assert!(matches!(CATEGORIES[5].items[1].label, Label::Mirror)); - assert!(matches!(CATEGORIES[5].items[1].check, Check::MirrorPdf)); - assert!(matches!(CATEGORIES[5].items[3].label, Label::DarkerLines)); - assert!(matches!(CATEGORIES[5].items[3].show, Show::Always)); + assert!(matches!(CATEGORIES[6].items[1].label, Label::Mirror)); + assert!(matches!(CATEGORIES[6].items[1].check, Check::MirrorPdf)); + assert!(matches!(CATEGORIES[6].items[3].label, Label::DarkerLines)); + assert!(matches!(CATEGORIES[6].items[3].show, Show::Always)); assert_eq!(DARKER_NAMES, ["Off", "Medium", "Strong"]); assert_eq!((SIDE_BUTTON_NAMES.len(), SIDE_BUTTON_LABELS.len()), (4, 4)); assert_eq!((ERASER_NAMES.len(), ERASER_LABELS.len()), (2, 2)); diff --git a/rust/src/ui.rs b/rust/src/ui.rs index 5c1d6165..0623dde8 100644 --- a/rust/src/ui.rs +++ b/rust/src/ui.rs @@ -102,10 +102,14 @@ pub enum IconKind { Sort = 68, FolderOpen = 69, Home = 70, + /// A calculator icon a widget package may name (2.2, Rust only) + Calculator = 71, + /// A widget package, and Settings' Packages category (2.2, Rust only) + Package = 72, } impl IconKind { /// ICON_COUNT - pub const COUNT: usize = 71; + pub const COUNT: usize = 73; } #[derive(Clone, Copy, Debug, Default)] @@ -330,6 +334,8 @@ const K_ICON_CP: [u32; IconKind::COUNT] = { k[IconKind::Sort as usize] = 0xF04BA; // md-sort k[IconKind::FolderOpen as usize] = 0xF0770; // md-folder_open k[IconKind::Home as usize] = 0xF02DC; // md-home + k[IconKind::Calculator as usize] = 0xF00EC; // md-calculator + k[IconKind::Package as usize] = 0xF03D7; // md-package_variant_closed k }; diff --git a/rust/src/widgetpkg.rs b/rust/src/widgetpkg.rs new file mode 100644 index 00000000..c59e30f0 --- /dev/null +++ b/rust/src/widgetpkg.rs @@ -0,0 +1,1834 @@ +//! Widget packages (issue #200): manifests, platform checks, installation and the installed index. +//! +//! A package is a `package.yaml` and an artifact under `packages/widgets//`, with the list of +//! installed packages in `packages/index.json`. The files are the source of truth; a manifest is +//! validated before anything is written and an install is staged and swapped in whole. +//! +//! This module is the package manager's store and its pure parts. Fetching a repository and drawing +//! the Settings → Packages → Widgets page live in widgetpkgui.rs; the WASM host is a separate runtime. + +use crate::prelude::*; +use crate::sha256::sha256_of; +use std::cell::RefCell; + +pub const WIDGET_PKG_INDEX: &str = "packages/index.json"; +pub const WIDGET_PKG_DIR: &str = "packages/widgets"; +pub const WIDGET_PKG_MANIFEST_MAX: usize = 256 * 1024; +pub const WIDGET_PKG_ARTIFACT_MAX: u64 = 32 * 1024 * 1024; +pub const WIDGET_PKG_COUNT_MAX: usize = 64; +pub const WIDGET_PKG_URL_MAX: usize = 1024; +pub const WIDGET_SETTINGS_MAX: usize = 32; +const WIDGET_SETTINGS_KEY_MAX: usize = 64; +const WIDGET_SETTINGS_VALUE_MAX: usize = 64; +const WIDGET_SETTINGS_CHOICES_MAX: usize = 16; +const WIDGET_SETTINGS_FILE_MAX: usize = 64 * 1024; + +// ---- the platform registry ---- + +/// Every platform a manifest may name. `all` is the sentinel: it matches every device Grimoire supports +/// and is never a device's own id. +pub const WIDGET_PLATFORMS: [(&str, &str); 3] = [ + ("all", "All supported devices"), + ("kindle-scribe-2022", "Kindle Scribe (2022)"), + ("kindle-scribe-2024", "Kindle Scribe (2024)"), +]; + +pub fn widget_platform_known(id: &str) -> bool { + WIDGET_PLATFORMS.iter().any(|(k, _)| *k == id) +} + +pub fn widget_platform_label(id: &str) -> &'static str { + WIDGET_PLATFORMS.iter().find(|(k, _)| *k == id).map_or("", |(_, v)| *v) +} + +/// The current device's platform id, or `unknown` where Grimoire cannot tell (only `all` matches then). +/// `GRIMOIRE_WIDGET_PLATFORM` is the simulator's and a test's way to stand in for a model. +pub fn widget_current_platform() -> &'static str { + if let Ok(v) = std::env::var("GRIMOIRE_WIDGET_PLATFORM") { + let v = v.trim(); + if widget_platform_known(v) && v != "all" { + return match v { + "kindle-scribe-2022" => "kindle-scribe-2022", + "kindle-scribe-2024" => "kindle-scribe-2024", + _ => "unknown", + }; + } + return "unknown"; + } + if cfg!(feature = "kindle") { + let mut model = String::new(); + if let Ok(raw) = std::fs::read("/proc/device-tree/model") { + model = raw.iter().take_while(|&&c| c != 0).map(|&c| c as char).collect(); + } + let lower = model.to_lowercase(); + if lower.contains("scribe") { + if lower.contains("2024") { + return "kindle-scribe-2024"; + } + return "kindle-scribe-2022"; + } + } + "unknown" +} + +pub fn widget_platform_supported(platforms: &[String]) -> bool { + if platforms.iter().any(|p| p == "all") { + return true; + } + let current = widget_current_platform(); + current != "unknown" && platforms.iter().any(|p| p == current) +} + +// ---- a small YAML reader: the manifest's subset ---- +// +// The manifest uses mappings, block and inline sequences, and plain or quoted scalars. A full YAML +// implementation would be more than the format needs; this reader refuses anything else instead of +// guessing, so a manifest that parses is one whose fields were read as written. + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Yaml { + Scalar(String), + List(Vec), + Map(Vec<(String, Yaml)>), +} + +impl Yaml { + fn get(&self, key: &str) -> Option<&Yaml> { + match self { + Yaml::Map(kv) => kv.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + fn str(&self) -> Option<&str> { + match self { + Yaml::Scalar(s) => Some(s), + _ => None, + } + } + fn list(&self) -> Option<&[Yaml]> { + match self { + Yaml::List(v) => Some(v), + _ => None, + } + } +} + +#[derive(Clone, Debug)] +struct YLine { + indent: usize, + text: String, +} + +fn yaml_lines(text: &str) -> Result, String> { + let mut out = Vec::new(); + for (n, raw) in text.lines().enumerate() { + let raw = raw.trim_end_matches('\r'); + let mut s = raw; + if n == 0 { + s = s.trim_start_matches('\u{feff}'); + } + let mut indent = 0usize; + for c in s.chars() { + match c { + ' ' => indent += 1, + '\t' => return Err("a tab is used for indentation".into()), + _ => break, + } + } + let body = &s[indent..]; + if body.trim().is_empty() || body.starts_with('#') || body == "---" || body == "..." { + continue; + } + let text = strip_yaml_comment(body); + if text.trim().is_empty() { + continue; + } + out.push(YLine { indent, text: text.trim_end().to_string() }); + } + Ok(out) +} + +fn strip_yaml_comment(s: &str) -> &str { + let mut quote = 0u8; + let mut escaped = false; + for (i, b) in s.bytes().enumerate() { + if escaped { + escaped = false; + continue; + } + match quote { + b'"' if b == b'\\' => escaped = true, + b'"' if b == b'"' => quote = 0, + b'\'' if b == b'\'' => quote = 0, + 0 if b == b'"' || b == b'\'' => quote = b, + 0 if b == b'#' && (i == 0 || s.as_bytes()[i - 1].is_ascii_whitespace()) => return &s[..i], + _ => {} + } + } + s +} + +fn yaml_scalar(s: &str) -> Result { + let t = s.trim(); + if t.is_empty() { + return Ok(Yaml::Scalar(String::new())); + } + if t.starts_with('[') { + if !t.ends_with(']') { + return Err("an unclosed list".into()); + } + let inner = &t[1..t.len() - 1]; + let mut v = Vec::new(); + for part in split_inline(inner)? { + if !part.trim().is_empty() { + v.push(yaml_scalar(part)?); + } + } + return Ok(Yaml::List(v)); + } + if t.starts_with('"') { + if !t.ends_with('"') || t.len() < 2 { + return Err("an unclosed quoted value".into()); + } + let mut out = String::new(); + let mut it = t[1..t.len() - 1].chars(); + while let Some(c) = it.next() { + if c != '\\' { + out.push(c); + continue; + } + let Some(e) = it.next() else { return Err("a quoted value ends in a backslash".into()) }; + out.push(match e { + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + '"' => '"', + '\\' => '\\', + _ => return Err(format!("an unknown escape \\{e}")), + }); + } + return Ok(Yaml::Scalar(out)); + } + if t.starts_with('\'') { + if !t.ends_with('\'') || t.len() < 2 { + return Err("an unclosed quoted value".into()); + } + return Ok(Yaml::Scalar(t[1..t.len() - 1].replace("''", "'"))); + } + Ok(Yaml::Scalar(t.to_string())) +} + +fn split_inline(s: &str) -> Result, String> { + let mut v = Vec::new(); + let mut start = 0usize; + let mut quote = 0u8; + let mut depth = 0i32; + let bytes = s.as_bytes(); + let mut i = 0usize; + while i < bytes.len() { + let b = bytes[i]; + if quote != 0 { + if b == quote { + if quote == b'\'' && i + 1 < bytes.len() && bytes[i + 1] == b'\'' { + i += 2; + continue; + } + quote = 0; + } else if b == b'\\' && quote == b'"' { + i += 1; + } + i += 1; + continue; + } + match b { + b'"' | b'\'' => quote = b, + b'[' => depth += 1, + b']' => depth -= 1, + b',' if depth == 0 => { + v.push(&s[start..i]); + start = i + 1; + } + _ => {} + } + i += 1; + } + if quote != 0 { + return Err("an unclosed quote".into()); + } + if depth != 0 { + return Err("an unclosed list".into()); + } + v.push(&s[start..]); + Ok(v) +} + +fn yaml_parse_block(lines: &[YLine], at: &mut usize, indent: usize) -> Result { + if *at >= lines.len() || lines[*at].indent < indent { + return Ok(Yaml::Map(Vec::new())); + } + let seq = lines[*at].text == "-" || lines[*at].text.starts_with("- "); + if seq { + let mut v = Vec::new(); + while *at < lines.len() && lines[*at].indent == indent && (lines[*at].text == "-" || lines[*at].text.starts_with("- ")) { + let rest = lines[*at].text[1..].trim_start().to_string(); + *at += 1; + if rest.is_empty() { + let child = if *at < lines.len() && lines[*at].indent > indent { + yaml_parse_block(lines, at, lines[*at].indent)? + } else { + Yaml::Scalar(String::new()) + }; + v.push(child); + continue; + } + if let Some((key, value)) = yaml_split_key(&rest) { + let mut kv = Vec::new(); + if value.is_empty() { + let child = if *at < lines.len() && lines[*at].indent > indent { + yaml_parse_block(lines, at, lines[*at].indent)? + } else { + Yaml::Scalar(String::new()) + }; + kv.push((key.to_string(), child)); + } else { + kv.push((key.to_string(), yaml_scalar(value)?)); + } + // Further keys of the same sequence item are indented under it. + while *at < lines.len() && lines[*at].indent > indent { + let child_indent = lines[*at].indent; + let Yaml::Map(more) = yaml_parse_block(lines, at, child_indent)? else { + return Err("a sequence item mixes a value with a mapping".into()); + }; + kv.extend(more); + } + v.push(Yaml::Map(kv)); + } else { + v.push(yaml_scalar(&rest)?); + } + } + return Ok(Yaml::List(v)); + } + let mut kv = Vec::new(); + while *at < lines.len() && lines[*at].indent == indent && !(lines[*at].text == "-" || lines[*at].text.starts_with("- ")) { + let line = lines[*at].text.clone(); + let Some((key, value)) = yaml_split_key(&line) else { + return Err(format!("`{line}` is not a key and a value")); + }; + *at += 1; + if value.is_empty() { + let child = if *at < lines.len() && lines[*at].indent > indent { + yaml_parse_block(lines, at, lines[*at].indent)? + } else { + Yaml::Scalar(String::new()) + }; + kv.push((key.to_string(), child)); + } else { + kv.push((key.to_string(), yaml_scalar(value)?)); + } + } + Ok(Yaml::Map(kv)) +} + +fn yaml_split_key(s: &str) -> Option<(&str, &str)> { + let mut quote = 0u8; + let bytes = s.as_bytes(); + let mut i = 0usize; + while i < bytes.len() { + let b = bytes[i]; + if quote != 0 { + if b == quote { + quote = 0; + } else if b == b'\\' && quote == b'"' { + i += 1; + } + i += 1; + continue; + } + if b == b'"' || b == b'\'' { + quote = b; + } else if b == b':' && (i + 1 == bytes.len() || bytes[i + 1].is_ascii_whitespace()) { + let key = s[..i].trim(); + if key.is_empty() { + return None; + } + return Some((key.trim_matches('"').trim_matches('\''), s[i + 1..].trim_start())); + } + i += 1; + } + None +} + +pub fn yaml_parse(text: &str) -> Result { + let lines = yaml_lines(text)?; + let mut at = 0usize; + if lines.is_empty() { + return Ok(Yaml::Map(Vec::new())); + } + let indent = lines[0].indent; + let v = yaml_parse_block(&lines, &mut at, indent)?; + if at != lines.len() { + return Err(format!("`{}` is indented under nothing", lines[at].text)); + } + Ok(v) +} + +// ---- manifests ---- + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WidgetSizeMode { + #[default] + Fixed, + Resizable, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WidgetSize { + pub mode: WidgetSizeMode, + pub default: (i32, i32), + pub min: (i32, i32), + pub max: (i32, i32), +} + +impl Default for WidgetSize { + fn default() -> Self { + WidgetSize { mode: WidgetSizeMode::Fixed, default: (220, 160), min: (220, 160), max: (220, 160) } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WidgetArtifact { + pub path: String, + pub sha256: String, + pub size: u64, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WidgetRelease { + pub version: String, + pub url: String, + pub sha256: String, +} + +/// How a package setting is changed in Settings → Packages → Widgets. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WidgetSettingKind { + /// an on/off switch, its values `true` and `false` + #[default] + Toggle, + /// one of `choices`, changed by tapping the row + Choice, +} + +/// One setting a package declares in its manifest. The host draws it, so a package needs no UI of +/// its own for a switch or a small list of choices. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WidgetSetting { + pub key: String, + pub label: String, + pub kind: WidgetSettingKind, + pub default: String, + pub choices: Vec, + /// optional icon name, as `spec.icon`; empty means the gear + pub icon: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WidgetSpec { + pub runtime: String, + pub entry: String, + pub icon: String, + pub minimizable: bool, + pub size: WidgetSize, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WidgetPackage { + pub name: String, + pub id: String, + pub type_: String, + pub version: String, + pub author: String, + pub description: String, + pub license: String, + pub license_url: String, + pub min_grimoire_version: String, + pub platforms: Vec, + pub repository: String, + pub artifact: WidgetArtifact, + pub releases: Vec, + pub capabilities: Vec, + pub settings: Vec, + pub spec: WidgetSpec, +} + +fn ystr(v: &Yaml, key: &str) -> String { + v.get(key).and_then(Yaml::str).unwrap_or("").trim().to_string() +} + +fn ybool(v: &Yaml, key: &str, default: bool) -> bool { + match v.get(key).and_then(Yaml::str) { + Some("true") => true, + Some("false") => false, + _ => default, + } +} + +fn ylist(v: &Yaml, key: &str) -> Result, String> { + let Some(x) = v.get(key) else { return Ok(Vec::new()) }; + match x { + Yaml::Scalar(s) if s.is_empty() => Ok(Vec::new()), + Yaml::List(items) => items + .iter() + .map(|i| i.str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)) + .collect::>>() + .ok_or_else(|| format!("`{key}` holds a value that is not a string")), + _ => Err(format!("`{key}` is not a list")), + } +} + +fn ypair(v: Option<&Yaml>, key: &str, out: &mut (i32, i32)) -> Result<(), String> { + let Some(v) = v else { return Ok(()) }; + let items = v.list().ok_or_else(|| format!("`{key}` is not a [width, height] list"))?; + if items.len() != 2 { + return Err(format!("`{key}` needs two numbers")); + } + let mut p = [0i32; 2]; + for (i, it) in items.iter().enumerate() { + let s = it.str().ok_or_else(|| format!("`{key}` holds a value that is not a number"))?; + p[i] = s.parse::().map_err(|_| format!("`{key}` holds `{s}`, not a number"))?; + if p[i] <= 0 { + return Err(format!("`{key}` must be positive")); + } + } + *out = (p[0], p[1]); + Ok(()) +} + +fn ysize(v: Option<&Yaml>) -> Result { + let mut size = WidgetSize::default(); + let Some(v) = v else { return Ok(size) }; + if matches!(v, Yaml::Scalar(s) if s.is_empty()) { + return Ok(size); + } + let mode = v.get("mode").and_then(Yaml::str).unwrap_or("fixed"); + size.mode = match mode { + "fixed" => WidgetSizeMode::Fixed, + "resizable" => WidgetSizeMode::Resizable, + _ => return Err(format!("`spec.size.mode` is `{mode}`, not resizable or fixed")), + }; + ypair(v.get("default"), "spec.size.default", &mut size.default)?; + ypair(v.get("min"), "spec.size.min", &mut size.min)?; + ypair(v.get("max"), "spec.size.max", &mut size.max)?; + if size.mode == WidgetSizeMode::Fixed { + size.min = size.default; + size.max = size.default; + } + Ok(size) +} + +fn setting_key_ok(key: &str) -> bool { + !key.is_empty() + && key.len() <= WIDGET_SETTINGS_KEY_MAX + && key.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-' || b == b'_') + && key.as_bytes()[0] != b'.' + && key.as_bytes()[key.len() - 1] != b'.' + && !key.contains("..") +} + +fn setting_text_ok(s: &str, max: usize) -> bool { + !s.is_empty() && s.len() <= max && !s.chars().any(char::is_control) +} + +fn setting_value_ok(s: &WidgetSetting, value: &str) -> bool { + match s.kind { + WidgetSettingKind::Toggle => value == "true" || value == "false", + WidgetSettingKind::Choice => s.choices.iter().any(|c| c == value), + } +} + +fn ysettings(v: &Yaml) -> Result, String> { + let Some(x) = v.get("settings") else { return Ok(Vec::new()) }; + if matches!(x, Yaml::Scalar(s) if s.is_empty()) { + return Ok(Vec::new()); + } + let items = x.list().ok_or("`settings` is not a list")?; + if items.len() > WIDGET_SETTINGS_MAX { + return Err(format!("`settings` has more than {WIDGET_SETTINGS_MAX} entries")); + } + let mut out: Vec = Vec::new(); + for (n, item) in items.iter().enumerate() { + let key = ystr(item, "key"); + if !setting_key_ok(&key) { + return Err(format!("`settings[{n}].key` must be lowercase letters, digits, dots, hyphens or underscores")); + } + if out.iter().any(|s| s.key == key) { + return Err(format!("`settings[{n}].key` (`{key}`) is used twice")); + } + let label = ystr(item, "label"); + if !setting_text_ok(&label, 160) { + return Err(format!("`settings[{n}].label` is missing or too long")); + } + let type_ = ystr(item, "type"); + let kind = match type_.as_str() { + "toggle" => WidgetSettingKind::Toggle, + "choice" => WidgetSettingKind::Choice, + _ => return Err(format!("`settings[{n}].type` must be `toggle` or `choice`")), + }; + let mut choices = if kind == WidgetSettingKind::Choice { ylist(item, "choices")? } else { Vec::new() }; + let mut default = ystr(item, "default"); + if kind == WidgetSettingKind::Toggle { + if default.is_empty() { + default = "true".into(); + } + if default != "true" && default != "false" { + return Err(format!("`settings[{n}].default` must be true or false")); + } + } else { + if !(2..=WIDGET_SETTINGS_CHOICES_MAX).contains(&choices.len()) { + return Err(format!("`settings[{n}].choices` needs 2 to {WIDGET_SETTINGS_CHOICES_MAX} values")); + } + for (i, c) in choices.iter().enumerate() { + if !setting_text_ok(c, WIDGET_SETTINGS_VALUE_MAX) { + return Err(format!("`settings[{n}].choices[{i}]` is empty or too long")); + } + if choices[..i].contains(c) { + return Err(format!("`settings[{n}].choices` repeats `{c}`")); + } + } + if default.is_empty() { + default = choices[0].clone(); + } else if !choices.contains(&default) { + return Err(format!("`settings[{n}].default` is not one of its choices")); + } + } + out.push(WidgetSetting { + key, + label, + kind, + default, + choices: std::mem::take(&mut choices), + icon: ystr(item, "icon"), + }); + } + Ok(out) +} + +/// Reads a `package.yaml`. Unknown top-level keys are kept out and are not an error (forward compatibility). +pub fn widget_package_parse(text: &str) -> Result { + if text.len() > WIDGET_PKG_MANIFEST_MAX { + return Err("the manifest is too large".into()); + } + if text.as_bytes().contains(&0) { + return Err("the manifest holds a NUL byte".into()); + } + let y = yaml_parse(text)?; + if !matches!(y, Yaml::Map(_)) { + return Err("the manifest is not a mapping".into()); + } + let mut p = WidgetPackage { + name: ystr(&y, "name"), + id: ystr(&y, "id"), + type_: ystr(&y, "type"), + version: ystr(&y, "version"), + author: ystr(&y, "author"), + description: ystr(&y, "description"), + license: ystr(&y, "license"), + license_url: ystr(&y, "license_url"), + min_grimoire_version: ystr(&y, "min_grimoire_version"), + // (omitted means every supported device; an explicit empty list is not the same and is refused) + platforms: if y.get("platforms").is_none() { vec!["all".to_string()] } else { ylist(&y, "platforms")? }, + repository: ystr(&y, "repository"), + capabilities: ylist(&y, "capabilities")?, + settings: ysettings(&y)?, + ..Default::default() + }; + if let Some(a) = y.get("artifact") { + p.artifact = WidgetArtifact { + path: ystr(a, "path"), + sha256: ystr(a, "sha256"), + size: ystr(a, "size").parse().unwrap_or(0), + }; + } + if let Some(rs) = y.get("releases") { + for r in rs.list().ok_or("`releases` is not a list")? { + p.releases.push(WidgetRelease { + version: ystr(r, "version"), + url: ystr(r, "url"), + sha256: ystr(r, "sha256"), + }); + } + } + if let Some(s) = y.get("spec") { + p.spec = WidgetSpec { + runtime: ystr(s, "runtime"), + entry: ystr(s, "entry"), + icon: ystr(s, "icon"), + minimizable: ybool(s, "minimizable", true), + size: ysize(s.get("size"))?, + }; + } + Ok(p) +} + +fn id_ok(id: &str) -> bool { + !id.is_empty() + && id.len() <= 128 + && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-') + && id.as_bytes()[0] != b'.' + && id.as_bytes()[id.len() - 1] != b'.' + && !id.contains("..") +} + +fn semver_ok(v: &str) -> bool { + let core = v.split_once('-').map_or(v, |(c, _)| c); + let parts: Vec<&str> = core.split('.').collect(); + if parts.len() != 3 { + return false; + } + for p in &parts { + if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) { + return false; + } + if p.len() > 1 && p.starts_with('0') { + return false; + } + } + if let Some((_, pre)) = v.split_once('-') { + if pre.is_empty() || !pre.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-') { + return false; + } + } + true +} + +fn sha_ok(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +fn path_ok(p: &str) -> bool { + !p.is_empty() + && p.len() <= 240 + && !p.starts_with('/') + && !p.contains('\\') + && p.split('/').all(|s| !s.is_empty() && s != "." && s != "..") +} + +fn cap_ok(c: &str) -> bool { + matches!(c, "editor:overlay" | "storage:widget-local") +} + +/// Validates a manifest for this build and this device. `canvas_w` and `canvas_h` are the editor +/// canvas's size, for the absolute maximum (70% either way). +pub fn widget_package_validate(p: &WidgetPackage, canvas_w: i32, canvas_h: i32) -> Result<(), String> { + if p.type_ != "widget" { + return Err("This repository is not a widget package".into()); + } + if !id_ok(&p.id) { + return Err("`id` must be lowercase letters, digits, dots and hyphens".into()); + } + if p.name.trim().is_empty() { + return Err("`name` is missing".into()); + } + if !semver_ok(&p.version) { + return Err(format!("`version` (`{}`) is not a valid version", p.version)); + } + if !p.min_grimoire_version.is_empty() { + if !update_version_key(&p.min_grimoire_version, &mut [0; 3]) { + return Err("`min_grimoire_version` is not a valid version".into()); + } + if update_version_cmp(GRIMOIRE_VERSION, &p.min_grimoire_version) < 0 { + return Err(format!("This widget needs Grimoire {} or newer.", p.min_grimoire_version)); + } + } + if p.platforms.is_empty() { + return Err("`platforms` is an empty list (omit it to mean all devices)".into()); + } + for name in &p.platforms { + if !widget_platform_known(name) { + let all: Vec<&str> = WIDGET_PLATFORMS.iter().map(|(k, _)| *k).collect(); + return Err(format!("Unknown platform '{name}'. Supported: {}", all.join(", "))); + } + } + if !p.platforms.iter().any(|x| x == "all") && !widget_platform_supported(&p.platforms) { + let current = widget_current_platform(); + let label = if current == "unknown" { "this device".to_string() } else { widget_platform_label(current).to_string() }; + return Err(format!("This widget does not support your device ({label}).")); + } + for c in &p.capabilities { + if !cap_ok(c) { + return Err(format!("Unknown capability '{c}'.")); + } + } + if p.spec.runtime != "wasm" { + return Err("`spec.runtime` must be `wasm`; Grimoire does not run native widget code".into()); + } + if !path_ok(&p.artifact.path) + || p.artifact.path == "package.yaml" + || p.artifact.path == "state" + || p.artifact.path.starts_with("state/") + { + return Err("`artifact.path` is not a safe relative path (it cannot be package.yaml or inside state/)".into()); + } + if !sha_ok(&p.artifact.sha256) { + return Err("`artifact.sha256` is not a SHA-256 digest".into()); + } + if p.artifact.size == 0 || p.artifact.size > WIDGET_PKG_ARTIFACT_MAX { + return Err("`artifact.size` is outside the allowed size".into()); + } + for r in &p.releases { + if !semver_ok(&r.version) { + return Err("a `releases` entry has an invalid version".into()); + } + if !(r.url.starts_with("https://") || r.url.starts_with("http://")) { + return Err("a `releases` entry has no http or https URL".into()); + } + if !sha_ok(&r.sha256) { + return Err("a `releases` entry has an invalid sha256".into()); + } + } + let floor_w = ui_px(120.0).max(1); + let floor_h = ui_px(80.0).max(1); + let ceil_w = (canvas_w * 70 / 100).max(floor_w); + let ceil_h = (canvas_h * 70 / 100).max(floor_h); + let s = &p.spec.size; + for (w, h) in [s.default, s.min, s.max] { + if w < floor_w || h < floor_h { + return Err(format!("Widget size {w}x{h} is below the minimum of {floor_w}x{floor_h}")); + } + if w > ceil_w || h > ceil_h { + return Err(format!("Widget size {w}x{h} exceeds the maximum of {ceil_w}x{ceil_h}")); + } + } + if s.mode == WidgetSizeMode::Resizable && (s.min.0 > s.max.0 || s.min.1 > s.max.1) { + return Err("`spec.size.min` is larger than `spec.size.max`".into()); + } + Ok(()) +} + +/// The artifact a repository's manifest names for this version: its release entry when there is one, +/// else the repository tree's `artifact.path`. +pub fn widget_package_artifact_url(manifest_url: &str, p: &WidgetPackage) -> Option { + if let Some(r) = p.releases.iter().find(|r| r.version == p.version) { + return Some(r.url.clone()); + } + let base = manifest_url.rsplit_once('/').map_or("", |(b, _)| b); + if base.is_empty() { + return None; + } + Some(format!("{base}/{}", p.artifact.path)) +} + +/// The expected digest and size of the artifact for this version (a release can carry them separately). +pub fn widget_package_artifact_digest(p: &WidgetPackage) -> (&str, u64) { + if let Some(r) = p.releases.iter().find(|r| r.version == p.version) { + if sha_ok(&r.sha256) { + return (&r.sha256, p.artifact.size); + } + } + (&p.artifact.sha256, p.artifact.size) +} + +// ---- installed state ---- + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WidgetInstall { + pub id: String, + pub name: String, + pub version: String, + pub author: String, + pub description: String, + /// the manifest's spec.icon: a name in widgets::widget_icon, empty for a package without one + pub icon: String, + pub path: String, + pub sha: String, + pub installed_at: i64, + pub source_url: String, +} + +fn root() -> String { + store_root() +} + +pub fn widget_package_dir(id: &str) -> String { + format!("{}/{}/{}", root(), WIDGET_PKG_DIR, id) +} + +pub fn widget_package_index_path() -> String { + format!("{}/{}", root(), WIDGET_PKG_INDEX) +} + +fn now_secs() -> i64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64) +} + +fn json_escape(s: &str, out: &mut String) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); +} + +pub fn widget_package_index_save(items: &[WidgetInstall]) -> i32 { + if root().is_empty() { + return 0; + } + let mut s = String::from("{\n \"version\": 1,\n \"packages\": ["); + for (i, it) in items.iter().enumerate() { + if i > 0 { + s.push(','); + } + s.push_str("\n {\"id\":"); + json_escape(&it.id, &mut s); + s.push_str(",\"name\":"); + json_escape(&it.name, &mut s); + s.push_str(",\"version\":"); + json_escape(&it.version, &mut s); + s.push_str(",\"author\":"); + json_escape(&it.author, &mut s); + s.push_str(",\"description\":"); + json_escape(&it.description, &mut s); + s.push_str(",\"icon\":"); + json_escape(&it.icon, &mut s); + s.push_str(",\"path\":"); + json_escape(&it.path, &mut s); + s.push_str(",\"sha\":"); + json_escape(&it.sha, &mut s); + s.push_str(&format!(",\"installed_at\":{},\"source_url\":", it.installed_at)); + json_escape(&it.source_url, &mut s); + s.push('}'); + } + s.push_str("\n ]\n}\n"); + mkdir_p(&format!("{}/packages", root())); + write_file_atomic(&widget_package_index_path(), s.as_bytes()) +} + +fn json_get_str(text: &[u8], toks: &[JsonTok], obj: i32, key: &str) -> String { + let v = json_get(text, toks, obj, key); + if v < 0 { + return String::new(); + } + let mut b = Vec::new(); + if json_string(text, &toks[v as usize], &mut b, 1024) { + String::from_utf8_lossy(&b).into_owned() + } else { + String::new() + } +} + +pub fn widget_package_index_load() -> Vec { + let Some(data) = read_file_max(&widget_package_index_path(), 256 * 1024) else { + return Vec::new(); + }; + let mut toks = vec![JsonTok::default(); 4096]; + let n = json_parse(&data, &mut toks); + if n < 0 { + qlog!("packages: index.json did not parse"); + return Vec::new(); + } + let arr = json_get(&data, &toks[..n as usize], 0, "packages"); + if arr < 0 || toks[arr as usize].type_ != JsonType::Array { + return Vec::new(); + } + let mut out = Vec::new(); + for i in 0..toks[arr as usize].size.min(WIDGET_PKG_COUNT_MAX as i32) { + let it = json_item(&toks[..n as usize], arr, i); + if it < 0 || toks[it as usize].type_ != JsonType::Object { + continue; + } + let id = json_get_str(&data, &toks[..n as usize], it, "id"); + if !id_ok(&id) { + continue; + } + out.push(WidgetInstall { + name: json_get_str(&data, &toks[..n as usize], it, "name"), + id, + version: json_get_str(&data, &toks[..n as usize], it, "version"), + author: json_get_str(&data, &toks[..n as usize], it, "author"), + description: json_get_str(&data, &toks[..n as usize], it, "description"), + icon: json_get_str(&data, &toks[..n as usize], it, "icon"), + path: json_get_str(&data, &toks[..n as usize], it, "path"), + sha: json_get_str(&data, &toks[..n as usize], it, "sha"), + installed_at: { + let v = json_get(&data, &toks[..n as usize], it, "installed_at"); + let mut n2 = 0i32; + if v >= 0 && json_int(&data, &toks[v as usize], &mut n2) { n2 as i64 } else { 0 } + }, + source_url: json_get_str(&data, &toks[..n as usize], it, "source_url"), + }); + } + out +} + +pub fn widget_package_installed(id: &str) -> Option { + widget_package_index_load().into_iter().find(|p| p.id == id) +} + +/// An installed package's manifest, re-read from its folder (its author and license are not all in +/// the index, and an install from before those fields were kept has only in the manifest). +pub fn widget_package_installed_manifest(id: &str) -> Option { + parse_installed(&widget_package_installed(id)?) +} + +fn parse_installed(p: &WidgetInstall) -> Option { + let path = widget_package_dir(&p.id); + let data = read_file_max(&format!("{path}/package.yaml"), WIDGET_PKG_MANIFEST_MAX)?; + let text = String::from_utf8_lossy(&data); + let m = widget_package_parse(&text).ok()?; + (m.id == p.id).then_some(m) +} + +/// The installed packages whose manifest still reads and whose device is supported. +pub fn widget_package_installed_manifests() -> Vec<(WidgetInstall, WidgetPackage)> { + let mut v = Vec::new(); + for it in widget_package_index_load() { + let Some(m) = parse_installed(&it) else { continue }; + if m.platforms.is_empty() || !widget_platform_supported(&m.platforms) { + continue; + } + v.push((it, m)); + } + v +} + +/// Installs a validated manifest and its artifact. Existing versions are replaced only after the new +/// directory is complete; the old one is kept as `.previous` for a rollback. +pub fn widget_package_install(manifest: &str, artifact: &[u8], source_url: &str, canvas_w: i32, canvas_h: i32) -> Result { + let p = widget_package_parse(manifest)?; + widget_package_validate(&p, canvas_w, canvas_h)?; + let (want_sha, want_size) = widget_package_artifact_digest(&p); + if want_size != artifact.len() as u64 { + return Err(format!("The artifact is {} bytes, not {want_size}.", artifact.len())); + } + let got = sha256_of(artifact); + if !got.eq_ignore_ascii_case(want_sha) { + return Err("The artifact's SHA-256 does not match the manifest.".into()); + } + let index = widget_package_index_load(); + if index.len() >= WIDGET_PKG_COUNT_MAX && !index.iter().any(|x| x.id == p.id) { + return Err("No more widget packages can be installed.".into()); + } + let dir = widget_package_dir(&p.id); + let stage = format!("{}/{}/.install-{}", root(), WIDGET_PKG_DIR, std::process::id()); + let _ = std::fs::remove_dir_all(&stage); + if std::fs::create_dir_all(&stage).is_err() { + return Err("Could not make the package's folder.".into()); + } + if write_file_atomic(&format!("{stage}/package.yaml"), manifest.as_bytes()) != 0 { + let _ = std::fs::remove_dir_all(&stage); + return Err("Could not write the manifest.".into()); + } + let dest = format!("{stage}/{}", p.artifact.path); + if let Some(parent) = dest.rsplit_once('/').map(|(d, _)| d) { + if std::fs::create_dir_all(parent).is_err() { + let _ = std::fs::remove_dir_all(&stage); + return Err("Could not make the artifact's folder.".into()); + } + } + if write_file_atomic(&dest, artifact) != 0 { + let _ = std::fs::remove_dir_all(&stage); + return Err("Could not write the artifact.".into()); + } + let old = format!("{dir}.previous"); + let _ = std::fs::remove_dir_all(&old); + if std::fs::metadata(&dir).is_ok() && std::fs::rename(&dir, &old).is_err() { + let _ = std::fs::remove_dir_all(&stage); + return Err("Could not move the installed version aside.".into()); + } + if let Err(e) = std::fs::rename(&stage, &dir) { + if std::fs::metadata(&old).is_ok() { + let _ = std::fs::rename(&old, &dir); + } + let _ = std::fs::remove_dir_all(&stage); + return Err(format!("Could not put the package in place: {e}")); + } + // The package's own state survives an update; it is never part of the artifact. + if std::fs::metadata(format!("{old}/state")).is_ok() { + let _ = std::fs::rename(format!("{old}/state"), format!("{dir}/state")); + } + let it = WidgetInstall { + id: p.id.clone(), + name: p.name.clone(), + version: p.version.clone(), + author: p.author.clone(), + description: p.description.clone(), + icon: p.spec.icon.trim().to_string(), + path: format!("{}/{}/{}", WIDGET_PKG_DIR, p.id, p.artifact.path), + sha: got, + installed_at: now_secs(), + source_url: source_url.to_string(), + }; + let mut next: Vec = index.into_iter().filter(|x| x.id != it.id).collect(); + next.push(it.clone()); + if widget_package_index_save(&next) != 0 { + // Put the previous version, and the state that came with it, back. + if std::fs::metadata(format!("{dir}/state")).is_ok() { + let _ = std::fs::rename(format!("{dir}/state"), format!("{old}/state")); + } + let _ = std::fs::remove_dir_all(&dir); + if std::fs::metadata(&old).is_ok() { + let _ = std::fs::rename(&old, &dir); + } + return Err("Could not save the package index.".into()); + } + widget_catalog_invalidate(); + Ok(it) +} + +/// Removes an installed package and its files. The `state` folder is kept when `keep_state` is set. +pub fn widget_package_remove(id: &str, keep_state: bool) -> Result<(), String> { + if !id_ok(id) { + return Err("That id is not a widget package's.".into()); + } + let dir = widget_package_dir(id); + if keep_state { + let state = format!("{dir}/state"); + if std::fs::metadata(&state).is_ok() { + let keep = format!("{}/{}/.state-{}", root(), WIDGET_PKG_DIR, std::process::id()); + let _ = std::fs::remove_dir_all(&keep); + std::fs::rename(&state, &keep).ok(); + let _ = std::fs::remove_dir_all(&dir); + if std::fs::create_dir_all(&dir).is_ok() { + let _ = std::fs::rename(&keep, &format!("{dir}/state")); + } + } else { + let _ = std::fs::remove_dir_all(&dir); + } + } else { + let _ = std::fs::remove_dir_all(&dir); + } + let mut index = widget_package_index_load(); + index.retain(|p| p.id != id); + if widget_package_index_save(&index) != 0 { + return Err("Could not save the package index.".into()); + } + let mut frames = crate::widgets::widgets_load(); + frames.retain(|f| f.id != id); + crate::widgets::widgets_save(&frames); + widget_catalog_invalidate(); + Ok(()) +} + +/// Rolls an install back to the `.previous` copy. +pub fn widget_package_rollback(id: &str) -> Result<(), String> { + if !id_ok(id) { + return Err("That id is not a widget package's.".into()); + } + let dir = widget_package_dir(id); + let old = format!("{dir}.previous"); + if std::fs::metadata(&old).is_err() { + return Err("There is no previous version to roll back to.".into()); + } + let bad = format!("{dir}.bad-{}", std::process::id()); + let _ = std::fs::remove_dir_all(&bad); + if std::fs::metadata(&dir).is_ok() && std::fs::rename(&dir, &bad).is_err() { + return Err("Could not move the current version aside.".into()); + } + if std::fs::rename(&old, &dir).is_err() { + let _ = std::fs::rename(&bad, &dir); + return Err("Could not restore the previous version.".into()); + } + let _ = std::fs::remove_dir_all(&bad); + let data = read_file_max(&format!("{dir}/package.yaml"), WIDGET_PKG_MANIFEST_MAX); + let Some(data) = data else { return Err("The previous version has no manifest.".into()) }; + let p = widget_package_parse(&String::from_utf8_lossy(&data))?; + let mut index = widget_package_index_load(); + for it in &mut index { + if it.id == id { + it.version = p.version.clone(); + it.name = p.name.clone(); + it.author = p.author.clone(); + it.description = p.description.clone(); + } + } + widget_package_index_save(&index); + widget_catalog_invalidate(); + Ok(()) +} + +// ---- package settings ---- + +/// Where a package's setting values live. It is inside the package's state folder, so an update and +/// a remove that keeps state carry it along; the file is the host's, not the package's artifact. +pub fn widget_settings_path(id: &str) -> String { + format!("{}/state/settings.json", widget_package_dir(id)) +} + +/// Every declared setting at its default. A package with no settings has an empty list. +pub fn widget_settings_defaults(schema: &[WidgetSetting]) -> Vec<(String, String)> { + schema.iter().map(|s| (s.key.clone(), s.default.clone())).collect() +} + +/// The value a tap produces: the other side of a toggle, or the next choice (the first for a value +/// the manifest no longer offers). +pub fn widget_setting_next(s: &WidgetSetting, current: &str) -> String { + match s.kind { + WidgetSettingKind::Toggle => (if current == "true" { "false" } else { "true" }).into(), + WidgetSettingKind::Choice => { + let at = s.choices.iter().position(|c| c == current); + match at { + Some(i) => s.choices[(i + 1) % s.choices.len()].clone(), + None => s.choices.first().cloned().unwrap_or_default(), + } + } + } +} + +/// A package's saved values in its manifest's order. A missing file, a malformed value or a value +/// this version no longer offers reads as the default; an old key is left out. +pub fn widget_settings_load(id: &str, schema: &[WidgetSetting]) -> Vec<(String, String)> { + let mut out = widget_settings_defaults(schema); + if !id_ok(id) { + return out; + } + let Some(data) = read_file_max(&widget_settings_path(id), WIDGET_SETTINGS_FILE_MAX) else { return out }; + let mut toks = vec![JsonTok::default(); 2048]; + let n = json_parse(&data, &mut toks); + if n < 0 { + return out; + } + let values = json_get(&data, &toks[..n as usize], 0, "values"); + if values < 0 || toks[values as usize].type_ != JsonType::Object { + return out; + } + for (i, s) in schema.iter().enumerate() { + let tok = json_get(&data, &toks[..n as usize], values, &s.key); + if tok < 0 { + continue; + } + let mut buf = Vec::new(); + if !json_string(&data, &toks[tok as usize], &mut buf, WIDGET_SETTINGS_VALUE_MAX + 1) { + continue; + } + let value = String::from_utf8_lossy(&buf); + if setting_value_ok(s, &value) { + out[i].1 = value.into_owned(); + } + } + out +} + +/// Writes setting values atomically under the package's state folder. Keys that are not valid +/// setting keys are skipped, as are values longer than a choice can hold. +pub fn widget_settings_save(id: &str, values: &[(String, String)]) -> i32 { + if !id_ok(id) { + return -1; + } + let mut body = String::from("{\n \"version\": 1,\n \"values\": {"); + let mut n = 0usize; + for (key, value) in values { + if !setting_key_ok(key) || value.len() > WIDGET_SETTINGS_VALUE_MAX || value.chars().any(char::is_control) { + continue; + } + if n > 0 { + body.push(','); + } + body.push_str("\n "); + json_escape(key, &mut body); + body.push_str(": "); + json_escape(value, &mut body); + n += 1; + } + if n > 0 { + body.push('\n'); + } + body.push_str(" }\n}\n"); + let dir = format!("{}/state", widget_package_dir(id)); + if mkdir_p(&dir) != 0 { + return -1; + } + write_file_atomic(&widget_settings_path(id), body.as_bytes()) +} + +/// Removes the saved values, so every setting reads its manifest default again. A missing file is +/// already reset. +pub fn widget_settings_clear(id: &str) -> i32 { + if !id_ok(id) { + return -1; + } + match std::fs::remove_file(widget_settings_path(id)) { + Ok(()) => 0, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, + Err(_) => -1, + } +} + +/// The value of one setting from a loaded list, or the fallback. +pub fn widget_setting_value<'a>(values: &'a [(String, String)], key: &str, fallback: &'a str) -> &'a str { + values.iter().find(|(k, _)| k == key).map_or(fallback, |(_, v)| v) +} + +// ---- fetching ---- + +/// One `curl` run, its answer read as it comes. The package manager has no TLS of its own; curl is +/// the repository fetcher (as KPM is Grimoire's update fetcher), and an install never waits on it on +/// the UI thread. The caller ticks it from the library tick. +pub struct WidgetFetch { + pid: libc::pid_t, + fd: i32, + err_fd: i32, + data: Vec, + err: Vec, + cap: usize, + started: std::time::Instant, + finished: bool, +} + +/// A fetch may take this long; after it the child is killed. (The timeout is ours, not curl's: +/// some Kindles' curl rejects timeout options, and an install must not hang on one.) +const FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(45); + +impl WidgetFetch { + pub fn start(url: &str, cap: usize) -> Result { + if url.len() > WIDGET_PKG_URL_MAX || !url.starts_with("https://") { + return Err("Only https addresses can be fetched.".into()); + } + let Ok(curl) = std::ffi::CString::new("curl") else { return Err("Could not start the fetcher.".into()) }; + let Ok(c_url) = std::ffi::CString::new(url) else { return Err("That address has a NUL byte.".into()) }; + let mut p = [0i32; 2]; + // SAFETY: pipe writes the two descriptors into our array. + if unsafe { libc::pipe(p.as_mut_ptr()) } != 0 { + return Err("Could not make the fetcher's pipe.".into()); + } + let mut e = [0i32; 2]; + // SAFETY: as above, a second pipe for curl's own error text. + if unsafe { libc::pipe(e.as_mut_ptr()) } != 0 { + unsafe { + libc::close(p[0]); + libc::close(p[1]); + } + return Err("Could not make the fetcher's pipe.".into()); + } + // SAFETY: fork has no preconditions; the child only sets up descriptors and execs, or _exits. + let pid = unsafe { libc::fork() }; + if pid < 0 { + // SAFETY: closing the descriptors the pipes just made. + unsafe { + libc::close(p[0]); + libc::close(p[1]); + libc::close(e[0]); + libc::close(e[1]); + } + return Err("Could not start the fetcher.".into()); + } + if pid == 0 { + // SAFETY: in the child, dup2/close/fcntl on descriptors it owns, execvp with + // NUL-terminated strings and a NULL-terminated list, _exit if it fails. + unsafe { + libc::dup2(p[1], 1); + libc::dup2(e[1], 2); + libc::close(p[0]); + libc::close(p[1]); + libc::close(e[0]); + libc::close(e[1]); + libc::fcntl(1, libc::F_SETFD, 0); + libc::fcntl(2, libc::F_SETFD, 0); + // (nothing else of Grimoire's: an inherited descriptor is no use to curl and can be + // a terminal, a notebook or another child's pipe) + for fd in 3..1024 { + libc::close(fd); + } + // The plainest invocation curl has: -q ignores a .curlrc that might name an option this + // build does not have, and -fsSL is older than every curl on a Kindle or a computer. + // No timeout option: the parent kills the child after FETCH_TIMEOUT instead, because + // some Kindles' curl rejects the options real curl uses for one. + // HTTPS is checked by start (and the artifact's SHA-256 by the install). + let args: [*const libc::c_char; 5] = [ + curl.as_ptr(), + c"-q".as_ptr(), + c"-fsSL".as_ptr(), + c_url.as_ptr(), + std::ptr::null(), + ]; + libc::execvp(curl.as_ptr(), args.as_ptr()); + libc::_exit(127); + } + } + // SAFETY: closing the write ends the parent does not use; fcntl on the read ends we own. + unsafe { + libc::close(p[1]); + libc::close(e[1]); + libc::fcntl(p[0], libc::F_SETFL, libc::fcntl(p[0], libc::F_GETFL, 0) | libc::O_NONBLOCK); + libc::fcntl(e[0], libc::F_SETFL, libc::fcntl(e[0], libc::F_GETFL, 0) | libc::O_NONBLOCK); + } + Ok(WidgetFetch { pid, fd: p[0], err_fd: e[0], data: Vec::with_capacity(cap.min(64 * 1024)), err: Vec::new(), cap, started: std::time::Instant::now(), finished: false }) + } + + fn read_into(fd: i32, out: &mut Vec, cap: usize) { + let mut buf = [0u8; 16 * 1024]; + while out.len() < cap { + let room = (cap - out.len()).min(buf.len()); + // SAFETY: read into our stack buffer, room bytes at most; the fd is ours. + let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, room) }; + if n > 0 { + out.extend_from_slice(&buf[..n as usize]); + } else { + break; + } + } + } + + fn drain(&mut self) { + Self::read_into(self.fd, &mut self.data, self.cap); + // (curl's failure text; enough for its message, never the whole page it did not send) + Self::read_into(self.err_fd, &mut self.err, 4096); + } + + /// Kills and reaps the child after a failed fetch, then closes its pipes. + fn stop(&mut self) { + // SAFETY: signals and reaps the child this fetcher still owns, then closes its pipes. + unsafe { + libc::kill(self.pid, libc::SIGKILL); + libc::waitpid(self.pid, std::ptr::null_mut(), 0); + libc::close(self.fd); + libc::close(self.err_fd); + } + self.finished = true; + } + + fn err_text(&self) -> String { + let text = String::from_utf8_lossy(&self.err); + let one_line = text.split_whitespace().collect::>().join(" "); + if one_line.chars().count() > 180 { + one_line.chars().take(180).collect::() + "..." + } else { + one_line + } + } + + /// None while curl runs, then its answer or the failure. The caller drops the fetcher after Some. + pub fn tick(&mut self) -> Option, String>> { + if self.finished { + return Some(Err("the fetch was already read".into())); + } + self.drain(); + let mut status = 0; + // SAFETY: waitpid writes the status into our int. + let reaped = unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) } == self.pid; + self.drain(); + if !reaped { + if self.data.len() >= self.cap { + self.stop(); + return Some(Err("The answer is larger than the package manager accepts.".into())); + } + if self.started.elapsed() >= FETCH_TIMEOUT { + self.stop(); + return Some(Err("The repository did not answer in time.".into())); + } + return None; + } + // SAFETY: closing the read ends this fetch owns. + unsafe { + libc::close(self.fd); + libc::close(self.err_fd); + } + self.finished = true; + let code = if libc::WIFEXITED(status) { libc::WEXITSTATUS(status) } else { -1 }; + if code != 0 { + let detail = self.err_text(); + let base = if code == 28 { + "The repository did not answer in time." + } else if code == 127 { + "The Kindle has no curl to fetch packages with." + } else { + "Could not fetch the repository" + }; + return Some(Err(if detail.is_empty() { format!("{base} (curl exited {code}).") } else { format!("{base} (curl exited {code}): {detail}") })); + } + Some(Ok(std::mem::take(&mut self.data))) + } +} + +impl Drop for WidgetFetch { + fn drop(&mut self) { + if !self.finished { + self.stop(); + } + } +} + +// ---- catalog entries ---- + +thread_local! { + static PACKAGE_DEFS: RefCell>> = const { RefCell::new(None) }; +} + +pub fn widget_catalog_invalidate() { + PACKAGE_DEFS.with(|d| *d.borrow_mut() = None); +} + +fn leak(s: String) -> &'static str { + Box::leak(s.into_boxed_str()) +} + +fn package_def(p: &WidgetPackage) -> &'static WidgetDef { + let size = &p.spec.size; + let (min_w, min_h, max_w, max_h) = if size.mode == WidgetSizeMode::Resizable { + (size.min.0 as f32, size.min.1 as f32, size.max.0 as f32, size.max.1 as f32) + } else { + let w = size.default.0 as f32; + let h = size.default.1 as f32; + (w, h, w, h) + }; + // A package without an icon gets the generic widget grid. + let icon = if p.spec.icon.trim().is_empty() { + IconKind::Grid + } else { + crate::widgets::widget_icon(&p.spec.icon) + }; + let def = WidgetDef { + id: leak(p.id.clone()), + name: leak(p.name.clone()), + icon, + default_w: size.default.0 as f32, + default_h: size.default.1 as f32, + min_w, + min_h, + max_w, + max_h, + resizable: size.mode == WidgetSizeMode::Resizable, + version: leak(p.version.clone()), + author: leak(p.author.clone()), + description: leak(p.description.clone()), + }; + Box::leak(Box::new(def)) +} + +pub fn widget_package_defs() -> Vec<&'static WidgetDef> { + PACKAGE_DEFS.with(|d| { + let mut d = d.borrow_mut(); + if d.is_none() { + let mut v = Vec::new(); + for (_, p) in widget_package_installed_manifests() { + v.push(package_def(&p)); + } + *d = Some(v); + } + d.as_ref().unwrap().clone() + }) +} + +/// Checks a repository input and returns the manifest URL: `user/repo` is GitHub's default branch, +/// else main then master; a custom URL must end in `.yaml`. +pub fn widget_manifest_url(input: &str) -> Result<(String, bool), String> { + let input = input.trim(); + if input.is_empty() { + return Err("Enter a repository or a .yaml address.".into()); + } + if input.len() > WIDGET_PKG_URL_MAX { + return Err("That address is too long.".into()); + } + if input.starts_with("https://") || input.starts_with("http://") { + let path = input.split(['?', '#']).next().unwrap_or(input); + if !path.to_ascii_lowercase().ends_with(".yaml") { + return Err("The address must end in .yaml.".into()); + } + return Ok((input.to_string(), false)); + } + if input.starts_with('/') { + return Err("Enter user/repo, not a path.".into()); + } + let parts: Vec<&str> = input.split('/').collect(); + if parts.len() != 2 || parts.iter().any(|p| p.is_empty() || p.contains(' ')) { + return Err("Enter user/repo or an https .yaml address.".into()); + } + let user = parts[0]; + let repo = parts[1]; + if !user.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') + || !repo.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') + { + return Err("That GitHub name has a character it cannot have.".into()); + } + Ok((format!("https://raw.githubusercontent.com/{user}/{repo}/main/package.yaml"), true)) +} + +/// A GitHub repository's `user/repo`, from a repository address, a `user/repo` shorthand or a raw +/// file URL, or None for anything else (another host, a local path). +pub fn widget_github_repo(source: &str) -> Option { + fn name_ok(s: &str) -> bool { + !s.is_empty() + && s.len() <= 100 + && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') + && s != "." + && s != ".." + } + let s = source.trim(); + let rest = if let Some(r) = s + .strip_prefix("https://github.com/") + .or_else(|| s.strip_prefix("http://github.com/")) + .or_else(|| s.strip_prefix("https://raw.githubusercontent.com/")) + .or_else(|| s.strip_prefix("http://raw.githubusercontent.com/")) + { + r + } else if s.contains("://") || s.starts_with('/') { + return None; + } else { + s + }; + let parts: Vec<&str> = rest.split('/').filter(|p| !p.is_empty()).collect(); + if parts.len() < 2 { + return None; + } + let repo = parts[1].strip_suffix(".git").unwrap_or(parts[1]); + if !name_ok(parts[0]) || !name_ok(repo) { + return None; + } + Some(format!("{}/{}", parts[0], repo)) +} + +/// The repository's GitHub page, for its QR code: only a GitHub repository has one. +pub fn widget_github_repo_url(source: &str) -> Option { + widget_github_repo(source).map(|r| format!("https://github.com/{r}")) +} + +/// The GitHub repository API URL for a shorthand input, or None for a custom URL. +pub fn widget_github_api(input: &str) -> Option { + let parts: Vec<&str> = input.trim().split('/').collect(); + if parts.len() == 2 && !parts[0].is_empty() && !input.trim().starts_with("http") { + Some(format!("https://api.github.com/repos/{}/{}", parts[0], parts[1])) + } else { + None + } +} + +/// The default branch named by GitHub's repository answer, if it has one. +pub fn widget_github_branch(json: &str) -> Option { + let key = "\"default_branch\""; + let at = json.find(key)? + key.len(); + let rest = &json[at..]; + let colon = rest.find(':')?; + let rest = rest[colon + 1..].trim_start(); + let rest = rest.strip_prefix('"')?; + let end = rest.find('"')?; + let branch = &rest[..end]; + (!branch.is_empty() && branch.len() <= 128 && !branch.contains('/')).then(|| branch.to_string()) +} + +/// Every installed package's detail, for a UI list. +pub fn widget_package_list() -> Vec { + let mut v = widget_package_index_load(); + v.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then(a.id.cmp(&b.id))); + v +} + +/// Packages whose files are no longer there, removed from the index (a manual delete, a failed move). +pub fn widget_package_repair() { + let mut index = widget_package_index_load(); + let before = index.len(); + index.retain(|p| parse_installed(p).is_some()); + if index.len() != before { + widget_package_index_save(&index); + widget_catalog_invalidate(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn manifest(id: &str) -> String { + format!( + r#"name: Test Widget +id: {id} +type: widget +version: 1.2.0 +author: Jane +description: A test. +license: MIT +min_grimoire_version: 2.0.0 +platforms: [all] +artifact: + path: dist/widget.bin + sha256: {sha} + size: 4 +capabilities: [editor:overlay, storage:widget-local] +settings: + - key: show_percent + label: Show percent key + type: toggle + default: false + - key: layout + label: Layout + type: choice + default: large + choices: [compact, large] +spec: + runtime: wasm + entry: _start + minimizable: true + size: + mode: resizable + default: [220, 160] + min: [120, 80] + max: [800, 600] +"#, + sha = sha256_of(b"test") + ) + } + + #[test] + fn a_manifest_reads_and_validates() { + ui_init(300.0); + let p = widget_package_parse(&manifest("com.example.test")).unwrap(); + assert_eq!(p.name, "Test Widget"); + assert_eq!(p.platforms, ["all"]); + assert_eq!(p.spec.size.default, (220, 160)); + assert_eq!(p.spec.size.mode, WidgetSizeMode::Resizable); + widget_package_validate(&p, 1860, 2480).unwrap(); + } + + #[test] + fn validation_names_the_offending_field() { + ui_init(300.0); + let good = manifest("com.example.test"); + for (bad, want) in [ + (good.replace("type: widget", "type: plugin"), "not a widget"), + (good.replace("com.example.test", "Bad Id"), "lowercase"), + (good.replace("platforms: [all]", "platforms: [kindle-oasis]"), "Unknown platform"), + (good.replace("capabilities: [editor:overlay, storage:widget-local]", "capabilities: [net]"), "Unknown capability"), + (good.replace("path: dist/widget.bin", "path: package.yaml"), "safe relative path"), + (good.replace("path: dist/widget.bin", "path: state/widget.bin"), "safe relative path"), + (good.replace("runtime: wasm", "runtime: native"), "must be `wasm`"), + ] { + let p = widget_package_parse(&bad).unwrap(); + let e = widget_package_validate(&p, 1860, 2480).unwrap_err(); + assert!(e.contains(want), "{e}"); + } + } + + #[test] + fn a_package_declares_its_settings() { + let p = widget_package_parse(&manifest("com.example.test")).unwrap(); + assert_eq!(p.settings.len(), 2); + assert_eq!(p.settings[0].kind, WidgetSettingKind::Toggle); + assert_eq!(p.settings[0].default, "false"); + assert_eq!(p.settings[1].choices, ["compact", "large"]); + assert_eq!(p.settings[1].default, "large"); + assert_eq!(widget_setting_next(&p.settings[0], "false"), "true"); + assert_eq!(widget_setting_next(&p.settings[1], "large"), "compact"); + assert_eq!(widget_setting_next(&p.settings[1], "gone"), "compact"); + + let good = manifest("com.example.test"); + for (bad, want) in [ + (good.replace("type: toggle", "type: switch"), "`toggle` or `choice`"), + (good.replace("key: show_percent", "key: Show Percent"), "settings[0].key"), + (good.replace("key: layout", "key: show_percent"), "used twice"), + (good.replace("default: large", "default: wide"), "not one of its choices"), + (good.replace("choices: [compact, large]", "choices: [compact]"), "needs 2"), + ] { + let e = widget_package_parse(&bad).unwrap_err(); + assert!(e.contains(want), "{e}"); + } + } + + #[test] + fn settings_load_save_and_fall_back_to_defaults() { + ui_init(300.0); + let root = std::env::temp_dir().join(format!("grimoire-widget-settings-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + assert_eq!(store_init(root.to_str().unwrap()), 0); + let m = manifest("com.example.test"); + let it = widget_package_install(&m, b"test", "https://example.org/p.yaml", 1860, 2480).unwrap(); + let schema = widget_package_installed_manifest(&it.id).unwrap().settings; + let defaults = widget_settings_defaults(&schema); + assert_eq!(widget_settings_load(&it.id, &schema), defaults); + assert_eq!(widget_settings_save(&it.id, &defaults), 0); + assert_eq!(widget_settings_load(&it.id, &schema), defaults); + + let changed = vec![ + ("show_percent".to_string(), "true".to_string()), + ("layout".to_string(), "compact".to_string()), + ]; + assert_eq!(widget_settings_save(&it.id, &changed), 0); + assert_eq!(widget_settings_load(&it.id, &schema), changed); + assert_eq!(widget_setting_value(&changed, "layout", "large"), "compact"); + assert_eq!(widget_setting_value(&changed, "missing", "fallback"), "fallback"); + + // The state folder carries the values through an update and a remove that keeps state. + let m2 = m.replace("version: 1.2.0", "version: 1.3.0"); + widget_package_install(&m2, b"test", "https://example.org/p.yaml", 1860, 2480).unwrap(); + assert_eq!(widget_settings_load(&it.id, &schema), changed); + widget_package_remove(&it.id, true).unwrap(); + widget_package_install(&m2, b"test", "https://example.org/p.yaml", 1860, 2480).unwrap(); + assert_eq!(widget_settings_load(&it.id, &schema), changed); + assert_eq!(widget_settings_clear(&it.id), 0); + assert_eq!(widget_settings_load(&it.id, &schema), defaults); + + // A hand-edited value the manifest no longer offers reads as its default. + std::fs::write( + widget_settings_path(&it.id), + br#"{"version":1,"values":{"show_percent":"maybe","layout":"wide","old":"x"}}"#, + ) + .unwrap(); + assert_eq!(widget_settings_load(&it.id, &schema), defaults); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn repository_inputs_resolve_to_yaml() { + let (u, short) = widget_manifest_url("jane/widgets").unwrap(); + assert!(short); + assert_eq!(u, "https://raw.githubusercontent.com/jane/widgets/main/package.yaml"); + let (u, short) = widget_manifest_url("https://example.org/w.yaml").unwrap(); + assert!(!short); + assert_eq!(u, "https://example.org/w.yaml"); + assert!(widget_manifest_url("https://example.org/w.zip").is_err()); + assert!(widget_manifest_url("jane").is_err()); + assert_eq!(widget_github_branch(r#"{"default_branch":"trunk"}"#).as_deref(), Some("trunk")); + } + + #[test] + fn only_github_addresses_name_a_repository() { + for (source, want) in [ + ("jane/widgets", Some("jane/widgets")), + ("https://github.com/jane/widgets", Some("jane/widgets")), + ("https://github.com/jane/widgets.git", Some("jane/widgets")), + ("https://github.com/jane/widgets/tree/main", Some("jane/widgets")), + ("https://raw.githubusercontent.com/jane/widgets/main/package.yaml", Some("jane/widgets")), + ("https://example.org/widgets", None), + ("https://example.org/w.yaml", None), + ("/home/me/widgets", None), + ("jane", None), + ] { + assert_eq!(widget_github_repo(source).as_deref(), want, "{source}"); + } + assert_eq!(widget_github_repo_url("jane/widgets").as_deref(), Some("https://github.com/jane/widgets")); + assert!(widget_github_repo_url("https://example.org/widgets").is_none()); + } + + #[test] + fn a_package_installs_replaces_and_removes() { + ui_init(300.0); + let root = std::env::temp_dir().join(format!("grimoire-widgetpkg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + assert_eq!(store_init(root.to_str().unwrap()), 0); + let m = manifest("com.example.test"); + let it = widget_package_install(&m, b"test", "https://example.org/p.yaml", 1860, 2480).unwrap(); + assert_eq!(it.version, "1.2.0"); + assert!(std::fs::metadata(format!("{}/package.yaml", widget_package_dir(&it.id))).is_ok()); + assert_eq!(widget_package_list().len(), 1); + assert_eq!(widget_package_defs().len(), 1); + let state = format!("{}/state", widget_package_dir(&it.id)); + std::fs::create_dir_all(&state).unwrap(); + std::fs::write(format!("{state}/session"), b"keep").unwrap(); + let m2 = m.replace("version: 1.2.0", "version: 1.3.0"); + let it = widget_package_install(&m2, b"test", "https://example.org/p.yaml", 1860, 2480).unwrap(); + assert_eq!(it.version, "1.3.0"); + assert_eq!(widget_package_list().len(), 1); + assert_eq!(widget_def(&it.id).unwrap().icon, IconKind::Grid); + assert_eq!(std::fs::read(format!("{state}/session")).unwrap(), b"keep"); + widget_package_remove(&it.id, true).unwrap(); + assert!(widget_package_list().is_empty()); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/rust/src/widgetpkgui.rs b/rust/src/widgetpkgui.rs new file mode 100644 index 00000000..c033e5a5 --- /dev/null +++ b/rust/src/widgetpkgui.rs @@ -0,0 +1,1388 @@ +//! The Settings → Packages → Widgets page (issue #200): the widget package manager. +//! +//! Installed packages are rows, as every Settings submenu's are. Install from a repository, +//! trust and license are asked before anything is written, and Remove and Check for updates are +//! here too. The page draws with the Settings page's header, Back and X, and pages long lists +//! with `ui_row_page`; it is not a separate editor overlay. +//! +//! The state lives on `App` (`pkg`) because Settings can be opened over the Library or over a +//! notebook. Its fetch runs in a child and is polled from the library tick, so no contact waits +//! on the network. + +use crate::prelude::*; + +const H_CLOSE: i32 = 1; +const H_ROW: i32 = 2; +const H_INSTALL: i32 = 100; +const H_BACK: i32 = 101; +const H_REMOVE: i32 = 102; +const H_REMOVE_YES: i32 = 103; +const H_TRUST: i32 = 105; +const H_LICENSE_YES: i32 = 106; +const H_UPDATE: i32 = 108; +const H_PREV: i32 = 109; +const H_NEXT: i32 = 110; +const H_UPDATE_ALL: i32 = 111; +const H_LICENSE_VIEW: i32 = 112; +const H_QR: i32 = 113; +const H_LICENSE_PREV: i32 = 114; +const H_LICENSE_NEXT: i32 = 115; +const H_SETTINGS: i32 = 116; +const H_SETTING: i32 = 117; +const H_SETTINGS_RESET: i32 = 118; +const H_SETTINGS_PREV: i32 = 119; +const H_SETTINGS_NEXT: i32 = 120; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PkgView { + #[default] + List, + Detail, + Install, + Busy, + Trust, + License, + Qr, + Remove, + Settings, + Error, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FetchStage { + Branch, + Manifest, + /// a license file named by the manifest or found beside it (one the manifest named must read, + /// one only discovered may be absent) + LicenseProbe, + Artifact, +} + +struct InstallJob { + stage: FetchStage, + fetch: WidgetFetch, + url: String, + input: String, + manifest_url: String, +} + +#[derive(Default)] +pub struct WidgetPkgUi { + pub open: bool, + pub view: PkgView, + pub kb: Keyboard, + pub items: Vec, + pub selected: Option, + page: i32, + pub hits: HitList, + press: Press, + /// the control under the contact and the pressed look it got, as every Settings row's + pressed: Option, + pressed_hit: Option, + pub status: String, + pub error: String, + /// the manifest being installed or updated, once its repository answered + manifest: Option, + /// the repository address the manifest and artifact came from + manifest_url: String, + /// the manifest's bytes as fetched, kept for the install after consent + manifest_yaml: String, + /// the repository input the install started with + input: String, + /// the manifest is for the selected package's Check for updates, not a new install + updating: bool, + artifact_url: String, + license_url: String, + license_text: String, + /// the selected package's own manifest, re-read when its detail page opens (its author and + /// license are not all in the index) + detail_manifest: Option, + /// the license files to try, how many were tried, and whether they were only a search (a + /// LICENSE file beside the manifest) rather than a license_url the manifest promised + license_candidates: Vec, + license_try: usize, + license_required: bool, + /// the License page was opened from the detail page's View license, not the install flow + license_viewer: bool, + /// the package whose license text is loaded, so a second View license does not fetch again + license_for: String, + /// the license text's page (0-based), for a license longer than one page + license_page: i32, + /// the GitHub repository page the QR view shows + qr_url: String, + /// the settings page's manifest schema and current values, in schema order + setting_schema: Vec, + setting_values: Vec<(String, String)>, + setting_page: i32, + job: Option, + /// Update all: the packages left to check, how many were updated and failed, and the last + /// failure's text (the summary names it if nothing updated). + update_all: bool, + update_queue: Vec, + update_pos: usize, + update_ok: i32, + update_failed: i32, + update_note: String, + /// the page's rect, for feedback and redraw + pub rect: Rect, +} + +impl WidgetPkgUi { + fn refresh(&mut self) { + self.items = widget_package_list(); + } +} + +/// Opens Settings → Packages → Widgets. The caller has Settings open (library.rs): closing this +/// page comes back to it, not out of Settings. +pub fn packages_ui_open(a: &mut App) { + let ui = &mut a.pkg; + ui.open = true; + ui.view = PkgView::List; + ui.status.clear(); + ui.error.clear(); + ui.selected = None; + ui.page = 0; + ui.license_text.clear(); + ui.detail_manifest = None; + ui.license_candidates.clear(); + ui.license_try = 0; + ui.license_required = false; + ui.license_viewer = false; + ui.license_for.clear(); + ui.license_page = 0; + ui.qr_url.clear(); + ui.setting_schema.clear(); + ui.setting_values.clear(); + ui.setting_page = 0; + ui.manifest = None; + ui.manifest_yaml.clear(); + ui.input.clear(); + ui.updating = false; + ui.job = None; + ui.pressed = None; + ui.pressed_hit = None; + ui.update_all = false; + ui.update_queue.clear(); + ui.update_pos = 0; + ui.update_ok = 0; + ui.update_failed = 0; + ui.update_note.clear(); + ui.refresh(); + crate::library::packages_redraw(a); +} + +fn clear_update_all(ui: &mut WidgetPkgUi) { + ui.update_all = false; + ui.update_queue.clear(); + ui.update_pos = 0; + ui.update_ok = 0; + ui.update_failed = 0; + ui.update_note.clear(); +} + +fn close(a: &mut App) { + let ui = &mut a.pkg; + ui.open = false; + ui.job = None; + clear_update_all(ui); + keyboard_close(&mut ui.kb); + crate::library::packages_closed(a); +} + +/// Back from the first page: Settings itself, as a Settings submenu's Back does. +fn back_to_settings(a: &mut App) { + let ui = &mut a.pkg; + ui.open = false; + ui.job = None; + clear_update_all(ui); + keyboard_close(&mut ui.kb); + crate::library::packages_redraw(a); +} + +fn redraw(a: &mut App) { + crate::library::packages_redraw(a); +} + +/// A row's label from two parts, with the version in parentheses. +fn labeled(name: &str, version: &str) -> String { + if version.is_empty() { + name.to_string() + } else { + format!("{name} ({version})") + } +} + +/// A package's own icon: the manifest's name, else its widget definition's (an installed package +/// whose index entry was written before icons still shows the definition's icon), else the grid. +fn install_icon(it: &WidgetInstall) -> IconKind { + if !it.icon.trim().is_empty() { + return widget_icon(&it.icon); + } + widget_def(&it.id).map_or(IconKind::Grid, |d| d.icon) +} + +fn setting_icon(s: &WidgetSetting) -> IconKind { + if s.icon.trim().is_empty() { IconKind::Gear } else { widget_icon(&s.icon) } +} + +fn stage_status(stage: FetchStage, of: Option<(usize, usize)>) -> String { + let what = match stage { + FetchStage::Branch => tr("Looking up the repository..."), + FetchStage::Manifest => tr("Reading package.yaml..."), + FetchStage::LicenseProbe => tr("Reading the license..."), + FetchStage::Artifact => tr("Downloading the widget..."), + }; + match of { + Some((n, all)) => format!("{what} ({n}/{all})"), + None => what.to_string(), + } +} + +/// Starts a fetch and makes the page Busy. Err leaves the page as it was: a caller that has more to +/// do (Update all) counts it, and one that does not shows it (start_job). +fn new_job(ui: &mut WidgetPkgUi, stage: FetchStage, url: &str, input: &str, manifest_url: &str, of: Option<(usize, usize)>) -> Result<(), String> { + let cap = if stage == FetchStage::Artifact { WIDGET_PKG_ARTIFACT_MAX as usize } else { 512 * 1024 }; + let fetch = WidgetFetch::start(url, cap)?; + ui.status = stage_status(stage, of); + ui.view = PkgView::Busy; + ui.job = Some(InstallJob { + stage, + fetch, + url: url.to_string(), + input: input.to_string(), + manifest_url: manifest_url.to_string(), + }); + Ok(()) +} + +fn start_job(ui: &mut WidgetPkgUi, stage: FetchStage, url: String, input: &str, manifest_url: &str) { + if let Err(e) = new_job(ui, stage, &url, input, manifest_url, None) { + ui.error = e; + ui.view = PkgView::Error; + ui.job = None; + } +} + +/// The license files a repository may keep beside its manifest, in the order tried. +const LICENSE_FILES: [&str; 5] = ["LICENSE", "LICENSE.md", "LICENSE.txt", "COPYING", "COPYING.md"]; + +fn license_urls(base: &str) -> Vec { + LICENSE_FILES.iter().map(|name| format!("{base}/{name}")).collect() +} + +/// The license files to try for a manifest that is being installed. A `license_url` is the only +/// answer; a manifest that names a license (`license: MIT`) but no URL gets its repository's +/// LICENSE file, so the agreement shows without the author having to write the URL. +fn manifest_license_candidates(manifest_url: &str, p: &WidgetPackage) -> Vec { + if !p.license_url.is_empty() { + return vec![p.license_url.clone()]; + } + if p.license.is_empty() { + return Vec::new(); + } + let base = manifest_url.rsplit_once('/').map_or("", |(b, _)| b); + if base.is_empty() { + return Vec::new(); + } + license_urls(base) +} + +/// The same for a package that is already installed: its `license_url`, else the LICENSE file of +/// the repository it came from (a direct `.yaml` address or a GitHub repository). +fn installed_license_candidates(source: &str, p: &WidgetPackage) -> Vec { + if !p.license_url.is_empty() { + return vec![p.license_url.clone()]; + } + if p.license.is_empty() { + return Vec::new(); + } + let s = source.trim(); + let mut out = Vec::new(); + if s.starts_with("https://") || s.starts_with("http://") { + let path = s.split(['?', '#']).next().unwrap_or(s); + if path.to_ascii_lowercase().ends_with(".yaml") { + if let Some((base, _)) = path.rsplit_once('/') { + out.extend(license_urls(base)); + } + return out; + } + } + if let Some(repo) = widget_github_repo(s) { + // (the branch the install used is not kept, so try GitHub's two usual defaults) + for branch in ["main", "master"] { + out.extend(license_urls(&format!("https://raw.githubusercontent.com/{repo}/{branch}"))); + } + } + out +} + +/// Starts the next license fetch. False when no candidate is left (or none starts at all). +fn start_next_license(ui: &mut WidgetPkgUi) -> bool { + while ui.license_try < ui.license_candidates.len() { + let url = ui.license_candidates[ui.license_try].clone(); + ui.license_try += 1; + let (input, manifest_url) = (ui.input.clone(), ui.manifest_url.clone()); + if new_job(ui, FetchStage::LicenseProbe, &url, &input, &manifest_url, None).is_ok() { + return true; + } + } + false +} + +/// No license file answered: the viewer says so, while an install goes on (the manifest only +/// named a license, not a file that must be read). +fn license_exhausted(ui: &mut WidgetPkgUi) { + ui.job = None; + if ui.license_viewer { + ui.license_text.clear(); + ui.view = PkgView::License; + } else { + start_artifact(ui); + } +} + +fn start_artifact(ui: &mut WidgetPkgUi) { + let url = ui.artifact_url.clone(); + let input = ui.input.clone(); + let manifest_url = ui.manifest_url.clone(); + start_job(ui, FetchStage::Artifact, url, &input, &manifest_url); +} + +fn begin_install(ui: &mut WidgetPkgUi, input: &str) { + let input = input.trim().to_string(); + ui.input = input.clone(); + ui.updating = false; + ui.update_all = false; + ui.license_viewer = false; + if input.is_empty() { + ui.error = "Enter a repository or a .yaml address.".into(); + ui.view = PkgView::Error; + return; + } + if let Some(api) = widget_github_api(&input) { + start_job(ui, FetchStage::Branch, api, &input, ""); + return; + } + match widget_manifest_url(&input) { + Ok((url, _)) => start_job(ui, FetchStage::Manifest, url.clone(), &input, &url), + Err(e) => { + ui.error = e; + ui.view = PkgView::Error; + } + } +} + +/// The repository address to check an installed package from. A package installed before the +/// index kept repositories may say `https://github.com/user/repo`: its manifest is the raw YAML +/// there, and the update asks the repository for its default branch first. +fn update_repo_input(source: &str) -> String { + let s = source.trim(); + let rest = s + .strip_prefix("https://github.com/") + .or_else(|| s.strip_prefix("http://github.com/")); + if let Some(rest) = rest { + let rest = rest.trim_end_matches('/'); + let rest = rest.strip_suffix(".git").unwrap_or(rest); + let parts: Vec<&str> = rest.split('/').filter(|p| !p.is_empty()).collect(); + if parts.len() == 2 { + return format!("{}/{}", parts[0], parts[1]); + } + } + s.to_string() +} + +/// Starts an update check from an installed package's repository (or its raw .yaml), resolving +/// GitHub's default branch when the source is a repository rather than a direct manifest. +fn start_update_fetch(ui: &mut WidgetPkgUi, input: &str, of: Option<(usize, usize)>) -> Result<(), String> { + ui.input = input.to_string(); + if let Some(api) = widget_github_api(input) { + return new_job(ui, FetchStage::Branch, &api, input, "", of); + } + let (url, _) = widget_manifest_url(input)?; + new_job(ui, FetchStage::Manifest, &url, input, &url, of) +} + +fn begin_update(ui: &mut WidgetPkgUi, it: &WidgetInstall) { + ui.updating = true; + ui.update_all = false; + ui.license_viewer = false; + if it.source_url.is_empty() { + ui.error = "This package was installed by hand; there is no repository to check.".into(); + ui.view = PkgView::Error; + return; + } + let input = update_repo_input(&it.source_url); + if let Err(e) = start_update_fetch(ui, &input, None) { + ui.error = e; + ui.view = PkgView::Error; + ui.job = None; + } +} + +/// Update all: checks every installed package that came from a repository, in list order, and +/// installs the newer ones as their manifests and artifacts arrive. The packages were trusted when +/// they were installed, so this does not ask again for each one. +fn begin_update_all(ui: &mut WidgetPkgUi) { + ui.updating = false; + ui.update_all = false; + ui.license_viewer = false; + ui.refresh(); + ui.update_queue = ui.items.iter().filter(|it| !it.source_url.is_empty()).cloned().collect(); + if ui.update_queue.is_empty() { + ui.status = "No widget packages have a repository to update from.".into(); + ui.view = PkgView::List; + return; + } + ui.update_all = true; + ui.update_pos = 0; + ui.update_ok = 0; + ui.update_failed = 0; + ui.update_note.clear(); + ui.selected = None; + ui.view = PkgView::Busy; + update_all_next(ui); +} + +fn update_all_next(ui: &mut WidgetPkgUi) { + while ui.update_pos < ui.update_queue.len() { + let it = ui.update_queue[ui.update_pos].clone(); + let n = ui.update_pos + 1; + let all = ui.update_queue.len(); + ui.update_pos += 1; + ui.status = format!("Checking {}... ({n}/{all})", it.name); + let input = update_repo_input(&it.source_url); + if let Err(e) = start_update_fetch(ui, &input, Some((n, all))) { + ui.update_failed += 1; + ui.update_note = e; + continue; + } + ui.status = format!("Checking {}... ({n}/{all})", it.name); + return; + } + update_all_done(ui); +} + +fn update_all_done(ui: &mut WidgetPkgUi) { + let (ok, failed) = (ui.update_ok, ui.update_failed); + let note = std::mem::take(&mut ui.update_note); + ui.update_all = false; + ui.update_queue.clear(); + ui.update_pos = 0; + ui.update_ok = 0; + ui.update_failed = 0; + ui.job = None; + ui.view = PkgView::List; + ui.selected = None; + ui.refresh(); + ui.status = if ok == 0 && failed == 0 { + "All widget packages are up to date.".into() + } else if failed == 0 { + format!("Updated {ok} widget package{}.", if ok == 1 { "" } else { "s" }) + } else if ok == 0 && !note.is_empty() { + format!("Could not update: {note}") + } else { + format!("Updated {ok} widget package{}; {failed} failed.", if ok == 1 { "" } else { "s" }) + }; +} + +fn after_manifest(ui: &mut WidgetPkgUi, data: &[u8], a: &App, manifest_url: &str) { + let text = String::from_utf8_lossy(data); + let p = match widget_package_parse(&text).and_then(|p| { + widget_package_validate(&p, a.w, a.h - status_reserved(a)).map(|_| p) + }) { + Ok(p) => p, + Err(e) => { + if ui.update_all { + ui.update_failed += 1; + ui.update_note = e; + update_all_next(ui); + } else { + ui.error = e; + ui.view = PkgView::Error; + } + return; + } + }; + let artifact = if let Some(u) = widget_package_artifact_url(manifest_url, &p) { + u + } else { + if ui.update_all { + ui.update_failed += 1; + ui.update_note = "The manifest names no artifact that can be downloaded.".into(); + update_all_next(ui); + } else { + ui.error = "The manifest names no artifact that can be downloaded.".into(); + ui.view = PkgView::Error; + } + return; + }; + if ui.update_all { + let Some(old) = ui.items.iter().find(|x| x.id == p.id).cloned() else { + // A repository may not turn an update into a new, untrusted package. + ui.update_failed += 1; + ui.update_note = "The repository no longer names the installed package.".into(); + update_all_next(ui); + return; + }; + if update_version_cmp(&p.version, &old.version) <= 0 { + ui.status = format!("{} is up to date.", old.name); + update_all_next(ui); + return; + } + ui.license_url = p.license_url.clone(); + ui.artifact_url = artifact.clone(); + ui.manifest_url = manifest_url.to_string(); + ui.manifest = Some(p); + ui.status.clear(); + let of = Some((ui.update_pos, ui.update_queue.len())); + let mu = manifest_url.to_string(); + if let Err(e) = new_job(ui, FetchStage::Artifact, &artifact, &mu, &mu, of) { + ui.update_failed += 1; + ui.update_note = e; + update_all_next(ui); + } + return; + } + if ui.updating { + if let Some(old) = widget_package_list().into_iter().find(|x| x.id == p.id) { + if update_version_cmp(&p.version, &old.version) <= 0 { + ui.status = format!("{} is up to date ({}).", old.name, old.version); + ui.view = PkgView::Detail; + return; + } + } + } + ui.license_candidates = manifest_license_candidates(manifest_url, &p); + ui.license_try = 0; + ui.license_required = !p.license_url.is_empty(); + ui.license_viewer = false; + ui.license_for.clear(); + ui.license_text.clear(); + ui.license_page = 0; + ui.license_url = p.license_url.clone(); + ui.artifact_url = artifact; + ui.manifest_url = manifest_url.to_string(); + ui.manifest = Some(p); + ui.status.clear(); + ui.view = PkgView::Trust; +} + +/// An open frame of a package that just changed takes the new definition now, not at its next open. +fn apply_new_def(a: &mut App, it: &WidgetInstall) { + if let Some(ed) = a.ed.as_deref_mut() { + if let Some(i) = ed.widgets.index_of(&it.id) { + if let Some(def) = widget_def(&it.id) { + ed.widgets.frames[i].def = def; + } + } + } +} + +fn after_artifact(ui: &mut WidgetPkgUi, data: &[u8], a: &mut App) { + if ui.manifest.is_none() || ui.manifest_yaml.is_empty() { + ui.error = "The package's manifest was lost.".into(); + ui.view = PkgView::Error; + return; + } + let manifest = ui.manifest_yaml.clone(); + let source = if ui.input.is_empty() { ui.manifest_url.as_str() } else { ui.input.as_str() }; + match widget_package_install(&manifest, data, source, a.w, a.h - status_reserved(a)) { + Ok(it) => { + apply_new_def(a, &it); + ui.status.clear(); + ui.view = PkgView::List; + ui.selected = None; + ui.refresh(); + } + Err(e) => { + ui.error = e; + ui.view = PkgView::Error; + } + } +} + +fn after_artifact_update_all(ui: &mut WidgetPkgUi, data: &[u8], a: &mut App) { + if ui.manifest.is_none() || ui.manifest_yaml.is_empty() { + ui.update_failed += 1; + ui.update_note = "The package's manifest was lost.".into(); + update_all_next(ui); + return; + } + let manifest = ui.manifest_yaml.clone(); + let source = if ui.input.is_empty() { ui.manifest_url.as_str() } else { ui.input.as_str() }; + match widget_package_install(&manifest, data, source, a.w, a.h - status_reserved(a)) { + Ok(it) => { + apply_new_def(a, &it); + ui.update_ok += 1; + update_all_next(ui); + } + Err(e) => { + ui.update_failed += 1; + ui.update_note = e; + update_all_next(ui); + } + } +} + +/// Polls the install's curl and runs the open keyboard's hold and settle timers, as every screen's +/// tick does. Called from the library tick. +pub fn packages_ui_tick(a: &mut App, now: u32) { + if !a.pkg.open { + return; + } + if a.pkg.kb.open { + // A key draws and refreshes only the keyboard (app_keyboard_pointer); this is its held + // delete's repeats and the one grayscale clean-up after typing pauses, as in every other + // keyboard. The page under it does not move while it is open. + let mut kb = std::mem::take(&mut a.pkg.kb); + app_keyboard_tick(a, &mut kb, now); + a.pkg.kb = kb; + return; + } + let mut ui = std::mem::take(&mut a.pkg); + let mut redraw_page = false; + if let Some(mut job) = ui.job.take() { + match job.fetch.tick() { + None => { + ui.job = Some(job); + } + Some(res) => { + redraw_page = true; + match res { + Err(e) => { + if ui.update_all { + ui.update_failed += 1; + ui.update_note = e; + update_all_next(&mut ui); + } else if job.stage == FetchStage::Branch { + // The GitHub API is an optimization: a failed lookup falls back to main. + let url = widget_manifest_url(&job.input).map(|(u, _)| u).unwrap_or_default(); + if !url.is_empty() { + start_job(&mut ui, FetchStage::Manifest, url.clone(), &job.input, &url); + } else { + ui.error = e; + ui.view = PkgView::Error; + } + } else if job.stage == FetchStage::LicenseProbe { + if ui.license_required { + ui.error = e; + ui.view = PkgView::Error; + } else if !start_next_license(&mut ui) { + license_exhausted(&mut ui); + } + } else { + ui.error = e; + ui.view = PkgView::Error; + } + } + Ok(data) => match job.stage { + FetchStage::Branch => { + let input = job.input.clone(); + let fallback = widget_manifest_url(&input).map(|(u, _)| u).unwrap_or_default(); + let url = widget_github_branch(&String::from_utf8_lossy(&data)) + .and_then(|b| { + let parts: Vec<&str> = input.split('/').collect(); + (parts.len() == 2).then(|| format!("https://raw.githubusercontent.com/{}/{}/{b}/package.yaml", parts[0], parts[1])) + }) + .unwrap_or(fallback); + if url.is_empty() { + ui.error = "That repository has no package.yaml.".into(); + ui.view = PkgView::Error; + } else { + start_job(&mut ui, FetchStage::Manifest, url.clone(), &input, &url); + } + } + FetchStage::Manifest => { + ui.input = job.input.clone(); + ui.manifest_yaml = String::from_utf8_lossy(&data).into_owned(); + let mu = job.manifest_url.clone(); + after_manifest(&mut ui, &data, a, &mu); + } + FetchStage::LicenseProbe => { + ui.license_text = String::from_utf8_lossy(&data).into_owned(); + ui.license_url = job.url.clone(); + ui.license_page = 0; + ui.view = PkgView::License; + } + FetchStage::Artifact => { + if ui.update_all { + after_artifact_update_all(&mut ui, &data, a); + } else { + after_artifact(&mut ui, &data, a); + } + } + }, + } + } + } + } + a.pkg = ui; + if redraw_page { + crate::library::packages_redraw(a); + } +} + +fn close_or_cancel(a: &mut App) { + let mut ui = std::mem::take(&mut a.pkg); + match ui.view { + PkgView::List => { + a.pkg = ui; + back_to_settings(a); + return; + } + PkgView::Error => { + ui.error.clear(); + ui.view = PkgView::List; + } + PkgView::Settings => { + ui.view = PkgView::Detail; + ui.status.clear(); + ui.setting_page = 0; + } + PkgView::Detail | PkgView::Install | PkgView::Remove => { + ui.view = PkgView::List; + keyboard_close(&mut ui.kb); + ui.selected = None; + } + PkgView::Qr => { + ui.view = PkgView::Detail; + } + PkgView::License if ui.license_viewer => { + ui.view = PkgView::Detail; + ui.license_viewer = false; + ui.job = None; + } + PkgView::Trust | PkgView::License | PkgView::Busy => { + ui.view = PkgView::List; + ui.job = None; + clear_update_all(&mut ui); + ui.status.clear(); + ui.error.clear(); + } + } + a.pkg = ui; + redraw(a); +} + +fn do_tap(a: &mut App, h: Hit) { + let mut ui = std::mem::take(&mut a.pkg); + match h.id { + H_CLOSE => { + a.pkg = ui; + close(a); + return; + } + H_BACK => { + a.pkg = ui; + close_or_cancel(a); + return; + } + H_ROW => { + if let Some(it) = ui.items.get(h.arg as usize).cloned() { + ui.selected = Some(it.id.clone()); + ui.detail_manifest = widget_package_installed_manifest(&it.id); + ui.manifest = None; + ui.license_text.clear(); + ui.license_for.clear(); + ui.qr_url.clear(); + ui.setting_schema.clear(); + ui.setting_values.clear(); + ui.setting_page = 0; + ui.status.clear(); + ui.error.clear(); + ui.view = PkgView::Detail; + } + } + H_PREV => ui.page = (ui.page - 1).max(0), + H_NEXT => ui.page += 1, + H_SETTINGS_PREV => ui.setting_page = (ui.setting_page - 1).max(0), + H_SETTINGS_NEXT => ui.setting_page += 1, + H_INSTALL => { + ui.view = PkgView::Install; + ui.error.clear(); + keyboard_open(&mut ui.kb, tr("Widget repository"), b""); + } + H_TRUST => { + if !start_next_license(&mut ui) { + if ui.license_required { + ui.error = "The manifest's license address could not be fetched.".into(); + ui.view = PkgView::Error; + } else { + start_artifact(&mut ui); + } + } + } + H_LICENSE_YES => start_artifact(&mut ui), + H_LICENSE_VIEW => { + if let Some(it) = ui.items.iter().find(|x| Some(&x.id) == ui.selected.as_ref()).cloned() { + if ui.license_for == it.id && !ui.license_text.is_empty() { + ui.license_page = 0; + ui.view = PkgView::License; + ui.status.clear(); + } else { + ui.license_viewer = true; + ui.license_text.clear(); + ui.license_page = 0; + ui.license_for = it.id.clone(); + ui.status.clear(); + ui.error.clear(); + ui.license_candidates = widget_package_installed_manifest(&it.id) + .map(|m| installed_license_candidates(&it.source_url, &m)) + .unwrap_or_default(); + ui.license_try = 0; + ui.license_required = false; + if !start_next_license(&mut ui) { + ui.view = PkgView::License; + } + } + } + } + H_LICENSE_PREV => ui.license_page = (ui.license_page - 1).max(0), + H_LICENSE_NEXT => ui.license_page += 1, + H_QR => { + if let Some(it) = ui.items.iter().find(|x| Some(&x.id) == ui.selected.as_ref()).cloned() { + let repo = ui + .detail_manifest + .as_ref() + .and_then(|m| widget_github_repo_url(&m.repository)) + .or_else(|| widget_github_repo_url(&it.source_url)); + if let Some(url) = repo { + ui.qr_url = url; + ui.view = PkgView::Qr; + } + } + } + H_SETTINGS => { + if let Some(id) = ui.selected.clone() { + if let Some(m) = widget_package_installed_manifest(&id) { + if !m.settings.is_empty() { + ui.setting_schema = m.settings; + ui.setting_values = widget_settings_load(&id, &ui.setting_schema); + ui.setting_page = 0; + ui.status.clear(); + ui.view = PkgView::Settings; + } + } + } + } + H_SETTING => { + let at = h.arg as usize; + let Some(s) = ui.setting_schema.get(at).cloned() else { + a.pkg = ui; + return; + }; + let current = widget_setting_value(&ui.setting_values, &s.key, &s.default).to_string(); + let next = widget_setting_next(&s, ¤t); + if let Some(v) = ui.setting_values.iter_mut().find(|(k, _)| *k == s.key) { + v.1 = next; + } + if let Some(id) = ui.selected.clone() { + if widget_settings_save(&id, &ui.setting_values) == 0 { + ui.status.clear(); + if let Some(s) = a.ed.as_mut() { s.widgets.reload_settings(&id); } + } else { + ui.status = tr("Could not save the widget's settings.").to_string(); + } + } + } + H_SETTINGS_RESET => { + ui.setting_values = widget_settings_defaults(&ui.setting_schema); + if let Some(id) = ui.selected.clone() { + if widget_settings_clear(&id) == 0 { + ui.status = tr("Settings reset to defaults.").to_string(); + if let Some(s) = a.ed.as_mut() { s.widgets.reload_settings(&id); } + } else { + ui.status = tr("Could not save the widget's settings.").to_string(); + } + } + } + H_REMOVE => ui.view = PkgView::Remove, + H_REMOVE_YES => { + if let Some(id) = ui.selected.clone() { + match widget_package_remove(&id, true) { + Ok(()) => { + // An open frame goes with its package. + if let Some(ed) = a.ed.as_deref_mut() { + while let Some(i) = ed.widgets.index_of(&id) { + ed.widgets.close(i); + } + ed.widgets.save(); + } + ui.status.clear(); + ui.view = PkgView::List; + ui.selected = None; + ui.refresh(); + } + Err(e) => { + ui.error = e; + ui.view = PkgView::Error; + } + } + } + } + H_UPDATE => { + if let Some(it) = ui.items.iter().find(|x| Some(&x.id) == ui.selected.as_ref()).cloned() { + begin_update(&mut ui, &it); + } + } + H_UPDATE_ALL => begin_update_all(&mut ui), + _ => {} + } + a.pkg = ui; + redraw(a); +} + +pub fn packages_ui_pointer(a: &mut App, ph: i32, ev: &InEvent) { + if !a.pkg.open { + return; + } + if a.pkg.kb.open { + // Exactly what a key costs on the Library's keyboard: the text line and the key, each on its + // own fast refresh, and nothing at all for a sample that changed nothing. The page under it + // is drawn again only when the keyboard closes (Done or Cancel). + let mut ui = std::mem::take(&mut a.pkg); + let r = app_keyboard_pointer(a, &mut ui.kb, ph, ev); + let finished = r == KbResult::Done || r == KbResult::Cancel; + if finished { + keyboard_close(&mut ui.kb); + if r == KbResult::Done { + let text = ui.kb.text.as_str().to_string(); + begin_install(&mut ui, &text); + } else { + ui.view = PkgView::List; + } + } + a.pkg = ui; + if finished { + redraw(a); + } + return; + } + if ph == 0 { + press_begin(&mut a.pkg.press, ev.x, ev.y, ev.t_ms); + a.pkg.pressed = None; + a.pkg.pressed_hit = None; + // Exactly a Settings row's pressed look: the control under the contact, in the panel now. + if let Some(h) = hits_find(&a.pkg.hits, ev.x, ev.y).copied() { + app_press_feedback(a, h.r); + a.pkg.pressed = Some(h.r); + a.pkg.pressed_hit = Some(h); + } + return; + } + press_move(&mut a.pkg.press, ev.x, ev.y); + if ph != 2 { + return; + } + // The lift takes the pressed look off and refreshes only that row; a contact that moved or + // touched nothing does no more than that (the page is not drawn again). + let mut pressed = a.pkg.pressed.take(); + let back = app_press_release(a, &mut pressed); + let cancelled = touch_cancelled(ev); + let hit = a.pkg.pressed_hit.take().filter(|h| !cancelled && press_is_tap(&a.pkg.press, h.r)); + if let Some(h) = hit { + do_tap(a, h); + return; + } + if !rect_is_empty(back) { + app_invalidate(a, back, RefreshMode::Ui); + } +} + +fn draw_actions(c: &mut Canvas, ui: &mut WidgetPkgUi, area: Rect, start_y: i32, labels: &[(&str, IconKind, i32)]) { + let bh = ui_px(112.0); + let gap = ui_px(18.0); + let mut y = start_y; + for (label, icon, id) in labels { + if y + bh > area.y + area.h { + break; + } + let r = Rect { x: area.x, y, w: area.w, h: bh }; + let row = Row::new(*icon, *label); + ui_row(c, r, &row); + hits_add(&mut ui.hits, r, *id, 0); + y += bh + gap; + } +} + +fn body_text(c: &mut Canvas, r: Rect, text: &str) { + ui_text(c, FontFace::Regular, ui_text_size(), ui_small_size(), r, text, 12, false, 0); +} + +/// One action row, disabled (and without a hit) when `enabled` is false, as a pager's end arrow. +fn action_row(c: &mut Canvas, ui: &mut WidgetPkgUi, r: Rect, label: &str, icon: IconKind, id: i32, enabled: bool) { + let mut row = Row::new(icon, label); + if !enabled { + row.style = ButtonStyle::Disabled; + } + ui_row(c, r, &row); + if enabled { + hits_add(&mut ui.hits, r, id, 0); + } +} + +/// A license's text as lines that fit `width` at `px`, at its own line breaks (a license therefore +/// keeps its paragraphs instead of shrinking to one size-fit block). A word longer than the page is +/// broken between its characters. +fn license_lines(text: &str, px: f32, width: i32) -> Vec { + let f = FontFace::Regular; + let space = font_measure(f, px, " "); + let mut out: Vec = Vec::new(); + for raw in text.lines() { + let raw = raw.trim_end_matches('\r'); + if raw.trim().is_empty() { + out.push(String::new()); + continue; + } + let mut line = String::new(); + let mut w = 0i32; + for word in raw.split_whitespace() { + let ww = font_measure(f, px, word); + if !line.is_empty() && w + space + ww > width { + out.push(std::mem::take(&mut line)); + w = 0; + } + if !line.is_empty() { + line.push(' '); + w += space; + } + if ww <= width { + line.push_str(word); + w += ww; + continue; + } + let mut rest = word; + while font_measure(f, px, rest) > width { + let mut cut = 0usize; + for (i, _) in rest.char_indices().skip(1) { + if font_measure(f, px, &rest[..i]) > width { + break; + } + cut = i; + } + if cut == 0 { + break; + } + out.push(rest[..cut].to_string()); + rest = &rest[cut..]; + } + line.push_str(rest); + w = font_measure(f, px, rest); + } + out.push(line); + } + if out.is_empty() { + out.push(String::new()); + } + out +} + +pub fn packages_ui_draw(a: &mut App) { + if !a.pkg.open { + return; + } + let screen = Rect { x: 0, y: 0, w: a.w, h: a.h }; + let title = match a.pkg.view { + PkgView::List | PkgView::Error => tr("Widgets"), + PkgView::Detail => tr("Widget package"), + PkgView::Install => tr("Install a widget"), + PkgView::Busy if a.pkg.license_viewer => tr("License"), + PkgView::Busy => tr("Installing"), + PkgView::Trust => tr("Install this widget?"), + PkgView::License if a.pkg.license_viewer => tr("License"), + PkgView::License => tr("License agreement"), + PkgView::Qr => tr("Repository"), + PkgView::Remove => tr("Remove this package?"), + PkgView::Settings => tr("Widget settings"), + }; + let App { screen: c, pkg: ui, .. } = a; + ui.hits.h.clear(); + let page = crate::library::settings_page(c, a.w, a.h, title, true, false); + hits_add(&mut ui.hits, page.back, H_BACK, 0); + hits_add(&mut ui.hits, page.close, H_CLOSE, 0); + ui.rect = Rect { x: 0, y: 0, w: a.w, h: a.h }; + let content = page.content; + let bottom = if ui.kb.open { ui.kb.area.y - ui_px(12.0) } else { content.y + content.h }; + match ui.view { + PkgView::List => { + let n = ui.items.len(); + let actions = 2 + n; + let rows_area = Rect { x: content.x, y: content.y, w: content.w, h: bottom - content.y }; + let list = ui_row_page(rows_area, actions, ui.page, ui_px(118.0), ui_px(74.0)); + ui.page = list.page; + for (i, rr) in list.rows.iter().enumerate() { + let k = list.first + i; + if k == 0 { + // The one package-list-wide action, above the packages it updates. + let row = Row::new(IconKind::Update, tr("Update all")); + ui_row(c, *rr, &row); + hits_add(&mut ui.hits, *rr, H_UPDATE_ALL, 0); + } else if k == 1 { + let row = Row::new(IconKind::Download, tr("Install from repository...")); + ui_row(c, *rr, &row); + hits_add(&mut ui.hits, *rr, H_INSTALL, 0); + } else if let Some(it) = ui.items.get(k - 2) { + let label = labeled(&it.name, &it.version); + let row = Row::new(install_icon(it), &label); + ui_row(c, *rr, &row); + hits_add(&mut ui.hits, *rr, H_ROW, (k - 2) as i32); + } + } + ui_row_pager(c, &list); + if list.page > 0 { + hits_add(&mut ui.hits, list.prev, H_PREV, 0); + } + if list.page + 1 < list.pages { + hits_add(&mut ui.hits, list.next, H_NEXT, 0); + } + if ui.items.is_empty() { + // Below both actions: the message used to start inside Install from repository. + let y = list.rows.last().map(|r| r.y + r.h + ui_px(24.0)).unwrap_or(content.y); + ui_text(c, FontFace::Regular, ui_small_size(), ui_small_size(), Rect { x: content.x, y, w: content.w, h: ui_px(100.0) }, tr("No widget packages are installed."), 2, false, 120); + } + } + PkgView::Detail => { + let Some(it) = ui.items.iter().find(|x| Some(&x.id) == ui.selected.as_ref()).cloned() else { + ui.view = PkgView::List; + return; + }; + let title = labeled(&it.name, &it.version); + let icon = Rect { x: content.x, y: content.y, w: ui_px(58.0), h: ui_px(58.0) }; + ui_icon(c, install_icon(&it), icon, 0); + let tx = icon.x + icon.w + ui_px(18.0); + ui_text(c, FontFace::Bold, ui_text_size(), ui_small_size(), Rect { x: tx, y: content.y, w: content.w - (tx - content.x), h: ui_px(78.0) }, &title, 1, false, 0); + let m = ui.detail_manifest.as_ref(); + let author = m.map(|m| m.author.as_str()).filter(|s| !s.is_empty()).unwrap_or(&it.author); + let license = m.map(|m| m.license.as_str()).unwrap_or(""); + let source = m.map(|m| m.repository.as_str()).filter(|s| !s.is_empty()).unwrap_or(&it.source_url); + let repo = widget_github_repo_url(source).unwrap_or_else(|| source.to_string()); + let github = m.and_then(|m| widget_github_repo_url(&m.repository)).or_else(|| widget_github_repo_url(&it.source_url)); + let mut line = String::new(); + let mut y = content.y + ui_px(82.0); + if !author.is_empty() { + csnprintf!(&mut line, 512, "%s %s", tr("Author:"), author); + body_text(c, Rect { x: content.x, y, w: content.w, h: ui_px(46.0) }, &line); + y += ui_px(48.0); + } + if !it.description.is_empty() { + body_text(c, Rect { x: content.x, y, w: content.w, h: ui_px(100.0) }, &it.description); + y += ui_px(104.0); + } + if !license.is_empty() { + csnprintf!(&mut line, 512, "%s %s", tr("License:"), license); + body_text(c, Rect { x: content.x, y, w: content.w, h: ui_px(46.0) }, &line); + y += ui_px(48.0); + } + if !repo.is_empty() { + csnprintf!(&mut line, 1100, "%s %s", tr("Repository:"), &repo); + body_text(c, Rect { x: content.x, y, w: content.w, h: ui_px(46.0) }, &line); + y += ui_px(48.0); + } + if !ui.status.is_empty() { + // Its own row above the actions: the buttons used to start inside this text. + body_text(c, Rect { x: content.x, y, w: content.w, h: ui_px(70.0) }, &ui.status); + y += ui_px(70.0); + } + let mut actions: Vec<(&str, IconKind, i32)> = Vec::new(); + if m.is_some_and(|m| !m.settings.is_empty()) { + actions.push((tr("Settings..."), IconKind::Gear, H_SETTINGS)); + } + actions.push((tr("Check for updates"), IconKind::Update, H_UPDATE)); + if !license.is_empty() || m.is_some_and(|m| !m.license_url.is_empty()) { + actions.push((tr("View license"), IconKind::Paper, H_LICENSE_VIEW)); + } + if github.is_some() { + actions.push((tr("View QR code"), IconKind::Link, H_QR)); + } + actions.push((tr("Remove..."), IconKind::Close, H_REMOVE)); + draw_actions(c, ui, Rect { x: content.x, y: content.y, w: content.w, h: bottom - content.y }, y + ui_px(20.0), &actions); + } + PkgView::Install => { + // The repository is typed on the one global keyboard: its text line above the keys is the + // field, as on every other keyboard, and its Done starts the install. No second text box. + body_text(c, Rect { x: content.x, y: content.y, w: content.w, h: ui_px(210.0) }, tr("Enter a GitHub repository as user/repo, or an https address ending in .yaml.")); + body_text(c, Rect { x: content.x, y: content.y + ui_px(220.0), w: content.w, h: ui_px(80.0) }, tr("Tap Done on the keyboard to install.")); + } + PkgView::Busy => { + body_text(c, Rect { x: content.x, y: content.y, w: content.w, h: ui_px(220.0) }, &ui.status); + } + PkgView::Trust => { + let m = ui.manifest.clone().unwrap_or_default(); + let mut text = String::new(); + csnprintf!(&mut text, 1000, "%s by %s, version %s.\n\nYou MUST trust the author of this package. Grimoire does not review, vet, or verify widget code and is not responsible for any damage, data loss, or malfunction caused by installing or running it.", &m.name, &m.author, &m.version); + body_text(c, Rect { x: content.x, y: content.y, w: content.w, h: ui_px(520.0) }, &text); + draw_actions(c, ui, Rect { x: content.x, y: content.y, w: content.w, h: bottom - content.y }, content.y + ui_px(560.0), &[ + (tr("I trust this author, continue"), IconKind::Download, H_TRUST), + ]); + } + PkgView::License => { + let name = ui + .manifest + .as_ref() + .map(|m| m.license.as_str()) + .or_else(|| ui.detail_manifest.as_ref().map(|m| m.license.as_str())) + .unwrap_or(""); + let head = if name.is_empty() { tr("License").to_string() } else { name.to_string() }; + ui_text(c, FontFace::Bold, ui_small_size(), ui_small_size(), Rect { x: content.x, y: content.y, w: content.w, h: ui_px(80.0) }, &head, 2, false, 0); + let text = if ui.license_text.is_empty() { + tr("No license text was found in the repository.") + } else { + ui.license_text.as_str() + }; + let px = ui_text_size(); + let line_h = (font_ascent(FontFace::Regular, px) + font_descent(FontFace::Regular, px)).max(1); + let bh = ui_px(112.0); + let gap = ui_px(18.0); + // The pager (two rows) and an agreement's button keep their room, so the text never + // runs under them. + let reserve_rows = if ui.license_viewer { 2 } else { 3 }; + let reserve = reserve_rows * bh + (reserve_rows - 1) * gap + ui_px(16.0); + let body = Rect { + x: content.x, + y: content.y + ui_px(80.0), + w: content.w, + h: (bottom - content.y - ui_px(80.0) - reserve).max(line_h), + }; + let lines = license_lines(text, px, content.w); + let per = (body.h / line_h).max(1); + let pages = (((lines.len() as i32) + per - 1) / per).max(1); + let page = ui.license_page.clamp(0, pages - 1); + ui.license_page = page; + let from = page as usize * per as usize; + let to = (from + per as usize).min(lines.len()); + for (i, line) in lines[from..to].iter().enumerate() { + font_draw_left(c, FontFace::Regular, px, Rect { x: body.x, y: body.y + i as i32 * line_h, w: body.w, h: line_h }, line, 0); + } + let rows = (if pages > 1 { 2 } else { 0 }) + i32::from(!ui.license_viewer); + if rows > 0 { + let mut y = bottom - (rows * bh + (rows - 1) * gap); + if pages > 1 { + action_row(c, ui, Rect { x: content.x, y, w: content.w, h: bh }, tr("Previous page"), IconKind::Prev, H_LICENSE_PREV, page > 0); + y += bh + gap; + action_row(c, ui, Rect { x: content.x, y, w: content.w, h: bh }, tr("Next page"), IconKind::Next, H_LICENSE_NEXT, page + 1 < pages); + y += bh + gap; + } + if !ui.license_viewer { + action_row(c, ui, Rect { x: content.x, y, w: content.w, h: bh }, tr("I have read and agree"), IconKind::Download, H_LICENSE_YES, true); + } + } + } + PkgView::Qr => { + font_draw_left(c, FontFace::Regular, ui_text_size(), Rect { x: content.x, y: content.y, w: content.w, h: ui_px(70.0) }, tr("Scan with a phone's camera"), 0); + let top = content.y + ui_px(110.0); + let side = (bottom - top - ui_px(170.0)).max(0).min(content.w); + let sym = crate::qr::ui_qr(c, Rect { x: content.x + (content.w - side) / 2, y: top, w: side, h: side }, &ui.qr_url, false); + let ty = if rect_is_empty(sym) { top } else { sym.y + sym.h + ui_px(30.0) }; + ui_text(c, FontFace::Regular, ui_text_size(), ui_small_size(), Rect { x: content.x, y: ty, w: content.w, h: ui_px(90.0) }, &ui.qr_url, 2, true, 0); + } + PkgView::Settings => { + let schema = ui.setting_schema.clone(); + let values = ui.setting_values.clone(); + let n = schema.len() + 1; + let hint = if ui.status.is_empty() { + tr("Changes are saved on this Kindle.").to_string() + } else { + ui.status.clone() + }; + body_text(c, Rect { x: content.x, y: content.y, w: content.w, h: ui_px(60.0) }, &hint); + let top = content.y + ui_px(70.0); + let rows_area = Rect { x: content.x, y: top, w: content.w, h: bottom - top }; + let list = ui_row_page(rows_area, n, ui.setting_page, ui_px(118.0), ui_px(74.0)); + ui.setting_page = list.page; + for (i, rr) in list.rows.iter().enumerate() { + let k = list.first + i; + if let Some(s) = schema.get(k) { + let value = widget_setting_value(&values, &s.key, &s.default); + match s.kind { + WidgetSettingKind::Toggle => { + let row = Row::toggled(setting_icon(s), &s.label, value == "true"); + ui_row(c, *rr, &row); + } + WidgetSettingKind::Choice => { + let label = format!("{}: {}", s.label, value); + let row = Row::new(setting_icon(s), &label); + ui_row(c, *rr, &row); + } + } + hits_add(&mut ui.hits, *rr, H_SETTING, k as i32); + } else { + let row = Row::new(IconKind::Update, tr("Reset all to defaults")); + ui_row(c, *rr, &row); + hits_add(&mut ui.hits, *rr, H_SETTINGS_RESET, 0); + } + } + ui_row_pager(c, &list); + if list.page > 0 { + hits_add(&mut ui.hits, list.prev, H_SETTINGS_PREV, 0); + } + if list.page + 1 < list.pages { + hits_add(&mut ui.hits, list.next, H_SETTINGS_NEXT, 0); + } + } + PkgView::Remove => { + let name = ui.items.iter().find(|x| Some(&x.id) == ui.selected.as_ref()).map(|x| x.name.clone()).unwrap_or_default(); + let text = format!("Remove {name}? Its widget is closed and its files are deleted. Your layout is kept."); + body_text(c, Rect { x: content.x, y: content.y, w: content.w, h: ui_px(200.0) }, &text); + draw_actions(c, ui, Rect { x: content.x, y: content.y, w: content.w, h: bottom - content.y }, content.y + ui_px(230.0), &[ + (tr("Remove"), IconKind::Close, H_REMOVE_YES), + ]); + } + PkgView::Error => { + body_text(c, Rect { x: content.x, y: content.y, w: content.w, h: ui_px(300.0) }, &ui.error); + } + } + if !ui.status.is_empty() && ui.view == PkgView::List { + ui_text(c, FontFace::Regular, ui_small_size(), ui_small_size(), Rect { x: content.x, y: bottom - ui_px(70.0), w: content.w, h: ui_px(60.0) }, &ui.status, 1, false, 90); + } + if ui.kb.open { + let kr = keyboard_draw(&mut ui.kb, c, screen); + ui.rect = rect_union(ui.rect, kr); + } +} + +/// A named control on the Packages page, for the scenario runner (`tap panel packages.install`). +pub fn packages_ui_control_point(ui: &WidgetPkgUi, name: &str) -> Option<(f32, f32)> { + let id = match name { + "close" => H_CLOSE, + "install" => H_INSTALL, + "update-all" => H_UPDATE_ALL, + "trust" => H_TRUST, + "license-yes" => H_LICENSE_YES, + "license-view" => H_LICENSE_VIEW, + "license-prev" => H_LICENSE_PREV, + "license-next" => H_LICENSE_NEXT, + "qr" => H_QR, + "remove" => H_REMOVE, + "remove-yes" => H_REMOVE_YES, + "update" => H_UPDATE, + "settings" => H_SETTINGS, + "settings-reset" => H_SETTINGS_RESET, + "back" => H_BACK, + _ => { + if let Some(key) = name.strip_prefix("setting.") { + let at = key.parse::().ok() + .or_else(|| ui.setting_schema.iter().position(|s| s.key == key))? as i32; + if at as usize >= ui.setting_schema.len() { return None; } + return ui.hits.h.iter().find(|h| h.id == H_SETTING && h.arg == at).map(|h| ((h.r.x + h.r.w / 2) as f32, (h.r.y + h.r.h / 2) as f32)); + } + let id = name.strip_prefix("row.")?; + let i = id.parse::().ok() + .or_else(|| ui.items.iter().position(|x| x.id == id))? as i32; + if i as usize >= ui.items.len() { return None; } + return ui.hits.h.iter().find(|h| h.id == H_ROW && h.arg == i).map(|h| ((h.r.x + h.r.w / 2) as f32, (h.r.y + h.r.h / 2) as f32)); + } + }; + ui.hits.h.iter().find(|h| h.id == id).map(|h| ((h.r.x + h.r.w / 2) as f32, (h.r.y + h.r.h / 2) as f32)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn labels_carry_the_version_only_when_there_is_one() { + assert_eq!(labeled("Timer", "1.0.0"), "Timer (1.0.0)"); + assert_eq!(labeled("Timer", ""), "Timer"); + } +} diff --git a/rust/src/widgets.rs b/rust/src/widgets.rs new file mode 100644 index 00000000..49c89366 --- /dev/null +++ b/rust/src/widgets.rs @@ -0,0 +1,595 @@ +//! widgets.c: the editor's widget windows and their layout. +//! +//! Every widget comes from an installed package (widgetpkg.rs). A widget is a small window on the +//! editor canvas: it can be raised, dragged by its title bar, minimized, resized from its +//! bottom-right grip, and closed. Its place and size are kept in widgets.ini at the store root, so +//! they come back on the next launch. +//! +//! The module is geometry, frame state and the runtime handle. editor.rs draws the frames and +//! routes input; widgetwasm.rs runs the package's WebAssembly. + +use crate::prelude::*; + +/// The most widgets that can be open at once. +pub const WIDGETS_MAX: usize = 8; +/// The square a minimized widget takes, at 300 dpi. +const WIDGET_MINIMIZED: f32 = 112.0; +/// How far from the canvas edge a new widget starts. +const WIDGET_MARGIN: f32 = 28.0; +/// How far each new widget is offset from the one before it. +const WIDGET_CASCADE: f32 = 22.0; +/// The smallest frame the editor will make, whatever a widget asks for, at 300 dpi. +const WIDGET_FLOOR_W: f32 = 120.0; +const WIDGET_FLOOR_H: f32 = 80.0; +/// A frame never takes more than this share of the canvas either way. +const WIDGET_MAX_SHARE: i32 = 70; + +/// One entry in the widget catalog. Sizes are at 300 dpi, as the rest of the UI's constants. +#[derive(Clone, Copy, Debug)] +pub struct WidgetDef { + pub id: &'static str, + pub name: &'static str, + pub icon: IconKind, + pub default_w: f32, + pub default_h: f32, + pub min_w: f32, + pub min_h: f32, + pub max_w: f32, + pub max_h: f32, + pub resizable: bool, + /// the installed package's version, author and description + pub version: &'static str, + pub author: &'static str, + pub description: &'static str, +} + +/// The catalog starts empty: every widget is an installed package (widgetpkg.rs). +pub const WIDGET_CATALOG: [WidgetDef; 0] = []; + +/// The icon a package names in its manifest. Unknown names get the generic grid. +pub fn widget_icon(name: &str) -> IconKind { + let name = name.trim().to_ascii_lowercase(); + let name = name.strip_prefix("md-").unwrap_or(&name); + match name { + "calculator" => IconKind::Calculator, + "package" => IconKind::Package, + "clock" => IconKind::Clock, + "timer" | "hourglass" => IconKind::Hourglass, + "music" => IconKind::Music, + "notebook" => IconKind::Notebook, + "pdf" => IconKind::Pdf, + "image" | "photo" => IconKind::Image, + "files" | "folder" => IconKind::Files, + "search" => IconKind::Search, + "download" => IconKind::Download, + "language" => IconKind::Language, + "gear" | "settings" => IconKind::Gear, + "update" => IconKind::Update, + "paper" | "page" => IconKind::Paper, + "library" => IconKind::Library, + "link" => IconKind::Link, + "live" => IconKind::Live, + "gamepad" => IconKind::Gamepad, + "eye" => IconKind::Eye, + _ => IconKind::Grid, + } +} + +/// The installed packages in name order. The package entries are cached by widgetpkg.rs and +/// refreshed after an install, update or remove. +pub fn widget_catalog() -> Vec<&'static WidgetDef> { + let mut v: Vec<&'static WidgetDef> = WIDGET_CATALOG.iter().collect(); + v.extend(crate::widgetpkg::widget_package_defs()); + v +} + +pub fn widget_def(id: &str) -> Option<&'static WidgetDef> { + WIDGET_CATALOG.iter().find(|d| d.id == id).or_else(|| crate::widgetpkg::widget_package_defs().into_iter().find(|d| d.id == id)) +} + +/// A widget window's place on the canvas. x, y, w and h are in screen pixels; w and h are the +/// restored size while minimized too, so a restore comes back the size it was. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WidgetLayout { + pub x: i32, + pub y: i32, + pub w: i32, + pub h: i32, + pub minimized: bool, + pub z: i32, +} + +/// An open widget window and the generic runtime its package supplies. +#[derive(Debug)] +pub struct WidgetFrame { + pub def: &'static WidgetDef, + pub layout: WidgetLayout, + pub runtime: Option, + pub runtime_error: Option, +} + +/// Where a contact came down in a frame. The editor routes input by these. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WidgetPart { + #[default] + None, + Title, + Close, + Minimize, + Resize, + Body, +} + +/// The state of one contact on a widget: which frame and part, where it came down, and the frame's +/// place then. +#[derive(Clone, Copy, Debug)] +pub struct WidgetDrag { + pub index: usize, + pub part: WidgetPart, + pub down_x: i32, + pub down_y: i32, + pub start: Rect, + pub moved: bool, +} + +impl WidgetFrame { + pub fn new(def: &'static WidgetDef) -> Self { + WidgetFrame { + def, + layout: WidgetLayout { + x: 0, + y: 0, + w: ui_px(def.default_w), + h: ui_px(def.default_h), + minimized: false, + z: 0, + }, + runtime: None, + runtime_error: None, + } + } + + /// Loads the package's WASM instance on the first draw, or keeps the error for the body. + pub fn ensure_runtime(&mut self) { + if self.runtime.is_some() || self.runtime_error.is_some() { + return; + } + match WidgetRuntime::new(self.def.id) { + Ok(r) => self.runtime = Some(r), + Err(e) => self.runtime_error = Some(e), + } + } + + /// The last runtime error, if its package or module could not start. + pub fn error(&self) -> Option<&str> { + self.runtime_error.as_deref().or_else(|| self.runtime.as_ref().and_then(WidgetRuntime::error)) + } + + /// The frame as drawn and hit: a minimized widget is a small square at its corner. + pub fn rect(&self) -> Rect { + if self.layout.minimized { + let s = ui_px(WIDGET_MINIMIZED).min(self.layout.w).min(self.layout.h).max(ui_px(64.0)); + Rect { x: self.layout.x, y: self.layout.y, w: s, h: s } + } else { + Rect { x: self.layout.x, y: self.layout.y, w: self.layout.w, h: self.layout.h } + } + } + + /// The sizes this frame may take on `area`: the widget's own bounds, never past the screen's + /// floor and share. + pub fn limits(&self, area: Rect) -> (i32, i32, i32, i32) { + let floor_w = ui_px(WIDGET_FLOOR_W); + let floor_h = ui_px(WIDGET_FLOOR_H); + let share_w = (area.w * WIDGET_MAX_SHARE / 100).max(floor_w); + let share_h = (area.h * WIDGET_MAX_SHARE / 100).max(floor_h); + let min_w = ui_px(self.def.min_w).clamp(floor_w, share_w); + let min_h = ui_px(self.def.min_h).clamp(floor_h, share_h); + let max_w = ui_px(self.def.max_w).clamp(min_w, share_w); + let max_h = ui_px(self.def.max_h).clamp(min_h, share_h); + (min_w, min_h, max_w, max_h) + } + + /// Keeps the frame's size in its bounds and its whole rectangle on `area`. + pub fn clamp(&mut self, area: Rect) -> bool { + let before = self.layout; + let (min_w, min_h, max_w, max_h) = self.limits(area); + self.layout.w = self.layout.w.clamp(min_w, max_w); + self.layout.h = self.layout.h.clamp(min_h, max_h); + let r = self.rect(); + self.layout.x = clampi(self.layout.x, area.x, area.x + area.w - r.w); + self.layout.y = clampi(self.layout.y, area.y, area.y + area.h - r.h); + self.layout != before + } + + pub fn move_to(&mut self, x: i32, y: i32, area: Rect) -> bool { + let r = self.rect(); + let nx = clampi(x, area.x, area.x + area.w - r.w); + let ny = clampi(y, area.y, area.y + area.h - r.h); + let changed = nx != self.layout.x || ny != self.layout.y; + self.layout.x = nx; + self.layout.y = ny; + changed + } + + pub fn resize_to(&mut self, w: i32, h: i32, area: Rect) -> bool { + let before = self.layout; + let (min_w, min_h, max_w, max_h) = self.limits(area); + self.layout.w = w.clamp(min_w, max_w); + self.layout.h = h.clamp(min_h, max_h); + let r = self.rect(); + self.layout.x = clampi(self.layout.x, area.x, area.x + area.w - r.w); + self.layout.y = clampi(self.layout.y, area.y, area.y + area.h - r.h); + self.layout != before + } + + pub fn title_rect(&self) -> Rect { + let r = self.rect(); + let h = (ui_px(64.0)).min(r.h); + Rect { x: r.x, y: r.y, w: r.w, h } + } + + pub fn close_rect(&self) -> Rect { + let r = self.rect(); + let side = ui_px(64.0).min(r.h).min(r.w / 3); + Rect { x: r.x + r.w - side, y: r.y, w: side, h: side } + } + + pub fn minimize_rect(&self) -> Rect { + let r = self.close_rect(); + Rect { x: r.x - r.w, y: r.y, w: r.w, h: r.h } + } + + pub fn resize_rect(&self) -> Rect { + let r = self.rect(); + let side = ui_px(72.0).min(r.w / 3).min(r.h / 3); + Rect { x: r.x + r.w - side, y: r.y + r.h - side, w: side, h: side } + } +} + +/// The editor's open widgets. Draw order is z order; the topmost wins a hit. +#[derive(Debug)] +pub struct WidgetHost { + pub frames: Vec, + next_z: i32, + /// Whether widgets.ini has been read (the editor reads it when it first opens). + pub loaded: bool, +} + +impl Default for WidgetHost { + fn default() -> Self { + WidgetHost::new() + } +} + +impl WidgetHost { + pub fn new() -> Self { + WidgetHost { frames: Vec::new(), next_z: 0, loaded: false } + } + + pub fn is_open(&self, id: &str) -> bool { + self.frames.iter().any(|f| f.def.id == id) + } + + pub fn index_of(&self, id: &str) -> Option { + self.frames.iter().position(|f| f.def.id == id) + } + + /// Lets an open frame of this package read the settings that were just saved. + pub fn reload_settings(&mut self, id: &str) { + if let Some(i) = self.index_of(id) { + if let Some(rt) = self.frames[i].runtime.as_mut() { + rt.reload_settings(id); + } + } + } + + /// Raises a frame to the top, returning whether its z changed. + pub fn raise(&mut self, index: usize) -> bool { + let Some(f) = self.frames.get_mut(index) else { return false }; + let z = self.next_z.max(0); + if f.layout.z == z { + return false; + } + f.layout.z = z; + self.next_z = z + 1; + true + } + + /// Opens a catalog widget, or raises it when it is already open. + pub fn spawn(&mut self, def: &'static WidgetDef, area: Rect, panel: Rect) -> bool { + if let Some(i) = self.index_of(def.id) { + self.raise(i); + return false; + } + if self.frames.len() >= WIDGETS_MAX { + return false; + } + let mut f = WidgetFrame::new(def); + let (_, _, max_w, max_h) = f.limits(area); + f.layout.w = f.layout.w.clamp(ui_px(WIDGET_FLOOR_W), max_w); + f.layout.h = f.layout.h.clamp(ui_px(WIDGET_FLOOR_H), max_h); + // Top right of the canvas, left of the panel when the panel is there: the first thing a + // new widget shows should not be hidden under the toolbar. + let mut x = area.x + area.w - f.layout.w - ui_px(WIDGET_MARGIN); + if panel.x > area.x + area.w / 2 { + x = panel.x - f.layout.w - ui_px(WIDGET_MARGIN); + } + let step = ui_px(WIDGET_CASCADE) * self.frames.len() as i32; + let y = area.y + ui_px(WIDGET_MARGIN) + step; + f.layout.x = clampi(x - step, area.x, (area.x + area.w - f.layout.w).max(area.x)); + f.layout.y = clampi(y, area.y, (area.y + area.h - f.layout.h).max(area.y)); + f.layout.z = self.next_z; + self.next_z += 1; + self.frames.push(f); + true + } + + /// Opens a frame from widgets.ini, with its saved place and size, clamped to this screen. + pub fn restore(&mut self, def: &'static WidgetDef, layout: WidgetLayout, area: Rect) { + if self.is_open(def.id) || self.frames.len() >= WIDGETS_MAX { + return; + } + let mut f = WidgetFrame::new(def); + f.layout = layout; + f.clamp(area); + self.next_z = self.next_z.max(f.layout.z + 1); + self.frames.push(f); + } + + pub fn close(&mut self, index: usize) -> bool { + if index < self.frames.len() { + self.frames.remove(index); + true + } else { + false + } + } + + /// The topmost frame under a point, and which part of it. + pub fn hit(&self, x: i32, y: i32) -> Option<(usize, WidgetPart)> { + let mut order: Vec = (0..self.frames.len()).collect(); + order.sort_by_key(|&i| self.frames[i].layout.z); + for &i in order.iter().rev() { + let f = &self.frames[i]; + let r = f.rect(); + if !rect_contains(r, x, y) { + continue; + } + if f.layout.minimized { + return Some((i, WidgetPart::Title)); + } + if rect_contains(f.close_rect(), x, y) { + return Some((i, WidgetPart::Close)); + } + if rect_contains(f.minimize_rect(), x, y) { + return Some((i, WidgetPart::Minimize)); + } + if f.def.resizable && rect_contains(f.resize_rect(), x, y) { + return Some((i, WidgetPart::Resize)); + } + if rect_contains(f.title_rect(), x, y) { + return Some((i, WidgetPart::Title)); + } + return Some((i, WidgetPart::Body)); + } + None + } + + pub fn draw_order(&self) -> Vec { + let mut order: Vec = (0..self.frames.len()).collect(); + order.sort_by_key(|&i| self.frames[i].layout.z); + order + } + + /// Keeps every frame on this screen after a turn or a resize. + pub fn reclamp(&mut self, area: Rect) -> bool { + let mut changed = false; + for f in &mut self.frames { + changed |= f.clamp(area); + } + changed + } + + pub fn load(&mut self, area: Rect) { + self.frames.clear(); + self.next_z = 0; + for e in widgets_load() { + if let Some(def) = widget_def(&e.id) { + self.restore(def, e.layout, area); + } + } + self.loaded = true; + } + + pub fn save(&self) -> i32 { + let entries: Vec = self + .frames + .iter() + .map(|f| WidgetEntry { id: f.def.id.to_string(), layout: f.layout }) + .collect(); + widgets_save(&entries) + } +} + +/// One line of widgets.ini. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WidgetEntry { + pub id: String, + pub layout: WidgetLayout, +} + +fn widgets_path() -> String { + format!("{}/widgets.ini", store_root()) +} + +/// Reads widgets.ini. A missing or unreadable file is an empty layout. Lines that are not a known +/// id with seven comma-separated fields are skipped; the file is small and human-editable. +pub fn widgets_load() -> Vec { + let root = store_root(); + if root.is_empty() { + return Vec::new(); + } + let Some(data) = read_file_max(&widgets_path(), 64 * 1024) else { + return Vec::new(); + }; + let text = String::from_utf8_lossy(&data); + let mut out = Vec::new(); + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') || line.starts_with(';') { + continue; + } + let Some((id, rest)) = line.split_once('=') else { continue }; + let id = id.trim(); + if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-' || b == b'_') { + continue; + } + let v: Vec<&str> = rest.split(',').map(str::trim).collect(); + if v.len() != 7 { + continue; + } + let Ok(x) = v[0].parse::() else { continue }; + let Ok(y) = v[1].parse::() else { continue }; + let Ok(w) = v[2].parse::() else { continue }; + let Ok(h) = v[3].parse::() else { continue }; + let Ok(minimized) = v[4].parse::() else { continue }; + let Ok(z) = v[5].parse::() else { continue }; + // Seven fields are required, but the last is reserved for a future flag; accept it only as + // a number so a malformed line cannot make the rest look valid. + if v[6].parse::().is_err() { + continue; + } + if w <= 0 || h <= 0 { + continue; + } + out.push(WidgetEntry { + id: id.to_string(), + layout: WidgetLayout { x, y, w, h, minimized: minimized != 0, z }, + }); + } + out +} + +/// Writes widgets.ini atomically. The open frames are the file: a closed widget has no line. +pub fn widgets_save(entries: &[WidgetEntry]) -> i32 { + let root = store_root(); + if root.is_empty() { + return 0; + } + let _ = mkdir_p(&root); + let mut s = String::from("# Grimoire widget layout. One line per open widget:\n"); + s.push_str("# id=x,y,w,h,minimized,z\n"); + for e in entries { + s.push_str(&format!( + "{}={},{},{},{},{},{},0\n", + e.id, e.layout.x, e.layout.y, e.layout.w, e.layout.h, e.layout.minimized as i32, e.layout.z + )); + } + write_file_atomic(&widgets_path(), s.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn area() -> Rect { + Rect { x: 0, y: 0, w: 1860, h: 2480 } + } + + fn panel() -> Rect { + Rect { x: 1700, y: 220, w: 128, h: 1700 } + } + + static TEST_WIDGET: WidgetDef = WidgetDef { + id: "test.widget", + name: "Test", + icon: IconKind::Grid, + default_w: 300.0, + default_h: 420.0, + min_w: 240.0, + min_h: 360.0, + max_w: 460.0, + max_h: 620.0, + resizable: true, + version: "", + author: "", + description: "", + }; + + #[test] + fn a_package_icon_names_a_grimoire_icon() { + assert_eq!(widget_icon("calculator"), IconKind::Calculator); + assert_eq!(widget_icon("package"), IconKind::Package); + assert_eq!(widget_icon("md-timer"), IconKind::Hourglass); + assert_eq!(widget_icon("not one"), IconKind::Grid); + } + + #[test] + fn spawn_stays_on_the_canvas_and_to_the_left_of_the_panel() { + ui_init(300.0); + let mut h = WidgetHost::new(); + let notes = &TEST_WIDGET; + assert!(h.spawn(notes, area(), panel())); + let r = h.frames[0].rect(); + assert!(r.x >= 0 && r.y >= 0 && r.x + r.w <= area().w && r.y + r.h <= area().h); + assert!(r.x + r.w <= panel().x); + // The same widget again raises, does not duplicate. + let z = h.frames[0].layout.z; + assert!(!h.spawn(notes, area(), panel())); + assert_eq!(h.frames.len(), 1); + assert!(h.frames[0].layout.z >= z); + } + + #[test] + fn clamp_and_resize_keep_the_floor_and_the_share() { + ui_init(300.0); + let mut f = WidgetFrame::new(&TEST_WIDGET); + f.resize_to(1, 1, area()); + let (min_w, min_h, _, _) = f.limits(area()); + assert_eq!((f.layout.w, f.layout.h), (min_w, min_h)); + f.resize_to(100_000, 100_000, area()); + let (_, _, max_w, max_h) = f.limits(area()); + assert_eq!((f.layout.w, f.layout.h), (max_w, max_h)); + f.move_to(-500, 9000, area()); + assert!(f.layout.x >= area().x && f.layout.y + f.rect().h <= area().h); + } + + #[test] + fn minimized_rect_is_a_square_and_restore_keeps_the_size() { + ui_init(300.0); + let mut f = WidgetFrame::new(&TEST_WIDGET); + let (w, h) = (f.layout.w, f.layout.h); + f.layout.minimized = true; + let r = f.rect(); + assert_eq!(r.w, r.h); + f.layout.minimized = false; + assert_eq!((f.layout.w, f.layout.h), (w, h)); + } + + #[test] + fn layout_round_trips_through_widgets_ini() { + ui_init(300.0); + let root = std::env::temp_dir().join(format!("grimoire-widgets-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + assert_eq!(store_init(root.to_str().unwrap()), 0); + let entries = vec![WidgetEntry { + id: "test.widget".to_string(), + layout: WidgetLayout { x: 10, y: 20, w: 260, h: 220, minimized: true, z: 3 }, + }]; + assert_eq!(widgets_save(&entries), 0); + assert_eq!(widgets_load(), entries); + // A bad line is skipped, not a reason to lose the good ones. + std::fs::write( + root.join("widgets.ini"), + "# c\ntest.widget=1,2,3,4,0,5,0\nbad=1,2\nother=1,2,3,4,0,6,0\n", + ) + .unwrap(); + let got = widgets_load(); + assert_eq!(got.len(), 2); + assert_eq!(got[0].id, "test.widget"); + assert_eq!(got[1].layout.z, 6); + let _ = std::fs::remove_dir_all(&root); + } + +} diff --git a/rust/src/widgetwasm.rs b/rust/src/widgetwasm.rs new file mode 100644 index 00000000..6fc672d2 --- /dev/null +++ b/rust/src/widgetwasm.rs @@ -0,0 +1,305 @@ +//! The WebAssembly widget host (2.2): a generic frame body, nothing about any one widget. +//! +//! A package's artifact is a WebAssembly module with a `memory` export and two exports the host +//! calls: +//! +//! ```text +//! widget_draw(width: i32, height: i32, scale_milli: i32) +//! widget_tap(id: i32) +//! ``` +//! +//! `widget_draw` draws through the `grimoire` imports below. Coordinates are screen pixels inside +//! the frame's body; `scale_milli` is the UI scale times 1000, so a package can keep 300 dpi sizes. +//! `widget_tap` receives the id of the hit region under the tap, or -1 for a tap elsewhere in the +//! body. A package keeps its state through `state_get` / `state_set`, which the host saves under +//! `packages/widgets//state/runtime.bin`. +//! +//! Imports (`grimoire`): +//! +//! ```text +//! rect(x, y, w, h, style) +//! text(x, y, w, h, ptr, len, px, center) +//! button(id, x, y, w, h, ptr, len, style) +//! hit(id, x, y, w, h) +//! status(ptr, len) +//! request_redraw(after_ms) +//! setting(key_ptr, key_len, out_ptr, out_cap) -> i32 +//! state_get(ptr, cap) -> i32 +//! state_set(ptr, len) +//! now() -> i64 +//! ``` +//! +//! `style` is 0 (normal), 1 (selected) or 2 (disabled). Strings are UTF-8 in the module's memory. +//! `setting` and `state_get` return the number of bytes written, at most `out_cap` / `cap`. + +use crate::prelude::*; +use std::time::{Duration, Instant}; +use wasmi::{Caller, Config, Engine, Extern, Linker, Module, Store, StoreLimits, StoreLimitsBuilder}; + +const ABI: &str = "grimoire"; +const ARTIFACT_MAX: usize = 32 * 1024 * 1024; +const STATE_MAX: usize = 64 * 1024; +const STATE_FILE: &str = "state/runtime.bin"; +/// A widget gets this many instructions per call. A drawing pass that needs more is looping. +const FUEL_PER_CALL: u64 = 20_000_000; +/// A widget's linear memory may not grow past this, so one package cannot exhaust the device. +const MEMORY_MAX: usize = 32 * 1024 * 1024; + +/// A drawing command recorded by the module and rendered by the host. Coordinates are body-local. +#[derive(Clone, Debug)] +enum DrawCmd { + Rect { x: i32, y: i32, w: i32, h: i32, style: i32 }, + Text { x: i32, y: i32, w: i32, h: i32, text: String, px: i32, center: bool }, + Button { x: i32, y: i32, w: i32, h: i32, text: String, style: i32 }, +} + +struct HostState { + commands: Vec, + hits: Vec<(i32, Rect)>, + state: Vec, + state_path: String, + settings: Vec<(String, String)>, + status: String, + dirty: bool, + limits: StoreLimits, + redraw_at: Option, +} + +/// One open package's WebAssembly instance, its last draw and its saved state. +pub struct WidgetRuntime { + _engine: Engine, + store: Store, + instance: wasmi::Instance, + hits: Vec<(i32, Rect)>, + texts: Vec, + status: String, + error: Option, +} + +impl std::fmt::Debug for WidgetRuntime { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WidgetRuntime").field("hits", &self.hits.len()).field("error", &self.error).finish() + } +} + +impl WidgetRuntime { + /// Compiles and instantiates the installed package's artifact. + pub fn new(id: &str) -> Result { + let Some(m) = crate::widgetpkg::widget_package_installed_manifest(id) else { + return Err("The widget package is not installed.".into()); + }; + if m.spec.runtime != "wasm" { + return Err("This package is not a WebAssembly widget.".into()); + } + let path = format!("{}/{}", crate::widgetpkg::widget_package_dir(id), m.artifact.path); + let bytes = read_file_max(&path, ARTIFACT_MAX).ok_or("The widget's artifact could not be read.")?; + let mut config = Config::default(); + config.consume_fuel(true); + let engine = Engine::new(&config); + let module = Module::new(&engine, &bytes[..]).map_err(|e| format!("The widget's WebAssembly is invalid: {e}"))?; + let state_path = format!("{}/{STATE_FILE}", crate::widgetpkg::widget_package_dir(id)); + let state = read_file_max(&state_path, STATE_MAX).unwrap_or_default(); + let settings = crate::widgetpkg::widget_settings_load(id, &m.settings); + let mut store = Store::new(&engine, HostState { + commands: Vec::new(), + hits: Vec::new(), + state, + state_path, + settings, + status: String::new(), + dirty: false, + limits: StoreLimitsBuilder::new().memory_size(MEMORY_MAX).build(), + redraw_at: None, + }); + store.limiter(|st| &mut st.limits); + // The start section runs here, before a frame can draw: give it the same budget as a call. + let _ = store.set_fuel(FUEL_PER_CALL); + let mut linker = Linker::new(&engine); + linker.func_wrap(ABI, "rect", |mut caller: Caller<'_, HostState>, x: i32, y: i32, w: i32, h: i32, style: i32| { + caller.data_mut().commands.push(DrawCmd::Rect { x, y, w, h, style }); + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "text", |mut caller: Caller<'_, HostState>, x: i32, y: i32, w: i32, h: i32, ptr: i32, len: i32, px: i32, center: i32| { + let text = String::from_utf8_lossy(&read_mem(&caller, ptr, len)).into_owned(); + caller.data_mut().commands.push(DrawCmd::Text { x, y, w, h, text, px, center: center != 0 }); + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "button", |mut caller: Caller<'_, HostState>, id: i32, x: i32, y: i32, w: i32, h: i32, ptr: i32, len: i32, style: i32| { + let text = String::from_utf8_lossy(&read_mem(&caller, ptr, len)).into_owned(); + let st = caller.data_mut(); + st.commands.push(DrawCmd::Button { x, y, w, h, text, style }); + st.hits.push((id, Rect { x, y, w, h })); + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "hit", |mut caller: Caller<'_, HostState>, id: i32, x: i32, y: i32, w: i32, h: i32| { + caller.data_mut().hits.push((id, Rect { x, y, w, h })); + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "status", |mut caller: Caller<'_, HostState>, ptr: i32, len: i32| { + caller.data_mut().status = String::from_utf8_lossy(&read_mem(&caller, ptr, len)).into_owned(); + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "request_redraw", |mut caller: Caller<'_, HostState>, after_ms: i32| { + let after_ms = after_ms.clamp(16, 86_400_000) as u64; + caller.data_mut().redraw_at = Some(Instant::now() + Duration::from_millis(after_ms)); + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "setting", |mut caller: Caller<'_, HostState>, key_ptr: i32, key_len: i32, out_ptr: i32, out_cap: i32| -> i32 { + let key = read_mem(&caller, key_ptr, key_len); + let value = caller.data().settings.iter().find(|(k, _)| k.as_bytes() == key.as_slice()).map(|(_, v)| v.as_bytes().to_vec()).unwrap_or_default(); + write_mem(&mut caller, out_ptr, out_cap, &value) + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "state_get", |mut caller: Caller<'_, HostState>, ptr: i32, cap: i32| -> i32 { + let state = caller.data().state.clone(); + write_mem(&mut caller, ptr, cap, &state) + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "state_set", |mut caller: Caller<'_, HostState>, ptr: i32, len: i32| { + let state = read_mem(&caller, ptr, len); + let st = caller.data_mut(); + st.state = state.into_iter().take(STATE_MAX).collect(); + st.dirty = true; + }).map_err(|e| e.to_string())?; + linker.func_wrap(ABI, "now", || -> i64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64) + }).map_err(|e| e.to_string())?; + let instance = linker.instantiate_and_start(&mut store, &module).map_err(|e| format!("The widget could not start: {e}"))?; + if instance.get_memory(&store, "memory").is_none() { + return Err("The widget has no memory export.".into()); + } + Ok(WidgetRuntime { _engine: engine, store, instance, hits: Vec::new(), texts: Vec::new(), status: String::new(), error: None }) + } + + /// Calls `widget_draw` and renders its commands into `body`. + pub fn draw(&mut self, c: &mut Canvas, body: Rect) { + if self.error.is_some() { + return; + } + let draw = match self.instance.get_typed_func::<(i32, i32, i32), ()>(&self.store, "widget_draw") { + Ok(f) => f, + Err(e) => { self.error = Some(format!("The widget has no widget_draw export: {e}")); return; } + }; + self.store.data_mut().status.clear(); + self.store.data_mut().redraw_at = None; + let _ = self.store.set_fuel(FUEL_PER_CALL); + let scale = ui_px(1000.0); + if let Err(e) = draw.call(&mut self.store, (body.w, body.h, scale)) { + self.error = Some(format!("The widget stopped: {e}")); + return; + } + self.save(); + let commands = std::mem::take(&mut self.store.data_mut().commands); + self.hits = std::mem::take(&mut self.store.data_mut().hits); + self.status = std::mem::take(&mut self.store.data_mut().status); + self.texts.clear(); + canvas_fill(c, body, 255); + for cmd in commands { + match cmd { + DrawCmd::Rect { x, y, w, h, style } => { + let r = Rect { x: body.x + x, y: body.y + y, w, h }; + let fill = match style { 1 => 210, _ => 255 }; + ui_frame(c, r, ui_px(8.0), fill, true, 0); + ui_frame(c, r, ui_px(8.0), 0, false, ui_px(2.0)); + } + DrawCmd::Text { x, y, w, h, text, px, center } => { + let r = Rect { x: body.x + x, y: body.y + y, w, h }; + let px = px.max(1) as f32; + ui_text(c, FontFace::Regular, px, px, r, &text, 1, center, 0); + self.texts.push(text); + } + DrawCmd::Button { x, y, w, h, text, style } => { + let r = Rect { x: body.x + x, y: body.y + y, w, h }; + let style = match style { 1 => ButtonStyle::Selected, 2 => ButtonStyle::Disabled, _ => ButtonStyle::Plain }; + ui_button(c, r, IconKind::None, &text, style); + self.texts.push(text); + } + } + } + } + + /// Sends a tap in body-local coordinates. Returns whether the module was called. + pub fn tap(&mut self, x: i32, y: i32) { + if self.error.is_some() { + return; + } + let id = self.hits.iter().find(|(_, r)| rect_contains(*r, x, y)).map_or(-1, |(id, _)| *id); + self.store.data_mut().redraw_at = None; + let tap = match self.instance.get_typed_func::<(i32,), ()>(&self.store, "widget_tap") { + Ok(f) => f, + Err(_) => return, + }; + let _ = self.store.set_fuel(FUEL_PER_CALL); + if tap.call(&mut self.store, (id,)).is_err() { + self.error = Some("The widget stopped while handling a tap.".into()); + return; + } + self.save(); + } + + pub fn error(&self) -> Option<&str> { + self.error.as_deref() + } + + /// Reads the package's settings again after the settings page saved them. + pub fn reload_settings(&mut self, id: &str) { + let Some(m) = crate::widgetpkg::widget_package_installed_manifest(id) else { return }; + self.store.data_mut().settings = crate::widgetpkg::widget_settings_load(id, &m.settings); + } + + pub fn status(&self) -> &str { + &self.status + } + + /// The text drawn in the last frame, joined by `|`, for generic scenario probes. + pub fn text(&self) -> String { + self.texts.join("|") + } + + /// A drawn hit region, for generic scenario taps. + pub fn hit(&self, id: i32) -> Option { + self.hits.iter().find(|(hit, _)| *hit == id).map(|(_, r)| *r) + } + + pub fn hit_count(&self) -> usize { + self.hits.len() + } + + /// Whether the package asked for its next draw by now. + pub fn redraw_due(&self, now: Instant) -> bool { + self.store.data().redraw_at.is_some_and(|at| at <= now) + } + + fn save(&mut self) { + if !self.store.data().dirty { + return; + } + let st = self.store.data_mut(); + st.dirty = false; + if let Some(dir) = st.state_path.rsplit_once('/').map(|(d, _)| d) { + let _ = mkdir_p(dir); + } + if write_file_atomic(&st.state_path, &st.state) != 0 { + st.dirty = true; + } + } +} + +fn read_mem(caller: &Caller<'_, HostState>, ptr: i32, len: i32) -> Vec { + if ptr < 0 || len <= 0 { + return Vec::new(); + } + let Some(memory) = caller.get_export("memory").and_then(Extern::into_memory) else { return Vec::new() }; + let data = memory.data(caller); + let start = ptr as usize; + let end = start.saturating_add(len as usize).min(data.len()); + if start >= end { return Vec::new() } + data[start..end].to_vec() +} + +fn write_mem(caller: &mut Caller<'_, HostState>, ptr: i32, cap: i32, bytes: &[u8]) -> i32 { + if ptr < 0 || cap <= 0 { + return 0; + } + let Some(memory) = caller.get_export("memory").and_then(Extern::into_memory) else { return 0 }; + let data = memory.data_mut(caller); + let start = ptr as usize; + if start >= data.len() { + return 0; + } + let n = bytes.len().min(cap as usize).min(data.len() - start); + data[start..start + n].copy_from_slice(&bytes[..n]); + n as i32 +} diff --git a/rust/tests/test_panel.rs b/rust/tests/test_panel.rs index 92f4364e..ae855a39 100644 --- a/rust/tests/test_panel.rs +++ b/rust/tests/test_panel.rs @@ -1,6 +1,6 @@ // The editor's floating panel. With 0 to 3 pens pinned it fits the // 2022/2024 Scribes' screen and the Scribe 3's and Colorsoft's, upright and sideways, keeping its -// 12 px margins (93 px buttons with three pins on older Scribes sideways, otherwise full size). +// 12 px margins (one, two and three pins sideways on older Scribes take 99, 93 and 88 px buttons). // The collapsed square never changes. Next and previous // tool go through its pens alone, and the tool picker's next and previous through the picker's nine. // Index loops and float comparisons are written as the C test writes them. @@ -11,20 +11,21 @@ use grimoire::prelude::*; use testlib::*; fn fits_both_scribes_both_ways() { - check!(PANEL_BUTTONS == 14); + check!(PANEL_BUTTONS == 15); check!(PANEL_PINS_MAX == 3); for (w,h) in [(1860,2480),(2480,1860),(1986,2648),(2648,1986)] { for pins in 0..=PANEL_PINS_MAX as i32 { let f = panel_fit(h,pins); check!(panel_height(f,pins)+2*ui_px(PANEL_MARGIN as f32)<=h); - check!(panel_w()+2*ui_px(PANEL_MARGIN as f32)<=w && f.scale >= 0.93 && f.space >= 0.5); - check!(panel_btn_h(f)>=ui_px(93.0)); - // Two or three pins on the older Scribes in landscape need smaller buttons. - check!(panel_btn_h(f)==ui_px(if h==1860 && pins==3 {93.0}else if h==1860 && pins==2 {99.0}else{100.0})); + check!(panel_w()+2*ui_px(PANEL_MARGIN as f32)<=w && f.scale >= 0.88 && f.space >= 0.5); + check!(panel_btn_h(f)>=ui_px(88.0)); + // Two or three pins on the older Scribes in landscape need smaller buttons (the Widgets + // button leaves 89 px with three). + check!(panel_btn_h(f)==ui_px(if h==1860 && pins==3 {88.0}else if h==1860 && pins==2 {93.0}else if h==1860 && pins==1 {99.0}else if h==1986 && pins==3 {95.0}else{100.0})); if h>=2480 {check!(f.scale==1.0 && f.space==1.0);} } } - check!(panel_height(PanelFit{scale:1.0,space:1.0},0)==1734); + check!(panel_height(PanelFit{scale:1.0,space:1.0},0)==1842); check!(panel_box()==ui_px(120.0)); } @@ -210,7 +211,7 @@ fn the_page_chip_keeps_one_form_in_a_notebook() { } let mut sizes: Vec = fits.iter().map(|f| panel_chip_px(*f)).collect(); sizes.sort_by(|a, b| b.total_cmp(a)); - check!(sizes == [34.0, 33.66, 31.62]); + check!(sizes == [34.0, 33.66, 32.3, 31.62, 29.92]); let every_page = |m: i32| m <= 250 || (990..=1010).contains(&m) || (1990..=2000).contains(&m) || m >= 9990; for (name, theme, family) in styles { ui_set_theme(theme); @@ -241,7 +242,7 @@ fn the_page_chip_keeps_one_form_in_a_notebook() { check!(wrong == 0); check!(alone_cut == 0); // every count under 100 shows the page and the count, as before #119; none of 1000 or more does - check!(small == 99 && big == 0); + check!(small == 99 && (big == 0 || px < 31.62)); check!(panel_page_label(1, 1, f) == "1 / 1" && panel_page_label(99, 99, f) == "99 / 99"); check!(panel_page_label(1, 1000, f) == "1" && panel_page_label(1995, 2000, f) == "1995"); check!(panel_page_label(1, 2000, f) == "1" && panel_page_label(9999, 9999, f) == "9999"); diff --git a/rust/tests/test_sec_invariants.rs b/rust/tests/test_sec_invariants.rs index 5af8904f..b66b1ea2 100644 --- a/rust/tests/test_sec_invariants.rs +++ b/rust/tests/test_sec_invariants.rs @@ -443,9 +443,13 @@ struct Crates { } /// Packages the lock names for a target or a feature no build of Grimoire has, when neither a ban nor a skip is -/// the right word for them: (name, version, why the build never compiles it). Empty: the one such crate, glifo, -/// is banned in deny.toml, which also makes CI's deny job refuse a build that would take it. -const NAMED_NOT_BUILT: &[(&str, &str, &str)] = &[]; +/// the right word for them: (name, version, why the build never compiles it). glifo, the one such crate before +/// this, is banned in deny.toml, which also makes CI's deny job refuse a build that would take it. +const NAMED_NOT_BUILT: &[(&str, &str, &str)] = &[( + "string-interner", + "0.19.0", + "wasmi_collections' optional `hash-collections` feature: grimoire builds wasmi without default features and never asks for it (nor for the hashbrown 0.15.5 below it)", +)]; fn crates(fails: &mut Vec) -> Crates { let pkgs = lock_packages(); diff --git a/rust/tests/test_ui.rs b/rust/tests/test_ui.rs index b057f158..6dcc6a49 100644 --- a/rust/tests/test_ui.rs +++ b/rust/tests/test_ui.rs @@ -32,6 +32,7 @@ const ICONS: [IconKind; IconKind::COUNT - 1] = [ IconKind::Live, IconKind::Gamepad, IconKind::Update, IconKind::Clock, IconKind::Search, IconKind::Eye, IconKind::LinkPlus, IconKind::Bubbles, IconKind::Gestures, IconKind::Lasso, IconKind::Hourglass, IconKind::Font, IconKind::Ban, IconKind::Files, IconKind::Image, IconKind::Pdf, IconKind::FileOther, IconKind::LinkOff, IconKind::Sort, IconKind::FolderOpen, IconKind::Home, + IconKind::Calculator, IconKind::Package, ]; fn slider_snap() { diff --git a/tests/fixtures/widgetcalc/packages/index.json b/tests/fixtures/widgetcalc/packages/index.json new file mode 100644 index 00000000..9d9e9eef --- /dev/null +++ b/tests/fixtures/widgetcalc/packages/index.json @@ -0,0 +1,6 @@ +{ + "version": 1, + "packages": [ + {"id":"com.grimoire.calculator","name":"Calculator","version":"1.2.0","author":"Nebuff","description":"Simple, scientific and programming calculators, with a unit converter.","icon":"calculator","path":"packages/widgets/com.grimoire.calculator/calculator.bin","sha":"cbdded0a54dfea3029f85dfe92ecb016dfd4ebe5be9f08ab55c15309269f42cb","installed_at":1,"source_url":""} + ] +} diff --git a/tests/fixtures/widgetcalc/packages/widgets/com.grimoire.calculator/calculator.bin b/tests/fixtures/widgetcalc/packages/widgets/com.grimoire.calculator/calculator.bin new file mode 100644 index 00000000..14e6d3b9 Binary files /dev/null and b/tests/fixtures/widgetcalc/packages/widgets/com.grimoire.calculator/calculator.bin differ diff --git a/tests/fixtures/widgetcalc/packages/widgets/com.grimoire.calculator/package.yaml b/tests/fixtures/widgetcalc/packages/widgets/com.grimoire.calculator/package.yaml new file mode 100644 index 00000000..b1c0ea95 --- /dev/null +++ b/tests/fixtures/widgetcalc/packages/widgets/com.grimoire.calculator/package.yaml @@ -0,0 +1,42 @@ +name: Calculator +id: com.grimoire.calculator +type: widget +version: 1.2.0 +author: Nebuff +description: Simple, scientific and programming calculators, with a unit converter. +license: MIT +min_grimoire_version: 2.1.0 +platforms: [all] +artifact: + path: calculator.bin + sha256: cbdded0a54dfea3029f85dfe92ecb016dfd4ebe5be9f08ab55c15309269f42cb + size: 106958 +capabilities: [] +settings: + - key: default_calculator + label: Default calculator + type: choice + default: Simple + choices: [Simple, Scientific, Programming] + - key: enable_simple + label: Simple calculator + type: toggle + default: true + - key: enable_scientific + label: Scientific calculator + type: toggle + default: true + - key: enable_programming + label: Programming calculator + type: toggle + default: true +spec: + runtime: wasm + entry: _start + icon: calculator + minimizable: true + size: + mode: resizable + default: [340, 560] + min: [280, 480] + max: [620, 820] diff --git a/tests/fixtures/widgetpkg/packages/index.json b/tests/fixtures/widgetpkg/packages/index.json new file mode 100644 index 00000000..c36318e1 --- /dev/null +++ b/tests/fixtures/widgetpkg/packages/index.json @@ -0,0 +1,6 @@ +{ + "version": 1, + "packages": [ + {"id":"com.example.timer","name":"Timer","version":"1.0.0","author":"Jane Doe","description":"A small timer widget.","icon":"timer","path":"packages/widgets/com.example.timer/timer.bin","sha":"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08","installed_at":1,"source_url":"https://example.org/timer.yaml"} + ] +} diff --git a/tests/fixtures/widgetpkg/packages/widgets/com.example.timer/package.yaml b/tests/fixtures/widgetpkg/packages/widgets/com.example.timer/package.yaml new file mode 100644 index 00000000..82c5ac14 --- /dev/null +++ b/tests/fixtures/widgetpkg/packages/widgets/com.example.timer/package.yaml @@ -0,0 +1,33 @@ +name: Timer +id: com.example.timer +type: widget +version: 1.0.0 +author: Jane Doe +description: A small timer widget. +license: MIT +min_grimoire_version: 2.0.0 +platforms: [all] +repository: https://example.org/timer +artifact: + path: timer.bin + sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + size: 4 +capabilities: [editor:overlay, storage:widget-local] +settings: + - key: show_seconds + label: Show seconds + type: toggle + default: true + - key: layout + label: Layout + type: choice + default: compact + choices: [compact, large] +spec: + runtime: wasm + entry: _start + icon: timer + minimizable: true + size: + mode: fixed + default: [220, 160] diff --git a/tests/fixtures/widgetpkg/packages/widgets/com.example.timer/timer.bin b/tests/fixtures/widgetpkg/packages/widgets/com.example.timer/timer.bin new file mode 100644 index 00000000..30d74d25 --- /dev/null +++ b/tests/fixtures/widgetpkg/packages/widgets/com.example.timer/timer.bin @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/tests/scenario-times.txt b/tests/scenario-times.txt index 892a32dc..969b66ef 100644 --- a/tests/scenario-times.txt +++ b/tests/scenario-times.txt @@ -324,4 +324,5 @@ z_tpl_9_white_caches 28.0 z_tpl_a_restore_first_close 1.8 z_tpl_b_previews_leave_cards 4.1 z_undo_patches 11.7 +z_widgets 8.0 z_wifi 1.5 diff --git a/tests/scenarios/v_actions_screen.qs b/tests/scenarios/v_actions_screen.qs index 8faf7da9..c79a083d 100644 --- a/tests/scenarios/v_actions_screen.qs +++ b/tests/scenarios/v_actions_screen.qs @@ -31,7 +31,7 @@ key 16 0 expect settings.pinch_zoom is 0 key 16 0 expect settings.pinch_zoom is 1 -expect editor.panel_rect is 1704 220 128 1734 +expect editor.panel_rect is 1704 220 128 1842 expect display.presents not clear key 17 0 expect settings.theme is classic diff --git a/tests/scenarios/y_all_screens.qs b/tests/scenarios/y_all_screens.qs index 9afcd152..335d0498 100644 --- a/tests/scenarios/y_all_screens.qs +++ b/tests/scenarios/y_all_screens.qs @@ -359,7 +359,7 @@ expect library.sheet is none tap 1535 95 wait 50 expect library.sheet is settings -tap library settings.cat.5 +tap library settings.cat.6 wait 50 tap library ko wait 50 @@ -378,7 +378,7 @@ wait 100 shot 03-settings-other-style tap library theme wait 100 -tap library settings.cat.5 +tap library settings.cat.6 wait 50 tap library mirror wait 50 @@ -1284,18 +1284,18 @@ tap 267 530 wait 200 expect screen is editor shot 48-editor-landscape -touch down 2026 264 +touch down 2026 179 wait 700 -touch up 2026 264 +touch up 2026 179 wait 100 expect editor.quicksize is ballpoint shot 48-quick-sizes-landscape tap 600 700 wait 150 expect editor.quicksize is 0 -touch down 2026 372 +touch down 2026 287 wait 700 -touch up 2026 372 +touch up 2026 287 wait 100 expect editor.quicksize is eraser shot 48-quick-sizes-eraser-landscape diff --git a/tests/scenarios/y_fonts_own_2_missing.qs b/tests/scenarios/y_fonts_own_2_missing.qs index d0587377..ec882faa 100644 --- a/tests/scenarios/y_fonts_own_2_missing.qs +++ b/tests/scenarios/y_fonts_own_2_missing.qs @@ -60,7 +60,7 @@ expect settings.font_bold is Gone-Bold.ttf # Another setting saved: the lines stay tap 1535 95 wait 50 -tap library settings.cat.5 +tap library settings.cat.6 wait 100 tap library mirror wait 50 diff --git a/tests/scenarios/y_fonts_unknown.qs b/tests/scenarios/y_fonts_unknown.qs index 05816cbf..1f84edbb 100644 --- a/tests/scenarios/y_fonts_unknown.qs +++ b/tests/scenarios/y_fonts_unknown.qs @@ -27,7 +27,7 @@ expect library.sheet is settings expect font is terminess expect settings.kept.font is comic-sans # Another setting saved: the line stays -tap library settings.cat.5 +tap library settings.cat.6 wait 50 tap library mirror wait 50 diff --git a/tests/scenarios/y_live_chip.qs b/tests/scenarios/y_live_chip.qs index 307bf2fe..d70dce6b 100644 --- a/tests/scenarios/y_live_chip.qs +++ b/tests/scenarios/y_live_chip.qs @@ -22,26 +22,26 @@ tap 1564 2254 wait 400 expect screen is editor expect live.on is 1 -# Beside the panel (the panel is 128 wide and 1734 tall at x 1704, y 220, its header 80 tall): left of it, level with the header. -expect editor.panel_rect is 1704 220 128 1734 +# Beside the panel (the panel is 128 wide and 1842 tall at x 1704, y 220, its header 80 tall): left of it, level with the header. +expect editor.panel_rect is 1704 220 128 1842 expect live.chip is 1654 239 42 42 shot 01-beside-the-panel # It follows the panel: dragged to the middle of the page, the chip comes along; dragged to the left edge it is on # the panel's right. drag touch 1737 260 933 760 5 wait 400 -expect editor.panel_rect is 900 720 128 1734 -expect live.chip is 850 739 42 42 -drag touch 933 760 33 760 5 +expect editor.panel_rect is 900 638 128 1842 +expect live.chip is 850 657 42 42 +drag touch 933 660 33 660 5 wait 400 -expect editor.panel_rect is 0 720 128 1734 -expect live.chip is 136 739 42 42 +expect editor.panel_rect is 0 638 128 1842 +expect live.chip is 136 657 42 42 shot 02-left-edge # Folded, the panel is one box and the chip is level with it. tap panel collapse wait 400 expect editor.panel is collapsed -expect live.chip is 136 759 42 42 +expect live.chip is 136 677 42 42 shot 03-folded tap panel expand wait 400 @@ -53,7 +53,7 @@ expect live.chip is tap 70 70 wait 400 expect editor.modal is none -expect live.chip is 136 739 42 42 +expect live.chip is 136 657 42 42 # The Pages view covers everything: none there either. tap panel pages tap panel pages.graph @@ -67,7 +67,7 @@ expect live.chip is tap 100 100 wait 500 expect editor.modal is none -expect live.chip is 136 739 42 42 +expect live.chip is 136 657 42 42 # Back on the Library it is in the top right corner again, and gone with Live view. tap panel library wait 600 diff --git a/tests/scenarios/y_live_toolbar_menus.qs b/tests/scenarios/y_live_toolbar_menus.qs index 2c7e0a93..7c92fc0d 100644 --- a/tests/scenarios/y_live_toolbar_menus.qs +++ b/tests/scenarios/y_live_toolbar_menus.qs @@ -31,105 +31,105 @@ tap 510 460 tap 1564 2254 wait 400 expect screen is editor -expect editor.panel_rect is 1704 220 128 1734 -expect live.panel is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect editor.panel_rect is 1704 220 128 1842 +expect live.panel is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 expect display.presents not -1 # The Display sheet beside the panel, nothing changed: the toolbar stays in the browser. tap panel display wait 400 expect editor.modal is display # (the Kindle's refreshes as before: the pressed button, then the sheet with the button let go) -expect display.presents is fast 1718 1624 100 100, ui 0 0 1860 2480 -expect live.panel is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect display.presents is fast 1718 1732 100 100, ui 0 0 1860 2480 +expect live.panel is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 # The brightness dragged, a box ticked: it stays. expect light.intensity is 12 drag touch 900 296 1100 296 3 wait 400 expect light.intensity is 7 -expect live.panel is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect live.panel is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 tap panel display.newpage wait 400 expect settings.gesture_new_page is 0 -expect live.panel is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect live.panel is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 tap panel display.done wait 400 expect editor.modal is none # (the sheet again after the drag, the New page row pressed and the sheet again, the X pressed and the screen # without the sheet) expect display.presents is ui 0 0 1860 2480, fast 80 704 1700 120, ui 0 0 1860 2480, fast 1660 20 150 150, ui 0 0 1860 2480 -expect live.panel is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect live.panel is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 # Another sheet beside it (Paper), and closed again. tap panel paper wait 400 expect editor.modal is paper -expect live.panel is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect live.panel is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 tap 100 2400 wait 400 expect editor.modal is none -expect live.stale.1704.220.128.1734 is 0 +expect live.stale.1704.220.128.1842 is 0 # The panel dragged into the middle, where the Display sheet covers its top: the layer holds the sheet there and # the toolbar below it, as the Kindle shows them, while a setting changes and after the sheet closes. drag touch 1737 260 933 760 5 wait 400 -expect editor.panel_rect is 900 720 128 1734 -expect live.panel is 900 720 128 1734 -expect live.stale.900.720.128.1734 is 0 +expect editor.panel_rect is 900 638 128 1842 +expect live.panel is 900 638 128 1842 +expect live.stale.900.638.128.1842 is 0 tap panel display wait 400 expect editor.modal is display -expect live.panel is 900 720 128 1734 -expect live.stale.900.720.128.1734 is 0 +expect live.panel is 900 638 128 1842 +expect live.stale.900.638.128.1842 is 0 shot 02-display-over-the-panel drag touch 1100 296 900 296 3 wait 400 expect light.intensity is 2 -expect live.stale.900.720.128.1734 is 0 +expect live.stale.900.638.128.1842 is 0 tap panel display.newpage wait 400 expect settings.gesture_new_page is 1 -expect live.stale.900.720.128.1734 is 0 +expect live.stale.900.638.128.1842 is 0 tap panel display.done wait 400 expect editor.modal is none -expect live.panel is 900 720 128 1734 -expect live.stale.900.720.128.1734 is 0 -drag touch 933 760 1737 260 5 +expect live.panel is 900 638 128 1842 +expect live.stale.900.638.128.1842 is 0 +drag touch 933 660 1737 243 5 wait 400 -expect editor.panel_rect is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect editor.panel_rect is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 # Settings over the notebook: the frame is the whole screen and the browser shows what the Kindle does while a # setting changes there and in its Display sheet; closed, the toolbar's layer is back, in the style just picked. tap panel settings wait 600 expect editor.modal is settings expect live.panel is -expect live.stale.1704.220.128.1734 is 0 +expect live.stale.1704.220.128.1842 is 0 tap 250 422 wait 100 tap library rotate wait 600 expect settings.follow_rotation is 0 -expect live.stale.1704.220.128.1734 is 0 +expect live.stale.1704.220.128.1842 is 0 tap library display wait 600 -expect live.stale.1704.220.128.1734 is 0 +expect live.stale.1704.220.128.1842 is 0 drag touch 900 296 1100 296 3 wait 400 expect light.intensity is 7 -expect live.stale.1704.220.128.1734 is 0 +expect live.stale.1704.220.128.1842 is 0 tap library display.back wait 600 expect editor.modal is settings tap library dark wait 600 expect settings.invert is 1 -expect live.stale.1704.220.128.1734 is 0 +expect live.stale.1704.220.128.1842 is 0 tap library dark wait 600 expect settings.invert is 0 @@ -139,11 +139,11 @@ expect settings.follow_rotation is 1 tap library theme wait 600 expect settings.theme is classic -expect live.stale.1704.220.128.1734 is 0 +expect live.stale.1704.220.128.1842 is 0 tap library done wait 600 expect editor.modal is none -expect live.panel is 1704 220 128 1734 -expect live.stale.1704.220.128.1734 is 0 +expect live.panel is 1704 220 128 1842 +expect live.stale.1704.220.128.1842 is 0 shot 03-classic-after-settings quit diff --git a/tests/scenarios/y_menus_over_panel.qs b/tests/scenarios/y_menus_over_panel.qs index c6744e31..aa9889be 100644 --- a/tests/scenarios/y_menus_over_panel.qs +++ b/tests/scenarios/y_menus_over_panel.qs @@ -15,10 +15,10 @@ tap 510 460 tap 1564 2254 wait 400 expect screen is editor -# The panel down the left of the page, as low as it goes: 100 px from the left edge, to y 746 (the screen's height less the panel's 1734). +# The panel down the left of the page, as low as it goes: 100 px from the left edge, to y 638 (the screen's height less the panel's 1842). drag touch 1737 260 133 1200 6 wait 400 -expect editor.panel_rect is 100 746 128 1734 +expect editor.panel_rect is 100 638 128 1842 expect editor.layers is ok # The Links bar, along the bottom, over the panel's foot; closed again. key 37 0 @@ -74,15 +74,15 @@ tap panel tool-picker wait 400 # The quick sizes card (an eraser held 600 ms) beside the panel at the left, over the page: five chips (the fifth # at 12 mm), no Pen feel chip, the whole 912 x 416 card on the screen. -touch down 164 992 +touch down 164 884 wait 700 -touch up 164 992 +touch up 164 884 wait 300 expect editor.modal is quick-size expect editor.layers is ok -expect editor.quicksize.rect is 238 942 912 416 +expect editor.quicksize.rect is 238 834 912 416 expect editor.quicksize.chip.4 is 12 mm -expect editor.at.quicksize.4 is 1046 1127 +expect editor.at.quicksize.4 is 1046 1019 expect editor.at.quicksize.5 is expect editor.at.quicksize.pen-feel is shot 05-quick-sizes-over-panel @@ -101,7 +101,7 @@ wait 500 expect editor.modal is none expect editor.layers is ok # Dragged to the middle of the page (by its grip) and the Display sheet opened over most of it. -drag touch 133 774 833 760 6 +drag touch 133 666 833 760 6 wait 400 expect editor.modal is none expect editor.layers is ok @@ -113,14 +113,14 @@ tap 70 70 wait 400 expect editor.layers is ok # The same with the panel in the middle of the page: the card goes beside it, never over the held button. -touch down 864 978 +touch down 864 870 wait 700 -touch up 864 978 +touch up 864 870 wait 300 expect editor.modal is quick-size expect editor.layers is ok -expect editor.quicksize.rect is 814 1052 912 416 -expect editor.at.quicksize.4 is 1622 1237 +expect editor.quicksize.rect is 814 958 912 416 +expect editor.at.quicksize.4 is 1622 1143 expect editor.at.quicksize.5 is expect editor.at.quicksize.pen-feel is shot 07-quick-sizes-panel-in-the-middle diff --git a/tests/scenarios/y_touch_selftest.qs b/tests/scenarios/y_touch_selftest.qs index d8010232..a534bb4e 100644 --- a/tests/scenarios/y_touch_selftest.qs +++ b/tests/scenarios/y_touch_selftest.qs @@ -19,11 +19,12 @@ expect editor.panel_at.1768.1046 is expect editor.panel_at.1768.1242 is pages expect editor.panel_at.1768.1330 is next expect editor.panel_at.1768.1458 is links -expect editor.panel_at.1768.1566 is paper -expect editor.panel_at.1768.1674 is display +expect editor.panel_at.1768.1566 is widgets +expect editor.panel_at.1768.1674 is paper expect editor.panel_at.1768.682 is pen-feel -expect editor.panel_at.1768.1782 is settings -expect editor.panel_at.1768.1890 is library +expect editor.panel_at.1768.1782 is display +expect editor.panel_at.1768.1890 is settings +expect editor.panel_at.1768.1998 is library expect editor.panel_at.1768.810 is expect editor.panel_at.300.300 is # a stroke: Undo is there, with no wait for the settle diff --git a/tests/scenarios/y_touch_selftest_pins.qs b/tests/scenarios/y_touch_selftest_pins.qs index 7ad837c8..3603c943 100644 --- a/tests/scenarios/y_touch_selftest_pins.qs +++ b/tests/scenarios/y_touch_selftest_pins.qs @@ -14,7 +14,7 @@ wait 400 expect screen is editor expect editor.pins is highlighter,fineliner,marker expect editor.panel_button is 100 -expect editor.panel_rect is 1704 220 128 2058 +expect editor.panel_rect is 1704 220 128 2166 pen line 300 700 1300 720 20 0.6 0.6 tap panel undo expect editor.strokes is 0 @@ -27,10 +27,10 @@ expect editor.tool is eraser pentap panel tool:marker wait 200 expect editor.tool is marker -# sideways: the added Settings cog leaves 93 px buttons with three pins. +# sideways: the Widgets button leaves 88 px buttons with three pins. rotate 1 wait 400 -expect editor.panel_button is 93 +expect editor.panel_button is 88 expect editor.panel_fits is 0 pen line 300 700 1300 720 20 0.6 0.6 tap panel undo diff --git a/tests/scenarios/z_calculator_settings.qs b/tests/scenarios/z_calculator_settings.qs new file mode 100644 index 00000000..b10df634 --- /dev/null +++ b/tests/scenarios/z_calculator_settings.qs @@ -0,0 +1,99 @@ +# settings: status_mode=1 +# rust-only +# copy: tests/fixtures/widgetcalc . +# The calculator package's settings choose its default mode and which calculators its dropdown +# offers. Changing them applies to an open frame; a mode that is turned off falls back. +wait 300 +tap 965 95 +wait 100 +tap 1564 2254 +wait 300 +expect screen is editor +# Settings → Packages → Widgets → the calculator's detail page and settings. +tap panel settings +wait 400 +tap panel settings.cat.5 +wait 300 +tap panel settings.packages +wait 400 +expect editor.packages is 1 com.grimoire.calculator 1.2.0 +tap panel packages.row.0 +wait 300 +tap panel packages.settings +wait 400 +expect editor.package.0.settings.default_calculator is Simple +expect editor.package.0.settings.enable_simple is true +expect editor.package.0.settings.enable_scientific is true +expect editor.package.0.settings.enable_programming is true +shot 00-calculator-settings +# The default cycles Simple → Scientific; then Simple is turned off. +tap panel packages.setting.0 +wait 200 +expect editor.package.0.settings.default_calculator is Scientific +tap panel packages.setting.1 +wait 200 +expect editor.package.0.settings.enable_simple is false +shot 01-calculator-settings-changed +tap panel packages.close +wait 400 +expect screen is editor +# The popup opens the frame on the new default, and Simple is missing from the dropdown's modes. +tap panel widgets +wait 300 +tap panel widgets.com.grimoire.calculator +wait 400 +expect editor.widget.0.status is scientific|0|scientific,programming +shot 02-calculator-settings-frame +# Turning off the mode a frame is showing falls back to the first enabled calculator. +tap panel settings +wait 400 +tap panel settings.cat.5 +wait 300 +tap panel settings.packages +wait 400 +tap panel packages.row.0 +wait 300 +tap panel packages.settings +wait 400 +tap panel packages.setting.3 +wait 400 +expect editor.package.0.settings.enable_programming is false +tap panel packages.close +wait 400 +# The open frame reads the saved settings on its next draw. +expect editor.widget.0.status is scientific|0|scientific +shot 03-calculator-settings-fallback +# Reset restores all three calculators; the open frame keeps its valid mode. +tap panel settings +wait 400 +tap panel settings.cat.5 +wait 300 +tap panel settings.packages +wait 400 +tap panel packages.row.0 +wait 300 +tap panel packages.settings +wait 400 +tap panel packages.settings-reset +wait 400 +expect editor.package.0.settings.default_calculator is Simple +expect editor.package.0.settings.enable_simple is true +expect editor.package.0.settings.enable_scientific is true +expect editor.package.0.settings.enable_programming is true +tap panel packages.close +wait 400 +expect editor.widget.0.status is scientific|0|simple,scientific,programming +shot 04-calculator-settings-reset +# A new frame opens on the default again, and the old frame can be closed. +tap panel widget.0.close +wait 300 +expect editor.widgets is 0 +tap panel widgets +wait 300 +tap panel widgets.com.grimoire.calculator +wait 400 +expect editor.widget.0.status is simple|0|simple,scientific,programming +tap panel widget.0.close +wait 200 +wait 1800 +quit diff --git a/tests/scenarios/z_lasso_19_drag_dense.qs b/tests/scenarios/z_lasso_19_drag_dense.qs index 0503e6e2..2e8fce09 100644 --- a/tests/scenarios/z_lasso_19_drag_dense.qs +++ b/tests/scenarios/z_lasso_19_drag_dense.qs @@ -610,7 +610,7 @@ expect editor.strokes is 24 expect editor.undo_kind is lasso expect editor.sel_box is 1077 437 193 186 expect editor.drag_copy is 0 -expect display.presents is ui 10 220 1822 1734 +expect display.presents is ui 10 220 1822 1842 expect editor.live_matches_render is 1 expect editor.layers is ok shot 03-moved diff --git a/tests/scenarios/z_lasso_1_select_move.qs b/tests/scenarios/z_lasso_1_select_move.qs index a05bc72c..b0598f78 100644 --- a/tests/scenarios/z_lasso_1_select_move.qs +++ b/tests/scenarios/z_lasso_1_select_move.qs @@ -151,7 +151,7 @@ pentap panel redo wait 100 expect editor.strokes is 9 expect editor.live_matches_render is 1 -expect display.presents is fast 1718 868 100 100, ui 428 220 1404 1734 +expect display.presents is fast 1718 868 100 100, ui 428 220 1404 1842 # cut the pasted group: off the page, one step pen down 500 1300 pen move 1000 1300 diff --git a/tests/scenarios/z_link_4_undo.qs b/tests/scenarios/z_link_4_undo.qs index 0e4e5455..c89debd6 100644 --- a/tests/scenarios/z_link_4_undo.qs +++ b/tests/scenarios/z_link_4_undo.qs @@ -104,4 +104,4 @@ wait 300 expect editor.links is 2 2 expect toast is # (the panel's refresh, Redo enabled now, joins the boxes' one: a GL16 over the page, never a Full or a DU) -expect display.presents is fast 1718 760 100 100, ui 295 220 1537 1734 +expect display.presents is fast 1718 760 100 100, ui 295 220 1537 1842 diff --git a/tests/scenarios/z_pdf_darker_1_row.qs b/tests/scenarios/z_pdf_darker_1_row.qs index c7f1ae7e..b5210e10 100644 --- a/tests/scenarios/z_pdf_darker_1_row.qs +++ b/tests/scenarios/z_pdf_darker_1_row.qs @@ -9,7 +9,7 @@ tap library settings wait 100 expect library.sheet is settings -tap library settings.cat.5 +tap library settings.cat.6 wait 100 expect settings.pdf_gamma is 1.0 shot 01-system @@ -46,7 +46,7 @@ wait 600 expect screen is library tap library settings wait 100 -tap library settings.cat.5 +tap library settings.cat.6 wait 100 tap library darker-lines wait 100 diff --git a/tests/scenarios/z_pdf_darker_5_es_fit.qs b/tests/scenarios/z_pdf_darker_5_es_fit.qs index 5850fb5a..b904b773 100644 --- a/tests/scenarios/z_pdf_darker_5_es_fit.qs +++ b/tests/scenarios/z_pdf_darker_5_es_fit.qs @@ -7,7 +7,7 @@ # rust-only tap library settings wait 100 -tap library settings.cat.5 +tap library settings.cat.6 wait 100 shot 01-row-off tap library darker-lines diff --git a/tests/scenarios/z_pdf_darker_6_es_fit_classic.qs b/tests/scenarios/z_pdf_darker_6_es_fit_classic.qs index b94358b3..9d4fde65 100644 --- a/tests/scenarios/z_pdf_darker_6_es_fit_classic.qs +++ b/tests/scenarios/z_pdf_darker_6_es_fit_classic.qs @@ -8,7 +8,7 @@ # rust-only tap library settings wait 100 -tap library settings.cat.5 +tap library settings.cat.6 wait 100 shot 01-row-off tap library darker-lines diff --git a/tests/scenarios/z_qsize_1_hold.qs b/tests/scenarios/z_qsize_1_hold.qs index e5395f1e..dbfa7d50 100644 --- a/tests/scenarios/z_qsize_1_hold.qs +++ b/tests/scenarios/z_qsize_1_hold.qs @@ -59,7 +59,7 @@ expect editor.quicksize.chip.0 is 1 mm expect editor.quicksize.chip.4 is 12 mm expect editor.quicksize.rect is 782 632 912 416 # (the button's press look, then the card with the whole toolbar, whose marks moved with the pen, in one Ui) -expect display.presents is fast 1718 632 100 100, ui 782 220 1050 1950 +expect display.presents is fast 1718 632 100 100, ui 782 220 1050 2058 shot 01-eraser-card # The lift after the hold acts as nothing: the card stays, the eraser is not put back to the pencil. touch up 1768 682 diff --git a/tests/scenarios/z_rc2_controls.qs b/tests/scenarios/z_rc2_controls.qs index b5370811..23e57eeb 100644 --- a/tests/scenarios/z_rc2_controls.qs +++ b/tests/scenarios/z_rc2_controls.qs @@ -67,7 +67,7 @@ tap panel links expect editor.link_mode is 0 rotate 1 wait 200 -expect editor.panel_button is 93 +expect editor.panel_button is 88 tap panel shapes expect editor.shapes_menu is 1 shot 03-shapes-menu-landscape @@ -80,7 +80,7 @@ tap library done expect screen is editor expect editor.modal is none expect editor.pins is highlighter,fineliner,marker -expect editor.panel_button is 93 +expect editor.panel_button is 88 tap panel display expect editor.modal is display shot 04-display-without-status-mode diff --git a/tests/scenarios/z_refresh_1_toolbar.qs b/tests/scenarios/z_refresh_1_toolbar.qs index 6308b5bd..58d9c5af 100644 --- a/tests/scenarios/z_refresh_1_toolbar.qs +++ b/tests/scenarios/z_refresh_1_toolbar.qs @@ -14,7 +14,7 @@ wait 100 tap 1564 2254 wait 200 expect screen is editor -expect editor.panel_rect is 1704 220 128 1734 +expect editor.panel_rect is 1704 220 128 1842 # (the launch repaints the whole screen 1.2 s and 3.5 s after it starts: past both before counting) wait 3700 expect display.presents not -1 @@ -42,9 +42,9 @@ expect display.stale.800.300.400.1800 not 0 expect display.presents not -1 touch up 1737 700 wait 300 -expect editor.panel_rect is 1704 660 128 1734 +expect editor.panel_rect is 1704 638 128 1842 # one flash of the whole trail, where it began, went round and ended -expect display.presents is clean 867 220 965 2174 +expect display.presents is clean 867 220 965 2260 expect display.stale.800.300.400.1800 is 0 expect display.stale.0.300.1860.2100 is 0 expect editor.wear is 0 @@ -63,7 +63,7 @@ finger 1 move 1100 900 frame 100 pen hover 300 300 wait 300 -expect editor.panel_rect is 1067 746 128 1734 +expect editor.panel_rect is 1067 638 128 1842 expect display.presents has ui expect display.presents not has clean expect editor.wear is 0 owed diff --git a/tests/scenarios/z_refresh_2_erase.qs b/tests/scenarios/z_refresh_2_erase.qs index 2dfc8677..12435e4d 100644 --- a/tests/scenarios/z_refresh_2_erase.qs +++ b/tests/scenarios/z_refresh_2_erase.qs @@ -54,7 +54,7 @@ expect editor.strokes is 1 expect editor.wear is 8 pen leave wait 400 -expect display.presents is ui 270 220 1562 1734 +expect display.presents is ui 270 220 1562 1842 expect editor.wear is 8 # The scribble erased: past a quarter, but the pen is still near, so no flash yet. eraser line 800 650 820 1750 20 diff --git a/tests/scenarios/z_shape_8_sliders.qs b/tests/scenarios/z_shape_8_sliders.qs index 2d9e449b..2f7f1f2f 100644 --- a/tests/scenarios/z_shape_8_sliders.qs +++ b/tests/scenarios/z_shape_8_sliders.qs @@ -97,15 +97,15 @@ pen leave wait 100 expect editor.shapes_menu is 1 expect editor.strokes is 0 -# Sideways: the menu at 826,126, the rows centred at y 840 and 976, the tracks from x 1415. +# Sideways: the menu at 826,41, the rows centred at y 755 and 891, the tracks from x 1415. rotate 1 wait 300 -expect editor.tools_rect is 826 126 1116 1212 +expect editor.tools_rect is 826 41 1116 1212 shot 04-menu-sideways -touch down 1530 840 +touch down 1530 755 expect settings.shape_corner is 25 -touch up 1530 840 -tap 1553 976 +touch up 1530 755 +tap 1553 891 expect settings.shape_min_mm is 14 shot 05-sideways-set rotate 0 diff --git a/tests/scenarios/z_sideways_toolbar.qs b/tests/scenarios/z_sideways_toolbar.qs index a70a840e..fa8b2379 100644 --- a/tests/scenarios/z_sideways_toolbar.qs +++ b/tests/scenarios/z_sideways_toolbar.qs @@ -6,25 +6,25 @@ wait 300 tap 200 400 wait 300 -expect editor.panel_rect is 1704 220 128 1734 +expect editor.panel_rect is 1704 220 128 1842 rotate 1 wait 200 -expect editor.panel_rect is 1962 126 128 1734 +expect editor.panel_rect is 1962 41 128 1819 shot 01-right-margin # Flipping between landscape orientations also retains the margin placement. rotate 3 wait 200 -expect editor.panel_rect is 1962 126 128 1734 +expect editor.panel_rect is 1962 41 128 1819 rotate 0 wait 200 touch down 1736 260 touch move 100 260 touch up 100 260 wait 100 -expect editor.panel_rect is 68 220 128 1734 +expect editor.panel_rect is 68 220 128 1842 rotate 1 wait 200 -expect editor.panel_rect is 390 126 128 1734 +expect editor.panel_rect is 390 41 128 1819 shot 02-left-margin rotate 0 wait 200 @@ -33,5 +33,5 @@ key 17 0 expect settings.landscape_fit is 0 rotate 1 wait 200 -expect editor.panel_rect is 68 126 128 1734 +expect editor.panel_rect is 68 41 128 1819 shot 03-width-view-unchanged diff --git a/tests/scenarios/z_tool_2_pins.qs b/tests/scenarios/z_tool_2_pins.qs index cf8d390f..c08514d3 100644 --- a/tests/scenarios/z_tool_2_pins.qs +++ b/tests/scenarios/z_tool_2_pins.qs @@ -21,7 +21,7 @@ wait 400 expect screen is editor expect editor.pins is expect settings.panel_tools is -expect editor.panel_rect is 1704 220 128 1734 +expect editor.panel_rect is 1704 220 128 1842 expect editor.panel_button is 100 expect editor.tool_button is pencil # Pin mode: Highlighter, then Fineliner @@ -46,7 +46,7 @@ pentap editor picker.tool:fineliner wait 200 expect editor.pins is highlighter,fineliner expect settings.panel_tools is highlighter,fineliner -expect editor.panel_rect is 1704 220 128 1950 +expect editor.panel_rect is 1704 220 128 2058 expect editor.tool is pencil shot 02-two-pinned # Done, then a tap outside closes the picker @@ -134,13 +134,13 @@ expect editor.panel_rect is 1712 220 120 120 tap panel expand wait 300 expect editor.panel is expanded -expect editor.panel_rect is 1704 220 128 1950 +expect editor.panel_rect is 1704 220 128 2058 # Sideways: two pins fit where the panel was (its place kept from the collapse) rotate 1 wait 300 expect size is 2480x1860 -expect editor.panel_rect is 1962 30 128 1830 -expect editor.panel_button is 99 +expect editor.panel_rect is 1962 40 128 1820 +expect editor.panel_button is 93 shot 04-sideways-two-pins # The third pin added sideways (Marker): the panel keeps its 12 px margins, # its buttons 7% smaller; the picker stays where it opened (the fineliner's pin is in use: the @@ -157,8 +157,8 @@ pentap editor picker.tool:marker wait 200 expect editor.pins is highlighter,fineliner,marker expect settings.panel_tools is highlighter,fineliner,marker -expect editor.panel_rect is 1962 30 128 1820 -expect editor.panel_button is 93 +expect editor.panel_rect is 1962 40 128 1820 +expect editor.panel_button is 88 # A fourth: refused, with a toast pentap editor picker.tool:calligraphy wait 200 @@ -188,7 +188,7 @@ expect editor.tool is marker rotate 0 wait 300 expect size is 1860x2480 -expect editor.panel_rect is 1704 220 128 2058 +expect editor.panel_rect is 1704 220 128 2166 expect editor.panel_button is 100 shot 07-upright-three-pins # The tool button's own pen pinned (Fineliner out, Pencil in): the tool button shows a grid (the @@ -290,7 +290,7 @@ pentap editor picker.tool:pencil wait 200 expect editor.pins is expect settings.panel_tools is -expect editor.panel_rect is 1704 220 128 1734 +expect editor.panel_rect is 1704 220 128 1842 pentap editor picker.pin-mode wait 200 pentap 300 1800 diff --git a/tests/scenarios/z_tool_7_pins_colorsoft.qs b/tests/scenarios/z_tool_7_pins_colorsoft.qs index 70ee4c49..66d6ed99 100644 --- a/tests/scenarios/z_tool_7_pins_colorsoft.qs +++ b/tests/scenarios/z_tool_7_pins_colorsoft.qs @@ -1,7 +1,7 @@ # settings: status_mode=1 # Three pinned pens (panel_tools in settings.ini, as the tool picker's Pin mode writes it) on a # 1986x2648 screen (the Scribe 3 and the Scribe Colorsoft): the panel fits upright and sideways -# with its buttons at full size and its 12 px margins (editor.panel_rect: x y w h), the pins in +# with its buttons at full size upright, and 95 px buttons sideways (editor.panel_rect: x y w h), the pins in # their order under the tool button; collapsed it is the same square as ever. (The 1860x2480 # Scribes, sideways: z_tool_2_pins; every count of pins on both: rust/tests/test_panel.rs.) # root: b_library @@ -19,7 +19,7 @@ tap 347 636 wait 500 expect screen is editor expect editor.pins is highlighter,fineliner,marker -expect editor.panel_rect is 1830 220 128 2058 +expect editor.panel_rect is 1830 220 128 2166 expect editor.panel_button is 100 shot 01-upright-three-pins # The first pin, the highlighter, picked (under the tool button, 108 px apart) @@ -29,22 +29,22 @@ expect editor.tool is highlighter rotate 1 wait 300 expect size is 2648x1986 -expect editor.panel_rect is 2093 31 128 1955 -expect editor.panel_button is 100 +expect editor.panel_rect is 2093 27 128 1959 +expect editor.panel_button is 95 shot 02-sideways-three-pins # Collapsed sideways: the same square, where the panel's top right was pentap panel collapse wait 300 expect editor.panel is collapsed -expect editor.panel_rect is 2101 31 120 120 +expect editor.panel_rect is 2101 27 120 120 tap panel expand wait 300 expect editor.panel is expanded -expect editor.panel_rect is 2093 31 128 1955 +expect editor.panel_rect is 2093 27 128 1959 # Upright again: the panel where it was put sideways, as far right as it goes rotate 0 wait 300 -expect editor.panel_rect is 1858 31 128 2058 +expect editor.panel_rect is 1858 27 128 2166 expect editor.panel_button is 100 pentap panel library wait 500 diff --git a/tests/scenarios/z_tool_9_fit.qs b/tests/scenarios/z_tool_9_fit.qs index 605bec17..6ce60f7e 100644 --- a/tests/scenarios/z_tool_9_fit.qs +++ b/tests/scenarios/z_tool_9_fit.qs @@ -1,7 +1,7 @@ # settings: status_mode=1 # The panel with 0 to 3 pinned pens on the 2022 and 2024 Scribes' screen (1860x2480), upright and # sideways: always inside the screen with 12 px free above and below it, its buttons at full size -# (editor.panel_fits), but for two pins sideways (99 px) and three pins (93 px). Each pen is pinned in the +# (editor.panel_fits), but for one pin sideways (99 px), two (93 px) and three (88 px). Each pen is pinned in the # tool picker's Pin mode. (The Scribe 3's and the Colorsoft's screen: z_tool_a_fit_colorsoft.) # settings: mirror_pdf=0 # rust-only @@ -34,7 +34,8 @@ expect editor.pins is highlighter expect editor.panel_fits is 1 rotate 1 wait 300 -expect editor.panel_fits is 1 +expect editor.panel_fits is 0 +expect editor.panel_button is 99 rotate 0 wait 300 expect editor.panel_fits is 1 @@ -54,7 +55,7 @@ expect editor.panel_fits is 1 rotate 1 wait 300 expect editor.panel_fits is 0 -expect editor.panel_button is 99 +expect editor.panel_button is 93 rotate 0 wait 300 expect editor.panel_fits is 1 @@ -74,7 +75,7 @@ expect editor.panel_fits is 1 rotate 1 wait 300 expect editor.panel_fits is 0 -expect editor.panel_button is 93 +expect editor.panel_button is 88 rotate 0 wait 300 expect editor.panel_fits is 1 @@ -97,9 +98,9 @@ expect editor.pins is highlighter,fineliner,marker expect editor.panel_fits is 1 rotate 1 wait 300 -# Fourteen base buttons plus three pins fit within the margins; buttons are 93 px sideways. +# Fifteen base buttons plus three pins fit within the margins; buttons are 88 px sideways. expect editor.panel_fits is 0 -expect editor.panel_button is 93 +expect editor.panel_button is 88 shot 01-three-pins-sideways rotate 2 wait 300 @@ -110,7 +111,7 @@ rotate 3 wait 300 expect size is 2480x1860 expect editor.panel_fits is 0 -expect editor.panel_button is 93 +expect editor.panel_button is 88 rotate 0 wait 300 expect editor.panel_fits is 1 diff --git a/tests/scenarios/z_tool_a_fit_colorsoft.qs b/tests/scenarios/z_tool_a_fit_colorsoft.qs index 2b956e5f..bb89fd45 100644 --- a/tests/scenarios/z_tool_a_fit_colorsoft.qs +++ b/tests/scenarios/z_tool_a_fit_colorsoft.qs @@ -1,8 +1,8 @@ # settings: status_mode=1 # The panel with 0 to 3 pinned pens on the Scribe 3's and the Scribe Colorsoft's screen # (1986x2648), upright and sideways: always inside the screen with 12 px free above and below it, -# its buttons at full size (editor.panel_fits); older Scribes need smaller buttons sideways with -# two or three pins (z_tool_9_fit). Each +# its buttons at full size upright (editor.panel_fits); sideways three pins need 95 px buttons. +# The older Scribes' screen: z_tool_9_fit. Each # pen is pinned in the tool picker's Pin mode, in a notebook b_library made. # root: b_library # env: GRIMOIRE_SIM_SIZE=1986x2648 @@ -76,7 +76,7 @@ expect editor.pins is highlighter,fineliner,marker expect editor.panel_fits is 1 rotate 1 wait 300 -expect editor.panel_fits is 1 +expect editor.panel_fits is 0 rotate 0 wait 300 expect editor.panel_fits is 1 @@ -99,7 +99,7 @@ expect editor.pins is highlighter,fineliner,marker expect editor.panel_fits is 1 rotate 1 wait 300 -expect editor.panel_fits is 1 +expect editor.panel_fits is 0 shot 01-three-pins-sideways rotate 2 wait 300 @@ -109,8 +109,8 @@ expect editor.panel_button is 100 rotate 3 wait 300 expect size is 2648x1986 -expect editor.panel_fits is 1 -expect editor.panel_button is 100 +expect editor.panel_fits is 0 +expect editor.panel_button is 95 rotate 0 wait 300 expect editor.panel_fits is 1 diff --git a/tests/scenarios/z_tool_d_picker_middle.qs b/tests/scenarios/z_tool_d_picker_middle.qs index 21a2b732..19a19926 100644 --- a/tests/scenarios/z_tool_d_picker_middle.qs +++ b/tests/scenarios/z_tool_d_picker_middle.qs @@ -14,7 +14,7 @@ tap 510 460 tap 1564 2254 wait 400 expect screen is editor -expect editor.panel_rect is 900 220 128 1734 +expect editor.panel_rect is 900 220 128 1842 pentap panel tool-picker wait 200 expect editor.modal is tools @@ -64,7 +64,7 @@ wait 300 pentap panel tool-picker wait 200 expect editor.modal is tools -expect editor.tools_rect is 826 126 1116 768 +expect editor.tools_rect is 826 41 1116 768 pentap 300 1700 wait 200 expect editor.modal is none diff --git a/tests/scenarios/z_toolbar_edges.qs b/tests/scenarios/z_toolbar_edges.qs index f24d4533..f629faa4 100644 --- a/tests/scenarios/z_toolbar_edges.qs +++ b/tests/scenarios/z_toolbar_edges.qs @@ -7,35 +7,35 @@ wait 300 tap 200 400 wait 300 -expect editor.panel_rect is 1704 220 128 1734 +expect editor.panel_rect is 1704 220 128 1842 drag touch 1737 260 1737 0 5 wait 300 -expect editor.panel_rect is 1704 0 128 1734 +expect editor.panel_rect is 1704 0 128 1842 expect editor.layers is ok expect editor.panel_at.1737.30 is grip expect editor.panel_at.1768.138 is tool-picker -tap 1768 1454 +tap 1768 1562 wait 300 expect editor.modal is display tap panel display.done wait 300 expect editor.modal is none -# The foot on the bottom edge (2480 less the panel's 1734). +# The foot on the bottom edge (2480 less the panel's 1842). drag touch 1737 40 1737 2470 5 wait 300 -expect editor.panel_rect is 1704 746 128 1734 +expect editor.panel_rect is 1704 638 128 1842 expect editor.layers is ok # Sideways it keeps to the edges too: dragged up, its top at y 0. rotate 1 wait 300 -expect editor.panel_rect is 1962 126 128 1734 -drag touch 1995 166 1995 0 5 +expect editor.panel_rect is 1962 41 128 1819 +drag touch 1995 60 1995 0 5 wait 300 -expect editor.panel_rect is 1962 0 128 1734 +expect editor.panel_rect is 1962 0 128 1819 expect editor.layers is ok rotate 0 wait 300 -expect editor.panel_rect is 1732 0 128 1734 +expect editor.panel_rect is 1732 0 128 1842 # A drag the pen's coming near cancels (the off-screen cancel) stays where it was last drawn, never # thrown into the corner. pen leave @@ -48,7 +48,7 @@ finger 1 move 1765 440 frame 100 pen hover 300 300 wait 300 -expect editor.panel_rect is 1732 400 128 1734 +expect editor.panel_rect is 1732 400 128 1842 finger 1 up 1765 440 frame pen leave diff --git a/tests/scenarios/z_touch_rejections.qs b/tests/scenarios/z_touch_rejections.qs index b9d0066f..b8116c50 100644 --- a/tests/scenarios/z_touch_rejections.qs +++ b/tests/scenarios/z_touch_rejections.qs @@ -70,11 +70,11 @@ wait 100 tap 1564 2254 wait 300 expect screen is editor -expect editor.panel_at.1768.1674 is display -pen hover 1530 1674 -finger 1 down 1768 1674 +expect editor.panel_at.1768.1782 is display +pen hover 1530 1782 +finger 1 down 1768 1782 frame 40 -finger 1 up 1768 1674 +finger 1 up 1768 1782 frame wait 300 expect editor.modal is display diff --git a/tests/scenarios/z_touch_taps.qs b/tests/scenarios/z_touch_taps.qs index 79775375..7c6065a7 100644 --- a/tests/scenarios/z_touch_taps.qs +++ b/tests/scenarios/z_touch_taps.qs @@ -53,9 +53,9 @@ expect editor.modal is none # the nearest button; a greyed-out button (Previous, on page 1) still takes nothing. expect editor.panel_at.1768.517 is eraser expect editor.panel_at.1768.522 is shapes -expect editor.panel_at.1710.1674 is display +expect editor.panel_at.1710.1782 is display expect editor.panel_at.1768.1190 is -tap 1710 1674 +tap 1710 1782 wait 300 expect editor.modal is display tap 1735 95 diff --git a/tests/scenarios/z_widget_packages.qs b/tests/scenarios/z_widget_packages.qs new file mode 100644 index 00000000..6c2b884d --- /dev/null +++ b/tests/scenarios/z_widget_packages.qs @@ -0,0 +1,104 @@ +# settings: status_mode=1 +# rust-only +# copy: tests/fixtures/widgetpkg . +# The widget package manager: an installed package appears in Packages → Widgets and in the widget +# popup, a frame opens from it, Remove asks first, and Install from repository... opens the repository +# keyboard. +wait 300 +# From the Library: Settings → Packages → Widgets, then the X closes Settings back to the Library. +tap library settings +wait 400 +tap library settings.cat.5 +wait 300 +tap library settings.packages +wait 400 +expect editor.packages.open is 1 +tap library packages.close +wait 300 +expect screen is library +# Open a notebook for the editor's own Settings and the widget frames. +tap 965 95 +wait 100 +tap 1564 2254 +wait 300 +expect screen is editor +# Settings → Packages → Widgets (not the popup): the category and its Widgets row. +tap panel settings +wait 400 +tap panel settings.cat.5 +wait 300 +shot 00-settings-packages +tap panel settings.packages +wait 400 +expect editor.packages.open is 1 +expect editor.packages is 1 com.example.timer 1.0.0 +expect editor.package.com.example.timer is 1.0.0 +shot 01-packages +# A tap that finds no control (the empty part of the page) draws and refreshes nothing: +# the page is not redrawn for a contact that changed nothing. +expect display.presents not -1 +tap 900 1500 +wait 120 +expect display.presents is +# The installed package is in the popup too, and opens as a frame. +tap panel packages.close +wait 300 +tap panel widgets +wait 300 +tap panel widgets.com.example.timer +wait 400 +expect editor.widgets is 1 com.example.timer +shot 02-package-widget +tap panel widget.com.example.timer.close +wait 300 +# Its detail page, then Remove with its question. This time the popup's Manage widgets... opens +# the same Settings page. +tap panel widgets +wait 200 +tap panel widgets.manage +wait 400 +tap panel packages.row.com.example.timer +wait 300 +shot 03-package-detail +# The package's own settings: manifest-defined rows, saved as they are tapped, and reset together. +tap panel packages.settings +wait 300 +expect editor.package.com.example.timer.settings.show_seconds is true +expect editor.package.com.example.timer.settings.layout is compact +shot 03a-package-settings +tap panel packages.setting.show_seconds +wait 200 +expect editor.package.com.example.timer.settings.show_seconds is false +tap panel packages.setting.layout +wait 200 +expect editor.package.com.example.timer.settings.layout is large +shot 03b-package-settings-changed +tap panel packages.settings-reset +wait 200 +expect editor.package.com.example.timer.settings.show_seconds is true +expect editor.package.com.example.timer.settings.layout is compact +tap panel packages.back +wait 300 +tap panel packages.remove +wait 300 +shot 04-remove-question +tap panel packages.remove-yes +wait 400 +expect editor.packages is 0 +expect editor.packages.open is 1 +shot 05-package-removed +tap panel packages.install +wait 400 +shot 06-install-keyboard +# The repository is typed on the one global keyboard: a key refreshes its own line and key on the +# fast waveform, never the page under it (the page is not drawn again until Done or Cancel). +expect keyboard.draws not -1 +expect display.presents not -1 +tap 160 1787 +wait 100 +expect keyboard.draws is 2 +expect display.presents has fast +expect display.presents not has full +expect display.presents not has ui +shot 07-install-keyboard-typed +quit diff --git a/tests/scenarios/z_widgets.qs b/tests/scenarios/z_widgets.qs new file mode 100644 index 00000000..e7bc7a4f --- /dev/null +++ b/tests/scenarios/z_widgets.qs @@ -0,0 +1,119 @@ +# settings: status_mode=1 +# rust-only +# copy: tests/fixtures/widgetcalc . +# The installed calculator package: the toolbar's Widgets button opens the catalog popup; its row +# opens a frame; the frame draws its own keypad through the generic WebAssembly host. Controls are +# the package's hit regions, reached as widget.0.hit.N, and the status line it reports is read with +# editor.widget.0.status. The title's minimize button shrinks it and a tap on the title restores it; +# the title bar drags; the close button removes it. +wait 300 +tap 965 95 +wait 100 +tap 1564 2254 +wait 300 +expect screen is editor +expect editor.widgets is 0 +expect editor.widgets.open is 0 +tap panel widgets +wait 300 +expect editor.widgets.open is 1 +shot 01-widgets-popup +tap panel widgets.com.grimoire.calculator +wait 400 +expect editor.widgets.open is 0 +expect editor.widgets is 1 com.grimoire.calculator +expect editor.widget.0.state is normal +expect editor.widget.0.status is simple|0|simple,scientific,programming +shot 02-calculator-open +# 1 + 2 = 3 +tap panel widget.0.hit.12 +tap panel widget.0.hit.15 +tap panel widget.0.hit.13 +tap panel widget.0.hit.19 +wait 300 +expect editor.widget.0.status is simple|3|simple,scientific,programming +shot 03-calculator-three +# 3 x 4 = 12 +tap panel widget.0.hit.7 +tap panel widget.0.hit.8 +tap panel widget.0.hit.19 +wait 300 +expect editor.widget.0.status is simple|12|simple,scientific,programming +shot 04-calculator-twelve +# 1 / 0 = Error, and AC starts again. +tap panel widget.0.hit.0 +tap panel widget.0.hit.12 +tap panel widget.0.hit.3 +tap panel widget.0.hit.16 +tap panel widget.0.hit.19 +wait 300 +expect editor.widget.0.status is simple|Error|simple,scientific,programming +shot 05-calculator-error +tap panel widget.0.hit.0 +wait 200 +expect editor.widget.0.status is simple|0|simple,scientific,programming +# The mode dropdown; the scientific keypad evaluates an expression. +tap panel widget.0.hit.100 +wait 200 +shot 06-calculator-modes +tap panel widget.0.hit.102 +wait 300 +expect editor.widget.0.status is scientific|0|simple,scientific,programming +# sin(30) = 0.5 +tap panel widget.0.hit.5 +tap panel widget.0.hit.27 +tap panel widget.0.hit.28 +tap panel widget.0.hit.24 +wait 300 +expect editor.widget.0.status is scientific|0.5|simple,scientific,programming +shot 07-calculator-scientific +# The programmer keypad converts bases and opens the unit converter. +tap panel widget.0.hit.100 +wait 200 +tap panel widget.0.hit.103 +wait 300 +expect editor.widget.0.status is programming|0|simple,scientific,programming +tap panel widget.0.hit.24 +tap panel widget.0.hit.27 +wait 200 +expect editor.widget.0.status is programming|10|simple,scientific,programming +tap panel widget.0.hit.1 +wait 200 +expect editor.widget.0.status is programming|0xA|simple,scientific,programming +tap panel widget.0.hit.2 +wait 200 +expect editor.widget.0.status is programming|10|simple,scientific,programming +shot 08-calculator-programming +tap panel widget.0.hit.31 +wait 300 +shot 09-calculator-units +tap panel widget.0.hit.202 +wait 300 +shot 10-calculator-units-category +tap panel widget.0.hit.210 +wait 300 +# Back to the simple keypad. +tap panel widget.0.hit.100 +wait 200 +tap panel widget.0.hit.101 +wait 300 +expect editor.widget.0.status is simple|0|simple,scientific,programming +# Minimize, restore, and drag by the title. +tap panel widget.0.min +wait 300 +expect editor.widget.0.state is minimized +shot 11-calculator-minimized +tap panel widget.0.title +wait 300 +expect editor.widget.0.state is normal +drag touch 1546 60 1100 500 8 +wait 300 +expect editor.widget.0.state is normal +expect editor.owner is none +shot 12-calculator-dragged +tap panel widget.0.close +wait 300 +expect editor.widgets is 0 +shot 13-calculator-closed +wait 1800 +quit diff --git a/tools/crate_licenses.py b/tools/crate_licenses.py index 5da32b1a..ea9b2c3b 100755 --- a/tools/crate_licenses.py +++ b/tools/crate_licenses.py @@ -2,7 +2,8 @@ """app/licenses/rust-crates.txt (2.1.0-beta.2, DESIGN.md 5, D22): the licenses of the Rust crates Cargo.lock names for the Kindle binary (all of them: built in, build time only, or named and not compiled), and the notices of the data hayro carries (Foxit's standard fonts, Adobe's CMaps, the ICC profiles). Written at package time from -`cargo metadata --frozen` for the Kindle target, so it names exactly the crates Cargo.lock holds; +`cargo metadata --frozen`, so it names exactly the crates Cargo.lock holds, including proc macros that +run only on the build host; tests/package_check.sh checks every one of them is in it. A crate offered under "A OR B" is taken under the first of MIT, Zlib, BSD-3-Clause, Unlicense, 0BSD and @@ -68,7 +69,7 @@ def main(): cargo = sys.argv[3] if len(sys.argv) > 3 else "cargo" meta = json.loads( subprocess.run( - [cargo, "metadata", "--format-version", "1", "--frozen", "--filter-platform", "armv7-unknown-linux-musleabihf"], + [cargo, "metadata", "--format-version", "1", "--frozen"], cwd=rust, check=True, capture_output=True, text=True, ).stdout ) diff --git a/tools/widget-pack.sh b/tools/widget-pack.sh new file mode 100755 index 00000000..5dfbcbb3 --- /dev/null +++ b/tools/widget-pack.sh @@ -0,0 +1,205 @@ +#!/bin/sh +# Finish a Grimoire widget package: put a built artifact at the manifest's artifact.path and write +# the size and SHA-256 the installer checks. With no built file, check the pair already there. +# +# usage: tools/widget-pack.sh PACKAGE_DIR [BUILT_FILE] +# +# PACKAGE_DIR is the folder with package.yaml (the repository root). BUILT_FILE is the single file +# the package installs (a .wasm module, or the calculator's placeholder). It is copied to +# artifact.path, then artifact.size and artifact.sha256 are rewritten. Without BUILT_FILE the +# existing artifact must already match. +# +# The manifest must use the block form of artifact: with path, sha256 and size. This script edits +# only those two numbers: bump version yourself, and update a releases entry for the current +# version by hand (it has its own sha256). + +set -u + +die() { + printf 'widget-pack: %s\n' "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +usage: tools/widget-pack.sh PACKAGE_DIR [BUILT_FILE] + + PACKAGE_DIR the folder holding package.yaml + BUILT_FILE copy this file to artifact.path and write its size and SHA-256 + +Without BUILT_FILE, check the artifact already at artifact.path against the manifest. +EOF +} + +case "${1:-}" in + -h|--help) + usage + exit 0 + ;; +esac + +[ $# -ge 1 ] && [ $# -le 2 ] || { + usage >&2 + exit 2 +} + +dir=$1 +built=${2:-} +manifest=$dir/package.yaml + +[ -d "$dir" ] || die "not a directory: $dir" +[ -f "$manifest" ] || die "no package.yaml in $dir" +[ -r "$manifest" ] || die "cannot read $manifest" + +if grep -Eq '^artifact:[[:blank:]]*\{' "$manifest"; then + die "package.yaml uses an inline artifact: mapping; write it as a block with path, sha256 and size" +fi +if ! grep -Eq '^artifact:[[:blank:]]*$' "$manifest"; then + die "package.yaml has no top-level artifact: block" +fi + +# A scalar from package.yaml's artifact: block, unquoted. +artifact_field() { + awk -v key="$1" ' + BEGIN { inart = 0 } + /^artifact:[[:blank:]]*$/ { inart = 1; next } + inart && /^[^[:blank:]]/ { exit } + inart { + line = $0 + sub(/^[[:blank:]]*/, "", line) + name = line + sub(/:.*/, "", name) + if (name != key) next + sub(/^[^:]*:[[:blank:]]*/, "", line) + sub(/[[:blank:]]+#.*$/, "", line) + sub(/[[:blank:]]+$/, "", line) + if (line ~ /^".*"$/ || line ~ /^\047.*\047$/) + line = substr(line, 2, length(line) - 2) + print line + exit + } + ' "$manifest" +} + +path=$(artifact_field path) +sha=$(artifact_field sha256) +size=$(artifact_field size) + +[ -n "$path" ] || die "artifact.path is missing" +[ -n "$sha" ] || die "artifact.sha256 is missing (add a 64-digit placeholder first)" +[ -n "$size" ] || die "artifact.size is missing (add a placeholder first)" +[ ${#path} -le 240 ] || die "artifact.path is longer than 240 characters" + +case $path in + /*) die "artifact.path must be relative" ;; + package.yaml) die "artifact.path cannot be package.yaml" ;; + state|state/*) die "artifact.path cannot be inside state/" ;; +esac +case $path in + *\\*) die "artifact.path cannot contain a backslash" ;; +esac +case "/$path/" in + *"//"*) die "artifact.path has an empty component" ;; + *"/../"*|*"/./"*) die "artifact.path has a . or .. component" ;; +esac + +dest=$dir/$path + +if [ -n "$built" ]; then + [ -f "$built" ] || die "not a file: $built" + [ -r "$built" ] || die "cannot read $built" + mkdir -p "$(dirname "$dest")" || die "cannot make the folder for $dest" + if [ -e "$dest" ] && cmp -s "$built" "$dest"; then + : + else + cp "$built" "$dest" || die "cannot copy $built to $dest" + fi +fi + +[ -f "$dest" ] || die "no artifact at $dest (pass the built file to install it)" + +sha_tool= +if command -v sha256sum >/dev/null 2>&1; then + sha_tool=sha256sum +elif command -v shasum >/dev/null 2>&1; then + sha_tool=shasum +elif command -v openssl >/dev/null 2>&1; then + sha_tool=openssl +else + die "need sha256sum, shasum or openssl to compute the digest" +fi + +if [ "$sha_tool" = sha256sum ]; then + got_sha=$(sha256sum "$dest" | awk '{ print $1 }') || die "sha256sum failed" +elif [ "$sha_tool" = shasum ]; then + got_sha=$(shasum -a 256 "$dest" | awk '{ print $1 }') || die "shasum failed" +else + got_sha=$(openssl dgst -sha256 "$dest" | sed 's/.*= //') || die "openssl failed" +fi +got_sha=$(printf '%s' "$got_sha" | tr 'ABCDEF' 'abcdef') +case $got_sha in + ""|*[!0-9a-f]*) die "could not read the artifact's SHA-256" ;; +esac +[ ${#got_sha} -eq 64 ] || die "could not read the artifact's SHA-256" + +got_size=$(wc -c < "$dest" | tr -d '[:space:]') +[ -n "$got_size" ] || die "could not read the artifact's size" +[ "$got_size" -gt 0 ] 2>/dev/null || die "the artifact is empty" +[ "$got_size" -le 33554432 ] 2>/dev/null || die "the artifact is over 32 MiB" + +if [ -z "$built" ]; then + old_sha=$(printf '%s' "$sha" | tr 'ABCDEF' 'abcdef') + if [ "$old_sha" = "$got_sha" ] && [ "$size" = "$got_size" ]; then + printf 'widget-pack: %s is up to date (%s bytes, sha256 %s)\n' "$path" "$got_size" "$got_sha" + exit 0 + fi + printf 'widget-pack: %s does not match package.yaml\n' "$path" >&2 + printf ' manifest: %s bytes, sha256 %s\n' "$size" "$sha" >&2 + printf ' artifact: %s bytes, sha256 %s\n' "$got_size" "$got_sha" >&2 + printf 'widget-pack: pass the built file to update the manifest\n' >&2 + exit 1 +fi + +tmp=$manifest.tmp.$$ +trap 'rm -f "$tmp"' 0 +trap 'exit 1' 1 2 15 + +if ! awk -v size="$got_size" -v sha="$got_sha" ' + function indent(s) { + match(s, /^[[:blank:]]*/) + return substr(s, 1, RLENGTH) + } + BEGIN { inart = 0; done_size = 0; done_sha = 0 } + /^artifact:[[:blank:]]*$/ { inart = 1; print; next } + inart && /^[^[:blank:]]/ { inart = 0 } + { + if (inart) { + line = $0 + sub(/^[[:blank:]]*/, "", line) + name = line + sub(/:.*/, "", name) + if (name == "size") { + print indent($0) "size: " size + done_size = 1 + next + } + if (name == "sha256") { + print indent($0) "sha256: " sha + done_sha = 1 + next + } + } + print + } + END { + if (!done_size || !done_sha) + exit 3 + } +' "$manifest" > "$tmp"; then + die "package.yaml has no artifact.size or artifact.sha256 line to replace" +fi + +mv "$tmp" "$manifest" || die "cannot write $manifest" +tmp= +printf 'widget-pack: %s -> %s (%s bytes, sha256 %s)\n' "$built" "$path" "$got_size" "$got_sha" +printf 'widget-pack: package.yaml updated; bump version and update any releases entry by hand\n' diff --git a/wiki/_Sidebar.md b/wiki/_Sidebar.md index c9034bf7..f334426f 100644 --- a/wiki/_Sidebar.md +++ b/wiki/_Sidebar.md @@ -4,6 +4,7 @@ - [About](About) - [Install](Install) - [Using Grimoire](Using-Grimoire) +- [Widgets](Widgets) - [Fonts and Language](Fonts-and-Language) - [Importing](Importing) - [Getting Pages Off the Kindle](Exporting) diff --git a/wiki/english/Home.md b/wiki/english/Home.md index b2742b99..b864f2ac 100644 --- a/wiki/english/Home.md +++ b/wiki/english/Home.md @@ -36,6 +36,7 @@ updating; most people keep OTA updates blocked. |---|---| | [Install](Install) | Requirements, the release zip, KPM, updating and uninstalling | | [Using Grimoire](Using-Grimoire) | The Library, paper, pens, the toolbar, the Index, links, Live view, Wi-Fi, sleep and the passcode | +| [Widgets](Widgets) | Installing, using, updating and removing widgets, and making your own | | [Fonts and Language](Fonts-and-Language) | English, Spanish, Japanese and Polish, the Classic fonts, and your own fonts | | [Importing](Importing) | Templates, pictures, PDFs and pages you already have | | [Getting Pages Off the Kindle](Exporting) | Wi-Fi Share, Effects, USB PDFs and SSH | diff --git a/wiki/english/Widgets.md b/wiki/english/Widgets.md new file mode 100644 index 00000000..54e3ba0d --- /dev/null +++ b/wiki/english/Widgets.md @@ -0,0 +1,115 @@ +# Widgets + +Widgets are small windows that sit over a notebook: a calculator, a timer, a clock. From 2.2 a +widget is a package you install, so the list can grow without updating Grimoire itself. + +A widget's code is part of its package, not part of Grimoire. Each one is a small WebAssembly +module that draws its own window and remembers its own state; Grimoire only gives it a frame, +input and the files it may use. That is why any installed package can add a calculator, a timer, a +sticky note or something else without a new Grimoire release. + +The catalog only lists installed packages, so install the ones you want from their repositories. + +## Opening and moving a widget + +Open a notebook and tap the **Widgets** button on the toolbar. The popup beside the panel lists the +installed widgets: + +- Tap a row to open its widget, or to raise it if it is already open. +- Drag the widget by its title bar to move it. +- **−** minimizes it to a small square; tap the square to bring it back at the same size. +- The grip at the bottom right resizes a resizable widget. +- **×** closes it. Closing a widget does not remove the package. + +Up to eight widgets can be open at once. Their places and sizes are remembered per device, so they +come back after a restart. A widget's own saved state comes back too: the calculator keeps its +current number through a minimize, a close and a restart. + +## The calculator's modes + +The calculator has three modes, chosen from the bar at the top of its window: + +- **Simple** is the four-function keypad with percent, sign and backspace. +- **Scientific** reads an expression: parentheses, `sin`, `cos` and `tan` in degrees, `ln`, `log`, + square root, powers, π and e. Type the whole expression, then tap `=`. +- **Programming** converts between decimal, hexadecimal, binary and octal, and has bitwise + AND/OR/XOR/NOT, shifts, MOD and power. Its **Un** key opens a converter for length, mass, data + and temperature. + +Each mode keeps its own screen while you switch. A package can turn modes off; the ones that are +on are the ones the dropdown lists. + +## Installing a widget + +Open **Library > Settings > Packages > Widgets**, or tap **Manage widgets...** at the bottom of the +Widgets popup. There is no built-in directory to browse: a widget's project page gives the address +to enter. + +1. Tap **Install from repository...** +2. Enter a GitHub repository as `user/repo`, or an `https://` address ending in `.yaml`, and tap + **Done** on the keyboard. +3. Read the trust page. It names the widget, its author and its version. Grimoire does not review, + vet or verify widget code, so install only from authors you trust, then tap **I trust this + author, continue**. +4. If Grimoire finds the package's license text, read it and tap **I have read and agree**. + +Grimoire downloads the manifest and then the widget, checks its size and SHA-256, and only then +writes anything. The Kindle needs Wi-Fi, and the address must be `https://`. A package can support +both Scribe models or just one. + +The detail page shows the author, and the license and repository when the package declares them. +**View QR code** shows a GitHub package's address as a QR code for a phone. + +## Changing a widget's settings + +If a package came with settings, its detail page has a **Settings...** button. It lists that +widget's own switches and choices, such as which features are on or how it looks. Tap a switch to +turn it on or off; tap a choice to move to the next value. Each tap is saved at once, and **Reset +all to defaults** puts every setting back. + +The calculator uses its settings to choose which calculator a new window opens with and which ones +the mode bar offers. If you turn off the calculator a window is showing, that window falls back to +the first one still on; turning every calculator off leaves Simple on. + +## Updating + +- **Check for updates** on a package's detail page checks that package. +- **Update all** at the top of the list checks every package that has a repository to update from, + one after another. + +Only a newer version is installed. Grimoire keeps the old version until the new one is in place so a +failed write can be rolled back. A package's own saved state is kept across an update. + +## Removing + +Open the package's detail page and tap **Remove...**, then **Remove** to confirm. Its widget is +closed and its files are deleted; your widget layout is kept. The package's own saved state +(`packages/widgets//state/`) is also kept, so installing the package again brings it back. + +## Safety and privacy + +- Installing is a trust decision. There is no review and no signature. +- A widget runs as WebAssembly with no network, filesystem or process access, and with a fixed + instruction budget, so a broken widget cannot freeze Grimoire. It can draw in its frame, read + its settings and read and write its own saved state. +- The size and SHA-256 checks catch a truncated or corrupted download. They are not a signature: + they come from the same repository as the widget. +- Packages are fetched over HTTPS with `curl`. Grimoire has no account, cloud or telemetry, and + the installer sends nothing except those requests. +- A widget's saved state stays on the Kindle under `packages/widgets//state/`, with the rest of + your Grimoire data. + +## Making your own + +The developer guide is in the Grimoire repository: +[Writing and publishing a widget package](https://github.com/ganten1998/grimoire-scribe/blob/main/docs/WIDGETS.md). +It covers the `package.yaml` manifest, the artifact and its checksum, local testing with the +headless runner, and publishing. The helper +[`tools/widget-pack.sh`](https://github.com/ganten1998/grimoire-scribe/blob/main/tools/widget-pack.sh) +copies a built artifact into place and writes its size and SHA-256. + +A package chooses a size, an icon and optionally a repository and license. It can declare only the +`editor:overlay` and `storage:widget-local` capabilities. Its module exports `widget_draw` and +`widget_tap` and draws through a small, generic host ABI; the guide lists every import and export. +Grimoire has no built-in widget implementations, so a package never needs changes to Grimoire's +source. diff --git a/wiki/english/_Sidebar.md b/wiki/english/_Sidebar.md index 6e0fdce5..2c0073ef 100644 --- a/wiki/english/_Sidebar.md +++ b/wiki/english/_Sidebar.md @@ -4,6 +4,7 @@ - [About](About) - [Install](Install) - [Using Grimoire](Using-Grimoire) +- [Widgets](Widgets) - [Fonts and Language](Fonts-and-Language) - [Importing](Importing) - [Getting Pages Off the Kindle](Exporting)