mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-11 08:21:06 +00:00
M6: Sketch import: merge main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
6258ad2786
169 files changed
+8894
-1516
No files matched your search
@@ -21,11 +21,10 @@ jobs:
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# The craft-fonts commit release.yml builds with. Needs fonts/latin-manifest.txt (Inter):
|
||||
# crates/text/build.rs fails a build that requires craft-fonts without it. Only craft-fonts'
|
||||
# pr/latin-presentation-fonts has it; its main has Noto Sans Georgian but no Inter. Re-pin
|
||||
# once one commit has both (storytold/craft-fonts#42).
|
||||
craft-fonts-ref: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
|
||||
# Combined Latin presentation and core UI catalog. Required web builds enforce
|
||||
# Inter Regular/SemiBold and Noto Sans Georgian Regular after asset-policy filtering.
|
||||
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
require-craft-fonts: true
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
@@ -32,4 +32,4 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
run-package-check: true
|
||||
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
|
||||
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
@@ -24,13 +24,12 @@ jobs:
|
||||
with:
|
||||
app-name: figcraft
|
||||
app-title: FigCraft
|
||||
# Needs fonts/latin-manifest.txt (Inter): crates/text/build.rs fails a release without it. Only
|
||||
# craft-fonts' pr/latin-presentation-fonts has it; its main has Noto Sans Georgian but no Inter.
|
||||
# Re-pin once one commit has both (storytold/craft-fonts#42).
|
||||
craft-fonts-ref: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
|
||||
# Combined Latin presentation and core UI catalog. Required web builds enforce
|
||||
# Inter Regular/SemiBold and Noto Sans Georgian Regular after asset-policy filtering.
|
||||
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
has-server: true
|
||||
# The browser has no system fonts: without craft-fonts the web build can't draw text (#885).
|
||||
# crates/text/build.rs keeps the web build to Inter.
|
||||
# crates/text/build.rs keeps the web allowlist small (Inter and Georgian).
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
secrets:
|
||||
|
||||
+11
-2
@@ -26,8 +26,17 @@ Release builds embed fonts from the optional craft-fonts build input
|
||||
|---|---|---|
|
||||
| Inter | SIL Open Font License 1.1 | https://github.com/rsms/inter |
|
||||
| Archivo | SIL Open Font License 1.1 | [Google Fonts / Archivo](https://github.com/google/fonts/tree/6c70c829f09ea345d3590406693220ea35c6553f/ofl/archivo) |
|
||||
| Roboto, Montserrat, Lato, Open Sans, Poppins, Nunito Sans, Merriweather, Playfair Display, Source Sans 3, Source Serif 4, Carlito, Caladea | SIL Open Font License 1.1 | Google Fonts / upstream repositories (see craft-fonts) |
|
||||
| Roboto, Montserrat, Lato, Open Sans, Poppins, Nunito Sans, Merriweather, Playfair Display, Carlito, Caladea | SIL Open Font License 1.1 | Google Fonts / upstream repositories (see craft-fonts) |
|
||||
| Liberation Sans, Serif, Mono | SIL Open Font License 1.1 | https://github.com/liberationfonts |
|
||||
| BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans Arabic | SIL Open Font License 1.1 | Google Fonts (see craft-fonts) |
|
||||
| BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans Arabic, Noto Sans Georgian | SIL Open Font License 1.1 | Google Fonts (see craft-fonts) |
|
||||
|
||||
The central catalog also contains Adobe-authored Source Sans 3 and Source Serif 4.
|
||||
FigCraft filters both families from every build in accordance with its asset policy.
|
||||
|
||||
egui's default fonts (compiled into the `egui`/`epaint` crates) keep their own licences (OFL / Apache-2.0 / Ubuntu Font Licence); see those crates.
|
||||
|
||||
## egui dependency font icons
|
||||
|
||||
| Asset | Author | Source | Licence | Use |
|
||||
|---|---|---|---|---|
|
||||
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 6d518fc7](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset, included by default_fonts independently of monochrome_emoji_fonts; emoji-icon-font.ttf is the full monochrome fallback. Dependency assets unmodified here; no font file copied into this repository. |
|
||||
Generated
+441
-115
File diff suppressed because it is too large.
Load diff
+30
-8
@@ -6,7 +6,7 @@ exclude = ["plugins"]
|
||||
# default-members = ["crates/*", "apps/figcraft", "apps/figcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.10.0"
|
||||
version = "0.11.2"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -35,8 +35,12 @@ figcraft-plugin = { path = "crates/plugin" }
|
||||
# Which paths stored in a document may be followed (craft-libs).
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
|
||||
# Who draws the window frame on Linux — the compositor or the app — so every Craft app shows the
|
||||
# same native titlebar per desktop (craft-libs). The `egui` feature adds `decorate`/`decorations`.
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1f805378d454dac48b5c214029d254055fdf961b", features = ["egui"] }
|
||||
# same native titlebar per desktop (craft-libs). FigCraft only reads the probe result and maps it
|
||||
# to its own `TitleBar`, so it does not enable craft-window's optional `egui` helpers (which would
|
||||
# pull a second egui family version). The rev is the last merged one; the released 0.37 pin is
|
||||
# supplied by the migration's reviewed craft-libs revision.
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "db19c373c8d59a545972ca340987aecfb3611a4b", features = ["egui"] }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -79,9 +83,9 @@ wasmi = { version = "2", default-features = false, features = ["std", "stable",
|
||||
wat = "1.261"
|
||||
|
||||
# ui
|
||||
egui = "0.36"
|
||||
egui_extras = { version = "0.36", default-features = false }
|
||||
eframe = { version = "0.36", default-features = false }
|
||||
egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
webbrowser = "1"
|
||||
@@ -122,14 +126,32 @@ codegen-units = 4
|
||||
# wasm32-unknown-unknown always aborts on panic, so panic = "abort" changes nothing there.
|
||||
[profile.web-release]
|
||||
inherits = "release"
|
||||
opt-level = "s"
|
||||
# "z", not "s": 1.9 MB smaller (24.0 MiB -> 22.2 MiB after wasm-opt, 0.11.1), back under the gate.
|
||||
opt-level = "z"
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
debug = false
|
||||
strip = true
|
||||
panic = "abort"
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
[patch.crates-io]
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# craft-libs' vendored krilla 0.8.2: decoded PNGs are capped at 1 GiB and reserved fallibly, and a
|
||||
# panic while drawing unwinds without aborting.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef" }
|
||||
@@ -51,3 +51,20 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
|
||||
egui icon font subset (dependency asset)
|
||||
----------------------------------------
|
||||
epaint_default_fonts 0.37 embeds egui-icons.ttf, a five-glyph subset of
|
||||
emoji-icon-font by John Slegers. The full monochrome emoji-icon-font fallback
|
||||
uses the same MIT license. Upstream license text follows unchanged.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014 John Slegers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+8
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (`.sketch` import, best effort (Sketch 48 and newer); Dev Mode measurements kept on the canvas and a read-only layers panel; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (`.sketch` import, best effort (Sketch 48 and newer); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
|
||||
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
|
||||
@@ -132,6 +132,8 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-10-25** · egui 0.37 capture lifecycle: screenshots with hidden or unknown visibility queue, request a hidden paint, and expire after 60 seconds if no capture arrives (headless-tested contract). Logic-only edits, saves and inspection continue while hidden. Native visible GUI and forced hidden-window paint, browser and Wayland behavior remain unqualified; parity percentages are unchanged.
|
||||
- **2026-10-24** · Open, Save and the folder dialogs start in the folder of the last file or folder picked in the run (#1290): the Linux portal does not remember it between dialogs as the macOS and Windows panels do. A folder deleted since falls back to the system's choice. No numbers change.
|
||||
- **2026-10-24** · Dev Mode tail (M6, gap 16): Measurements kept on the canvas (gap 16): `devMode.addMeasurement {from?, to?, side?}` places one between two layers, along one side of a layer or (neither) to the layer around it, stored on the layer it starts from (saved in `.figcraft`, synced, undoable; old files open without them); Dev Mode draws them as labelled redlines that follow the layers, the Inspect tab lists them (those of the selected layer, or every one on the page), places and removes them; `devMode.removeMeasurement` and `devMode.measurements` remove and list them; a copy keeps those to layers copied with it. The layers panel is read-only in Dev Mode: rows select and expand, but don't rename, reorder, hide or lock. Dev Mode 98% / 78%.
|
||||
- **2026-10-24** · Boards (M12): File ▸ New board makes a board, a file kind of its own saved in `.figcraft` and carried to people joining a live session. Sticky notes (8 colours, text that shrinks as the note grows, the author's name, Shift+Cmd/Ctrl+Enter for the next one), shapes with text (7 outlines), connectors that re-route when what they join moves (computed in the engine's normalize pass, so local edits, undo and others' edits agree), marker, highlighter and eraser, stamps with the placer's name on hover; a board toolbar, a contextual bar over the selection and the Design panel hidden until asked for; prototyping and Dev Mode refuse on boards. Design files and boards have their own marks (a pen nib, a note) on tabs, the home screen and the Open files list. Checked in the app, with two app instances in one live session, and through MCP; the web build compiles ([boards-parity](docs/boards-parity.md)).
|
||||
- **2026-10-15** · Auto-save (M1, #305): Preferences ▸ Save files automatically (`pref.autoSave`, off by default, desktop only) saves each open file that has a path 3 s after its last change, never during a gesture, a live text preview or while a version is shown; the file is encoded off the UI thread, a failed save says why and is tried again a minute later. Numbers unchanged.
|
||||
@@ -143,6 +145,10 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
- **2026-10-15** · Web clipboard (M1, #375): copy and paste in the browser go through the system clipboard. Numbers unchanged.
|
||||
- **2026-10-15** · Alt-drag copies snap to their original and Duplicate (Cmd+D) repeats the last copy's offset (M1, #283). Numbers unchanged.
|
||||
- **2026-10-22** · `fill` and `stroke` props accept `"none"` and `null` (M1, #1036): `node.create`, `node.set` and the other prop appliers map them to an empty fills/strokes list, as `fills: []` already did, so an outline-only shape is one call (agents write `"none"` for no paint; the empty-list form was undocumented). The parameter docs (`KEYS`, shown by `list_commands` and the CLI) and `docs/mcp.md` say so, and the error message names the accepted forms. `fill_none_tests` covers create, set, undo, text and the error. Numbers unchanged.
|
||||
- **2026-10-20** · CLI option terminator (M0.9): `--` ends option parsing, so dash-prefixed
|
||||
filenames open normally; the global `--no-system-fonts` flag also respects the terminator.
|
||||
Binary regression coverage opens five such native files and checks their JSON info.
|
||||
|
||||
- **2026-10-17** · Control channel while the window is minimised (M8, #720): a minimised or covered window answers every request that acts on the app's state (edits, `ui.inspect`, `ui.pointer`, `ui.key`, `ui.type`, `ui.set`, `app.quit`…) without drawing, and what needs a drawn frame (`ui.screenshot`, `ui.input`, `window.new`) is an error at once; before, those waited up to 60 s and held up every later request on the connection (an attached agent's `inspect_ui` or window screenshot stalled until the window came back). Measured on Windows 11, minimised: requests ~100 ms each (eframe wakes a minimised window at most ten times a second; ~2 ms on screen), a window screenshot fails in ~100 ms instead of 60 s, idle CPU 0. Numbers unchanged.
|
||||
- **2026-10-17** · Number variables on text content (M3, #629): the Typography section's variable picker also lists number variables for a text layer's content, as the engine already accepted (the text shows the number, e.g. 42.5, and follows the variable). Other text fields keep their own types. Numbers unchanged.
|
||||
- **2026-10-17** · Frames and sections convert into each other (M1, #719): `object.convertToSection` turns a frame on the page or in a section into a section in place (same box, name, fill and layers, which stay where they are; what only a frame has goes: auto layout, clipping, layout grids, guides, scrolling), and `object.convertToFrame` now also turns a section into a frame that keeps its fill and doesn't clip, so the look stays. Nested frames, instances, main components and sections holding sections are refused with the reason; one undo step each. Both are in the canvas context menu (Convert to section / Convert to frame) and in Spanish. Numbers unchanged.
|
||||
@@ -329,6 +335,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-25 | minor | egui 0.37 capture lifecycle: screenshots with hidden or unknown visibility queue, request a hidden paint, and expire after 60 seconds if no capture arrives (headless-tested contract). Logic-only edits, saves and inspection continue while hidden. Native visible GUI and forced hidden-window paint, browser and Wayland behavior remain unqualified; parity percentages are unchanged. |
|
||||
| 2026-10-24 | minor | Dev Mode tail (M6, gap 16): Measurements kept on the canvas (gap 16): `devMode.addMeasurement {from?, to?, side?}` places one between two layers, along one side of a layer or (neither) to the layer around it, stored on the layer it starts from (saved in `.figcraft`, synced, undoable; old files open without them); Dev Mode draws them as labelled redlines that follow the layers, the Inspect tab lists them (those of the selected layer, or every one on the page), places and removes them; `devMode.removeMeasurement` and `devMode.measurements` remove and list them; a copy keeps those to layers copied with it. The layers panel is read-only in Dev Mode: rows select and expand, but don't rename, reorder, hide or lock. Dev Mode 97% → 98% breadth, 76% → 78% ready, 2–4 h → 1–2 h; headline numbers unchanged at this rounding |
|
||||
| 2026-10-24 | minor | Boards (M12): a file kind of its own (`file.newBoard`, saved in `.figcraft`, carried to live-session joiners) with sticky notes, shapes with text, connectors that re-route when what they join moves (an engine recompute, the same for local edits, undo and others' edits), marker, highlighter and eraser, stamps with the placer's name, a board toolbar and a contextual bar; prototyping and Dev Mode refuse on boards; design files and boards have their own marks on tabs and file rows. Boards row added outside the weighted numbers; headline numbers unchanged at this rounding |
|
||||
| 2026-10-21 | minor | Best-effort `.sketch` import (Sketch 48 and newer): open, import, drop, CLI and MCP; symbols become live components and instances, shared styles and Color Variables come across, Sketch 2025 frames, stacks (as auto layout) and tints too, text placed as Sketch places it; checked on three real files against Sketch's own renders ([file-format-parity](docs/file-format-parity.md)). Headline numbers unchanged |
|
||||
|
||||
@@ -20,6 +20,10 @@ impl Args {
|
||||
let mut bad: Option<CliError> = None;
|
||||
let mut it = argv.iter();
|
||||
while let Some(arg) = it.next() {
|
||||
if arg == "--" {
|
||||
a.positional.extend(it.cloned());
|
||||
break;
|
||||
}
|
||||
let name = if let Some(n) = arg.strip_prefix("--") {
|
||||
n
|
||||
} else if let Some(n) = arg.strip_prefix('-').filter(|n| n.len() == 1 && !n.starts_with(|c: char| c.is_ascii_digit())) {
|
||||
|
||||
@@ -108,10 +108,10 @@ impl From<String> for CliError {
|
||||
|
||||
pub type CliResult<T> = Result<T, CliError>;
|
||||
|
||||
fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
let system_fonts = !argv.iter().any(|a| a == "--no-system-fonts");
|
||||
let argv: Vec<String> = argv.iter().filter(|a| *a != "--no-system-fonts").cloned().collect();
|
||||
if system_fonts {
|
||||
fn parse_args(argv: &[String], valued: &[&str], flags: &[&str]) -> CliResult<Args> {
|
||||
let flags = [flags, &["no-system-fonts"]].concat();
|
||||
let args = Args::parse(argv, valued, &flags)?;
|
||||
if !args.flag("no-system-fonts") {
|
||||
// Text lays out with the installed fonts, like the desktop app, so headless renders and
|
||||
// auto layout sizes match what users see.
|
||||
figcraft_text::scan_system_fonts_on_demand();
|
||||
@@ -119,7 +119,16 @@ fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
// Nothing scans them then, not even a `.sketch` import matching its fonts.
|
||||
figcraft_text::opt_out_of_system_fonts();
|
||||
}
|
||||
let Some((cmd, rest)) = argv.split_first() else { return Err(CliError::Usage("missing subcommand".into())) };
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
let Some(command_index) = argv.iter().position(|a| a != "--no-system-fonts") else {
|
||||
return Err(CliError::Usage("missing subcommand".into()));
|
||||
};
|
||||
let cmd = argv.get(command_index).ok_or_else(|| CliError::Usage("missing subcommand".into()))?;
|
||||
// Keep leading global flags with the subcommand's options, where values and `--` are parsed.
|
||||
let rest: Vec<String> = argv.iter().enumerate().filter(|(i, _)| *i != command_index).map(|(_, a)| a.clone()).collect();
|
||||
match cmd.as_str() {
|
||||
"help" | "--help" | "-h" => {
|
||||
println!("{USAGE}");
|
||||
@@ -130,13 +139,13 @@ fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
Ok(ExitCode::SUCCESS)
|
||||
}
|
||||
"info" => {
|
||||
let a = Args::parse(rest, &ROOT_FLAGS, &["json"])?;
|
||||
let a = parse_args(&rest, &ROOT_FLAGS, &["json"])?;
|
||||
let file = a.one_positional("info <file>")?;
|
||||
confined(&a, || files::info(&file, a.flag("json")))
|
||||
}
|
||||
"export" => {
|
||||
let valued = [&["format", "scale", "page", "node", "o", "out", "bleed"][..], &ROOT_FLAGS[..]].concat();
|
||||
let a = Args::parse(rest, &valued, &["crop-marks", "bleed-marks", "cmyk"])?;
|
||||
let a = parse_args(&rest, &valued, &["crop-marks", "bleed-marks", "cmyk"])?;
|
||||
let file = a.one_positional("export <file> -o <out>")?;
|
||||
let out = a.value("o").or_else(|| a.value("out")).ok_or_else(|| CliError::Usage("export needs -o <out>".into()))?;
|
||||
let target =
|
||||
@@ -144,7 +153,7 @@ fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
confined(&a, || files::export(&file, &out, &target))
|
||||
}
|
||||
"convert" => {
|
||||
let a = Args::parse(rest, &ROOT_FLAGS, &[])?;
|
||||
let a = parse_args(&rest, &ROOT_FLAGS, &[])?;
|
||||
match a.positional.as_slice() {
|
||||
[i, o] => confined(&a, || files::convert(i, o)),
|
||||
_ => Err(CliError::Usage("convert <in> <out>".into())),
|
||||
@@ -152,19 +161,19 @@ fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
}
|
||||
"render" => {
|
||||
let valued = [&["o", "out", "scale", "page"][..], &ROOT_FLAGS[..]].concat();
|
||||
let a = Args::parse(rest, &valued, &[])?;
|
||||
let a = parse_args(&rest, &valued, &[])?;
|
||||
let file = a.one_positional("render <file> -o <out.png>")?;
|
||||
let out = a.value("o").or_else(|| a.value("out")).ok_or_else(|| CliError::Usage("render needs -o <out.png>".into()))?;
|
||||
confined(&a, || files::render(&file, &out, a.scale()?, a.value("page").as_deref()))
|
||||
}
|
||||
"run" => {
|
||||
let valued = [&["in", "out"][..], &ROOT_FLAGS[..]].concat();
|
||||
let a = Args::parse(rest, &valued, &[])?;
|
||||
let a = parse_args(&rest, &valued, &[])?;
|
||||
let script = a.one_positional("run <script.json|.jsonl>")?;
|
||||
confined(&a, || files::run_script(&script, a.value("in").as_deref(), a.value("out").as_deref()))
|
||||
}
|
||||
"commands" => {
|
||||
let a = Args::parse(rest, &["filter"], &["json"])?;
|
||||
let a = parse_args(&rest, &["filter"], &["json"])?;
|
||||
if !a.positional.is_empty() {
|
||||
return Err(CliError::Usage("commands takes no positional arguments".into()));
|
||||
}
|
||||
@@ -173,7 +182,7 @@ fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
}
|
||||
"mcp" => {
|
||||
let valued = [&["attach"][..], &ROOT_FLAGS[..]].concat();
|
||||
let a = Args::parse(rest, &valued, &[])?;
|
||||
let a = parse_args(&rest, &valued, &[])?;
|
||||
if !a.positional.is_empty() {
|
||||
return Err(CliError::Usage("mcp takes no positional arguments".into()));
|
||||
}
|
||||
@@ -188,7 +197,7 @@ fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
mcp(attach.as_deref(), roots_of(&a)?)
|
||||
}
|
||||
"plugin" => {
|
||||
let a = Args::parse(rest, &["server"], &[])?;
|
||||
let a = parse_args(&rest, &["server"], &[])?;
|
||||
match a.positional.as_slice() {
|
||||
[verb, folder] if verb == "publish" => {
|
||||
let server = a.value("server").ok_or_else(|| CliError::Usage("plugin publish needs --server ws://host:port/".into()))?;
|
||||
@@ -198,10 +207,10 @@ fn run(argv: &[String]) -> CliResult<ExitCode> {
|
||||
}
|
||||
}
|
||||
"perf" => {
|
||||
let a = Args::parse(rest, &["layers", "instances"], &[])?;
|
||||
let a = parse_args(&rest, &["layers", "instances"], &[])?;
|
||||
let sizes: Vec<usize> = a.usizes("layers", &[1000, 10_000])?.into_iter().map(|n| n.clamp(10, 2_000_000)).collect();
|
||||
let instances: Vec<usize> = a.usizes("instances", &[2000])?.into_iter().filter(|n| *n > 0).map(|n| n.min(100_000)).collect();
|
||||
perf::run(&sizes, &instances, system_fonts)
|
||||
perf::run(&sizes, &instances, !a.flag("no-system-fonts"))
|
||||
}
|
||||
other => Err(CliError::Usage(format!("unknown subcommand `{other}`"))),
|
||||
}
|
||||
|
||||
@@ -13,6 +13,38 @@ fn tmp(name: &str) -> std::path::PathBuf {
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn option_terminator_allows_dash_prefixed_filenames() {
|
||||
let dir = tmp("option-terminator");
|
||||
let doc = figcraft_doc::Document::new("Dash-prefixed file");
|
||||
let bytes = figcraft_format::save_bytes(&doc, None).unwrap();
|
||||
for name in ["--drawing.figcraft", "-h", "--json", "--no-system-fonts", "--"] {
|
||||
std::fs::write(dir.join(name), &bytes).unwrap();
|
||||
let output = bin().current_dir(&dir).args(["info", "--json", "--no-system-fonts", "--", name]).output().unwrap();
|
||||
assert!(output.status.success(), "{name}: {}", String::from_utf8_lossy(&output.stderr));
|
||||
let info: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(info["file"], name);
|
||||
assert_eq!(info["name"], "Dash-prefixed file");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_font_flag_respects_option_values() {
|
||||
for filter in ["--", "--no-system-fonts"] {
|
||||
let output = bin().args(["commands", "--filter", filter, "--no-system-fonts", "--json"]).output().unwrap();
|
||||
assert!(output.status.success(), "{filter}: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap().is_array());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_font_flag_can_precede_the_subcommand() {
|
||||
let output = bin().args(["--no-system-fonts", "commands", "--json"]).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(!serde_json::from_slice::<Vec<serde_json::Value>>(&output.stdout).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_exit_2_without_panicking() {
|
||||
for args in [
|
||||
|
||||
@@ -69,7 +69,15 @@ struct WebShell {
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
// `FigApp::ui` runs its own per-frame logic first (fonts, theme), like the desktop app.
|
||||
// eframe runs `logic` for visible tabs and, with only `run_logic`, for hidden ones: keep
|
||||
// autosave/live/control deadlines moving without a paint. `FigApp::ui` does not repeat it.
|
||||
/// Run the browser shell's eframe logic callback: guard `background_tick` so hidden tabs
|
||||
/// still advance autosave, live and control deadlines without painting. `FigApp::ui` does
|
||||
/// not repeat it.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
figcraft_ui_egui::windows::guard(&mut self.fig, ctx, |fig| fig.background_tick(ctx));
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.fig.ui(ui);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ figcraft-text = { workspace = true }
|
||||
# craft-libs#217 branch and must be repointed to a merged `rev` before this PR is mergeable.
|
||||
craft-window = { workspace = true }
|
||||
egui = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11"] }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
@@ -33,6 +33,7 @@ env_logger = { version = "0.11", default-features = false, features = ["auto-col
|
||||
# The system's reduce-motion setting (UISettings.AnimationsEnabled), interface language
|
||||
# (GlobalizationPreferences.Languages) and controllers for prototypes (Gaming.Input.Gamepad).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
windows = { version = "0.62", default-features = false, features = ["UI_ViewManagement", "System_UserProfile", "Foundation_Collections", "Gaming_Input"] }
|
||||
|
||||
# Finder double-clicks, Open With, Dock drops and `open -a FigCraft file.figcraft` arrive as a
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use figcraft_ui_egui::ControlRequest;
|
||||
use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate, RequestState};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type Queue = Arc<Mutex<Vec<ControlRequest>>>;
|
||||
@@ -21,6 +21,34 @@ const TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// core busy until it recovers.
|
||||
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Why a request's transport wait ended without a control reply.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum WaitFailure {
|
||||
Timeout,
|
||||
/// The UI side dropped its sender before replying (the app is closing).
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
/// Wait for the UI's reply, and settle a timeout under the same gate the UI's final commit uses.
|
||||
/// A commit that got the gate first has already queued its reply: consume that reply instead of
|
||||
/// reporting a timeout. If the gate is still open, cancel it so the UI writes nothing.
|
||||
fn wait_for_reply(rx: &std::sync::mpsc::Receiver<ControlReply>, gate: &RequestGate, timeout: Duration) -> Result<ControlReply, WaitFailure> {
|
||||
match rx.recv_timeout(timeout) {
|
||||
Ok(reply) => Ok(reply),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => after_timeout(rx, gate),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(WaitFailure::Disconnected),
|
||||
}
|
||||
}
|
||||
|
||||
/// The timeout branch of [`wait_for_reply`]. Kept separate so it can be tested deterministically
|
||||
/// against a gate whose commit already happened.
|
||||
fn after_timeout(rx: &std::sync::mpsc::Receiver<ControlReply>, gate: &RequestGate) -> Result<ControlReply, WaitFailure> {
|
||||
match gate.cancel_if_open() {
|
||||
RequestState::Replied => rx.try_recv().map_err(|_| WaitFailure::Disconnected),
|
||||
RequestState::Open | RequestState::Cancelled => Err(WaitFailure::Timeout),
|
||||
}
|
||||
}
|
||||
|
||||
/// Deferred requests for a hidden window must not make the UI's queue grow without a bound.
|
||||
pub fn drain_queue(queue: &Queue, target: &mut Vec<ControlRequest>) {
|
||||
target.retain(|request| !request.is_cancelled());
|
||||
@@ -69,6 +97,9 @@ fn spawn_connection(stream: TcpStream, queue: Queue, ctx: CtxSlot, workers: &mut
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one control connection: read bounded JSON lines, reject oversized frames and a
|
||||
/// full queue, queue one request, wait under its gate, and write one reply. Non-JSON input
|
||||
/// answers with an error and closes the connection so HTTP body lines cannot become commands.
|
||||
fn serve(mut out: TcpStream, queue: Queue, ctx: CtxSlot, timeout: Duration) -> std::io::Result<()> {
|
||||
out.set_read_timeout(Some(timeout))?;
|
||||
out.set_write_timeout(Some(timeout))?;
|
||||
@@ -96,7 +127,7 @@ fn serve(mut out: TcpStream, queue: Queue, ctx: CtxSlot, timeout: Duration) -> s
|
||||
let method = v.get("method").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let params = v.get("params").cloned().unwrap_or(json!({}));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let gate = RequestGate::new();
|
||||
let mut pending = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
pending.retain(|request| !request.is_cancelled());
|
||||
if pending.len() >= MAX_QUEUED_REQUESTS {
|
||||
@@ -104,20 +135,22 @@ fn serve(mut out: TcpStream, queue: Queue, ctx: CtxSlot, timeout: Duration) -> s
|
||||
writeln!(out, "{}", json!({"id": id, "ok": false, "error": "control request queue is full"}))?;
|
||||
continue;
|
||||
}
|
||||
pending.push(ControlRequest { id: id.clone(), method, params, reply: tx, cancelled: cancelled.clone() });
|
||||
pending.push(ControlRequest { id: id.clone(), method, params, reply: tx, state: gate.clone() });
|
||||
drop(pending);
|
||||
if let Some(c) = ctx.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() {
|
||||
c.request_repaint();
|
||||
}
|
||||
match rx.recv_timeout(timeout) {
|
||||
match wait_for_reply(&rx, &gate, timeout) {
|
||||
Ok(r) => match r.result {
|
||||
Ok(res) => json!({"id": r.id, "ok": true, "result": res}),
|
||||
Err(e) => json!({"id": r.id, "ok": false, "error": e}),
|
||||
},
|
||||
Err(_) => {
|
||||
cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
Err(WaitFailure::Timeout) => {
|
||||
json!({"id": id, "ok": false, "error": "timed out waiting for the UI: screenshots and input need the FigCraft window on screen (is it minimised or covered?)"})
|
||||
}
|
||||
Err(WaitFailure::Disconnected) => {
|
||||
json!({"id": id, "ok": false, "error": "the FigCraft window closed before answering"})
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -28,8 +28,9 @@ fn reply(reader: &mut BufReader<TcpStream>) -> Value {
|
||||
serde_json::from_str(&line).unwrap()
|
||||
}
|
||||
|
||||
/// Build a `ui.inspect` control request with a throwaway reply channel.
|
||||
fn request() -> ControlRequest {
|
||||
ControlRequest { id: json!(0), method: "ui.inspect".into(), params: json!({}), reply: mpsc::channel().0, cancelled: Default::default() }
|
||||
ControlRequest { id: json!(0), method: "ui.inspect".into(), params: json!({}), reply: mpsc::channel().0, state: Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -115,6 +116,52 @@ fn full_queue_rejects_before_dispatch_and_ui_queue_stays_bounded() {
|
||||
worker.join().unwrap().unwrap();
|
||||
}
|
||||
|
||||
/// Asserts a commit that writes the file and queues its reply wins the gate: the transport's
|
||||
/// timeout branch consumes that reply and leaves the state `Replied`.
|
||||
#[test]
|
||||
fn a_committed_reply_wins_over_the_transport_timeout() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-control-commit-{}", std::process::id()));
|
||||
let path = dir.join("shot.png");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let gate = RequestGate::new();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
// The UI's final commit gets the gate first: the file and reply are both committed before the
|
||||
// transport's timeout branch can look at the gate.
|
||||
let committed = gate.commit(|| {
|
||||
std::fs::write(&path, b"png").unwrap();
|
||||
tx.send(ControlReply { id: json!(7), result: Ok(json!({"path": path.to_string_lossy()})) }).unwrap();
|
||||
});
|
||||
assert!(committed.is_some());
|
||||
assert!(path.is_file());
|
||||
let reply = after_timeout(&rx, &gate).expect("the queued commit is consumed");
|
||||
assert_eq!(reply.id, json!(7));
|
||||
assert!(reply.result.is_ok());
|
||||
assert_eq!(gate.state(), RequestState::Replied, "the timeout must not overwrite a commit");
|
||||
assert!(path.is_file(), "a winning commit keeps its file");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Asserts a zero-duration wait reports `Timeout` and cancels the open gate.
|
||||
#[test]
|
||||
fn a_timeout_cancels_an_open_request() {
|
||||
let gate = RequestGate::new();
|
||||
let (_tx, rx) = mpsc::channel::<ControlReply>();
|
||||
assert!(matches!(wait_for_reply(&rx, &gate, Duration::ZERO), Err(WaitFailure::Timeout)));
|
||||
assert_eq!(gate.state(), RequestState::Cancelled, "nothing may write after the timeout");
|
||||
}
|
||||
|
||||
/// Asserts a closed reply channel reports `Disconnected` and leaves the gate `Open`, not
|
||||
/// cancelled.
|
||||
#[test]
|
||||
fn a_disconnected_reply_channel_is_not_reported_as_a_timeout() {
|
||||
let gate = RequestGate::new();
|
||||
let (tx, rx) = mpsc::channel::<ControlReply>();
|
||||
drop(tx);
|
||||
assert!(matches!(wait_for_reply(&rx, &gate, Duration::from_secs(1)), Err(WaitFailure::Disconnected)));
|
||||
assert_eq!(gate.state(), RequestState::Open, "a closed app is not a cancel decision");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_and_partial_frame_connections_expire() {
|
||||
for bytes in [b"".as_slice(), b"{\"id\":"] {
|
||||
@@ -227,6 +274,9 @@ fn a_limit_sized_frame_is_accepted_at_eof() {
|
||||
worker.join().unwrap().unwrap();
|
||||
}
|
||||
|
||||
/// Asserts expired requests stop occupying the UI queue cap, a later request is admitted
|
||||
/// and answered, and a window that finally draws discards its expired command before
|
||||
/// dispatch.
|
||||
#[test]
|
||||
fn timed_out_requests_release_a_full_deferred_ui_queue() {
|
||||
use figcraft_ui_egui::{FigApp, NoServices, control, windows};
|
||||
@@ -262,7 +312,7 @@ fn timed_out_requests_release_a_full_deferred_ui_queue() {
|
||||
// Include expired requests in the socket queue, too: admission must reclaim their slots.
|
||||
pending.lock().unwrap().extend((0..MAX_QUEUED_REQUESTS).map(|_| {
|
||||
let r = request();
|
||||
r.cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
r.state.cancel_if_open();
|
||||
r
|
||||
}));
|
||||
let (mut client, server) = pair();
|
||||
|
||||
@@ -62,6 +62,9 @@ struct App {
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
/// Native eframe logic callback: store the first context, drain control requests, run
|
||||
/// guarded background work, poll macOS open events, handle close requests and title
|
||||
/// changes, and schedule recovery repaints on the app clock.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
{
|
||||
let mut slot = self.ctx_slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
@@ -71,7 +74,9 @@ impl eframe::App for App {
|
||||
}
|
||||
let title = with_app(|fig| {
|
||||
control_server::drain_queue(&self.queue, &mut fig.control_queue);
|
||||
figcraft_ui_egui::control::drain_hidden(fig, ctx);
|
||||
// Phase-safe background work: control queues, autosave/recovery deadlines, live polling.
|
||||
// It runs on logic-only callbacks too, so it never reads UI input.
|
||||
figcraft_ui_egui::windows::guard(fig, ctx, |fig| fig.background_tick(ctx));
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events::poll(&self.apple_events, fig, ctx);
|
||||
// Closing the window asks about unsaved changes (and keeps the app running while other
|
||||
@@ -86,8 +91,14 @@ impl eframe::App for App {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
|
||||
self.title = title;
|
||||
}
|
||||
let now = ctx.input(|i| i.time);
|
||||
if let Some(wait) = with_app(|fig| recovery::lock(&self.recovery).as_mut().and_then(|r| r.tick(&fig.session, now))).flatten() {
|
||||
// Recovery deadlines use the same monotonic clock as the app's background work: a
|
||||
// logic-only tick leaves `ctx.input(i.time)` stale.
|
||||
if let Some(wait) = with_app(|fig| {
|
||||
let now = fig.now_secs();
|
||||
recovery::lock(&self.recovery).as_mut().and_then(|r| r.tick(&fig.session, now))
|
||||
})
|
||||
.flatten()
|
||||
{
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));
|
||||
}
|
||||
}
|
||||
@@ -117,6 +128,11 @@ impl eframe::App for App {
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&craft_update::suite::FIGCRAFT, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.iter().any(|a| a == "--version" || a == "-V") {
|
||||
@@ -199,6 +215,7 @@ fn main() -> eframe::Result {
|
||||
// open (no frame then).
|
||||
figcraft_ui_egui::i18n::set(&session.prefs.language, figcraft_ui_egui::Services::system_language(&svc).as_deref());
|
||||
let mut fig = FigApp::new(session, Box::new(svc));
|
||||
fig.set_startup_update_check(true);
|
||||
fig.automation_roots = roots;
|
||||
fig.ui.home = false;
|
||||
// Files named on the command line are the user's too: their missing fonts are listed.
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use figcraft_engine::{Prefs, Session};
|
||||
use figcraft_ui_egui::{DialogFuture, FigApp, Services};
|
||||
@@ -20,6 +20,8 @@ pub struct Desktop {
|
||||
language: Option<String>,
|
||||
/// Recovery copies of unsaved files (written at once after a panic).
|
||||
recovery: crate::recovery::Shared,
|
||||
/// The folder of the last file or folder a dialog picked, where the next one starts.
|
||||
last_folder: Arc<Mutex<Option<PathBuf>>>,
|
||||
}
|
||||
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
@@ -54,7 +56,15 @@ impl Desktop {
|
||||
let reduce_motion = Arc::new(AtomicBool::new(false));
|
||||
let flag = reduce_motion.clone();
|
||||
std::thread::spawn(move || flag.store(system_reduce_motion(), Ordering::Relaxed));
|
||||
Self { clipboard: arboard::Clipboard::new().ok(), dir, prefs, reduce_motion, language: system_language(), recovery }
|
||||
Self {
|
||||
clipboard: arboard::Clipboard::new().ok(),
|
||||
dir,
|
||||
prefs,
|
||||
reduce_motion,
|
||||
language: system_language(),
|
||||
recovery,
|
||||
last_folder: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,19 +272,57 @@ fn save_filters<'a>(exts: &'a [&'a str]) -> Vec<(&'static str, &'a [&'a str])> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder to start the next dialog in once `path` was picked: the file's folder, or the folder
|
||||
/// picked itself.
|
||||
pub(crate) fn folder_to_remember(path: &Path, is_folder: bool) -> Option<PathBuf> {
|
||||
let folder = if is_folder { Some(path) } else { path.parent() };
|
||||
folder.filter(|f| !f.as_os_str().is_empty()).map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// The remembered folder, unless it is gone since: then the system's own choice.
|
||||
pub(crate) fn start_folder(last: Option<PathBuf>) -> Option<PathBuf> {
|
||||
last.filter(|f| f.is_dir())
|
||||
}
|
||||
|
||||
impl Desktop {
|
||||
/// A dialog that starts in the last folder used. The Linux portal does not remember it between
|
||||
/// dialogs as macOS and Windows do.
|
||||
fn dialog_in_last_folder(&self, title: &str) -> rfd::AsyncFileDialog {
|
||||
let dialog = dialog(title);
|
||||
match start_folder(self.last_folder.lock().ok().and_then(|l| l.clone())) {
|
||||
Some(folder) => dialog.set_directory(folder),
|
||||
None => dialog,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `pick`, with the folder of what it picks kept in `last` for the next dialog.
|
||||
pub(crate) fn remembering(last: Arc<Mutex<Option<PathBuf>>>, pick: DialogFuture, is_folder: bool) -> DialogFuture {
|
||||
Box::pin(async move {
|
||||
let path = pick.await?;
|
||||
if let (Some(folder), Ok(mut last)) = (folder_to_remember(&path, is_folder), last.lock()) {
|
||||
*last = Some(folder);
|
||||
}
|
||||
Some(path)
|
||||
})
|
||||
}
|
||||
|
||||
impl Services for Desktop {
|
||||
fn pick_open(&mut self, title: &str, exts: &[&str]) -> DialogFuture {
|
||||
picked(dialog(title).add_filter("Supported files", exts).pick_file())
|
||||
let pick = picked(self.dialog_in_last_folder(title).add_filter("Supported files", exts).pick_file());
|
||||
remembering(self.last_folder.clone(), pick, false)
|
||||
}
|
||||
fn pick_save(&mut self, title: &str, name: &str, exts: &[&str]) -> DialogFuture {
|
||||
let mut dialog = dialog(title).set_file_name(name);
|
||||
let mut dialog = self.dialog_in_last_folder(title).set_file_name(name);
|
||||
for (label, extensions) in save_filters(exts) {
|
||||
dialog = dialog.add_filter(label, extensions);
|
||||
}
|
||||
picked(dialog.save_file())
|
||||
let pick = picked(dialog.save_file());
|
||||
remembering(self.last_folder.clone(), pick, false)
|
||||
}
|
||||
fn pick_folder(&mut self, title: &str) -> DialogFuture {
|
||||
picked(dialog(title).pick_folder())
|
||||
let pick = picked(self.dialog_in_last_folder(title).pick_folder());
|
||||
remembering(self.last_folder.clone(), pick, true)
|
||||
}
|
||||
fn clipboard_set_text(&mut self, s: &str) {
|
||||
if let Some(c) = self.clipboard.as_mut() {
|
||||
|
||||
@@ -117,3 +117,28 @@ fn quitting_keeps_the_preferences_and_ends_the_live_sessions() {
|
||||
assert_eq!(start(&dir).session.prefs.user_name, "Ada", "the preferences were kept");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #1290: the Linux portal opens every dialog where it likes, so the app keeps the folder itself.
|
||||
#[test]
|
||||
fn the_next_dialog_starts_in_the_folder_of_the_last_pick() {
|
||||
use crate::services::{folder_to_remember, remembering, start_folder};
|
||||
use std::path::PathBuf;
|
||||
let dir = root("last-folder");
|
||||
let file = dir.join("Poster.figcraft");
|
||||
assert_eq!(folder_to_remember(&file, false), Some(dir.clone()), "a file: its folder");
|
||||
assert_eq!(folder_to_remember(&dir, true), Some(dir.clone()), "a folder pick: the folder itself");
|
||||
assert_eq!(folder_to_remember(std::path::Path::new("Poster.figcraft"), false), None, "a bare name has no folder");
|
||||
|
||||
let last = Arc::new(Mutex::new(None::<PathBuf>));
|
||||
let mut pick = remembering(last.clone(), Box::pin(std::future::ready(Some(file.clone()))), false);
|
||||
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
assert_eq!(pick.as_mut().poll(&mut cx), std::task::Poll::Ready(Some(file)));
|
||||
assert_eq!(*last.lock().unwrap(), Some(dir.clone()), "a pick is remembered");
|
||||
let mut cancelled = remembering(last.clone(), Box::pin(std::future::ready(None)), false);
|
||||
assert_eq!(cancelled.as_mut().poll(&mut cx), std::task::Poll::Ready(None));
|
||||
assert_eq!(*last.lock().unwrap(), Some(dir.clone()), "a cancelled dialog keeps the folder");
|
||||
|
||||
assert_eq!(start_folder(Some(dir.clone())), Some(dir.clone()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(start_folder(Some(dir)), None, "a folder deleted since: the system's own");
|
||||
}
|
||||
@@ -87,7 +87,10 @@ fn a_local_share_is_joined_by_its_code_and_edits_sync() {
|
||||
let mut late = session("Cy");
|
||||
late.execute("collab.join", &json!({"code": shown})).unwrap();
|
||||
pump(&mut [&mut late], "the refusal", |s| matches!(s[0].live().status, Status::Failed { .. }));
|
||||
assert!(late.live().status.label().contains("Couldn't join"), "{:?}", late.live().status);
|
||||
// The port is free again: another program's host may have taken it, and that host refuses
|
||||
// the code's secret.
|
||||
let label = late.live().status.label();
|
||||
assert!(label.contains("Couldn't join") || label.contains("The host refused"), "{label}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -103,7 +106,10 @@ fn a_local_code_with_the_wrong_secret_or_a_typo_doesnt_join() {
|
||||
assert!(host.live().peers.is_empty());
|
||||
// A typing mistake is caught before anything connects.
|
||||
let mut typo: Vec<char> = local.code().chars().collect();
|
||||
typo[7] = if typo[7] == 'A' { 'B' } else { 'A' };
|
||||
// The last symbol contains only checksum bits. Changing payload bits can collide with
|
||||
// the eight-bit checksum, so it does not guarantee a malformed code.
|
||||
let last = typo.last_mut().unwrap();
|
||||
*last = if *last == 'A' { 'B' } else { 'A' };
|
||||
let e = guest.execute("collab.join", &json!({"code": typo.iter().collect::<String>()})).unwrap_err().to_string();
|
||||
assert!(e.contains("typing mistake"), "{e}");
|
||||
// A view-only code doesn't exist here, and says where it does.
|
||||
|
||||
@@ -488,6 +488,21 @@ fn silent_connections_time_out() {
|
||||
host.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connections_without_a_hello_are_told_why_they_end() {
|
||||
// A socket's read timeout can end a moment before the hello's deadline; the connection still
|
||||
// gets the refusal. Twelve at once, so that happens to some of them.
|
||||
let (mut host, _hp, invite) = start_with(NetLimits { hello_timeout: Duration::from_secs(1), ..fast_limits() }, Limits::default());
|
||||
let addr: SocketAddr = invite.server.host.parse().unwrap();
|
||||
std::thread::scope(|s| {
|
||||
let waits: Vec<_> = (0..12).map(|_| s.spawn(move || Raw::connect(addr).refusal())).collect();
|
||||
for w in waits {
|
||||
assert_eq!(w.join().unwrap().as_deref(), Some("no hello in time"));
|
||||
}
|
||||
});
|
||||
host.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guests_reconnect_after_a_network_failure() {
|
||||
let (mut host, mut hp, invite) = start();
|
||||
@@ -540,7 +555,9 @@ fn quiet_guests_stay_and_silent_connections_are_dropped() {
|
||||
let (mut host, mut hp, invite) = start_with(limits, Limits::default());
|
||||
let probe = Probe::new();
|
||||
let mut cfg = quick(GuestConfig::new(invite.clone(), "Ada".into()));
|
||||
cfg.limits = limits;
|
||||
// The guest pings as often as the host expects. Its own idle timeout stays long: it also bounds
|
||||
// the wait for the welcome, which a loaded machine can take longer than 600 ms to send.
|
||||
cfg.limits.keepalive = limits.keepalive;
|
||||
let _g = Guest::start(cfg, probe.inbox.clone()).unwrap();
|
||||
let mut gp = probe;
|
||||
gp.wait("welcome", welcomed);
|
||||
@@ -672,34 +689,42 @@ fn a_welcome_over_the_size_limit_says_the_file_is_too_large() {
|
||||
}
|
||||
|
||||
/// How long a connection that never says hello stays open while `poke` sends it something every
|
||||
/// 300 ms (told whether it's the first time); `None`: still open after 6 s.
|
||||
/// 300 ms (told whether it's the first time); `None`: still open after 6 s. A thread of its own
|
||||
/// reads the socket and notes when the host ends the stream, so pongs queued ahead of the close
|
||||
/// and a slow poke loop don't delay it.
|
||||
fn pre_hello_lifetime(mut poke: impl FnMut(&mut Raw, bool) -> bool) -> Option<Duration> {
|
||||
let (mut host, _hp, invite) = start_with(NetLimits { hello_timeout: Duration::from_secs(1), ..fast_limits() }, Limits::default());
|
||||
let addr: SocketAddr = invite.server.host.parse().unwrap();
|
||||
let mut r = Raw::connect(addr);
|
||||
let mut watch = r.0.get_ref().try_clone().unwrap();
|
||||
let t0 = Instant::now();
|
||||
let (ended_tx, ended) = std::sync::mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 1024];
|
||||
let until = Instant::now() + WAIT;
|
||||
loop {
|
||||
match watch.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(_) => {}
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) && Instant::now() < until => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
let _ = ended_tx.send(Instant::now());
|
||||
});
|
||||
let (mut closed, mut first) = (None, true);
|
||||
while t0.elapsed() < Duration::from_secs(6) {
|
||||
if !poke(&mut r, std::mem::take(&mut first)) {
|
||||
closed = Some(t0.elapsed());
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
// Drain what the host sent back (pongs, the close); an error means it hung up.
|
||||
r.0.get_mut().set_read_timeout(Some(Duration::from_millis(10))).unwrap();
|
||||
match r.0.read() {
|
||||
Ok(Message::Close(_)) | Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => {
|
||||
closed = Some(t0.elapsed());
|
||||
break;
|
||||
}
|
||||
Err(tungstenite::Error::Io(e)) if !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {
|
||||
closed = Some(t0.elapsed());
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
if let Ok(at) = ended.recv_timeout(Duration::from_millis(300)) {
|
||||
closed = Some(at.saturating_duration_since(t0));
|
||||
break;
|
||||
}
|
||||
}
|
||||
host.stop();
|
||||
let _ = reader.join();
|
||||
closed
|
||||
}
|
||||
|
||||
|
||||
@@ -195,17 +195,25 @@ impl Duplex {
|
||||
|
||||
impl Read for Duplex {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if let Some(d) = self.deadline {
|
||||
let left = d.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(io::ErrorKind::TimedOut.into());
|
||||
let n = loop {
|
||||
if let Some(d) = self.deadline {
|
||||
let left = d.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(io::ErrorKind::TimedOut.into());
|
||||
}
|
||||
self.read.set_read_timeout(Some(left))?;
|
||||
}
|
||||
self.read.set_read_timeout(Some(left))?;
|
||||
}
|
||||
let n = match &self.tls {
|
||||
Some(t) => tls::read(t, &mut self.read, &self.write, buf),
|
||||
None => self.read.read(buf),
|
||||
}?;
|
||||
let read = match &self.tls {
|
||||
Some(t) => tls::read(t, &mut self.read, &self.write, buf),
|
||||
None => self.read.read(buf),
|
||||
};
|
||||
match read {
|
||||
// The socket's timeout can run out a moment before the deadline (it counts whole
|
||||
// milliseconds): wait out the rest, so a read times out only once it has passed.
|
||||
Err(e) if self.deadline.is_some() && matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
|
||||
read => break read?,
|
||||
}
|
||||
};
|
||||
if let Some(m) = self.meter.as_mut() {
|
||||
m.add(n)?;
|
||||
}
|
||||
|
||||
@@ -89,6 +89,9 @@ fn rect(s: &mut Session) -> u64 {
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// Asserts two files are hosted and joined independently: each has its own port, session and
|
||||
/// edits, presence stays in its file's session, and closing one file's session leaves the
|
||||
/// other live.
|
||||
#[test]
|
||||
fn two_files_are_hosted_and_joined_independently() {
|
||||
let mut host = session("Hana");
|
||||
@@ -123,8 +126,15 @@ fn two_files_are_hosted_and_joined_independently() {
|
||||
host.execute("doc.switch", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(host.live_summary()["link"], a["link"]);
|
||||
assert_eq!(host.live_summary()["document"], 0);
|
||||
// Each joined file opens in front when its welcome arrives, and the two joins race: the file
|
||||
// whose welcome came last is in front.
|
||||
assert_eq!(guest.ds().unwrap().uid, guest.docs[2].uid, "the file that arrived last is in front");
|
||||
guest.execute("doc.switch", &json!({"index": guest.docs.iter().position(|d| d.uid == gb).unwrap()})).unwrap();
|
||||
// An edit in A reaches the guest's copy of A only, while B is in front at the guest.
|
||||
assert_eq!(guest.ds().unwrap().uid, gb, "the file joined last is in front");
|
||||
// Concurrent joins may complete in either order. Put B in front explicitly so the
|
||||
// following assertions exercise A's background session independent of network timing.
|
||||
guest.execute("doc.switch", &json!({"index": guest.docs.iter().position(|d| d.uid == gb).unwrap()})).unwrap();
|
||||
assert_eq!(guest.ds().unwrap().uid, gb, "B is in front while A receives edits");
|
||||
let in_a = rect(&mut host);
|
||||
host.execute("doc.switch", &json!({"index": 1})).unwrap();
|
||||
let in_b = rect(&mut host);
|
||||
|
||||
@@ -122,7 +122,8 @@ impl Color {
|
||||
/// Parse hex the way the colour field does: `#` optional, 1, 2, 3, 4, 6 or 8 digits
|
||||
/// (`F` → `FFFFFF`, `AB` → `ABABAB`, `ABC` → `AABBCC`).
|
||||
pub fn from_hex(s: &str) -> Option<Self> {
|
||||
let s = s.trim().trim_start_matches('#');
|
||||
let s = s.trim();
|
||||
let s = s.strip_prefix('#').unwrap_or(s);
|
||||
if !s.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -115,6 +115,15 @@ fn infinite_channels_clamp() {
|
||||
assert_eq!((c.r, c.g, c.b, c.a), (1.0, 0.0, 0.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_allows_at_most_one_leading_hash() {
|
||||
assert!(Color::from_hex("##ff0000").is_none());
|
||||
assert!(Color::from_hex("###fff").is_none());
|
||||
assert!(Color::from_hex_or_name("##ff0000").is_none());
|
||||
assert_eq!(Color::from_hex("#ff0000").unwrap().to_hex(), "FF0000");
|
||||
assert_eq!(Color::from_hex("ff0000").unwrap().to_hex(), "FF0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_alpha_or_extra_args_rejected() {
|
||||
assert_eq!(Color::parse_css("rgba(0,0,0,abc)"), None);
|
||||
|
||||
@@ -560,6 +560,16 @@ fn is_ancestor_holds_for_very_deep_chains() {
|
||||
assert!(matches!(d.reparent(root, leaf, None), Err(DocError::Cycle(..))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_insert_at_run_boundary_keeps_runs_disjoint() {
|
||||
let mut t = TextData::new("0123456789");
|
||||
t.restyle(0, 5, |s| s.font_size = 20.0);
|
||||
t.restyle(5, 10, |s| s.font_size = 30.0);
|
||||
t.replace_range(5, 5, "xx");
|
||||
let runs: Vec<(usize, usize)> = t.runs.iter().map(|r| (r.start, r.end)).collect();
|
||||
assert_eq!(runs, vec![(0, 7), (7, 12)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_small_vector_subpaths_build_and_stroke_without_rescans() {
|
||||
// Many closed subpaths whose last point repeats the start (#F-332), a long open chain (#F-334)
|
||||
|
||||
@@ -579,7 +579,14 @@ impl TextData {
|
||||
}
|
||||
self.runs.sort_by_key(|r| r.start);
|
||||
let mut merged: Vec<StyleRun> = Vec::with_capacity(self.runs.len());
|
||||
for r in std::mem::take(&mut self.runs) {
|
||||
for mut r in std::mem::take(&mut self.runs) {
|
||||
// Runs never overlap: a later run starts where the previous one ends at the earliest.
|
||||
if let Some(prev) = merged.last() {
|
||||
r.start = r.start.max(prev.end);
|
||||
if r.start >= r.end {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match merged.last_mut() {
|
||||
Some(prev) if prev.end == r.start && prev.style == r.style => prev.end = r.end,
|
||||
_ => merged.push(r),
|
||||
|
||||
@@ -206,8 +206,9 @@ fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {
|
||||
let mut items: Vec<(NodeId, Rect)> = ids.iter().filter_map(|i| doc.world_bounds(*i).map(|b| (*i, b))).collect();
|
||||
items.sort_by(|a, b| if horizontal { a.1.x0.total_cmp(&b.1.x0) } else { a.1.y0.total_cmp(&b.1.y0) });
|
||||
let total: f64 = items.iter().map(|(_, b)| if horizontal { b.width() } else { b.height() }).sum();
|
||||
let (Some(first), Some(last)) = (items.first(), items.last()) else { return ok() };
|
||||
let span = if horizontal { last.1.x1 - first.1.x0 } else { last.1.y1 - first.1.y0 };
|
||||
let Some(first) = items.first() else { return ok() };
|
||||
let end = items.iter().map(|(_, b)| if horizontal { b.x1 } else { b.y1 }).fold(f64::MIN, f64::max);
|
||||
let span = if horizontal { end - first.1.x0 } else { end - first.1.y0 };
|
||||
let gap = num(p, "spacing").unwrap_or((span - total) / (items.len().saturating_sub(1).max(1)) as f64);
|
||||
let mut pos = if horizontal { first.1.x0 } else { first.1.y0 };
|
||||
for (i, b) in items.clone() {
|
||||
|
||||
@@ -541,6 +541,7 @@ pub fn copy_to_clipboard(s: &mut Session, cmd: &str, ids: &[NodeId]) -> Result<(
|
||||
s.clipboard.nodes = nodes;
|
||||
s.clipboard.images = images;
|
||||
s.clipboard.bounds = bounds;
|
||||
s.clipboard.layers_generation = s.clipboard.layers_generation.wrapping_add(1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -600,6 +601,10 @@ pub fn design_clipboard_buffer(html: &str) -> Option<Vec<u8>> {
|
||||
figcraft_format::fig::is_fig(&bytes).then_some(bytes)
|
||||
}
|
||||
|
||||
/// Paste design layers from clipboard HTML or base64 `data`: decode and reject missing,
|
||||
/// invalid or oversized data, load a temporary `.fig`, take its top-level page layers,
|
||||
/// store them as a foreign-file clipboard source with a bumped layers generation, then
|
||||
/// delegate to `paste` and append import warnings.
|
||||
fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "edit.pasteDesignLayers";
|
||||
let bytes = match (string(p, "html"), string(p, "data")) {
|
||||
@@ -616,8 +621,18 @@ fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (nodes, images, bounds) = copied(&doc, &tops);
|
||||
let props = s.clipboard.props.take();
|
||||
// No open file has id 0. So paste treats this copy as a copy from a different file.
|
||||
s.clipboard =
|
||||
crate::Clipboard { nodes, images, props, bounds, source_doc: 0, source: Some(doc), source_path: None, copied_components: BTreeSet::new() };
|
||||
let layers_generation = s.clipboard.layers_generation.wrapping_add(1);
|
||||
s.clipboard = crate::Clipboard {
|
||||
nodes,
|
||||
images,
|
||||
props,
|
||||
bounds,
|
||||
source_doc: 0,
|
||||
source: Some(doc),
|
||||
source_path: None,
|
||||
copied_components: BTreeSet::new(),
|
||||
layers_generation,
|
||||
};
|
||||
let mut out = paste(s, p)?;
|
||||
if !other.issues.is_empty() {
|
||||
out["warnings"] = json!(other.issues);
|
||||
|
||||
@@ -144,7 +144,9 @@ pub(crate) fn sizing(v: &Value) -> Option<Sizing> {
|
||||
pub(crate) fn line_height(v: &Value) -> Option<LineHeight> {
|
||||
match v {
|
||||
Value::String(s) if s.eq_ignore_ascii_case("auto") => Some(LineHeight::Auto),
|
||||
Value::String(s) if s.trim().ends_with('%') => s.trim().trim_end_matches('%').trim().parse().ok().map(LineHeight::Percent),
|
||||
Value::String(s) if s.trim().ends_with('%') => {
|
||||
s.trim().trim_end_matches('%').trim().parse().ok().filter(|f: &f64| f.is_finite()).map(LineHeight::Percent)
|
||||
}
|
||||
Value::Object(_) => serde_json::from_value(v.clone()).ok(),
|
||||
other => f64_of(other).map(LineHeight::Pixels),
|
||||
}
|
||||
@@ -152,7 +154,9 @@ pub(crate) fn line_height(v: &Value) -> Option<LineHeight> {
|
||||
|
||||
pub(crate) fn letter_spacing(v: &Value) -> Option<LetterSpacing> {
|
||||
match v {
|
||||
Value::String(s) if s.trim().ends_with('%') => s.trim().trim_end_matches('%').trim().parse().ok().map(LetterSpacing::Percent),
|
||||
Value::String(s) if s.trim().ends_with('%') => {
|
||||
s.trim().trim_end_matches('%').trim().parse().ok().filter(|f: &f64| f.is_finite()).map(LetterSpacing::Percent)
|
||||
}
|
||||
Value::Object(_) => serde_json::from_value(v.clone()).ok(),
|
||||
other => f64_of(other).map(LetterSpacing::Pixels),
|
||||
}
|
||||
@@ -1277,3 +1281,17 @@ pub fn describe(doc: &Document, id: NodeId) -> Value {
|
||||
let _ = Color::BLACK;
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn non_finite_percent_strings_are_rejected() {
|
||||
for s in ["NaN%", "inf%", "-inf%"] {
|
||||
assert!(line_height(&json!(s)).is_none(), "line_height accepted {s}");
|
||||
assert!(letter_spacing(&json!(s)).is_none(), "letter_spacing accepted {s}");
|
||||
}
|
||||
assert!(matches!(line_height(&json!("150%")), Some(LineHeight::Percent(p)) if p == 150.0));
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,12 @@ pub(crate) fn num(v: f64) -> String {
|
||||
return "0".into();
|
||||
}
|
||||
let r = (v * 100.0).round() / 100.0;
|
||||
if (r - r.round()).abs() < 1e-9 { format!("{}", r.round() as i64) } else { format!("{r}") }
|
||||
if (r - r.round()).abs() < 1e-9 {
|
||||
// `as i64` saturates past 2^63, so larger whole values are printed from the float.
|
||||
if r.abs() < 9e18 { format!("{}", r.round() as i64) } else { format!("{:.0}", r.round()) }
|
||||
} else {
|
||||
format!("{r}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `code` with every pixel length (`12px`) in rem of `root` pixels (`0.75rem`); names that end
|
||||
@@ -1142,6 +1147,14 @@ mod tests {
|
||||
use crate::params::id_of;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn num_keeps_huge_whole_numbers() {
|
||||
assert_eq!(num(1e20), "100000000000000000000");
|
||||
assert_eq!(num(-1e20), "-100000000000000000000");
|
||||
assert_eq!(num(1e18), "1000000000000000000");
|
||||
assert_eq!(num(-0.0), "0");
|
||||
}
|
||||
|
||||
fn card(s: &mut Session) -> NodeId {
|
||||
let f = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100, "name": "Card"})).unwrap()["id"]).unwrap();
|
||||
s.execute("node.set", &json!({"id": f, "props": {"fills": ["#FFFFFF"], "cornerRadius": 12}})).unwrap();
|
||||
|
||||
@@ -225,7 +225,9 @@ pub fn type_name(name: &str) -> String {
|
||||
/// Words no generated parameter may be called (keywords of TypeScript, Swift and Kotlin, and
|
||||
/// names the generated code uses).
|
||||
const RESERVED: &[&str] = &[
|
||||
"arguments",
|
||||
"as",
|
||||
"await",
|
||||
"body",
|
||||
"break",
|
||||
"case",
|
||||
@@ -239,6 +241,7 @@ const RESERVED: &[&str] = &[
|
||||
"do",
|
||||
"else",
|
||||
"enum",
|
||||
"eval",
|
||||
"export",
|
||||
"extends",
|
||||
"extension",
|
||||
@@ -249,6 +252,7 @@ const RESERVED: &[&str] = &[
|
||||
"function",
|
||||
"guard",
|
||||
"if",
|
||||
"implements",
|
||||
"import",
|
||||
"in",
|
||||
"init",
|
||||
@@ -264,6 +268,7 @@ const RESERVED: &[&str] = &[
|
||||
"operator",
|
||||
"package",
|
||||
"private",
|
||||
"protected",
|
||||
"protocol",
|
||||
"public",
|
||||
"ref",
|
||||
|
||||
@@ -43,6 +43,18 @@ fn button_set(s: &mut Session) -> (NodeId, NodeId, NodeId) {
|
||||
(set, variants[0], variants[1])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_mode_reserved_words_are_not_parameter_names() {
|
||||
let mut s = Session::new();
|
||||
let (c, title, _) = card(&mut s);
|
||||
ex(&mut s, "component.addProperty", json!({"id": c, "name": "Protected", "type": "text", "layer": title}));
|
||||
let react = code(&mut s, c, "react");
|
||||
assert!(react.contains("protectedValue"), "React renames the property:\n{react}");
|
||||
for bad in [" protected?", " protected =", "{protected}"] {
|
||||
assert!(!react.contains(bad), "reserved word used as a binding ({bad:?}):\n{react}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn components_take_their_properties_as_parameters() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -329,6 +329,17 @@ pub struct TextEdit {
|
||||
pub anchor: usize,
|
||||
/// The node was created by this edit (deleted if left empty).
|
||||
pub created: bool,
|
||||
/// Identity of this editing session (`textedit::begin` assigns a fresh one).
|
||||
///
|
||||
/// The IME owner is `(document uid, node)`, which stays the same through ordinary edits
|
||||
/// and caret moves; this token changes only when editing is started again, so an IME
|
||||
/// context is never silently inherited by a replaced target that reuses the same node.
|
||||
///
|
||||
/// It is deliberately not serialized: current consumers only inspect a live session. A
|
||||
/// serialized `TextEdit` restored from data would get zero here, so it must not be restored
|
||||
/// into a live editor without minting (or otherwise invalidating) a new session.
|
||||
#[serde(default, skip_serializing)]
|
||||
pub editing_session: u64,
|
||||
/// An IME composition in progress, shown inline at the caret; the document gets it on commit.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub preedit: Option<Preedit>,
|
||||
@@ -774,6 +785,10 @@ pub struct Clipboard {
|
||||
pub source_doc: u64,
|
||||
/// Copied component/set roots, excluding cuts and originals discarded by undo (ids are reused).
|
||||
pub copied_components: std::collections::BTreeSet<NodeId>,
|
||||
/// Monotonic generation of the copied layers (contents, images, bounds and source). A UI
|
||||
/// clipboard mirror records it, so a later programmatic copy that never touched the system
|
||||
/// clipboard is not mistaken for the user's own copy just because the text still matches.
|
||||
pub layers_generation: u64,
|
||||
/// The document copied from (pastes into other files follow its mains) and its file path.
|
||||
pub source: Option<Arc<Document>>,
|
||||
pub source_path: Option<String>,
|
||||
|
||||
@@ -250,3 +250,21 @@ fn measure_distances_command() {
|
||||
assert!(s.execute("measure.distances", &json!({"ids": [f]})).is_err(), "top level: pass `to`");
|
||||
assert!(s.execute("measure.distances", &json!({"ids": [r], "to": 99999})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_the_canvas_clears_the_hover_measurement() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0, 50.0, 50.0, None);
|
||||
rect(&mut s, 100.0, 0.0, 50.0, 50.0, None);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
assert!(!hover(&mut s, 125.0, 25.0, true, false, false).is_empty());
|
||||
assert!(s.tool.overlay.measure_box.is_some());
|
||||
s.pointer_left();
|
||||
assert!(s.tool.overlay.guides.is_empty(), "{:?}", s.tool.overlay.guides);
|
||||
assert_eq!(s.tool.overlay.measure_box, None);
|
||||
// Dev Mode measures without Alt; leaving clears those too.
|
||||
s.tool.dev_mode = true;
|
||||
assert!(!hover(&mut s, 125.0, 25.0, false, false, false).is_empty());
|
||||
s.pointer_left();
|
||||
assert!(s.tool.overlay.guides.is_empty());
|
||||
}
|
||||
@@ -275,6 +275,20 @@ fn align_distribute_zorder() {
|
||||
assert_eq!(s.doc().unwrap().node(page).unwrap().children[0], c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distribute_spans_the_outermost_edge() {
|
||||
let mut s = sess();
|
||||
let a = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap());
|
||||
let b = id(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 500, "height": 500})).unwrap());
|
||||
let c = id(&s.execute("shape.rectangle", &json!({"x": 160, "y": 160, "width": 10, "height": 10})).unwrap());
|
||||
s.execute("distribute.horizontal", &json!({"ids": [a, b, c]})).unwrap();
|
||||
let xs: Vec<f64> = [a, b, c].iter().map(|i| s.doc().unwrap().world_bounds(*i).unwrap().x0).collect();
|
||||
assert_eq!(xs, [0.0, 75.0, 640.0]);
|
||||
s.execute("distribute.vertical", &json!({"ids": [a, b, c]})).unwrap();
|
||||
let ys: Vec<f64> = [a, b, c].iter().map(|i| s.doc().unwrap().world_bounds(*i).unwrap().y0).collect();
|
||||
assert_eq!(ys, [0.0, 75.0, 640.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_alone_on_the_page_has_nothing_to_align_to() {
|
||||
use crate::cmd::arrange::can_align;
|
||||
|
||||
@@ -60,11 +60,14 @@ fn arrows_and_deletes_step_over_whole_clusters() {
|
||||
key(&mut s, "Right", true, false, false).unwrap();
|
||||
assert_eq!(caret(&s), (1, 6));
|
||||
key(&mut s, "Left", false, false, false).unwrap();
|
||||
// Delete and Backspace remove a whole cluster.
|
||||
// Delete removes a whole cluster; Backspace takes a letter's marks one at a time (#1220) and
|
||||
// an emoji cluster whole.
|
||||
key(&mut s, "Delete", false, false, false).unwrap();
|
||||
assert_eq!(chars(&s, t), "ab\u{1F1EF}\u{1F1F5}e\u{0301}");
|
||||
key(&mut s, "Right", false, false, true).unwrap(); // to the end
|
||||
key(&mut s, "Backspace", false, false, false).unwrap();
|
||||
assert_eq!(chars(&s, t), "ab\u{1F1EF}\u{1F1F5}e");
|
||||
key(&mut s, "Backspace", false, false, false).unwrap();
|
||||
assert_eq!(chars(&s, t), "ab\u{1F1EF}\u{1F1F5}");
|
||||
key(&mut s, "Backspace", false, false, false).unwrap();
|
||||
assert_eq!(chars(&s, t), "ab");
|
||||
@@ -134,6 +137,63 @@ fn ime_composition_with_cjk() {
|
||||
assert!(s.ds().unwrap().text_edit.as_ref().unwrap().preedit.is_none());
|
||||
}
|
||||
|
||||
/// Asserts `delete_surrounding_bytes` removes an exact UTF-8 byte range across CJK and a
|
||||
/// supplementary emoji, leaves nothing past the start, and the whole edit is one undo step.
|
||||
#[test]
|
||||
fn ime_delete_surrounding_bytes_is_exact_and_one_undo_step() {
|
||||
// 0.37's `DeleteSurroundingBytes` counts UTF-8 bytes around the selection, before the paired
|
||||
// commit. Multibyte CJK and a supplementary emoji must be removed exactly, not as tofu or
|
||||
// extended to grapheme clusters, and the whole edit remains one undo step.
|
||||
let mut s = Session::new();
|
||||
let t = text(&mut s, "ab\u{4F60}\u{597D}c\u{1F600}d", json!({"fontSize": 24}));
|
||||
begin(&mut s, t, Some(4), false).unwrap();
|
||||
assert!(crate::textedit::delete_surrounding_bytes(&mut s, 6, 1).unwrap(), "你好 before and c after");
|
||||
assert_eq!(chars(&s, t), "ab\u{1F600}d");
|
||||
assert_eq!(caret(&s), (2, 2));
|
||||
crate::textedit::set_caret(&mut s, 3, false).unwrap();
|
||||
assert!(crate::textedit::delete_surrounding_bytes(&mut s, 4, 0).unwrap(), "the emoji is four bytes");
|
||||
assert_eq!(chars(&s, t), "abd");
|
||||
assert_eq!(caret(&s), (2, 2));
|
||||
// Past the start of the text: nothing more to delete, not an error.
|
||||
assert!(!crate::textedit::delete_surrounding_bytes(&mut s, 0, 0).unwrap());
|
||||
crate::textedit::end(&mut s).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(chars(&s, t), "ab\u{4F60}\u{597D}c\u{1F600}d", "one undo restores the whole session");
|
||||
}
|
||||
|
||||
/// Asserts a byte range that only partly covers a character leaves it in place, while an
|
||||
/// exact range deletes it, and a selection survives for the paired commit with its
|
||||
/// direction preserved.
|
||||
#[test]
|
||||
fn ime_delete_surrounding_bytes_keeps_partial_characters_and_selection() {
|
||||
// The fork deletes the byte range exactly and leaves a character the range only partly
|
||||
// covers. FigCraft's editor counts characters with the same rule (mirroring egui's
|
||||
// `surrounding_bytes_to_chars`), including around a selection.
|
||||
let mut s = Session::new();
|
||||
let t = text(&mut s, "\u{e9}x\u{1F600}", json!({"fontSize": 24}));
|
||||
let del = |s: &mut Session, b: usize, a: usize| crate::textedit::delete_surrounding_bytes(s, b, a).unwrap();
|
||||
begin(&mut s, t, Some(1), false).unwrap();
|
||||
assert!(!del(&mut s, 1, 0), "one byte ends inside 'é' (two bytes): leave it");
|
||||
assert_eq!(chars(&s, t), "\u{e9}x\u{1F600}");
|
||||
crate::textedit::set_caret(&mut s, 2, false).unwrap();
|
||||
assert!(!del(&mut s, 0, 2), "two bytes start inside the four-byte emoji: leave it");
|
||||
assert_eq!(chars(&s, t), "\u{e9}x\u{1F600}");
|
||||
assert!(del(&mut s, 0, 4), "its four bytes cover it exactly");
|
||||
assert_eq!(chars(&s, t), "\u{e9}x");
|
||||
assert_eq!(caret(&s), (2, 2));
|
||||
// Complete bytes before the selection go; a character the range only partly covers stays,
|
||||
// and the selection itself is kept for the paired commit.
|
||||
crate::textedit::set_caret(&mut s, 1, false).unwrap();
|
||||
crate::textedit::set_caret(&mut s, 1, true).unwrap();
|
||||
crate::textedit::set_caret(&mut s, 2, true).unwrap();
|
||||
assert!(del(&mut s, 2, 2), "é before (two bytes); two bytes start inside the four-byte emoji");
|
||||
// The selected 'x' is kept for the paired commit, as in stock `TextEdit`; the caret moves left
|
||||
// with the deleted prefix and the selection direction is preserved.
|
||||
assert_eq!(chars(&s, t), "x");
|
||||
assert_eq!(caret(&s), (0, 1));
|
||||
crate::textedit::end(&mut s).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_trim_through_node_set() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -1,9 +1,85 @@
|
||||
//! On-canvas text editing: caret, selection, typing. A whole editing session is one undo step.
|
||||
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
use figcraft_doc::{Document, ListStyle, NodeId, NodeKind, TextData};
|
||||
|
||||
use crate::{EngineError, Preedit, Result, Session, TextEdit};
|
||||
|
||||
/// Most committed UTF-8 bytes an outgoing IME snapshot may describe.
|
||||
///
|
||||
/// This mirrors the fork's `egui::output::MAX_IME_SURROUNDING_TEXT_BYTES`; the engine keeps its
|
||||
/// own constant so this layer has no egui dependency. The query below returns only this bounded
|
||||
/// window around the selection, never a copy of the whole document.
|
||||
pub const MAX_IME_SURROUNDING_BYTES: usize = 4000;
|
||||
|
||||
/// Stable identity of the on-canvas text edit an IME context belongs to.
|
||||
///
|
||||
/// `document` and `node` do not change through ordinary text or caret edits. `editing_session`
|
||||
/// changes when [`begin`] starts a new session for an equal `(document, node)` pair (leaving and
|
||||
/// re-entering the same layer), so a replaced target never inherits an old composition.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ImeEditOwner {
|
||||
/// The document tab's uid.
|
||||
pub document: u64,
|
||||
/// The edited text node.
|
||||
pub node: NodeId,
|
||||
/// [`TextEdit::editing_session`] of the current edit.
|
||||
pub editing_session: u64,
|
||||
}
|
||||
|
||||
/// Why the committed text around the IME caret cannot be described.
|
||||
///
|
||||
/// These are the only reasons this custom editor reports
|
||||
/// `egui::output::IMESurroundingText::Unavailable`; an empty text layer is available with empty
|
||||
/// text and a collapsed selection.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ImeSurroundingUnavailable {
|
||||
/// No text layer is being edited.
|
||||
NotEditing,
|
||||
/// The editing target is not a text node any more.
|
||||
NotText,
|
||||
/// The selection alone is wider than [`MAX_IME_SURROUNDING_BYTES`], so no bounded snapshot
|
||||
/// can contain both selection ends.
|
||||
SelectionTooWide,
|
||||
/// Defensive: the computed window was not a character-boundary slice. The rounding above
|
||||
/// makes this unreachable for a well-formed text model.
|
||||
InvalidWindow,
|
||||
}
|
||||
|
||||
/// One bounded, committed logical-text observation for the outgoing IME snapshot.
|
||||
///
|
||||
/// `text` is never display/bidi order and never contains the pre-edit (which is UI-only in this
|
||||
/// editor). `cursor` and `anchor` are UTF-8 byte offsets into `text`; `anchor > cursor` is a
|
||||
/// valid reversed selection.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImeSurrounding {
|
||||
/// Identity of the edit this observation belongs to.
|
||||
pub owner: ImeEditOwner,
|
||||
/// At most [`MAX_IME_SURROUNDING_BYTES`] bytes of committed text around the selection.
|
||||
pub text: String,
|
||||
/// UTF-8 byte offset of the primary caret in [`Self::text`].
|
||||
pub cursor: usize,
|
||||
/// UTF-8 byte offset of the selection anchor in [`Self::text`].
|
||||
pub anchor: usize,
|
||||
}
|
||||
|
||||
/// Every editing session gets its own token; zero is valid and never reused deliberately.
|
||||
///
|
||||
/// A mutex (rather than an atomic) also works on wasm32 targets without 64-bit atomics.
|
||||
static EDITING_SESSION: LazyLock<Mutex<u64>> = LazyLock::new(|| Mutex::new(0));
|
||||
|
||||
/// Return the next editing-session token from a mutex-protected counter (`wrapping_add`).
|
||||
/// Zero is a valid token; the mutex also works on wasm32 without 64-bit atomics.
|
||||
fn next_editing_session() -> u64 {
|
||||
let mut session = match EDITING_SESSION.lock() {
|
||||
Ok(session) => session,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
*session = session.wrapping_add(1);
|
||||
*session
|
||||
}
|
||||
|
||||
fn text_of(s: &Session, id: NodeId) -> Result<TextData> {
|
||||
match &s.doc()?.get(id)?.kind {
|
||||
NodeKind::Text(t) => Ok(t.clone()),
|
||||
@@ -23,7 +99,7 @@ pub fn begin(s: &mut Session, id: NodeId, caret: Option<usize>, created: bool) -
|
||||
Some(c) => (c.min(n), c.min(n)),
|
||||
None => (n, 0),
|
||||
};
|
||||
ds.text_edit = Some(TextEdit { id, caret, anchor, created, preedit: None });
|
||||
ds.text_edit = Some(TextEdit { id, caret, anchor, created, editing_session: next_editing_session(), preedit: None });
|
||||
ds.selection = vec![id];
|
||||
ds.revision += 1;
|
||||
s.live_text_notice(id);
|
||||
@@ -69,14 +145,33 @@ fn range(te: &TextEdit) -> (usize, usize) {
|
||||
(te.caret.min(te.anchor), te.caret.max(te.anchor))
|
||||
}
|
||||
|
||||
/// Apply an unconditional text-model mutation through `edit_if`, whose success clears the
|
||||
/// composition, clamps caret and anchor to the character count, marks a `characters` override
|
||||
/// when the node is source-backed, normalizes the document and bumps the revision.
|
||||
fn edit(s: &mut Session, f: impl FnOnce(&mut TextData, &mut TextEdit)) -> Result<()> {
|
||||
edit_if(s, |t, te| {
|
||||
f(t, te);
|
||||
true
|
||||
})
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// [`edit`] for a mutation that can still turn out to be a no-op.
|
||||
///
|
||||
/// The closure returns whether it changed the model; return `false` only before mutating (the
|
||||
/// text is handed over directly). A no-op leaves the composition (`preedit`), the revision and the
|
||||
/// document untouched, so an IME deletion that finds nothing to delete does not cancel an
|
||||
/// in-progress composition.
|
||||
fn edit_if(s: &mut Session, f: impl FnOnce(&mut TextData, &mut TextEdit) -> bool) -> Result<bool> {
|
||||
let ds = s.ds_mut()?;
|
||||
let Some(mut te) = ds.text_edit.clone() else { return Err(EngineError::Other("not editing text".into())) };
|
||||
let before = ds.doc.clone();
|
||||
let doc = ds.doc_mut();
|
||||
let n = doc.get_mut(te.id)?;
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("not a text layer".into())) };
|
||||
f(t, &mut te);
|
||||
if !f(t, &mut te) {
|
||||
return Ok(false);
|
||||
}
|
||||
// Any edit ends a composition (a commit replaces it with the final text).
|
||||
te.preedit = None;
|
||||
let len = t.char_count();
|
||||
@@ -88,16 +183,83 @@ fn edit(s: &mut Session, f: impl FnOnce(&mut TextData, &mut TextEdit)) -> Result
|
||||
crate::normalize(doc, &before);
|
||||
ds.text_edit = Some(te);
|
||||
ds.revision += 1;
|
||||
Ok(())
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// What an accepted IME `Commit` did to the committed model.
|
||||
///
|
||||
/// An IME receipt may label the snapshot `InputMethod` only for [`Self::Plain`]. AutoFormat
|
||||
/// (typing "- " at a line start turns the paragraph into a list) is an application
|
||||
/// transformation in the same command, so the frame's change must be reported as `Other`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ImeInsertion {
|
||||
/// Nothing was inserted (an empty, control-only, or bare-newline commit).
|
||||
Nothing,
|
||||
/// The committed text replaced the selection exactly.
|
||||
Plain,
|
||||
/// The editor transformed the commit before applying it: paragraph AutoFormat, or line-ending
|
||||
/// normalisation/control-character removal. The frame's change is application-origin.
|
||||
Transformed,
|
||||
}
|
||||
|
||||
/// Type (or paste) `text` replacing the selection. Line endings are normalised and other control
|
||||
/// characters dropped, so pasted plain text from any platform lands cleanly.
|
||||
pub fn insert(s: &mut Session, text: &str) -> Result<()> {
|
||||
let text: String = crate::cmd::props::normalize_line_endings(text).chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t')).collect();
|
||||
if text.is_empty() {
|
||||
insert_model(s, text, false).map(|_| ())
|
||||
}
|
||||
|
||||
/// End the composition without changing the document, for an empty IME commit.
|
||||
///
|
||||
/// Returns without touching the session when no composition is active (or nothing is being
|
||||
/// edited): an empty commit is otherwise a no-op, never an error.
|
||||
fn clear_composition(s: &mut Session) -> Result<()> {
|
||||
let composing = s.ds().ok().and_then(|d| d.text_edit.as_ref()).is_some_and(|te| te.preedit.is_some());
|
||||
if !composing {
|
||||
return Ok(());
|
||||
}
|
||||
let ds = s.ds_mut()?;
|
||||
if let Some(te) = ds.text_edit.as_mut() {
|
||||
te.preedit = None;
|
||||
}
|
||||
ds.revision += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply an IME `Commit`, reporting whether it was a plain insertion.
|
||||
///
|
||||
/// The UI calls this instead of [`insert`] so only a commit that the editor applied as a plain
|
||||
/// insertion can earn an `InputMethod` receipt. AutoFormat, line-ending normalisation and
|
||||
/// control-character removal are application transformations and are reported as
|
||||
/// [`ImeInsertion::Transformed`]. Like stock `TextEdit`, a bare `"\n"`/`"\r"` commit is ignored.
|
||||
pub fn insert_ime_commit(s: &mut Session, text: &str) -> Result<ImeInsertion> {
|
||||
insert_model(s, text, true)
|
||||
}
|
||||
|
||||
/// Insert committed text, optionally as an IME commit: normalize line endings, drop control
|
||||
/// characters except `\n`/`\t`, ignore a bare newline/CR IME commit, clear an active
|
||||
/// composition for an empty or control-only IME commit, and turn a committed space after a
|
||||
/// line-start `-`, `*` or `1.` into a bulleted/numbered list. Reports whether the insertion was
|
||||
/// plain, transformed, or a no-op.
|
||||
fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result<ImeInsertion> {
|
||||
// Stock `TextEdit` deliberately ignores these two commits (they are not a mutation); only a
|
||||
// real commit may do so, since typing Enter goes through `insert`.
|
||||
if ime_commit && matches!(text, "\n" | "\r") {
|
||||
return Ok(ImeInsertion::Nothing);
|
||||
}
|
||||
let normalized: String =
|
||||
crate::cmd::props::normalize_line_endings(text).chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t')).collect();
|
||||
if normalized.is_empty() {
|
||||
// An empty commit is how some integrations (Safari's egui web integration when the last
|
||||
// composition character is deleted) end the composition. It inserts nothing, but it must
|
||||
// still clear the pre-edit; stock `TextEdit` does the same in its non-ignored `Commit` arm.
|
||||
if ime_commit {
|
||||
clear_composition(s)?;
|
||||
}
|
||||
return Ok(ImeInsertion::Nothing);
|
||||
}
|
||||
// A commit the editor had to transform is an application edit, not a plain insertion.
|
||||
let mut outcome = if normalized == text { ImeInsertion::Plain } else { ImeInsertion::Transformed };
|
||||
let text = normalized;
|
||||
edit(s, |t, te| {
|
||||
let (a, b) = range(te);
|
||||
// "- ", "* " or "1. " typed at the start of a plain paragraph starts a list.
|
||||
@@ -114,13 +276,15 @@ pub fn insert(s: &mut Session, text: &str) -> Result<()> {
|
||||
t.replace_range(start, a, "");
|
||||
t.set_para_lists(start, start, |pl| pl.list = list);
|
||||
(te.caret, te.anchor) = (start, start);
|
||||
outcome = ImeInsertion::Transformed;
|
||||
return;
|
||||
}
|
||||
}
|
||||
t.replace_range(a, b, &text);
|
||||
te.caret = a + text.chars().count();
|
||||
te.anchor = te.caret;
|
||||
})
|
||||
})?;
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// List keys: Tab nests the selected list items a level deeper; Shift+Tab, Backspace at an item's
|
||||
@@ -249,7 +413,7 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R
|
||||
} else if word {
|
||||
word_left(&chars, a)
|
||||
} else {
|
||||
figcraft_text::grapheme_step(&t.characters, a, false)
|
||||
figcraft_text::backspace_step(&t.characters, a)
|
||||
};
|
||||
(from, a)
|
||||
} else {
|
||||
@@ -345,6 +509,160 @@ fn select(s: &mut Session, anchor: usize, caret: usize) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete the text surrounding the caret/selection that an IME reports with
|
||||
/// [`egui::ImeEvent::DeleteSurroundingBytes`]: `before_bytes` UTF-8 bytes end where the selection
|
||||
/// starts and `after_bytes` start where it ends. As in stock `TextEdit`, the selected text itself
|
||||
/// is kept for the paired `Commit`; only whole characters covered by the byte counts beyond the
|
||||
/// selection are removed (a character the range only partly covers stays). Returns whether
|
||||
/// anything was deleted.
|
||||
pub fn delete_surrounding_bytes(s: &mut Session, before_bytes: usize, after_bytes: usize) -> Result<bool> {
|
||||
let Some(te) = s.ds()?.text_edit.clone() else { return Ok(false) };
|
||||
let t = text_of(s, te.id)?;
|
||||
let (a, b) = range(&te);
|
||||
let (before, after) = surrounding_chars(&t.characters, a, b, before_bytes, after_bytes);
|
||||
if before == 0 && after == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
edit_if(s, |t, te| {
|
||||
let (a, b) = range(te);
|
||||
let (before, after) = surrounding_chars(&t.characters, a, b, before_bytes, after_bytes);
|
||||
if before == 0 && after == 0 {
|
||||
return false;
|
||||
}
|
||||
// Delete after the selection first so the before range's indices stay valid.
|
||||
if after > 0 {
|
||||
t.replace_range(b, b + after, "");
|
||||
}
|
||||
if before > 0 {
|
||||
t.replace_range(a - before, a, "");
|
||||
}
|
||||
// Keep the selection: both ends move left by the deleted prefix, reversed or not.
|
||||
te.caret = te.caret.saturating_sub(before);
|
||||
te.anchor = te.anchor.saturating_sub(before);
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Delete surrounding text counted in characters (the older `DeleteSurrounding` event). The
|
||||
/// selection is kept, as in stock `TextEdit`; only text before and after it is removed.
|
||||
pub fn delete_surrounding_chars(s: &mut Session, before_chars: usize, after_chars: usize) -> Result<bool> {
|
||||
let Some(te) = s.ds()?.text_edit.clone() else { return Ok(false) };
|
||||
let t = text_of(s, te.id)?;
|
||||
let (a, b) = range(&te);
|
||||
let (_, b_byte) = char_byte_offsets(&t.characters, a, b);
|
||||
let before = before_chars.min(a);
|
||||
let after = t.characters.get(b_byte..).map_or(0, |rest| rest.chars().take(after_chars).count());
|
||||
if before == 0 && after == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
edit_if(s, |t, te| {
|
||||
let (a, b) = range(te);
|
||||
let (_, b_byte) = char_byte_offsets(&t.characters, a, b);
|
||||
let before = before_chars.min(a);
|
||||
let after = t.characters.get(b_byte..).map_or(0, |rest| rest.chars().take(after_chars).count());
|
||||
if before == 0 && after == 0 {
|
||||
return false;
|
||||
}
|
||||
if after > 0 {
|
||||
t.replace_range(b, b + after, "");
|
||||
}
|
||||
if before > 0 {
|
||||
t.replace_range(a - before, a, "");
|
||||
}
|
||||
te.caret = te.caret.saturating_sub(before);
|
||||
te.anchor = te.anchor.saturating_sub(before);
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// The UTF-8 byte offsets of character indices `a` and `b` in one forward pass.
|
||||
///
|
||||
/// An index at or past the end maps to `text.len()`. Walking once (instead of twice) matters on
|
||||
/// every IME event over a large text layer; the walk is still O(max(a, b)) characters, and callers
|
||||
/// that need the end still pay O(n). See [`ime_surrounding`].
|
||||
fn char_byte_offsets(text: &str, a: usize, b: usize) -> (usize, usize) {
|
||||
let (mut a_byte, mut b_byte) = (None, None);
|
||||
for (i, (byte, _)) in text.char_indices().enumerate() {
|
||||
if a_byte.is_none() && i == a {
|
||||
a_byte = Some(byte);
|
||||
}
|
||||
if b_byte.is_none() && i == b {
|
||||
b_byte = Some(byte);
|
||||
}
|
||||
if a_byte.is_some() && b_byte.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(a_byte.unwrap_or(text.len()), b_byte.unwrap_or(text.len()))
|
||||
}
|
||||
|
||||
/// `(before, after)` characters covered by the IME's byte counts around the selection `[a, b)`
|
||||
/// (character indices): mirror of egui's own `surrounding_bytes_to_chars`.
|
||||
fn surrounding_chars(text: &str, a: usize, b: usize, before_bytes: usize, after_bytes: usize) -> (usize, usize) {
|
||||
let (a_byte, b_byte) = char_byte_offsets(text, a, b);
|
||||
let from = a_byte.saturating_sub(before_bytes);
|
||||
let before = text[..a_byte].char_indices().rev().take_while(|(i, _)| *i >= from).count();
|
||||
let after = text[b_byte..].char_indices().take_while(|(i, c)| i + c.len_utf8() <= after_bytes).count();
|
||||
(before, after)
|
||||
}
|
||||
|
||||
/// The committed text around the IME caret for the outgoing surrounding-text snapshot.
|
||||
///
|
||||
/// This is the edited node's logical model text (never the bidi display order), with the
|
||||
/// pre-edit excluded because a composition is UI-only in this editor until it is committed.
|
||||
/// Character caret/anchor indices become independent UTF-8 byte offsets, so a reversed
|
||||
/// selection stays reversed. At most [`MAX_IME_SURROUNDING_BYTES`] bytes are copied: the window
|
||||
/// is centred on the selection and rounded inward to character boundaries. An empty text layer
|
||||
/// is `Ok` with `text == ""` and both offsets zero; the result is [`ImeSurroundingUnavailable`]
|
||||
/// only when there is no text edit, the target is not a text node, or the selection alone is
|
||||
/// wider than the budget.
|
||||
///
|
||||
/// Cost: one character walk up to the later of the two cursor indices (to turn char indices into
|
||||
/// UTF-8 bytes) plus the bounded copy. The caret is a character index, so reaching a caret near
|
||||
/// the end of a very large layer is still O(n); the UI calls this once per pass and twice around
|
||||
/// each text-affecting event (`ime_stamp`), so such a layer pays O(caret/anchor) per event. The
|
||||
/// document is never cloned here.
|
||||
pub fn ime_surrounding(s: &Session) -> std::result::Result<ImeSurrounding, ImeSurroundingUnavailable> {
|
||||
let ds = s.ds().map_err(|_| ImeSurroundingUnavailable::NotEditing)?;
|
||||
let te = ds.text_edit.as_ref().ok_or(ImeSurroundingUnavailable::NotEditing)?;
|
||||
let node = ds.doc.node(te.id).ok_or(ImeSurroundingUnavailable::NotText)?;
|
||||
let NodeKind::Text(t) = &node.kind else { return Err(ImeSurroundingUnavailable::NotText) };
|
||||
let text = t.characters.as_str();
|
||||
// One pass for both offsets (the caret and anchor are already clamped by `edit`/`select`).
|
||||
let (cursor, anchor) = char_byte_offsets(text, te.caret, te.anchor);
|
||||
let (selection_start, selection_end) = (cursor.min(anchor), cursor.max(anchor));
|
||||
let selection_len = selection_end - selection_start;
|
||||
if selection_len > MAX_IME_SURROUNDING_BYTES {
|
||||
return Err(ImeSurroundingUnavailable::SelectionTooWide);
|
||||
}
|
||||
// Spend the budget on both sides, giving room unused on one side to the other.
|
||||
let budget = MAX_IME_SURROUNDING_BYTES - selection_len;
|
||||
let before_available = selection_start;
|
||||
let after_available = text.len() - selection_end;
|
||||
let mut before = (budget / 2).min(before_available);
|
||||
let mut after = (budget - before).min(after_available);
|
||||
before = (budget - after).min(before_available);
|
||||
after = (budget - before).min(after_available);
|
||||
let mut window_start = selection_start - before;
|
||||
let mut window_end = selection_end + after;
|
||||
// Round inward so the window stays within the byte budget and on character boundaries.
|
||||
while window_start < window_end && !text.is_char_boundary(window_start) {
|
||||
window_start += 1;
|
||||
}
|
||||
while window_end > window_start && !text.is_char_boundary(window_end) {
|
||||
window_end -= 1;
|
||||
}
|
||||
let Some(window) = text.get(window_start..window_end) else {
|
||||
return Err(ImeSurroundingUnavailable::InvalidWindow);
|
||||
};
|
||||
Ok(ImeSurrounding {
|
||||
owner: ImeEditOwner { document: ds.uid, node: te.id, editing_session: te.editing_session },
|
||||
text: window.to_owned(),
|
||||
cursor: cursor.saturating_sub(window_start),
|
||||
anchor: anchor.saturating_sub(window_start),
|
||||
})
|
||||
}
|
||||
|
||||
/// Show an IME composition inline at the caret (`cursor` = the IME's cursor inside it, in chars;
|
||||
/// default its end). The document doesn't change until the composition is committed with
|
||||
/// [`insert`]; an empty `text` cancels it. Starting to compose over a selection deletes it, as
|
||||
@@ -580,12 +898,25 @@ mod tests {
|
||||
end(&mut s).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_removes_only_the_final_thai_mark() {
|
||||
let (mut s, id) = setup("น้ำ");
|
||||
begin(&mut s, id, Some(3), false).unwrap();
|
||||
|
||||
key(&mut s, "Backspace", false, false, false).unwrap();
|
||||
|
||||
assert_eq!(data(&s, id).characters, "น้");
|
||||
}
|
||||
|
||||
fn ev(kind: PointerKind, x: f64, y: f64, shift: bool) -> PointerEvent {
|
||||
let mut e = PointerEvent::at(kind, x, y, 1.0);
|
||||
e.shift = shift;
|
||||
e
|
||||
}
|
||||
|
||||
/// Asserts double-clicking a text layer selects all text, a second double-click selects the
|
||||
/// word without changing the editing session, and drag and Shift+click extend the
|
||||
/// selection.
|
||||
#[test]
|
||||
fn pointer_double_click_drag_and_shift_click() {
|
||||
let (mut s, id) = setup("Hello world");
|
||||
@@ -602,10 +933,16 @@ mod tests {
|
||||
s.pointer(&ev(PointerKind::Up, mid, y, false)).unwrap();
|
||||
s.pointer(&ev(PointerKind::DoubleClick, mid, y, false)).unwrap();
|
||||
assert_eq!(sel(&s), (0, 11));
|
||||
let epoch = s.ds().unwrap().text_edit.as_ref().unwrap().editing_session;
|
||||
s.pointer(&ev(PointerKind::Down, mid, y, false)).unwrap();
|
||||
s.pointer(&ev(PointerKind::DoubleClick, mid, y, false)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, mid, y, false)).unwrap();
|
||||
assert_eq!(sel(&s), (6, 11));
|
||||
assert_eq!(
|
||||
s.ds().unwrap().text_edit.as_ref().unwrap().editing_session,
|
||||
epoch,
|
||||
"a double-click inside the edit is an ordinary edit: same IME replacement epoch"
|
||||
);
|
||||
// Drag-select from the start of "Hello" to the middle.
|
||||
s.pointer(&ev(PointerKind::Down, x_of(0) + 0.5, y, false)).unwrap();
|
||||
assert_eq!(sel(&s), (0, 0));
|
||||
@@ -817,4 +1154,203 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts surrounding text is logical UTF-8 text with byte offsets and keeps a reversed
|
||||
/// selection reversed.
|
||||
#[test]
|
||||
fn ime_surrounding_uses_logical_utf8_bytes_and_keeps_selection_direction() {
|
||||
let (mut s, id) = setup("café😀e\u{301}x");
|
||||
begin(&mut s, id, Some(8), false).unwrap();
|
||||
set_caret(&mut s, 8, false).unwrap();
|
||||
set_caret(&mut s, 5, true).unwrap(); // anchor after the emoji, caret before it
|
||||
let ime = ime_surrounding(&s).unwrap();
|
||||
assert_eq!(ime.text, "café😀e\u{301}x");
|
||||
assert_eq!((ime.cursor, ime.anchor), (9, 13), "char 5 and char 8 as UTF-8 bytes");
|
||||
assert!(ime.cursor < ime.anchor, "the reversed selection stays reversed");
|
||||
assert_eq!(ime.owner.node, id);
|
||||
assert_eq!(ime.owner.document, s.ds().unwrap().uid);
|
||||
}
|
||||
|
||||
/// Asserts an active composition is excluded from surrounding text and an empty text layer
|
||||
/// reports an available, empty payload.
|
||||
#[test]
|
||||
fn ime_surrounding_excludes_the_composition_and_empty_text_is_available() {
|
||||
let (mut s, id) = setup("Hi");
|
||||
begin(&mut s, id, Some(2), false).unwrap();
|
||||
preedit(&mut s, "にほ", Some(1)).unwrap();
|
||||
let ime = ime_surrounding(&s).unwrap();
|
||||
assert_eq!(ime.text, "Hi", "the composition is not committed text");
|
||||
assert_eq!((ime.cursor, ime.anchor), (2, 2));
|
||||
end(&mut s).unwrap();
|
||||
|
||||
let (mut s, id) = setup("");
|
||||
begin(&mut s, id, Some(0), false).unwrap();
|
||||
let ime = ime_surrounding(&s).unwrap();
|
||||
assert_eq!((ime.text.as_str(), ime.cursor, ime.anchor), ("", 0, 0), "an empty layer is available, not unavailable");
|
||||
}
|
||||
|
||||
/// Asserts surrounding text is capped at `MAX_IME_SURROUNDING_BYTES`, an exactly budget-sized
|
||||
/// selection is describable, and one byte more is `SelectionTooWide`.
|
||||
#[test]
|
||||
fn ime_surrounding_is_bounded_and_a_too_wide_selection_is_explicitly_unavailable() {
|
||||
let long = "a".repeat(5000);
|
||||
let (mut s, id) = setup(&long);
|
||||
begin(&mut s, id, Some(5000), false).unwrap();
|
||||
let ime = ime_surrounding(&s).unwrap();
|
||||
assert_eq!(ime.text.len(), MAX_IME_SURROUNDING_BYTES);
|
||||
assert_eq!((ime.cursor, ime.anchor), (MAX_IME_SURROUNDING_BYTES, MAX_IME_SURROUNDING_BYTES));
|
||||
|
||||
// Exactly the budget is still describable; one more byte is not.
|
||||
set_caret(&mut s, 1000, false).unwrap();
|
||||
set_caret(&mut s, 5000, true).unwrap();
|
||||
let ime = ime_surrounding(&s).unwrap();
|
||||
assert_eq!(ime.text.len(), 4000);
|
||||
assert_eq!((ime.cursor, ime.anchor), (4000, 0));
|
||||
set_caret(&mut s, 999, false).unwrap();
|
||||
set_caret(&mut s, 5000, true).unwrap();
|
||||
assert_eq!(ime_surrounding(&s), Err(ImeSurroundingUnavailable::SelectionTooWide));
|
||||
}
|
||||
|
||||
/// Asserts edits and caret moves keep the same IME owner, while ending and beginning a new
|
||||
/// edit session changes the generation.
|
||||
#[test]
|
||||
fn ime_owner_is_stable_through_edits_and_the_session_changes_on_begin() {
|
||||
let (mut s, id) = setup("Hello");
|
||||
begin(&mut s, id, Some(0), false).unwrap();
|
||||
let first = ime_surrounding(&s).unwrap().owner;
|
||||
insert(&mut s, "x").unwrap();
|
||||
set_caret(&mut s, 2, false).unwrap();
|
||||
assert_eq!(ime_surrounding(&s).unwrap().owner, first, "edits and caret moves keep the owner");
|
||||
end(&mut s).unwrap();
|
||||
begin(&mut s, id, Some(0), false).unwrap();
|
||||
let replaced = ime_surrounding(&s).unwrap().owner;
|
||||
assert_eq!(replaced.node, id);
|
||||
assert_ne!(replaced.editing_session, first.editing_session, "a new edit session is a replacement epoch");
|
||||
}
|
||||
|
||||
/// Asserts byte deletion around a reversed selection removes whole characters on both
|
||||
/// sides, keeps the selected text and direction, and a final no-op leaves the text alone.
|
||||
#[test]
|
||||
fn ime_delete_surrounding_bytes_keeps_the_reversed_selection_and_deletes_around_it() {
|
||||
let (mut s, id) = setup("ab你好cd");
|
||||
begin(&mut s, id, Some(4), false).unwrap();
|
||||
set_caret(&mut s, 4, false).unwrap();
|
||||
set_caret(&mut s, 2, true).unwrap(); // reversed: caret before 你, anchor after 好
|
||||
assert!(delete_surrounding_bytes(&mut s, 1, 1).unwrap());
|
||||
// "b" (whole character before the selection) and "c" (whole character after it) go; the
|
||||
// selected "你好" stays for the paired commit, and the reversed direction is preserved.
|
||||
assert_eq!(data(&s, id).characters, "a你好d");
|
||||
assert_eq!(sel(&s), (3, 1)); // (anchor, caret), still reversed
|
||||
assert!(delete_surrounding_bytes(&mut s, 1, 1).unwrap());
|
||||
assert_eq!(data(&s, id).characters, "你好");
|
||||
assert_eq!(sel(&s), (2, 0)); // (anchor, caret), still reversed
|
||||
assert!(!delete_surrounding_bytes(&mut s, 1, 1).unwrap(), "nothing is left around the selection");
|
||||
assert_eq!(data(&s, id).characters, "你好", "a no-op delete does not touch the text");
|
||||
}
|
||||
|
||||
/// Asserts character deletion keeps and shifts the selection, and a no-op delete leaves an
|
||||
/// active composition and the revision untouched.
|
||||
#[test]
|
||||
fn ime_delete_surrounding_chars_keeps_the_selection_and_ignores_a_no_op() {
|
||||
let (mut s, id) = setup("ab你好cd");
|
||||
begin(&mut s, id, Some(2), false).unwrap();
|
||||
set_caret(&mut s, 4, true).unwrap(); // "你好"
|
||||
assert!(delete_surrounding_chars(&mut s, 1, 1).unwrap());
|
||||
assert_eq!(data(&s, id).characters, "a你好d");
|
||||
assert_eq!(sel(&s), (1, 3), "the selection is kept, shifted by the deleted prefix");
|
||||
set_caret(&mut s, 0, false).unwrap();
|
||||
// A composition in progress survives a delete that finds nothing to remove.
|
||||
preedit(&mut s, "x", None).unwrap();
|
||||
let revision = s.ds().unwrap().revision;
|
||||
assert!(!delete_surrounding_chars(&mut s, 1, 0).unwrap());
|
||||
assert_eq!(s.ds().unwrap().text_edit.as_ref().and_then(|te| te.preedit.as_ref()).map(|p| p.text.as_str()), Some("x"));
|
||||
assert_eq!(s.ds().unwrap().revision, revision, "a no-op does not bump the revision");
|
||||
assert!(!delete_surrounding_bytes(&mut s, 1, 0).unwrap());
|
||||
assert_eq!(s.ds().unwrap().text_edit.as_ref().and_then(|te| te.preedit.as_ref()).map(|p| p.text.as_str()), Some("x"));
|
||||
assert_eq!(s.ds().unwrap().revision, revision);
|
||||
}
|
||||
|
||||
/// Asserts a text layer in another document has a different IME owner.
|
||||
#[test]
|
||||
fn ime_owner_identity_changes_with_the_document() {
|
||||
let (mut s, id) = setup("Hi");
|
||||
begin(&mut s, id, Some(2), false).unwrap();
|
||||
let first = ime_surrounding(&s).unwrap().owner;
|
||||
end(&mut s).unwrap();
|
||||
s.execute("file.new", &json!({"name": "Second"})).unwrap();
|
||||
let r = s.execute("text.create", &json!({"text": "There", "x": 0, "y": 0})).unwrap();
|
||||
let other = crate::params::id_of(&r["id"]).unwrap();
|
||||
begin(&mut s, other, Some(5), false).unwrap();
|
||||
let second = ime_surrounding(&s).unwrap().owner;
|
||||
assert_ne!(second.document, first.document, "another document is another IME owner");
|
||||
assert_eq!(second.node, other);
|
||||
}
|
||||
|
||||
/// Asserts a space committed after a line-start `-` becomes a bulleted list and reports
|
||||
/// `Transformed`; a plain `"x"` commit reports `Plain`, and an empty commit reports `Nothing`.
|
||||
#[test]
|
||||
fn ime_commit_reports_list_autoformat_as_an_application_transformation() {
|
||||
let (mut s, id) = setup("-");
|
||||
begin(&mut s, id, Some(1), false).unwrap();
|
||||
assert_eq!(insert_ime_commit(&mut s, " ").unwrap(), ImeInsertion::Transformed);
|
||||
assert_eq!(data(&s, id).characters, "");
|
||||
assert_eq!(data(&s, id).para_list(0).list, ListStyle::Bulleted);
|
||||
assert_eq!(insert_ime_commit(&mut s, "x").unwrap(), ImeInsertion::Plain);
|
||||
assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing);
|
||||
}
|
||||
|
||||
/// Asserts CRLF normalization reports `Transformed`, control-only input reports `Nothing`,
|
||||
/// and bare newline/CR commits are ignored while a live composition remains.
|
||||
#[test]
|
||||
fn ime_commit_normalisation_is_a_transformation_and_a_bare_newline_is_ignored() {
|
||||
let (mut s, id) = setup("Hi");
|
||||
begin(&mut s, id, Some(2), false).unwrap();
|
||||
// CRLF is inserted as LF, but the editor changed the commit: application-origin.
|
||||
assert_eq!(insert_ime_commit(&mut s, "a\r\nb").unwrap(), ImeInsertion::Transformed);
|
||||
assert_eq!(data(&s, id).characters, "Hia\nb");
|
||||
// Control characters are dropped; the commit itself is a no-op.
|
||||
assert_eq!(insert_ime_commit(&mut s, "\u{0}\u{7}").unwrap(), ImeInsertion::Nothing);
|
||||
assert_eq!(data(&s, id).characters, "Hia\nb");
|
||||
// Stock `TextEdit` ignores a bare newline/CR commit; typing Enter still inserts one.
|
||||
// (It also leaves a live composition alone, unlike the non-ignored commit below.)
|
||||
preedit(&mut s, "x", None).unwrap();
|
||||
assert_eq!(insert_ime_commit(&mut s, "\n").unwrap(), ImeInsertion::Nothing);
|
||||
assert_eq!(insert_ime_commit(&mut s, "\r").unwrap(), ImeInsertion::Nothing);
|
||||
assert_eq!(preedit_state(&s).map(|p| p.text), Some("x".into()));
|
||||
preedit(&mut s, "", None).unwrap();
|
||||
assert_eq!(data(&s, id).characters, "Hia\nb");
|
||||
insert(&mut s, "\n").unwrap();
|
||||
assert_eq!(data(&s, id).characters, "Hia\nb\n");
|
||||
}
|
||||
|
||||
/// Asserts an empty or control-only IME commit ends a live composition (bumping the revision
|
||||
/// once), inserts nothing, and is a harmless no-op when no composition is active.
|
||||
#[test]
|
||||
fn an_empty_ime_commit_ends_the_composition_without_inserting_text() {
|
||||
let (mut s, id) = setup("Hello");
|
||||
begin(&mut s, id, Some(5), false).unwrap();
|
||||
preedit(&mut s, "にほ", None).unwrap();
|
||||
assert_eq!(preedit_state(&s).map(|p| p.text), Some("にほ".into()));
|
||||
let revision = s.ds().unwrap().revision;
|
||||
assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing);
|
||||
assert_eq!(s.ds().unwrap().revision, revision + 1, "ending a live composition bumps the revision");
|
||||
assert!(preedit_state(&s).is_none(), "an empty commit ends the composition");
|
||||
assert!(preedit_doc(&s).is_none());
|
||||
assert_eq!(data(&s, id).characters, "Hello", "and inserts nothing");
|
||||
|
||||
// A control-only commit normalises to empty and ends the composition too.
|
||||
preedit(&mut s, "x", None).unwrap();
|
||||
let revision = s.ds().unwrap().revision;
|
||||
assert_eq!(insert_ime_commit(&mut s, "\u{0}\u{7}").unwrap(), ImeInsertion::Nothing);
|
||||
assert_eq!(s.ds().unwrap().revision, revision + 1, "clearing a live composition bumps the revision");
|
||||
assert!(preedit_state(&s).is_none());
|
||||
assert_eq!(data(&s, id).characters, "Hello");
|
||||
|
||||
// With no composition (and not even while editing) an empty commit stays a harmless no-op.
|
||||
let revision = s.ds().unwrap().revision;
|
||||
assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing);
|
||||
assert_eq!(s.ds().unwrap().revision, revision);
|
||||
end(&mut s).unwrap();
|
||||
assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use serde_json::json;
|
||||
|
||||
/// A fixed-width (auto-height) headline of `width` px at 64px. Returns its id.
|
||||
fn headline(s: &mut Session, text: &str, width: f64) -> NodeId {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let t = idv(&ex(s, "text.create", json!({"text": text, "x": 0, "y": 0, "props": {"name": "Headline", "fontSize": 64}})));
|
||||
ex(s, "node.set", json!({"id": t, "props": {"width": width, "textAutoResize": "height"}}));
|
||||
t
|
||||
@@ -63,8 +64,11 @@ fn a_one_word_last_line_is_avoided() {
|
||||
assert!(l.lines.len() == 1 || words.split_whitespace().count() > 1 || words.contains('\u{a0}'), "{words:?}");
|
||||
}
|
||||
|
||||
/// Asserts `data.fill` keeps a short copy's font size, shrinks a long copy, and leaves the
|
||||
/// source text layer untouched.
|
||||
#[test]
|
||||
fn data_fill_sizes_each_copys_text() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 1080, "height": 1350, "name": "Post"})));
|
||||
let t = idv(&ex(&mut s, "text.create", json!({"text": "Curto", "x": 80, "y": 80, "parent": f, "props": {"name": "Headline", "fontSize": 96}})));
|
||||
|
||||
@@ -971,6 +971,16 @@ pub(crate) fn scale_factor(handle: Handle, q: Point, w0: f64, h0: f64, anchor: (
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The pointer left the canvas: what hovering there showed goes (the distances Alt or Dev Mode
|
||||
/// measured and the box measured to, a vector region's highlight), unless a gesture holds it.
|
||||
pub fn pointer_left(&mut self) {
|
||||
if !self.tool.busy() {
|
||||
self.tool.overlay.guides.clear();
|
||||
self.tool.overlay.measure_box = None;
|
||||
}
|
||||
self.vector_pointer_left();
|
||||
}
|
||||
|
||||
/// What a marquee starting at page point `p` selects inside: the top-level frame it starts in
|
||||
/// (its children), or the focus view's frame.
|
||||
pub(crate) fn marquee_within(&self, p: Point) -> Result<Option<NodeId>> {
|
||||
@@ -2010,6 +2020,10 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle a double-click gesture: finish a pen path, rename or click labels/widgets,
|
||||
/// cancel an in-progress move/resize/draw/marquee, handle board double-clicks, enter text
|
||||
/// editing (select-all on entry, word-select inside the running edit), enter vector editing
|
||||
/// for selected shapes, and step groups/frames one level deeper.
|
||||
fn double_click(&mut self, ev: &PointerEvent) -> Result<()> {
|
||||
let ds = self.ds()?;
|
||||
let (doc, sel, page) = (ds.doc.clone(), ds.selection.clone(), ds.page);
|
||||
@@ -2059,13 +2073,15 @@ impl Session {
|
||||
&& doc.node(target).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))
|
||||
&& (sel.contains(&target) || select_target(&doc, leaf, &sel, false) == target)
|
||||
{
|
||||
// Entering a text selects all of it; in the text being edited, the word.
|
||||
// Entering a text selects all of it; in the text being edited, the word. A
|
||||
// double-click inside the running edit is an ordinary edit: starting a new session
|
||||
// here would replace the IME owner's epoch and drop a composition on a plain gesture.
|
||||
let editing = self.ds()?.text_edit.as_ref().is_some_and(|te| te.id == target);
|
||||
let idx = self.text_index_at(target, ev.p())?;
|
||||
textedit::begin(self, target, Some(idx), false)?;
|
||||
if editing {
|
||||
textedit::select_word(self, idx)?;
|
||||
} else {
|
||||
textedit::begin(self, target, Some(idx), false)?;
|
||||
textedit::key(self, "SelectAll", false, false, false)?;
|
||||
}
|
||||
return Ok(());
|
||||
|
||||
+16
-1
@@ -126,9 +126,24 @@ fn path_d(p: &BezPath) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// A matrix scale/shear coefficient to 6 significant digits (unlike [`num`], small values survive).
|
||||
fn coeff(v: f64) -> String {
|
||||
if !v.is_finite() || v == 0.0 {
|
||||
return "0".into();
|
||||
}
|
||||
let digits = 5 - v.abs().log10().floor() as i32;
|
||||
let p = 10f64.powi(digits);
|
||||
let r = (v * p).round() / p;
|
||||
format!("{r}")
|
||||
}
|
||||
|
||||
fn matrix(a: Affine) -> String {
|
||||
let c = a.as_coeffs();
|
||||
format!("matrix({} {} {} {} {} {})", num(c[0]), num(c[1]), num(c[2]), num(c[3]), num(c[4]), num(c[5]))
|
||||
// Snap float noise (e.g. 6e-17 from a 90 degree rotation) to zero, relative to the largest term.
|
||||
let eps = c[..4].iter().fold(0.0f64, |m, v| m.max(v.abs())) * 1e-12;
|
||||
let eps = eps.max(1e-12);
|
||||
let k = |v: f64| if v.abs() <= eps { "0".to_string() } else { coeff(v) };
|
||||
format!("matrix({} {} {} {} {} {})", k(c[0]), k(c[1]), k(c[2]), k(c[3]), num(c[4]), num(c[5]))
|
||||
}
|
||||
|
||||
/// A view of page area `b` at `k` device pixels per unit (fewer when that makes it larger than
|
||||
|
||||
@@ -264,3 +264,16 @@ fn a_filled_open_curve_is_closed_for_its_fill() {
|
||||
};
|
||||
assert_eq!(d.nodes().map(loops).sum::<usize>(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_keeps_small_scale_precision() {
|
||||
assert_eq!(matrix(Affine::scale(0.0375)), "matrix(0.0375 0 0 0.0375 0 0)");
|
||||
assert_eq!(matrix(Affine::scale(0.0001)), "matrix(0.0001 0 0 0.0001 0 0)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_snaps_rotation_noise_and_tiny_values() {
|
||||
let r = Affine::rotate(std::f64::consts::FRAC_PI_2);
|
||||
assert_eq!(matrix(r), "matrix(0 1 -1 0 0 0)");
|
||||
assert_eq!(matrix(Affine::scale(1e-320)), "matrix(0 0 0 0 0 0)");
|
||||
}
|
||||
+164
-23
@@ -1,32 +1,26 @@
|
||||
//! Embeds the optional craft-fonts build input (`CRAFT_FONTS_DIR`): both `fonts/manifest.txt` and the
|
||||
//! opt-in Latin presentation fonts in `fonts/latin-manifest.txt` (Inter, Roboto, …). Unset or missing,
|
||||
//! `CRAFT_FONTS` is empty and the app uses system fonts. Recipe: craft-fonts `docs/integration.md`.
|
||||
//! `CRAFT_FONTS` is empty and native apps use system fonts. Required web releases enforce Inter
|
||||
//! Regular/SemiBold and Noto Sans Georgian Regular after filtering. Recipe: craft-fonts `docs/integration.md`.
|
||||
//! Noto Sans CJK only with `FIGCRAFT_EMBED_CJK` set (the web build's only way to show CJK UI text).
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Font build script: emit `craft_fonts.rs` from `input_fonts`, passing the
|
||||
/// `CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, wasm target and `FIGCRAFT_EMBED_CJK` inputs;
|
||||
/// report generation and write failures with `cargo::error`.
|
||||
fn main() {
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
|
||||
println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_CJK");
|
||||
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
|
||||
if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) {
|
||||
let mut ok = false;
|
||||
for manifest in ["fonts/latin-manifest.txt", "fonts/manifest.txt"] {
|
||||
match craft_fonts(&dir, manifest) {
|
||||
Ok(entries) => {
|
||||
ok = true;
|
||||
src.push_str(&entries);
|
||||
}
|
||||
Err(e) if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() => {
|
||||
println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display());
|
||||
}
|
||||
Err(e) => println!("cargo::warning=craft-fonts {manifest} skipped: CRAFT_FONTS_DIR={}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
println!("cargo::warning=building without craft-fonts (once it is there, `cargo clean -p figcraft-text` makes the next build use it)");
|
||||
}
|
||||
let dir = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from);
|
||||
let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some();
|
||||
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
|
||||
let embed_cjk = std::env::var_os("FIGCRAFT_EMBED_CJK").is_some();
|
||||
match input_fonts(dir.as_deref(), wasm, required, embed_cjk) {
|
||||
Ok(entries) => src.push_str(&entries),
|
||||
Err(e) => println!("cargo::error={e}"),
|
||||
}
|
||||
src.push_str("];\n");
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs");
|
||||
@@ -35,13 +29,45 @@ fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect the effective catalog and enforce the required web release faces after filtering.
|
||||
fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_cjk: bool) -> Result<String, String> {
|
||||
let Some(dir) = dir else {
|
||||
return if required { Err("CRAFT_FONTS_REQUIRED is set but CRAFT_FONTS_DIR is missing".into()) } else { Ok(String::new()) };
|
||||
};
|
||||
let mut out = String::new();
|
||||
let mut faces = Vec::new();
|
||||
for manifest in ["fonts/latin-manifest.txt", "fonts/manifest.txt"] {
|
||||
let path = dir.join(manifest);
|
||||
if manifest == "fonts/latin-manifest.txt" && !path.exists() {
|
||||
watch(&path);
|
||||
continue;
|
||||
}
|
||||
match craft_fonts(dir, manifest, wasm, embed_cjk) {
|
||||
Ok(catalog) => {
|
||||
out.push_str(&catalog.entries);
|
||||
faces.extend(catalog.faces);
|
||||
}
|
||||
Err(e) if required => return Err(format!("CRAFT_FONTS_DIR={}: {e}", dir.display())),
|
||||
Err(e) => println!("cargo::warning=craft-fonts {manifest} skipped: CRAFT_FONTS_DIR={}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
if required && wasm {
|
||||
for (family, style) in [("Inter", "Regular"), ("Inter", "SemiBold"), ("Noto Sans Georgian", "Regular")] {
|
||||
if !faces.iter().any(|(f, s)| f == family && s == style) {
|
||||
return Err(format!("required web font missing: {family} {style}; CRAFT_FONTS_DIR must include both Latin and core release faces"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Rebuild when `manifest` changes or, while it is missing, when it is added to its folder.
|
||||
///
|
||||
/// Cargo takes a watched path that doesn't exist as changed on every build, and then rebuilds this
|
||||
/// crate and every crate that depends on it each time. So a missing manifest is never watched
|
||||
/// itself: its folder is, when there is one (a craft-fonts checkout without the Latin manifest).
|
||||
/// With no craft-fonts at all there is nothing to watch, so the build can't notice it arriving:
|
||||
/// the warning in `main` says how to pick it up.
|
||||
/// rebuild this crate after adding a previously absent checkout.
|
||||
fn watch(manifest: &std::path::Path) {
|
||||
let watched = if manifest.exists() { Some(manifest) } else { manifest.parent().filter(|folder| folder.is_dir()) };
|
||||
if let Some(path) = watched {
|
||||
@@ -49,20 +75,33 @@ fn watch(manifest: &std::path::Path) {
|
||||
}
|
||||
}
|
||||
|
||||
fn craft_fonts(dir: &std::path::Path, manifest_rel: &str) -> Result<String, String> {
|
||||
struct Catalog {
|
||||
entries: String,
|
||||
faces: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// Parse a font manifest of `family | style | file | scripts` rows into `CraftFont`
|
||||
/// entries: skip Adobe-authored families, skip CJK unless requested, keep the web catalog
|
||||
/// to its budgeted families, canonicalize and watch each face, and emit `include_bytes!`
|
||||
/// items.
|
||||
fn craft_fonts(dir: &std::path::Path, manifest_rel: &str, wasm: bool, embed_cjk: bool) -> Result<Catalog, String> {
|
||||
let manifest = dir.join(manifest_rel);
|
||||
watch(&manifest);
|
||||
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
|
||||
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
|
||||
let mut out = String::new();
|
||||
let mut faces = Vec::new();
|
||||
for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
|
||||
let f: Vec<&str> = line.split(" | ").map(str::trim).collect();
|
||||
let [family, style, file, scripts, ..] = f.as_slice() else {
|
||||
return Err(format!("malformed manifest line: {line}"));
|
||||
};
|
||||
// FigCraft's asset policy excludes Adobe-authored visual assets on every target.
|
||||
if matches!(*family, "Source Sans 3" | "Source Serif 4") {
|
||||
continue;
|
||||
}
|
||||
// CJK fonts are large; the desktop app finds system CJK fonts instead unless asked.
|
||||
let cjk = scripts.contains("Hans");
|
||||
if cjk && std::env::var_os("FIGCRAFT_EMBED_CJK").is_none() {
|
||||
if cjk && !embed_cjk {
|
||||
continue;
|
||||
}
|
||||
// Web builds have a size budget: Inter, Noto Sans Georgian (small, for the Georgian UI), only the
|
||||
@@ -73,7 +112,109 @@ fn craft_fonts(dir: &std::path::Path, manifest_rel: &str) -> Result<String, Stri
|
||||
}
|
||||
let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
|
||||
println!("cargo::rerun-if-changed={}", path.display());
|
||||
faces.push(((*family).to_owned(), (*style).to_owned()));
|
||||
let _ = writeln!(out, " CraftFont {{ family: {family:?}, style: {style:?}, bytes: include_bytes!({:?}) }},", path.display().to_string());
|
||||
}
|
||||
Ok(out)
|
||||
Ok(Catalog { entries: out, faces })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
/// Test fixture: create a unique temporary directory, write a synthetic face file and
|
||||
/// install the default Georgian manifest.
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("fig-font-input-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(dir.join("fonts")).unwrap();
|
||||
// The build script validates manifest/file presence; font bytes are checked centrally.
|
||||
std::fs::write(dir.join("fonts/face.ttf"), b"synthetic build-input fixture").unwrap();
|
||||
let fixture = Self(dir);
|
||||
fixture.manifest("manifest.txt", &[("Noto Sans Georgian", "Regular")]);
|
||||
fixture
|
||||
}
|
||||
|
||||
/// Test fixture: write manifest rows that all point at the fixture's `fonts/face.ttf` face.
|
||||
fn manifest(&self, name: &str, faces: &[(&str, &str)]) {
|
||||
let text = faces.iter().map(|(family, style)| format!("{family} | {style} | fonts/face.ttf | Latn\n")).collect::<String>();
|
||||
std::fs::write(self.0.join("fonts").join(name), text).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
/// Remove the fixture's temporary directory, ignoring errors.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts the native Latin catalog keeps its 43 permitted presentation faces, the web
|
||||
/// catalog keeps only the four Inter faces, Adobe-authored families are absent, and
|
||||
/// permitted native faces remain.
|
||||
#[test]
|
||||
fn restored_latin_catalog_preserves_permitted_native_faces_and_web_budget() {
|
||||
let f = Fixture::new();
|
||||
std::fs::write(f.0.join("fonts/latin-manifest.txt"), include_str!("tests/fixtures/latin-families.txt")).unwrap();
|
||||
let native = craft_fonts(&f.0, "fonts/latin-manifest.txt", false, false).unwrap();
|
||||
assert_eq!(native.faces.len(), 43, "all prior permitted presentation faces remain available");
|
||||
let web = craft_fonts(&f.0, "fonts/latin-manifest.txt", true, false).unwrap();
|
||||
assert_eq!(web.faces.len(), 4, "the web catalog keeps only the four Inter faces");
|
||||
for catalog in [&native, &web] {
|
||||
assert!(!catalog.entries.contains("Source Sans 3"));
|
||||
assert!(!catalog.entries.contains("Source Serif 4"));
|
||||
}
|
||||
assert!(native.faces.iter().any(|(family, _)| family == "Carlito"));
|
||||
assert!(native.faces.iter().any(|(family, _)| family == "Liberation Serif"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).is_ok());
|
||||
}
|
||||
|
||||
/// Asserts required web input rejects a catalog missing Inter Regular or Inter SemiBold.
|
||||
#[test]
|
||||
fn required_web_rejects_core_only_and_partial_latin_catalogs() {
|
||||
let f = Fixture::new();
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("Inter Regular"));
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Unrelated", "SemiBold")]);
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("Inter SemiBold"));
|
||||
}
|
||||
|
||||
/// Asserts required web input embeds the Inter and Georgian catalogs (three entries) and
|
||||
/// rejects a manifest without Noto Sans Georgian Regular.
|
||||
#[test]
|
||||
fn required_web_embeds_both_catalogs_and_requires_georgian() {
|
||||
let f = Fixture::new();
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]);
|
||||
let entries = input_fonts(Some(&f.0), true, true, false).unwrap();
|
||||
assert_eq!(entries.matches("CraftFont {").count(), 3);
|
||||
assert!(entries.contains("family: \"Inter\""));
|
||||
assert!(entries.contains("family: \"Noto Sans Georgian\""));
|
||||
f.manifest("manifest.txt", &[("Other", "Regular")]);
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("Noto Sans Georgian Regular"));
|
||||
}
|
||||
|
||||
/// Asserts absent font input is empty when optional and an error when required, while present
|
||||
/// input includes Noto Sans Georgian.
|
||||
#[test]
|
||||
fn optional_and_native_inputs_keep_their_existing_policy() {
|
||||
let f = Fixture::new();
|
||||
assert!(input_fonts(None, true, false, false).unwrap().is_empty());
|
||||
assert!(input_fonts(None, true, true, false).unwrap_err().contains("CRAFT_FONTS_DIR is missing"));
|
||||
assert!(input_fonts(Some(&f.0), true, false, false).unwrap().contains("Noto Sans Georgian"));
|
||||
assert!(input_fonts(Some(&f.0), false, true, false).unwrap().contains("Noto Sans Georgian"));
|
||||
}
|
||||
|
||||
/// Asserts required web input rejects a manifest whose face file is missing, even when every
|
||||
/// face row is listed.
|
||||
#[test]
|
||||
fn required_web_rejects_missing_asset_even_with_all_face_rows() {
|
||||
let f = Fixture::new();
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]);
|
||||
std::fs::remove_file(f.0.join("fonts/face.ttf")).unwrap();
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("fonts/face.ttf"));
|
||||
}
|
||||
}
|
||||
@@ -361,6 +361,18 @@ fn grapheme_clusters() {
|
||||
assert!(grapheme_starts("plain ascii").iter().all(|b| *b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_removes_marks_but_keeps_other_graphemes_atomic() {
|
||||
assert_eq!(crate::backspace_step("น้ำ", 3), 2); // Thai spacing mark
|
||||
assert_eq!(crate::backspace_step("e\u{0301}", 2), 1); // Latin combining mark
|
||||
assert_eq!(crate::backspace_step("👨👩👧", 5), 0); // Emoji ZWJ sequence
|
||||
assert_eq!(crate::backspace_step("🇯🇵", 2), 0); // Flag
|
||||
assert_eq!(crate::backspace_step("x", 1), 0); // Ordinary character
|
||||
assert_eq!(crate::backspace_step("\u{1112}\u{1161}\u{11AB}", 3), 0); // Hangul syllable as conjoining jamo
|
||||
assert_eq!(crate::backspace_step("a\u{200D}", 2), 0); // A letter ending in ZWJ
|
||||
assert_eq!(crate::backspace_step("1\u{FE0F}\u{20E3}", 3), 0); // Keycap
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cluster_is_shaped_with_one_face() {
|
||||
if face().is_none() {
|
||||
|
||||
@@ -89,7 +89,7 @@ pub(crate) fn grapheme_starts(text: &str) -> Vec<bool> {
|
||||
}
|
||||
|
||||
/// The char index of the grapheme cluster boundary after (`forward`) or before char `index` in
|
||||
/// `text`: where an arrow key, Delete or Backspace moves the caret to.
|
||||
/// `text`: where an arrow key or Delete moves the caret to.
|
||||
pub fn grapheme_step(text: &str, index: usize, forward: bool) -> usize {
|
||||
let mut at = 0;
|
||||
for g in text.graphemes(true) {
|
||||
@@ -102,6 +102,29 @@ pub fn grapheme_step(text: &str, index: usize, forward: bool) -> usize {
|
||||
at.min(index)
|
||||
}
|
||||
|
||||
/// The start of the text deleted by Backspace at char `index`.
|
||||
///
|
||||
/// A letter's trailing mark (Grapheme_Cluster_Break Extend or SpacingMark, such as Thai MAI THO or
|
||||
/// SARA AM) is deleted on its own; other grapheme clusters remain atomic, so emoji sequences, flags,
|
||||
/// keycaps and Hangul syllables written as conjoining jamo stay intact.
|
||||
pub fn backspace_step(text: &str, index: usize) -> usize {
|
||||
let end = text.chars().count().min(index);
|
||||
let start = grapheme_step(text, end, false);
|
||||
if start == end {
|
||||
return end;
|
||||
}
|
||||
|
||||
let cluster = text.chars().skip(start).take(end - start).collect::<Vec<_>>();
|
||||
let letter_cluster = cluster.len() > 1 && cluster.first().is_some_and(|c| c.is_alphabetic());
|
||||
if letter_cluster && cluster.last().is_some_and(|&c| is_trailing_mark(c)) { end - 1 } else { start }
|
||||
}
|
||||
|
||||
/// Whether `c` is Extend or SpacingMark: it joins a plain letter's cluster. ZWJ also joins one but
|
||||
/// is a joiner, not a mark.
|
||||
fn is_trailing_mark(c: char) -> bool {
|
||||
c != '\u{200D}' && format!("a{c}").graphemes(true).count() == 1
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -257,6 +257,11 @@ impl Item {
|
||||
fn is_space(&self) -> bool {
|
||||
crate::breaks::is_space(self.ch)
|
||||
}
|
||||
/// A space justified text widens: not U+200B, which only marks where a line may break (between
|
||||
/// the words of Thai, Lao, Khmer or Burmese text, written without spaces).
|
||||
fn stretches(&self) -> bool {
|
||||
self.is_space() && self.ch != '\u{200B}'
|
||||
}
|
||||
}
|
||||
|
||||
/// Bidi embedding levels per char, and whether each char's paragraph runs right to left.
|
||||
@@ -587,7 +592,7 @@ pub fn layout(text: &TextData, box_width: Option<f64>, box_height: Option<f64>)
|
||||
items.get(vis_end.wrapping_sub(1)).filter(|it| hang_end && !rtl_line && vis_end > *s + 1 && closes(it.ch)).map_or(0.0, |it| it.adv);
|
||||
let gstart = out.glyphs.len();
|
||||
// Justify: extra space per gap.
|
||||
let gaps = items.get(*s..vis_end).unwrap_or(&[]).iter().filter(|it| it.is_space()).count();
|
||||
let gaps = items.get(*s..vis_end).unwrap_or(&[]).iter().filter(|it| it.stretches()).count();
|
||||
let justify_extra = match (text.align_h, wrap) {
|
||||
(TextAlignH::Justified, Some(maxw)) if !para_end && !break_after(*e) && gaps > 0 => {
|
||||
((maxw - line_indent + hang_l + hang_r - width) / gaps as f64).max(0.0)
|
||||
@@ -603,7 +608,7 @@ pub fn layout(text: &TextData, box_width: Option<f64>, box_height: Option<f64>)
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|it| !is_line_break(it.ch))
|
||||
.map(|it| it.adv + if it.is_space() { justify_extra } else { 0.0 })
|
||||
.map(|it| it.adv + if it.stretches() { justify_extra } else { 0.0 })
|
||||
.sum();
|
||||
let mut pen = if rtl_line { -trailing } else { line_indent - hang_l };
|
||||
// List marker (before the line's text; zero-length char range so carets skip it).
|
||||
@@ -698,7 +703,7 @@ pub fn layout(text: &TextData, box_width: Option<f64>, box_height: Option<f64>)
|
||||
});
|
||||
}
|
||||
pen += it.adv;
|
||||
if it.is_space() {
|
||||
if it.stretches() {
|
||||
pen += justify_extra;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ pub mod fontdb;
|
||||
mod layout;
|
||||
mod onpath;
|
||||
|
||||
pub use breaks::grapheme_step;
|
||||
pub use breaks::{backspace_step, grapheme_step};
|
||||
pub use color::{ColorBitmap, ColorInk, ColorLayer};
|
||||
pub use fontdb::{
|
||||
Axis, CRAFT_FONTS, Coords, Face, FontDb, NamedInstance, Rescan, axis_label, db, face_with_char, family_names, family_styles, find_face,
|
||||
|
||||
@@ -519,3 +519,43 @@ fn lower_case_writes_final_sigma() {
|
||||
t.runs.push(figcraft_doc::StyleRun { start: 3, end: 4, style: other });
|
||||
assert_eq!(gids(&t).iter().map(|g| g.0).collect::<Vec<_>>(), want.iter().map(|g| g.0).collect::<Vec<_>>(), "split runs");
|
||||
}
|
||||
|
||||
/// Thai is written without spaces between words; U+200B ZERO WIDTH SPACE marks where a line may
|
||||
/// break. ภาษา|ไทย|เขียน|ติดกัน ("Thai is written joined up") ไม่มี|ช่องว่าง|ระหว่าง|คำ ("with no
|
||||
/// spaces between words"), with one real space between the two phrases.
|
||||
#[test]
|
||||
fn justified_lines_dont_widen_zero_width_spaces() {
|
||||
if !have_fonts() {
|
||||
return;
|
||||
}
|
||||
let lay_out = |s: &str, align, w| {
|
||||
let mut t = TextData::new(s);
|
||||
t.style.font_size = 20.0;
|
||||
t.align_h = align;
|
||||
t.auto_resize = figcraft_doc::TextAutoResize::Height;
|
||||
layout(&t, w, None)
|
||||
};
|
||||
let chars_before = |s: &str, pat: &str| s.find(pat).map(|b| s[..b].chars().count()).unwrap();
|
||||
for (s, why) in [
|
||||
("ภาษา\u{200B}ไทย\u{200B}เขียน\u{200B}ติดกัน ไม่มี\u{200B}ช่องว่าง\u{200B}ระหว่าง\u{200B}คำ", "the real space takes the extra room"),
|
||||
("ภาษา\u{200B}ไทย\u{200B}เขียน\u{200B}ติดกัน\u{200B}ไม่มี\u{200B}ช่องว่าง\u{200B}ระหว่าง\u{200B}คำ", "no space to widen: as left-aligned"),
|
||||
] {
|
||||
// A box that ends inside ช่องว่าง: the first line breaks at the U+200B before it.
|
||||
let word = chars_before(s, "ช่องว่าง");
|
||||
let natural = lay_out(s, TextAlignH::Left, None);
|
||||
let (a, b) = (natural.caret(word).0, natural.caret(word + 4).0);
|
||||
assert!(b > a, "{why}: chars need advances");
|
||||
let w = a + (b - a) / 2.0;
|
||||
let left = lay_out(s, TextAlignH::Left, Some(w));
|
||||
let just = lay_out(s, TextAlignH::Justified, Some(w));
|
||||
assert!(just.lines.len() >= 2 && just.lines[0].char_end == word, "{why}: {:?}", just.lines);
|
||||
let space = s.chars().position(|c| c == ' ');
|
||||
let extra = w - left.lines[0].width;
|
||||
assert!(extra > 0.0, "{why}");
|
||||
assert_eq!(left.glyphs.len(), just.glyphs.len());
|
||||
for (l, j) in left.glyphs.iter().zip(&just.glyphs).filter(|(g, _)| g.char_end <= word) {
|
||||
let want = if space.is_some_and(|sp| l.char_start > sp) { extra } else { 0.0 };
|
||||
assert!((j.x - l.x - want).abs() < 1e-6, "{why}: char {} moved {} (want {want})", l.char_start, j.x - l.x);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Exercise the actual build-script catalog policy without changing process environment.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../build.rs"]
|
||||
mod build_script;
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
# Synthetic paths; family/style inventory from craft-fonts 76ba5a0496503c0e2841abd626295038cbe07cde.
|
||||
Inter | Regular | fonts/face.ttf | Latn
|
||||
Inter | Italic | fonts/face.ttf | Latn
|
||||
Inter | SemiBold | fonts/face.ttf | Latn
|
||||
Inter | Bold | fonts/face.ttf | Latn
|
||||
Carlito | Regular | fonts/face.ttf | Latn
|
||||
Carlito | Bold | fonts/face.ttf | Latn
|
||||
Carlito | Italic | fonts/face.ttf | Latn
|
||||
Carlito | Bold Italic | fonts/face.ttf | Latn
|
||||
Caladea | Regular | fonts/face.ttf | Latn
|
||||
Caladea | Bold | fonts/face.ttf | Latn
|
||||
Caladea | Italic | fonts/face.ttf | Latn
|
||||
Caladea | Bold Italic | fonts/face.ttf | Latn
|
||||
Liberation Sans | Regular | fonts/face.ttf | Latn
|
||||
Liberation Sans | Bold | fonts/face.ttf | Latn
|
||||
Liberation Sans | Italic | fonts/face.ttf | Latn
|
||||
Liberation Sans | Bold Italic | fonts/face.ttf | Latn
|
||||
Liberation Serif | Regular | fonts/face.ttf | Latn
|
||||
Liberation Serif | Bold | fonts/face.ttf | Latn
|
||||
Liberation Serif | Italic | fonts/face.ttf | Latn
|
||||
Liberation Serif | Bold Italic | fonts/face.ttf | Latn
|
||||
Liberation Mono | Regular | fonts/face.ttf | Latn
|
||||
Liberation Mono | Bold | fonts/face.ttf | Latn
|
||||
Liberation Mono | Italic | fonts/face.ttf | Latn
|
||||
Liberation Mono | Bold Italic | fonts/face.ttf | Latn
|
||||
Source Sans 3 | Regular | fonts/face.ttf | Latn
|
||||
Source Sans 3 | Italic | fonts/face.ttf | Latn
|
||||
Source Sans 3 | Semibold | fonts/face.ttf | Latn
|
||||
Source Sans 3 | Bold | fonts/face.ttf | Latn
|
||||
Source Serif 4 | Regular | fonts/face.ttf | Latn
|
||||
Source Serif 4 | Italic | fonts/face.ttf | Latn
|
||||
Source Serif 4 | Semibold | fonts/face.ttf | Latn
|
||||
Source Serif 4 | Bold | fonts/face.ttf | Latn
|
||||
Montserrat | Variable | fonts/face.ttf | Latn
|
||||
Montserrat | Italic Variable | fonts/face.ttf | Latn
|
||||
Lato | Regular | fonts/face.ttf | Latn
|
||||
Lato | Bold | fonts/face.ttf | Latn
|
||||
Lato | Italic | fonts/face.ttf | Latn
|
||||
Open Sans | Variable | fonts/face.ttf | Latn
|
||||
Open Sans | Italic Variable | fonts/face.ttf | Latn
|
||||
Roboto | Variable | fonts/face.ttf | Latn
|
||||
Roboto | Italic Variable | fonts/face.ttf | Latn
|
||||
Merriweather | Regular | fonts/face.ttf | Latn
|
||||
Merriweather | Bold | fonts/face.ttf | Latn
|
||||
Merriweather | Italic | fonts/face.ttf | Latn
|
||||
Playfair Display | Variable | fonts/face.ttf | Latn
|
||||
Playfair Display | Italic Variable | fonts/face.ttf | Latn
|
||||
Poppins | Regular | fonts/face.ttf | Latn
|
||||
Poppins | Bold | fonts/face.ttf | Latn
|
||||
Poppins | Italic | fonts/face.ttf | Latn
|
||||
Nunito Sans | Variable | fonts/face.ttf | Latn
|
||||
Nunito Sans | Italic Variable | fonts/face.ttf | Latn
|
||||
@@ -18,7 +18,7 @@ figcraft-render = { workspace = true }
|
||||
figcraft-pathops = { workspace = true }
|
||||
figcraft-engine = { workspace = true }
|
||||
figcraft-format = { workspace = true }
|
||||
egui = { workspace = true }
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
@@ -34,3 +34,9 @@ toml = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
wat = { workspace = true }
|
||||
# Keep the test font features explicit; production uses the same bundled fallback faces.
|
||||
# Dependency dev-features do not propagate into app release builds.
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
@@ -207,6 +207,9 @@ name = "English"
|
||||
"CMYK colour" = "CMYK colour"
|
||||
"Can view" = "Can view"
|
||||
"Check" = "Check"
|
||||
"Check for Updates" = "Check for Updates"
|
||||
"Check for updates…" = "Check for updates…"
|
||||
"Checking for updates…" = "Checking for updates…"
|
||||
"Checking the fonts installed on this computer…" = "Checking the fonts installed on this computer…"
|
||||
"Checking the server…" = "Checking the server…"
|
||||
"Chevron" = "Chevron"
|
||||
@@ -327,6 +330,7 @@ name = "English"
|
||||
"Copy {value}" = "Copy {value}"
|
||||
"Corner radius" = "Corner radius"
|
||||
"Corner smoothing" = "Corner smoothing"
|
||||
"Could not check for updates:\n{error}" = "Could not check for updates:\n{error}"
|
||||
"Couldn't download the variables" = "Couldn't download the variables"
|
||||
"Couldn't reach {server}: showing what this computer remembers." = "Couldn't reach {server}: showing what this computer remembers."
|
||||
"Couldn't read {name}." = "Couldn't read {name}."
|
||||
@@ -506,6 +510,7 @@ name = "English"
|
||||
"Fetching from the server…" = "Fetching from the server…"
|
||||
"FigCraft couldn't open its window: {error}" = "FigCraft couldn't open its window: {error}"
|
||||
"FigCraft doesn't support every feature of these files yet. The notes list what was left out or changed in the imported copy; the original file is unchanged." = "FigCraft doesn't support every feature of these files yet. The notes list what was left out or changed in the imported copy; the original file is unchanged."
|
||||
"FigCraft {version} is currently the newest version available." = "FigCraft {version} is currently the newest version available."
|
||||
"File" = "File"
|
||||
"File name" = "File name"
|
||||
"File not found" = "File not found"
|
||||
@@ -1494,6 +1499,7 @@ name = "English"
|
||||
"Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard" = "Unsaved changes: save first ({save}), or close the tab with {alt}-click to discard"
|
||||
"Unsaved changes: save first, or close again with {key} to discard" = "Unsaved changes: save first, or close again with {key} to discard"
|
||||
"Up" = "Up"
|
||||
"Update check is not supported in the web browser." = "Update check is not supported in the web browser."
|
||||
"Update plugin" = "Update plugin"
|
||||
"Update" = "Update"
|
||||
"Update from main" = "Update from main"
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# FigCraft interface strings: Polish.
|
||||
#
|
||||
# Draft: machine-drafted, waiting for a native speaker's review.
|
||||
# Wording reviewed and approved by Lucas (@lukasz-sklad).
|
||||
# Complete Polish localization for FigCraft.
|
||||
# See docs/translating.md; plural forms follow Polish CLDR integer rules.
|
||||
|
||||
[meta]
|
||||
name = "Polski"
|
||||
status = "draft — needs native review"
|
||||
|
||||
[ui]
|
||||
"% of all commits" = "% wszystkich commitów"
|
||||
@@ -178,6 +179,7 @@ status = "draft — needs native review"
|
||||
"Both directions" = "W obu kierunkach"
|
||||
"Bottom" = "Dół"
|
||||
"Bottom left radius" = "Promień lewego dolnego narożnika"
|
||||
"Bottom padding" = "Margines dolny"
|
||||
"Bottom right radius" = "Promień prawego dolnego narożnika"
|
||||
"Branch" = "Gałąź"
|
||||
"Branch archived" = "Gałąź zarchiwizowana"
|
||||
@@ -512,7 +514,7 @@ status = "draft — needs native review"
|
||||
"Fill container" = "Wypełnij kontener"
|
||||
"Fill window" = "Wypełnij okno"
|
||||
"Fills" = "Wypełnienia"
|
||||
"Fill|sizing" = "Fill|sizing"
|
||||
"Fill|sizing" = "Wypełnij"
|
||||
"Filter and sort" = "Filtruj i sortuj"
|
||||
"Find" = "Znajdź"
|
||||
"Find and replace" = "Znajdź i zamień"
|
||||
@@ -646,6 +648,7 @@ status = "draft — needs native review"
|
||||
"Included" = "Uwzględniono"
|
||||
"Included in layout" = "Uwzględniono w układzie"
|
||||
"Individual corners" = "Niezależne narożniki"
|
||||
"Individual padding" = "Niezależne marginesy"
|
||||
"Individual strokes" = "Niezależne obrysy"
|
||||
"Ink" = "Farba"
|
||||
"Inner shadow" = "Cień wewnętrzny"
|
||||
@@ -667,6 +670,7 @@ status = "draft — needs native review"
|
||||
"Interaction" = "Interakcja"
|
||||
"Interactions" = "Interakcje"
|
||||
"Interface design and prototyping. A free, open-source, clean-room design tool written from scratch in Rust, part of the ArtCraft Crafting Apps." = "Projektowanie interfejsów i prototypowanie. Darmowe, otwartoźródłowe, czysto implementowane narzędzie projektowe napisane od podstaw w Rust, część ArtCraft Crafting Apps."
|
||||
"Interface size" = "Rozmiar interfejsu"
|
||||
"Intersect" = "Przetnij"
|
||||
"Intersects" = "Przecina"
|
||||
"Invalid color" = "Nieprawidłowy kolor"
|
||||
@@ -683,7 +687,7 @@ status = "draft — needs native review"
|
||||
"Joined" = "Dołączono"
|
||||
"Joined {file}" = "Dołączono do: {file}"
|
||||
"Joining…" = "Dołączanie…"
|
||||
"Join|stroke" = "Join|stroke"
|
||||
"Join|stroke" = "Łączenie"
|
||||
"Jul" = "Lip"
|
||||
"Jun" = "Cze"
|
||||
"Just now" = "Przed chwilą"
|
||||
@@ -717,6 +721,7 @@ status = "draft — needs native review"
|
||||
"Leaves" = "Opuszcza"
|
||||
"Left" = "Do lewej"
|
||||
"Left & right" = "Lewa i prawa"
|
||||
"Left padding" = "Margines lewy"
|
||||
"Left side" = "Lewa strona"
|
||||
"Left side width" = "Szerokość lewej strony"
|
||||
"Letter case" = "Wielkość liter"
|
||||
@@ -727,9 +732,9 @@ status = "draft — needs native review"
|
||||
"Library: click to collapse" = "Biblioteka: kliknij, aby zwinąć"
|
||||
"Library: click to expand" = "Biblioteka: kliknij, aby rozwinąć"
|
||||
"Library: its variables are read-only here; edit them in the library file and publish it" = "Biblioteka: jej zmienne są tutaj tylko do odczytu; edytuj je w pliku biblioteki i opublikuj"
|
||||
"Light" = "Lekki"
|
||||
"Light" = "Jasny"
|
||||
"Lighten" = "Jaśniej"
|
||||
"Light|glass" = "Light|glass"
|
||||
"Light|glass" = "Światło"
|
||||
"Line" = "Linia"
|
||||
"Line arrow" = "Strzałka liniowa"
|
||||
"Line delta" = "Różnica wierszy"
|
||||
@@ -946,7 +951,7 @@ status = "draft — needs native review"
|
||||
"Opened “{name}” in a new tab" = "Otwarto „{name}” w nowej karcie"
|
||||
"Opening the file…" = "Otwieranie pliku…"
|
||||
"Opening {n} files as new files" = { one = "Otwieranie jako nowy plik", few = "Otwieranie {n} plików jako nowe pliki", many = "Otwieranie {n} plików jako nowe pliki", other = "Otwieranie {n} plików jako nowe pliki" }
|
||||
"Open|comments" = "Open|comments"
|
||||
"Open|comments" = "Otwarte"
|
||||
"Options" = "Opcje"
|
||||
"Orange" = "Pomarańczowy"
|
||||
"Order" = "Kolejność"
|
||||
@@ -969,6 +974,7 @@ status = "draft — needs native review"
|
||||
"PDF print settings" = "Ustawienia druku PDF"
|
||||
"Padding" = "Marginesy wewnętrzne"
|
||||
"Page" = "Strona"
|
||||
"Page deleted" = "Strona została usunięta"
|
||||
"Pages" = "Strony"
|
||||
"Pages added to the document" = "Strony dodane do dokumentu"
|
||||
"Pink" = "Różowy"
|
||||
@@ -1083,6 +1089,7 @@ status = "draft — needs native review"
|
||||
"Reduce motion" = "Ogranicz ruch"
|
||||
"Refraction" = "Załamanie światła (refrakcja)"
|
||||
"Regular expression" = "Wyrażenie regularne"
|
||||
"Relative to your system's display scaling (100% is the system's own size). Document zoom is separate." = "Względem skalowania ekranu Twojego systemu (100% to domyślny rozmiar systemu). Powiększenie dokumentu jest niezależne."
|
||||
"Remove" = "Usuń"
|
||||
"Remove all" = "Usuń wszystko"
|
||||
"Remove annotation" = "Usuń adnotację"
|
||||
@@ -1122,6 +1129,7 @@ status = "draft — needs native review"
|
||||
"Rename on the server…" = "Zmień nazwę na serwerze…"
|
||||
"Rename page" = "Zmień nazwę strony"
|
||||
"Rename to" = "Zmień nazwę na"
|
||||
"Reorder selection" = "Zmień kolejność zaznaczenia"
|
||||
"Replace all" = "Zamień wszystko"
|
||||
"Replace mixed export settings" = "Zastąp zróżnicowane ustawienia eksportu"
|
||||
"Replace with" = "Zamień na"
|
||||
@@ -1157,6 +1165,7 @@ status = "draft — needs native review"
|
||||
"Review and merge" = "Przejrzyj i scal"
|
||||
"Ribbon" = "Wstążka"
|
||||
"Right" = "Do prawej"
|
||||
"Right padding" = "Margines prawy"
|
||||
"Right side" = "Prawa strona"
|
||||
"Right side width" = "Szerokość prawej strony"
|
||||
"Rotate 90°" = "Obróć o 90°"
|
||||
@@ -1208,6 +1217,7 @@ status = "draft — needs native review"
|
||||
"Search results" = "Wyniki wyszukiwania"
|
||||
"Search fonts" = "Szukaj czcionek"
|
||||
"Search layers" = "Szukaj warstw"
|
||||
"Search pages" = "Szukaj stron"
|
||||
"Search shortcuts" = "Szukaj skrótów"
|
||||
"Section" = "Sekcja"
|
||||
"Section color" = "Kolor sekcji"
|
||||
@@ -1326,6 +1336,7 @@ status = "draft — needs native review"
|
||||
"Start from a blank canvas" = "Zacznij od pustego płótna"
|
||||
"Start from a template" = "Zacznij od szablonu"
|
||||
"Start on path" = "Początek na ścieżce"
|
||||
"Start on the Home screen" = "Rozpoczynaj od ekranu głównego"
|
||||
"Start point" = "Punkt początkowy"
|
||||
"Start sharing" = "Rozpocznij udostępnianie"
|
||||
"Start sharing with the Share button, then pass on the code it gives" = "Rozpocznij udostępnianie przyciskiem Udostępnij, a następnie przekaż wygenerowany kod"
|
||||
@@ -1404,6 +1415,7 @@ status = "draft — needs native review"
|
||||
"The selection uses several text styles: click to apply one" = "Zaznaczenie używa kilku stylów tekstu: kliknij, aby zastosować jeden"
|
||||
"The server deletes this file if nobody opens it before {date}." = "Serwer usunie ten plik, jeśli nikt go nie otworzy przed {date}."
|
||||
"The whole file" = "Cały plik"
|
||||
"The window is too small for {size}%, so the interface is drawn at {drawn}%. Make the window larger to use {size}%." = "Okno jest zbyt małe dla {size}%, więc interfejs jest wyświetlany w {drawn}%. Powiększ okno, aby użyć {size}%."
|
||||
"Theme" = "Motyw"
|
||||
"There's no destination for that action" = "Brak miejsca docelowego dla tej akcji"
|
||||
"Thickness" = "Grubość"
|
||||
@@ -1414,6 +1426,7 @@ status = "draft — needs native review"
|
||||
"This condition is edited as an expression" = "Ten warunek jest edytowany jako wyrażenie"
|
||||
"This file" = "Ten plik"
|
||||
"This file has unsaved changes" = "Ten plik ma niezapisane zmiany"
|
||||
"This file is too large to join here (up to {mb} MB)" = "Ten plik jest zbyt duży, aby do niego dołączyć (maksymalnie {mb} MB)"
|
||||
"This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Ten plik używa czcionek, które nie są zainstalowane na tym komputerze. Do czasu ich zainstalowania tekst jest wyświetlany czcionką zastępczą."
|
||||
"This file is on {server}, open only to you. Share it to let others in with a new code." = "Ten plik znajduje się na {server}, otwarty tylko dla Ciebie. Udostępnij go, aby wpuścić innych nowym kodem."
|
||||
"This frame is new on the branch." = "Ta ramka jest nowa w gałęzi."
|
||||
@@ -1437,6 +1450,7 @@ status = "draft — needs native review"
|
||||
"Top" = "Góra"
|
||||
"Top & bottom" = "Góra i dół"
|
||||
"Top left radius" = "Promień górnego lewego narożnika"
|
||||
"Top padding" = "Margines górny"
|
||||
"Top right radius" = "Promień górnego prawego narożnika"
|
||||
"Transform" = "Przekształć"
|
||||
"Triangle" = "Trójkąt"
|
||||
@@ -1486,6 +1500,7 @@ status = "draft — needs native review"
|
||||
"Use number keys for opacity" = "Użyj klawiszy numerycznych dla nieprzezroczystości"
|
||||
"Use the .figcraft or .fig extension." = "Użyj rozszerzenia .figcraft lub .fig."
|
||||
"Use the layer's fill" = "Użyj wypełnienia warstwy"
|
||||
"Use your browser's zoom to change the interface size." = "Użyj powiększenia przeglądarki, aby zmienić rozmiar interfejsu."
|
||||
"Used in {files} · {instances}" = "Używane w {files} · {instances}"
|
||||
"Username" = "Nazwa użytkownika"
|
||||
"Value" = "Wartość"
|
||||
@@ -1757,6 +1772,7 @@ status = "draft — needs native review"
|
||||
"{n}m" = "{n} min"
|
||||
"{n}w" = "{n} tyg."
|
||||
"{page}, nothing selected" = "{page}, nic nie zaznaczono"
|
||||
"{percent}%" = "{percent}%"
|
||||
"{profile} (current)" = "{profile} (bieżący)"
|
||||
"{property} is its value; {property ? \"a\" : \"b\"} picks a string. Other {…} stays as written." = "{property} to jej wartość; {property ? \"a\" : \"b\"} wybiera tekst. Pozostałe wyrażenia {…} pozostają bez zmian."
|
||||
"{server} can't say what became of your files (it is older than this app)." = "{server} nie może określić stanu Twoich plików (jest starszy niż ta aplikacja)."
|
||||
@@ -1799,6 +1815,7 @@ status = "draft — needs native review"
|
||||
"arrange.front" = "Przesuń na sam wierzch"
|
||||
"arrange.packH" = "Upakuj w poziomie"
|
||||
"arrange.packV" = "Upakuj w pionie"
|
||||
"arrange.reorder" = "Zmień kolejność zaznaczenia"
|
||||
"arrange.roundToPixels" = "Zaokrąglij do pikseli"
|
||||
"arrange.spacing" = "Odstępy"
|
||||
"arrange.tidy" = "Uporządkuj"
|
||||
@@ -1938,6 +1955,7 @@ status = "draft — needs native review"
|
||||
"file.exportLayers" = "Eksportuj warstwy"
|
||||
"file.exportSvg" = "Eksportuj zaznaczenie jako SVG"
|
||||
"file.import" = "Importuj z pliku…"
|
||||
"file.moveTab" = "Przenieś kartę"
|
||||
"file.new" = "Nowy plik projektu"
|
||||
"file.newBoard" = "Nowa tablica"
|
||||
"file.newFromTemplate" = "Nowy z szablonu"
|
||||
@@ -2081,6 +2099,8 @@ status = "draft — needs native review"
|
||||
"pref.reduceMotion" = "Ogranicz animacje"
|
||||
"pref.renameDuplicates" = "Zmieniaj nazwy duplikatów"
|
||||
"pref.showDimensions" = "Pokazuj wymiary przy zaznaczeniu"
|
||||
"pref.startOnHome" = "Rozpoczynaj od ekranu głównego"
|
||||
"pref.uiScale" = "Rozmiar interfejsu"
|
||||
"pref.userName" = "Twoja nazwa w komentarzach"
|
||||
"proto.action.add" = "Dodaj akcję prototypu"
|
||||
"proto.action.move" = "Zmień kolejność akcji prototypu"
|
||||
@@ -2189,6 +2209,7 @@ status = "draft — needs native review"
|
||||
"text.listIndent" = "Zwiększ wcięcie listy"
|
||||
"text.listOutdent" = "Zmniejsz wcięcie listy"
|
||||
"text.listStyle" = "Styl listy"
|
||||
"text.loadFont" = "Wczytaj plik czcionki"
|
||||
"text.maxLines" = "Maksymalna liczba wierszy"
|
||||
"text.missingFonts" = "Brakujące czcionki"
|
||||
"text.numberList" = "Lista numerowana"
|
||||
@@ -2197,7 +2218,9 @@ status = "draft — needs native review"
|
||||
"text.paragraphSpacing" = "Odstęp między akapitami"
|
||||
"text.pathOptions" = "Opcje ścieżki tekstu"
|
||||
"text.preview" = "Podgląd zmiany tekstu"
|
||||
"text.refit" = "Dopasuj tekst do czcionek"
|
||||
"text.removeFromPath" = "Usuń tekst ze ścieżki"
|
||||
"text.rescanFonts" = "Wyszukaj ponownie zainstalowane czcionki"
|
||||
"text.set" = "Ustaw tekst"
|
||||
"text.setFeatures" = "Funkcje OpenType"
|
||||
"text.setVariations" = "Osie czcionki zmiennej (Variable Font)"
|
||||
|
||||
@@ -239,6 +239,10 @@ pub fn scroll_focus(nav: &mut Nav, ui: &Ui) {
|
||||
#[derive(Clone, Default)]
|
||||
struct Shared {
|
||||
canvas: Option<Id>,
|
||||
/// The root `Ui::scope_id` of the frame. A resizable panel's real `__resize` widget is
|
||||
/// `root_scope.with(<panel salt>).with("__resize")`; FigCraft's panels are fixed, so its own
|
||||
/// `panel_edge` and `pages_edge` IDs are the ones to exclude today.
|
||||
root_scope: Option<Id>,
|
||||
keyboard: bool,
|
||||
/// The focused widget showed its focus itself this frame (no ring needed).
|
||||
ring: Option<Id>,
|
||||
@@ -249,8 +253,10 @@ struct Shared {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// Run `f` on the per-context temporary `Shared` accessibility state keyed by
|
||||
/// `figcraft_a11y`.
|
||||
fn shared<R>(ctx: &Context, f: impl FnOnce(&mut Shared) -> R) -> R {
|
||||
ctx.data_mut(|d| f(d.get_temp_mut_or_default::<Shared>(Id::new("figcraft_a11y"))))
|
||||
ctx.data_mut(|d| f(d.get_temp_mut_or_default::<Shared>(Id::unique("figcraft_a11y"))))
|
||||
}
|
||||
|
||||
/// Whether a widget other than the canvas has the keyboard (a field, a focused button): the
|
||||
@@ -284,8 +290,10 @@ pub fn keyboard(ctx: &Context) -> bool {
|
||||
|
||||
/// Before the panels draw: pointer presses, the focused control's region, and the navigation
|
||||
/// keys (F6, Tab, arrows, Escape), which are taken out of the input when they move the keyboard.
|
||||
pub fn begin(app: &mut FigApp, ctx: &Context) {
|
||||
pub fn begin(app: &mut FigApp, ctx: &Context, root_scope: Id) {
|
||||
app.ui.nav.last = std::mem::take(&mut app.ui.nav.next);
|
||||
// Before the keys: a panel edge derived from the root scope must already be excluded.
|
||||
shared(ctx, |s| s.root_scope = Some(root_scope));
|
||||
keys(app, ctx);
|
||||
let keyboard = app.ui.nav.keyboard;
|
||||
shared(ctx, |s| {
|
||||
@@ -646,7 +654,13 @@ fn step_within(app: &mut FigApp, ctx: &Context, region: Region, step: i32) {
|
||||
/// them, are left out).
|
||||
fn focusables(ctx: &Context, nav: &Nav, region: Region) -> Vec<(Id, Rect)> {
|
||||
let canvas = nav.last.canvas;
|
||||
let edges = [Id::new("left_panel").with("__resize"), Id::new("right_panel").with("__resize")];
|
||||
// Both the real resize widgets (should a panel ever become resizable) and FigCraft's own
|
||||
// custom panel and pages-list edges, which must never enter the F6/Tab order.
|
||||
let mut edges = vec![Id::unique(("panel_edge", "left")), Id::unique(("panel_edge", "right")), Id::unique("pages_edge")];
|
||||
if let Some(root) = shared(ctx, |s| s.root_scope) {
|
||||
edges.push(root.with("left_panel").with("__resize"));
|
||||
edges.push(root.with("right_panel").with("__resize"));
|
||||
}
|
||||
ctx.viewport(|v| {
|
||||
v.prev_pass
|
||||
.widgets
|
||||
|
||||
@@ -403,3 +403,31 @@ fn the_align_buttons_are_off_for_a_layer_alone_on_the_page() {
|
||||
u.app.run("select.set", json!({"ids": [inner]}));
|
||||
assert!(!align_left(&tree(&mut u)), "one in a frame aligns to it");
|
||||
}
|
||||
|
||||
/// Asserts side-panel and Pages edges are not focusable, and Tab never stops on the
|
||||
/// side-panel edges.
|
||||
#[test]
|
||||
fn the_custom_panel_edges_never_enter_the_keyboard_or_focus_order() {
|
||||
// FigCraft's panels are fixed, so egui makes no `panel.__resize` widgets; the draggable edges
|
||||
// are `Id::unique(("panel_edge", ...))`. They sense the pointer but must not be focusable, or
|
||||
// Tab/F6 would stop on an unnamed control.
|
||||
let (mut u, _, _) = setup();
|
||||
let (left, right) = (egui::Id::unique(("panel_edge", "left")), egui::Id::unique(("panel_edge", "right")));
|
||||
// The Pages list's edge has the same contract as the side panels' edges.
|
||||
let pages = egui::Id::unique("pages_edge");
|
||||
for f in [left, right, pages] {
|
||||
let focusable = u.ctx.viewport(|v| v.prev_pass.widgets.get(f).map(|w| w.sense.is_focusable()));
|
||||
assert_eq!(focusable, Some(false), "the panel/pages edge still senses clicks/drags but is not focusable");
|
||||
}
|
||||
let mut seen = Vec::new();
|
||||
for back in [false, true] {
|
||||
f6(&mut u, back);
|
||||
for _ in 0..30 {
|
||||
press(&mut u, Key::Tab, Modifiers::NONE);
|
||||
if let Some(id) = u.ctx.memory(|m| m.focused()) {
|
||||
seen.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(!seen.contains(&left) && !seen.contains(&right), "Tab never stops on a panel edge: {seen:?}");
|
||||
}
|
||||
@@ -164,8 +164,9 @@ enum Act {
|
||||
Hide(NodeId, bool),
|
||||
}
|
||||
|
||||
/// Stable egui id for the assets drag payload.
|
||||
fn drag_id() -> Id {
|
||||
Id::new("asset_drag")
|
||||
Id::unique("asset_drag")
|
||||
}
|
||||
|
||||
/// Whether component `id` has the same layers in two versions of a document (layers an edit
|
||||
@@ -276,7 +277,7 @@ fn refresh_libraries(app: &mut FigApp, ui: &Ui) {
|
||||
return;
|
||||
}
|
||||
let paths: Vec<String> = doc.libraries.enabled.iter().map(|l| l.path.clone()).collect();
|
||||
let id = Id::new("asset_libraries_checked");
|
||||
let id = Id::unique("asset_libraries_checked");
|
||||
let now = ui.input(|i| i.time);
|
||||
let last: Option<f64> = ui.data(|d| d.get_temp(id));
|
||||
if last.is_none_or(|l| now - l >= LIBRARY_REFRESH) {
|
||||
@@ -285,7 +286,7 @@ fn refresh_libraries(app: &mut FigApp, ui: &Ui) {
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, now));
|
||||
// Team libraries: in the background, at once for one not fetched yet.
|
||||
let sid = Id::new("asset_server_libraries_checked");
|
||||
let sid = Id::unique("asset_server_libraries_checked");
|
||||
let fetched: Option<f64> = ui.data(|d| d.get_temp(sid));
|
||||
let unread = paths.iter().any(|p| is_server_link(p) && app.session.libraries.cached(p).is_none());
|
||||
if paths.iter().any(|p| is_server_link(p)) && (unread || fetched.is_none_or(|l| now - l >= SERVER_REFRESH)) {
|
||||
@@ -299,7 +300,7 @@ fn refresh_libraries(app: &mut FigApp, ui: &Ui) {
|
||||
/// The search field with the libraries button; returns the lowercase query.
|
||||
fn search_row(app: &mut FigApp, ui: &mut Ui, w: f32) -> String {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let filter_id = Id::new("asset_filter");
|
||||
let filter_id = Id::unique("asset_filter");
|
||||
let mut filter: String = ui.data(|d| d.get_temp(filter_id)).unwrap_or_default();
|
||||
let (fr, _) = ui.allocate_exact_size(vec2(w, 40.0), Sense::hover());
|
||||
let field = Rect::from_min_max(pos2(fr.min.x + 12.0, fr.min.y + 8.0), pos2(fr.max.x - 44.0, fr.max.y - 4.0));
|
||||
@@ -309,7 +310,7 @@ fn search_row(app: &mut FigApp, ui: &mut Ui, w: f32) -> String {
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(te_rect));
|
||||
let r = child.add(
|
||||
egui::TextEdit::singleline(&mut filter)
|
||||
.id(Id::new("asset_filter_field"))
|
||||
.id(Id::unique("asset_filter_field"))
|
||||
.frame(egui::Frame::NONE)
|
||||
.font(regular(11.0))
|
||||
.hint_text(tr("Search assets"))
|
||||
@@ -324,7 +325,7 @@ fn search_row(app: &mut FigApp, ui: &mut Ui, w: f32) -> String {
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(filter_id, filter.clone()));
|
||||
let br = Rect::from_center_size(pos2(fr.max.x - 26.0, field.center().y), vec2(24.0, 24.0));
|
||||
let bresp = ui.interact(br, Id::new("asset_libraries_btn"), Sense::click()).tip(tr("Libraries"));
|
||||
let bresp = ui.interact(br, Id::unique("asset_libraries_btn"), Sense::click()).tip(tr("Libraries"));
|
||||
if bresp.hovered() {
|
||||
ui.painter().rect_filled(br, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
@@ -342,7 +343,7 @@ fn updates_banner(app: &mut FigApp, ui: &mut Ui, w: f32, count: usize) {
|
||||
let r = Rect::from_min_max(pos2(row.min.x + 12.0, row.min.y + 4.0), pos2(row.max.x - 12.0, row.max.y - 4.0));
|
||||
ui.painter().rect_filled(r, CornerRadius::same(6), t.selected_row);
|
||||
let what = trn("{n} components and styles have newer versions", count, &[]);
|
||||
ui.interact(r, Id::new("asset_updates"), Sense::hover()).on_hover_text(what);
|
||||
ui.interact(r, Id::unique("asset_updates"), Sense::hover()).on_hover_text(what);
|
||||
ui.painter().text(pos2(r.min.x + 10.0, r.center().y), Align2::LEFT_CENTER, tr("Library updates available"), semibold(11.0), t.text);
|
||||
let mut child =
|
||||
ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_max(pos2(r.max.x - 70.0, r.min.y + 6.0), pos2(r.max.x - 6.0, r.max.y))));
|
||||
@@ -438,7 +439,7 @@ fn tiles(ui: &mut Ui, w: f32, src: &Source, list: &[Tile], thumbs: &Thumbs, want
|
||||
let r = Rect::from_min_size(pos2(x, y), vec2(tile, tile));
|
||||
let resp = ui.interact(
|
||||
r.union(Rect::from_min_size(r.left_bottom(), vec2(tile, TILE_LABEL))),
|
||||
Id::new(("asset", src, item.id.0)),
|
||||
Id::unique(("asset", src, item.id.0)),
|
||||
Sense::click_and_drag(),
|
||||
);
|
||||
ui.painter().rect_filled(r, CornerRadius::same(6), t.field);
|
||||
@@ -581,6 +582,10 @@ fn render_thumbs(ui: &Ui, w: f32, thumbs: &mut Thumbs, wanted: &[(Source, NodeId
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the Assets panel: refresh libraries, switch to the libraries view when asked,
|
||||
/// otherwise cache a listing keyed by revision, query and library state, render local and
|
||||
/// enabled-library assets with reused thumbnails, and dispatch place, style, hide, toggle
|
||||
/// and drag actions.
|
||||
pub fn show(app: &mut FigApp, ui: &mut Ui) {
|
||||
refresh_libraries(app, ui);
|
||||
if app.ui.libraries {
|
||||
@@ -593,7 +598,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) {
|
||||
let revision = ds.revision;
|
||||
let q = search_row(app, ui, w);
|
||||
let key = (revision, q.clone(), libraries_key(app, &doc));
|
||||
let listing_id = Id::new("asset_listing");
|
||||
let listing_id = Id::unique("asset_listing");
|
||||
let listing = match ui.data(|d| d.get_temp::<Arc<Listing>>(listing_id)) {
|
||||
Some(l) if l.key == key => l,
|
||||
_ => {
|
||||
@@ -605,12 +610,12 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) {
|
||||
if listing.updates > 0 {
|
||||
updates_banner(app, ui, w, listing.updates);
|
||||
}
|
||||
let mut thumbs: Thumbs = ui.data(|d| d.get_temp(Id::new("asset_thumbs"))).unwrap_or_default();
|
||||
let mut thumbs: Thumbs = ui.data(|d| d.get_temp(Id::unique("asset_thumbs"))).unwrap_or_default();
|
||||
let mut sources: Vec<(Source, Arc<Document>)> = vec![(Source::Local, doc.clone())];
|
||||
sources.extend(listing.libraries.iter().filter_map(|l| l.doc.clone().map(|d| (Source::Library(l.id.clone()), d))));
|
||||
invalidate_thumbs(ui, &mut thumbs, &sources);
|
||||
let mut wanted = Vec::new();
|
||||
let collapsed_id = Id::new("asset_collapsed_libraries");
|
||||
let collapsed_id = Id::unique("asset_collapsed_libraries");
|
||||
let collapsed: HashSet<String> = ui.data(|d| d.get_temp(collapsed_id)).unwrap_or_default();
|
||||
let mut act = None;
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
@@ -657,7 +662,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) {
|
||||
render_thumbs(ui, w, &mut thumbs, &wanted);
|
||||
let drag = ui.data(|d| d.get_temp::<AssetDrag>(drag_id()));
|
||||
let tex = drag.as_ref().and_then(|d| thumbs.map.get(&(d.src.clone(), d.component)).cloned().flatten());
|
||||
ui.data_mut(|d| d.insert_temp(Id::new("asset_thumbs"), thumbs));
|
||||
ui.data_mut(|d| d.insert_temp(Id::unique("asset_thumbs"), thumbs));
|
||||
match act {
|
||||
Some(Act::Drag(d)) => ui.data_mut(|m| {
|
||||
m.insert_temp(drag_id(), d);
|
||||
@@ -773,9 +778,11 @@ fn drag_feedback(app: &mut FigApp, ui: &mut Ui, doc: &Document, libs: &HashMap<S
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
|
||||
/// Draw the 64×64 component ghost on the tooltip layer, using the thumbnail when available
|
||||
/// and the component or component-set icon otherwise.
|
||||
fn ghost(ui: &Ui, p: Pos2, set: bool, tex: Option<egui::TextureHandle>) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, Id::new("asset_ghost")));
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, Id::unique("asset_ghost")));
|
||||
let r = Rect::from_center_size(p, vec2(64.0, 64.0));
|
||||
painter.rect_filled(r, CornerRadius::same(6), t.panel.gamma_multiply(0.9));
|
||||
painter.rect_stroke(r, CornerRadius::same(6), Stroke::new(1.0, COMPONENT), egui::StrokeKind::Inside);
|
||||
@@ -812,7 +819,7 @@ fn libraries_view(app: &mut FigApp, ui: &mut Ui) {
|
||||
let w = ui.available_width();
|
||||
let (hr, _) = ui.allocate_exact_size(vec2(w, 40.0), Sense::hover());
|
||||
let back = Rect::from_center_size(pos2(hr.min.x + 24.0, hr.center().y), vec2(24.0, 24.0));
|
||||
let bresp = ui.interact(back, Id::new("asset_libraries_back"), Sense::click()).tip(tr("Back to assets"));
|
||||
let bresp = ui.interact(back, Id::unique("asset_libraries_back"), Sense::click()).tip(tr("Back to assets"));
|
||||
if bresp.hovered() {
|
||||
ui.painter().rect_filled(back, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
@@ -831,8 +838,12 @@ fn libraries_view(app: &mut FigApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Draw the publish form: status, publishable components/styles/collections, description and
|
||||
/// publish buttons. Run `library.publish` locally or publish to the server in the
|
||||
/// background, reset the form on success, and report when the file is unsaved so other files
|
||||
/// cannot yet use it.
|
||||
fn publish_form(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
let form_id = Id::new("asset_publish_form");
|
||||
let form_id = Id::unique("asset_publish_form");
|
||||
let mut form: PublishForm = ui.data(|d| d.get_temp(form_id)).unwrap_or_default();
|
||||
title(ui, w, tr("This file"));
|
||||
let m = doc.published.as_ref().map(|p| &p.manifest);
|
||||
@@ -901,7 +912,7 @@ fn publish_form(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(PAD);
|
||||
if let Some(d) =
|
||||
crate::widgets::text_field(ui, Id::new("asset_publish_description"), &description, w - PAD * 2.0, tr("Description (optional)"))
|
||||
crate::widgets::text_field(ui, Id::unique("asset_publish_description"), &description, w - PAD * 2.0, tr("Description (optional)"))
|
||||
{
|
||||
form.description = Some(d);
|
||||
}
|
||||
@@ -965,7 +976,7 @@ fn publish_form(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
/// How other files use this file's library on its server (asked for with a button: it is a
|
||||
/// request to the server).
|
||||
fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) {
|
||||
let usage_id = Id::new(("asset_library_usage", link));
|
||||
let usage_id = Id::unique(("asset_library_usage", link));
|
||||
let loading = app.session.waiting_for(USAGE);
|
||||
let (mut ask, mut stop) = (false, false);
|
||||
ui.horizontal(|ui| {
|
||||
@@ -1010,6 +1021,8 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) {
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
|
||||
/// Draw the libraries enabled in this file with version/count/status, remove and swap
|
||||
/// actions, add-file and pasted-link controls, and background fetch/cancel handling.
|
||||
fn enabled_libraries(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
title(ui, w, tr("Libraries in this file"));
|
||||
@@ -1050,9 +1063,9 @@ fn enabled_libraries(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
let clip = Rect::from_min_size(pos2(r.min.x + PAD, r.min.y), vec2(text_w, r.height()));
|
||||
ui.painter().with_clip_rect(clip).galley(pos2(r.min.x + PAD, r.min.y + 6.0), name, t.text);
|
||||
ui.painter().with_clip_rect(clip).galley(pos2(r.min.x + PAD, r.min.y + 23.0), line, t.text_secondary);
|
||||
ui.interact(clip, Id::new(("asset_lib_row", &l.id)), Sense::hover()).on_hover_text(shown_path(&l.path));
|
||||
ui.interact(clip, Id::unique(("asset_lib_row", &l.id)), Sense::hover()).on_hover_text(shown_path(&l.path));
|
||||
let x = Rect::from_center_size(pos2(r.max.x - 24.0, r.center().y), vec2(24.0, 24.0));
|
||||
let xr = ui.interact(x, Id::new(("asset_lib_remove", &l.id)), Sense::click()).tip(tr("Remove library from this file"));
|
||||
let xr = ui.interact(x, Id::unique(("asset_lib_remove", &l.id)), Sense::click()).tip(tr("Remove library from this file"));
|
||||
if xr.hovered() {
|
||||
ui.painter().rect_filled(x, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
@@ -1063,7 +1076,7 @@ fn enabled_libraries(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
if swappable {
|
||||
let sw = Rect::from_center_size(pos2(r.max.x - 52.0, r.center().y), vec2(24.0, 24.0));
|
||||
let sr = ui
|
||||
.interact(sw, Id::new(("asset_lib_swap", &l.id)), Sense::click())
|
||||
.interact(sw, Id::unique(("asset_lib_swap", &l.id)), Sense::click())
|
||||
.tip(tr("Swap library: use another library's assets of the same names"));
|
||||
if sr.hovered() {
|
||||
ui.painter().rect_filled(sw, CornerRadius::same(5), t.hover);
|
||||
@@ -1089,7 +1102,7 @@ fn enabled_libraries(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) {
|
||||
let pasted = ui
|
||||
.horizontal(|ui| {
|
||||
ui.add_space(PAD);
|
||||
crate::widgets::text_field(ui, Id::new("asset_add_link"), "", w - PAD * 2.0, tr("Paste a team library link (a view link)"))
|
||||
crate::widgets::text_field(ui, Id::unique("asset_add_link"), "", w - PAD * 2.0, tr("Paste a team library link (a view link)"))
|
||||
})
|
||||
.inner;
|
||||
if let Some(link) = pasted.map(|l| l.trim().to_string()).filter(|l| !l.is_empty())
|
||||
@@ -1140,7 +1153,7 @@ fn added(app: &mut FigApp, r: &Value) {
|
||||
/// Tests: the components whose thumbnails are cached (for this file's assets).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cached_thumbnails(ctx: &egui::Context) -> Vec<NodeId> {
|
||||
let thumbs: Thumbs = ctx.data(|d| d.get_temp(Id::new("asset_thumbs"))).unwrap_or_default();
|
||||
let thumbs: Thumbs = ctx.data(|d| d.get_temp(Id::unique("asset_thumbs"))).unwrap_or_default();
|
||||
let mut out: Vec<NodeId> = thumbs.map.keys().filter(|(s, _)| *s == Source::Local).map(|(_, id)| *id).collect();
|
||||
out.sort();
|
||||
out
|
||||
|
||||
+24
-250
@@ -1,69 +1,23 @@
|
||||
//! Names in right-to-left and mixed-direction scripts (Hebrew, Arabic…) in the panels: layer, page,
|
||||
//! style, component and file names. egui has no bidi: it shapes each run of one font on its own,
|
||||
//! reversing right-to-left runs but leaving the words and runs of a name in logical order. So
|
||||
//! names go through [`figcraft_text::display`] (visual order, Arabic letters joined, mirrored
|
||||
//! brackets) and every shown cluster is laid out as its own section, which egui's shaper leaves as
|
||||
//! it is. Names are elided at their end (the left end of a right-to-left name) and edited by
|
||||
//! [`single_line`], whose caret, clicks and selection follow the shown text (the arrow keys move
|
||||
//! visually). Left-to-right names take egui's own path unchanged.
|
||||
//! style, component and file names. egui 0.37's epaint shapes the logical (typing-order) text with
|
||||
//! the Unicode bidirectional algorithm (UAX #9), lays every run out in visual order, joins Arabic
|
||||
//! letters through the font's OpenType features, mirrors brackets, and keeps one glyph per char so
|
||||
//! that caret, selection and click offsets stay logical. Names are therefore passed to egui in
|
||||
//! logical order and elided at their visual end. The rename editor is egui's own single-line
|
||||
//! `TextEdit`, whose arrow keys move the caret on screen while its state remains a logical range.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::text::{ByteIndex, CCursor, CCursorRange, LayoutJob, LayoutSection, TextFormat, TextWrapping};
|
||||
use egui::{Color32, FontId, Galley, Id, Painter, Pos2, Rect, Response, Stroke, Ui, pos2, vec2};
|
||||
use figcraft_text::display::{self, VisualLine};
|
||||
|
||||
/// Shown (visual, elided) lines by name, font and width: elision measures many candidates, so the
|
||||
/// result is kept between frames (cleared when it grows large).
|
||||
#[derive(Clone, Default)]
|
||||
struct Elided(Arc<std::sync::Mutex<HashMap<ElidedKey, VisualLine>>>);
|
||||
|
||||
/// A name, its font's size and family (proportional or not) and the width it was cut to (bits).
|
||||
type ElidedKey = (String, u32, bool, u32);
|
||||
|
||||
const ELIDED_MAX: usize = 4096;
|
||||
use egui::text::{LayoutJob, TextWrapping};
|
||||
use egui::{Color32, FontId, Galley, Id, Painter, Pos2, Rect, Response, Ui, pos2, vec2};
|
||||
|
||||
/// `name` on one line in `font`, at most `max_w` wide (ending in an ellipsis when cut), ready to
|
||||
/// paint: in visual order with Arabic letters joined when it has right-to-left text.
|
||||
/// paint. The text stays in logical order; egui shapes, joins and reorders it, and puts the
|
||||
/// ellipsis at the row's visual end (the left end of a right-to-left name).
|
||||
pub fn name_galley(painter: &Painter, name: &str, font: FontId, color: Color32, max_w: f32) -> Arc<Galley> {
|
||||
let max_w = max_w.max(1.0);
|
||||
if !display::has_rtl(name) {
|
||||
let mut job = LayoutJob::simple_singleline(name.to_string(), font, color);
|
||||
job.wrap = TextWrapping::truncate_at_width(max_w);
|
||||
return painter.layout_job(job);
|
||||
}
|
||||
let key = (name.to_string(), font.size.to_bits(), matches!(font.family, egui::FontFamily::Proportional), max_w.to_bits());
|
||||
let cache = painter.ctx().data_mut(|d| d.get_temp_mut_or_default::<Elided>(Id::new("bidi_elided")).clone());
|
||||
let hit = cache.0.lock().ok().and_then(|m| m.get(&key).cloned());
|
||||
let shown = hit.unwrap_or_else(|| {
|
||||
let fits = |v: &VisualLine| visual_galley(painter, v, &font, color).size().x <= max_w;
|
||||
let v = display::elide(name, fits);
|
||||
if let Ok(mut m) = cache.0.lock() {
|
||||
if m.len() >= ELIDED_MAX {
|
||||
m.clear();
|
||||
}
|
||||
m.insert(key, v.clone());
|
||||
}
|
||||
v
|
||||
});
|
||||
visual_galley(painter, &shown, &font, color)
|
||||
}
|
||||
|
||||
/// A line in display order laid out with each cluster as its own section, so egui's shaper (which
|
||||
/// would reverse a right-to-left run once more) gets one ordered, joined cluster at a time.
|
||||
fn visual_galley(painter: &Painter, line: &VisualLine, font: &FontId, color: Color32) -> Arc<Galley> {
|
||||
let chars: Vec<char> = line.text.chars().collect();
|
||||
let format = TextFormat::simple(font.clone(), color);
|
||||
let mut job = LayoutJob::default();
|
||||
for c in &line.clusters {
|
||||
let start = job.text.len();
|
||||
job.text.extend(chars.get(c.shown.clone()).unwrap_or_default());
|
||||
// Pushed as is: `LayoutJob::append` would merge it with the section before.
|
||||
if job.text.len() > start {
|
||||
job.sections.push(LayoutSection { leading_space: 0.0, byte_range: ByteIndex(start)..ByteIndex(job.text.len()), format: format.clone() });
|
||||
}
|
||||
}
|
||||
let mut job = LayoutJob::simple_singleline(name.to_string(), font, color);
|
||||
job.wrap = TextWrapping::truncate_at_width(max_w);
|
||||
painter.layout_job(job)
|
||||
}
|
||||
|
||||
@@ -76,209 +30,29 @@ pub fn paint_name(painter: &Painter, left_center: Pos2, name: &str, font: FontId
|
||||
rect
|
||||
}
|
||||
|
||||
/// Each shown cluster's left and right x in a galley of `v.text` laid out from x = 0.
|
||||
fn edges(v: &VisualLine, galley: &Galley) -> Vec<(f64, f64)> {
|
||||
let chars: Vec<(f64, f64)> = galley
|
||||
.rows
|
||||
.first()
|
||||
.map(|r| r.row.glyphs.iter().map(|g| (f64::from(g.pos.x), f64::from(g.pos.x + g.advance_width))).collect())
|
||||
.unwrap_or_default();
|
||||
v.cluster_edges(&chars)
|
||||
}
|
||||
|
||||
/// The shown text of a field being edited, laid out once per frame.
|
||||
struct Shown {
|
||||
line: VisualLine,
|
||||
galley: Arc<Galley>,
|
||||
edges: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
fn new(ui: &Ui, text: &str, font: &FontId, color: Color32) -> Shown {
|
||||
let line = display::visual_line(text);
|
||||
let galley = visual_galley(ui.painter(), &line, font, color);
|
||||
let edges = edges(&line, &galley);
|
||||
Shown { line, galley, edges }
|
||||
}
|
||||
|
||||
fn caret_x(&self, i: usize) -> f32 {
|
||||
self.line.caret_x(i, &self.edges) as f32
|
||||
}
|
||||
|
||||
fn hit(&self, x: f32) -> usize {
|
||||
self.line.hit(f64::from(x), &self.edges)
|
||||
}
|
||||
}
|
||||
|
||||
fn scroll_id(id: Id) -> Id {
|
||||
id.with("bidi_scroll")
|
||||
}
|
||||
|
||||
fn anchor_id(id: Id) -> Id {
|
||||
id.with("bidi_anchor")
|
||||
}
|
||||
|
||||
/// A frameless one-line text editor for a name (a [`egui::TextEdit`] with id `id`). Text with
|
||||
/// right-to-left characters shows in visual order, and the caret, the selection, clicks, drags and
|
||||
/// the left and right arrow keys follow what's on screen.
|
||||
/// A frameless one-line text editor for a name (a [`egui::TextEdit`] with id `id`). The editor's
|
||||
/// text is logical; egui's galley paints it in visual order, and its caret, selection, clicks,
|
||||
/// drags and left and right arrows follow what is on screen while reporting logical char offsets.
|
||||
pub fn single_line(ui: &mut Ui, id: Id, text: &mut String, font: FontId, width: f32) -> Response {
|
||||
let rtl = display::has_rtl(text);
|
||||
let focused = ui.memory(|m| m.has_focus(id));
|
||||
let color = ui.visuals().text_color();
|
||||
if rtl && focused {
|
||||
visual_arrows(ui, id, text, &font, color);
|
||||
}
|
||||
// Centred in the height it's given (a rename row), like the name it replaces.
|
||||
let height = ui.available_height().max(0.0);
|
||||
let edit = egui::TextEdit::singleline(text)
|
||||
egui::TextEdit::singleline(text)
|
||||
.id(id)
|
||||
.frame(egui::Frame::NONE)
|
||||
.font(font.clone())
|
||||
.font(font)
|
||||
.desired_width(width)
|
||||
.vertical_align(egui::Align::Center)
|
||||
.min_size(vec2(0.0, height));
|
||||
if !rtl {
|
||||
ui.data_mut(|d| d.remove::<f32>(scroll_id(id)));
|
||||
return edit.show(ui).response.response;
|
||||
}
|
||||
// egui would draw the chars in logical order: hide its text, caret and selection and draw the
|
||||
// shown text over it.
|
||||
let out = ui
|
||||
.scope(|ui| {
|
||||
let v = ui.visuals_mut();
|
||||
v.selection.bg_fill = Color32::TRANSPARENT;
|
||||
v.selection.stroke = Stroke::new(0.0, Color32::TRANSPARENT);
|
||||
v.text_cursor.stroke = Stroke::NONE;
|
||||
edit.text_color(Color32::TRANSPARENT).show(ui)
|
||||
})
|
||||
.inner;
|
||||
let response = out.response.response;
|
||||
let shown = Shown::new(ui, text, &font, color);
|
||||
let clip = out.text_clip_rect;
|
||||
let mut scroll: f32 = ui.data(|d| d.get_temp(scroll_id(id))).unwrap_or(0.0);
|
||||
let origin = |scroll: f32| pos2(clip.min.x - scroll, out.galley_pos.y);
|
||||
// Clicks and drags place the caret by what's on screen.
|
||||
let mut range = out.state.cursor.char_range();
|
||||
if let Some(p) = response.interact_pointer_pos() {
|
||||
let at = shown.hit(p.x - origin(scroll).x);
|
||||
if response.double_clicked() {
|
||||
let (a, b) = word_at(text, at);
|
||||
range = Some(CCursorRange::two(CCursor::new(a), CCursor::new(b)));
|
||||
} else if response.clicked() || (response.is_pointer_button_down_on() && !response.dragged()) {
|
||||
// Pressed (not yet dragging): the caret and the drag's anchor go here.
|
||||
ui.data_mut(|d| d.insert_temp(anchor_id(id), at));
|
||||
range = Some(CCursorRange::one(CCursor::new(at)));
|
||||
} else if response.dragged() {
|
||||
let anchor = ui.data(|d| d.get_temp::<usize>(anchor_id(id))).unwrap_or(at);
|
||||
range = Some(CCursorRange { primary: CCursor::new(at), secondary: CCursor::new(anchor), h_pos: None });
|
||||
}
|
||||
if range != out.state.cursor.char_range() {
|
||||
let mut state = out.state.clone();
|
||||
state.cursor.set_char_range(range);
|
||||
state.store(ui.ctx(), id);
|
||||
}
|
||||
}
|
||||
// Keep the caret in view.
|
||||
let caret = range.map_or(0, |r| r.primary.index.0);
|
||||
let cx = shown.caret_x(caret);
|
||||
let w = clip.width().max(1.0);
|
||||
if cx - scroll > w - 1.0 {
|
||||
scroll = cx - w + 1.0;
|
||||
}
|
||||
if cx - scroll < 0.0 {
|
||||
scroll = cx;
|
||||
}
|
||||
scroll = scroll.clamp(0.0, (shown.galley.size().x - w + 1.0).max(0.0));
|
||||
ui.data_mut(|d| d.insert_temp(scroll_id(id), scroll));
|
||||
let o = origin(scroll);
|
||||
let painter = ui.painter().with_clip_rect(clip.expand2(vec2(1.0, 0.0)));
|
||||
let h = shown.galley.size().y;
|
||||
if focused && let Some(r) = range {
|
||||
let (a, b) = (r.primary.index.0, r.secondary.index.0);
|
||||
for (x0, x1) in shown.line.selection(a, b, &shown.edges) {
|
||||
let sel = Rect::from_min_max(pos2(o.x + x0 as f32, o.y), pos2(o.x + x1 as f32, o.y + h));
|
||||
painter.rect_filled(sel, 0.0, ui.visuals().selection.bg_fill);
|
||||
}
|
||||
}
|
||||
painter.galley(o, shown.galley.clone(), color);
|
||||
if focused {
|
||||
let x = (o.x + cx).round() + 0.5;
|
||||
painter.line_segment([pos2(x, o.y), pos2(x, o.y + h)], ui.visuals().text_cursor.stroke);
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// Plain and Shift-held left and right arrows move the caret across the shown text (consumed so
|
||||
/// the editor doesn't move it logically). Word and line jumps stay logical.
|
||||
fn visual_arrows(ui: &mut Ui, id: Id, text: &str, font: &FontId, color: Color32) {
|
||||
let moves: Vec<(bool, bool)> = ui.input_mut(|i| {
|
||||
let mut out = Vec::new();
|
||||
i.events.retain(|e| match e {
|
||||
egui::Event::Key { key: key @ (egui::Key::ArrowLeft | egui::Key::ArrowRight), pressed: true, modifiers, .. }
|
||||
if !modifiers.alt && !modifiers.command && !modifiers.ctrl =>
|
||||
{
|
||||
out.push((*key == egui::Key::ArrowRight, modifiers.shift));
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
});
|
||||
out
|
||||
});
|
||||
if moves.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), id) else { return };
|
||||
let shown = Shown::new(ui, text, font, color);
|
||||
let mut r = state.cursor.char_range().unwrap_or_default();
|
||||
for (right, shift) in moves {
|
||||
let (lo, hi) = (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0));
|
||||
let next = if !shift && lo != hi {
|
||||
// A selection collapses to its end on the side of the arrow.
|
||||
let (xa, xb) = (shown.caret_x(lo), shown.caret_x(hi));
|
||||
if (xa < xb) == right { hi } else { lo }
|
||||
} else {
|
||||
shown.line.step(r.primary.index.0, right, &shown.edges)
|
||||
};
|
||||
r = if shift {
|
||||
CCursorRange { primary: CCursor::new(next), secondary: r.secondary, h_pos: None }
|
||||
} else {
|
||||
CCursorRange::one(CCursor::new(next))
|
||||
};
|
||||
}
|
||||
state.cursor.set_char_range(Some(r));
|
||||
state.store(ui.ctx(), id);
|
||||
}
|
||||
|
||||
/// The word around char `i` (letters, digits and marks; else the single char).
|
||||
fn word_at(text: &str, i: usize) -> (usize, usize) {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let is_word =
|
||||
|k: usize| chars.get(k).is_some_and(|c| c.is_alphanumeric() || matches!(*c as u32, 0x0300..=0x036F | 0x0591..=0x05C7 | 0x064B..=0x065F));
|
||||
let i = i.min(chars.len());
|
||||
let at = if is_word(i) {
|
||||
i
|
||||
} else if i > 0 && is_word(i - 1) {
|
||||
i - 1
|
||||
} else {
|
||||
return (i, (i + 1).min(chars.len()));
|
||||
};
|
||||
let mut a = at;
|
||||
while a > 0 && is_word(a - 1) {
|
||||
a -= 1;
|
||||
}
|
||||
let mut b = at;
|
||||
while is_word(b) {
|
||||
b += 1;
|
||||
}
|
||||
(a, b)
|
||||
.align(egui::Align2::LEFT_CENTER)
|
||||
.min_size(vec2(0.0, height))
|
||||
.show(ui)
|
||||
.response
|
||||
.response
|
||||
}
|
||||
|
||||
/// Faces the UI adds for scripts its own fonts lack (desktop: from the system), as egui font data;
|
||||
/// `taken` as for [`crate::theme::system_fallbacks`].
|
||||
pub fn script_fallbacks(have: &dyn Fn(char) -> bool, taken: &mut Vec<Arc<figcraft_text::Face>>) -> Vec<(String, egui::FontData)> {
|
||||
// Hebrew, Arabic letters, Arabic presentation forms (what joined names are drawn with).
|
||||
const SAMPLES: [char; 3] = ['\u{05D0}', '\u{0628}', '\u{FE91}'];
|
||||
// Hebrew and Arabic letters; egui's shaper selects the joined contextual forms itself.
|
||||
const SAMPLES: [char; 2] = ['\u{05D0}', '\u{0628}'];
|
||||
const FAMILIES: [&str; 11] = [
|
||||
"Segoe UI",
|
||||
"Arial",
|
||||
|
||||
@@ -170,7 +170,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let size = vec2(h.width(), 40.0);
|
||||
let at = place(sel, size, app.canvas.rect);
|
||||
let t = Tokens::get(ctx);
|
||||
egui::Area::new(egui::Id::new("board_bar")).fixed_pos(at).order(egui::Order::Middle).show(ctx, |ui| {
|
||||
egui::Area::new(egui::Id::unique("board_bar")).fixed_pos(at).order(egui::Order::Middle).show(ctx, |ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(size, Sense::click());
|
||||
a11y::container_bounds(ui, rect);
|
||||
let p = ui.painter();
|
||||
@@ -198,7 +198,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
fn color_part(app: &mut FigApp, ui: &mut Ui, mut x: f32, cy: f32, t: &Tokens) -> f32 {
|
||||
for (i, (name, c)) in BOARD_COLORS.iter().enumerate() {
|
||||
let r = Rect::from_center_size(pos2(x + SWATCH / 2.0, cy), vec2(SWATCH, SWATCH));
|
||||
let resp = ui.interact(r, ui.id().with(("bb_color", i)), Sense::click()).on_hover_text(tr(color_label(name)));
|
||||
let resp = ui.interact(r, ui.scope_id().with(("bb_color", i)), Sense::click()).on_hover_text(tr(color_label(name)));
|
||||
a11y::button(&resp, tr(color_label(name)));
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r.expand(2.0), CornerRadius::same(6), t.hover);
|
||||
@@ -215,7 +215,7 @@ fn color_part(app: &mut FigApp, ui: &mut Ui, mut x: f32, cy: f32, t: &Tokens) ->
|
||||
/// The shape menu at `at` (its left edge and middle), showing `shape`; where the next part starts.
|
||||
fn shape_part(app: &mut FigApp, ui: &mut Ui, shape: BoardShape, at: Pos2, t: &Tokens) -> f32 {
|
||||
let r = Rect::from_min_size(pos2(at.x, at.y - CELL / 2.0), vec2(CELL + 12.0, CELL));
|
||||
let resp = ui.interact(r, ui.id().with("bb_shape"), Sense::click()).on_hover_text(tr("Shape"));
|
||||
let resp = ui.interact(r, ui.scope_id().with("bb_shape"), Sense::click()).on_hover_text(tr("Shape"));
|
||||
a11y::menu_button(&resp, tr("Shape"), a11y::menu_open(&resp));
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), t.hover);
|
||||
@@ -240,7 +240,7 @@ fn shape_part(app: &mut FigApp, ui: &mut Ui, shape: BoardShape, at: Pos2, t: &To
|
||||
fn size_part(app: &mut FigApp, ui: &mut Ui, mut x: f32, cy: f32, t: &Tokens) -> f32 {
|
||||
for (label, size) in TEXT_SIZES {
|
||||
let r = Rect::from_center_size(pos2(x + CELL / 2.0, cy), vec2(CELL, CELL));
|
||||
let resp = ui.interact(r, ui.id().with(("bb_size", label)), Sense::click()).on_hover_text(tr("Text size"));
|
||||
let resp = ui.interact(r, ui.scope_id().with(("bb_size", label)), Sense::click()).on_hover_text(tr("Text size"));
|
||||
a11y::button(&resp, &format!("{} {label}", tr("Text size")));
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), t.hover);
|
||||
|
||||
@@ -56,12 +56,12 @@ fn pick_option(u: &mut Ui, i: usize, n: usize) {
|
||||
|
||||
/// Whether the bar over the selection showed in the last frame.
|
||||
fn bar_shown(ctx: &egui::Context) -> bool {
|
||||
ctx.memory(|m| m.areas().visible_last_frame(&egui::LayerId::new(egui::Order::Middle, egui::Id::new("board_bar"))))
|
||||
ctx.memory(|m| m.areas().visible_last_frame(&egui::LayerId::new(egui::Order::Middle, egui::Id::unique("board_bar"))))
|
||||
}
|
||||
|
||||
/// The bar over the selection, when it shows.
|
||||
fn bar(u: &Ui) -> Option<Rect> {
|
||||
bar_shown(&u.ctx).then(|| u.ctx.memory(|m| m.area_rect(egui::Id::new("board_bar")))).flatten()
|
||||
bar_shown(&u.ctx).then(|| u.ctx.memory(|m| m.area_rect(egui::Id::unique("board_bar")))).flatten()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -75,7 +75,7 @@ pub fn banner(app: &mut FigApp, ctx: &egui::Context, canvas: Rect) {
|
||||
let Some(b) = m.branches.iter().find(|b| b.id == id) else { return };
|
||||
let (file, name, active) = (m.doc.name.clone(), b.name.clone(), b.state == BranchState::Active);
|
||||
let t = Tokens::get(ctx);
|
||||
let review = widgets::canvas_banner(ctx, Id::new("branch_banner"), canvas, |ui| {
|
||||
let review = widgets::canvas_banner(ctx, Id::unique("branch_banner"), canvas, |ui| {
|
||||
ui.label(egui::RichText::new(format!("“{name}”")).font(semibold(11.0)).color(t.text));
|
||||
let state =
|
||||
if active { trf("Branch of {file}", &[("file", &file)]) } else { trf("Branch of {file} · merged or archived", &[("file", &file)]) };
|
||||
@@ -146,7 +146,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut action = None;
|
||||
egui::Window::new("Review and merge")
|
||||
.id(Id::new("branch_review_window"))
|
||||
.id(Id::unique("branch_review_window"))
|
||||
.title_bar(false)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
|
||||
@@ -163,12 +163,16 @@ fn pointer_event(app: &FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one canvas pass: update the viewport size and first-fit zoom; handle pointer/key input
|
||||
/// and accessibility; draw the drop overlay, guides, live pointer and preedit; request/poll
|
||||
/// renders and upload the texture; draw the page background and last texture; then draw overlays,
|
||||
/// labels, handles, comments, versions/branch/dev/live UI and the cursor.
|
||||
pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
|
||||
let rect = ui.max_rect();
|
||||
app.canvas.rect = rect;
|
||||
let ctx = ui.ctx().clone();
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let resp = ui.interact(rect, ui.id().with("canvas"), Sense::click_and_drag());
|
||||
let resp = ui.interact(rect, ui.scope_id().with("canvas"), Sense::click_and_drag());
|
||||
let key_box = app.ui.key_box;
|
||||
crate::a11y::canvas(&mut app.ui.nav, &resp, || key_box.map_or_else(|| describe(&app.session), describe_box));
|
||||
if let Ok(ds) = app.session.ds_mut()
|
||||
@@ -556,7 +560,7 @@ fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> bool {
|
||||
}
|
||||
// Leaving the canvas: nothing is hovered there any more.
|
||||
if !app.canvas.dragging && std::mem::take(&mut app.canvas.hovering) {
|
||||
app.session.vector_pointer_left();
|
||||
app.session.pointer_left();
|
||||
}
|
||||
// A pan whose button was released off the canvas is over.
|
||||
if !ctx.input(|i| i.pointer.button_down(egui::PointerButton::Middle) || i.pointer.primary_down()) {
|
||||
@@ -654,7 +658,7 @@ fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> bool {
|
||||
} else {
|
||||
// Something over the canvas took the pointer.
|
||||
if std::mem::take(&mut app.canvas.hovering) {
|
||||
app.session.vector_pointer_left();
|
||||
app.session.pointer_left();
|
||||
}
|
||||
None
|
||||
};
|
||||
@@ -702,6 +706,7 @@ pub fn open_context_menu(app: &mut FigApp, pos: Pos2, deep: bool) {
|
||||
}
|
||||
}
|
||||
app.ui.context_menu = Some((pos, app.session.selection()));
|
||||
app.ui.context_menu_shown = false;
|
||||
}
|
||||
|
||||
fn stroke(c: Color32, w: f32) -> Stroke {
|
||||
@@ -1484,7 +1489,9 @@ fn hatch(polys: &[Vec<Pos2>], gap: f32) -> Vec<[Pos2; 2]> {
|
||||
}
|
||||
|
||||
/// The layers that get canvas labels and layout grids, in z-order: the page's visible top-level
|
||||
/// layers and, inside sections whose contents show, their visible children (sections nest).
|
||||
/// layers and, inside sections whose contents show, their visible children (sections nest). A
|
||||
/// section comes after its children, so its title pill draws over (and takes clicks from) the
|
||||
/// labels of frames near its top-left (#1150).
|
||||
fn boards(doc: &Document, page: NodeId) -> Vec<NodeId> {
|
||||
fn walk(doc: &Document, id: NodeId, depth: usize, out: &mut Vec<NodeId>) {
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
@@ -1493,10 +1500,10 @@ fn boards(doc: &Document, page: NodeId) -> Vec<NodeId> {
|
||||
if !cn.visible {
|
||||
continue;
|
||||
}
|
||||
out.push(*c);
|
||||
if matches!(cn.kind, NodeKind::Section { contents_hidden: false }) && depth < 32 {
|
||||
walk(doc, *c, depth + 1, out);
|
||||
}
|
||||
out.push(*c);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Programmatic gestures never replace the user's system clipboard: keys and clicks injected
|
||||
//! through the control channel (`ui.input`, `ui.menu.invoke`, …) may copy inside FigCraft but the
|
||||
//! OS clipboard is the user's. Every copy command goes through `FigApp::clipboard_set_text` /
|
||||
//! `FigApp::clipboard_set_png`, which drop the write while the frame's input is synthetic.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use egui::{Event, Pos2, RawInput, Rect, vec2};
|
||||
use figcraft_doc::{NodeId, NodeKind};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::control::ControlRequest;
|
||||
use crate::{FigApp, Services};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Recorded {
|
||||
text: Vec<String>,
|
||||
pngs: usize,
|
||||
/// What the system clipboard holds now (the last text written).
|
||||
last_text: Option<String>,
|
||||
}
|
||||
|
||||
/// The system clipboard of the test machine.
|
||||
struct Clipboard(Arc<Mutex<Recorded>>);
|
||||
|
||||
impl Services for Clipboard {
|
||||
/// Record a system-clipboard text write in the test clipboard service.
|
||||
fn clipboard_set_text(&mut self, s: &str) {
|
||||
let mut r = self.0.lock().unwrap();
|
||||
r.text.push(s.to_string());
|
||||
r.last_text = Some(s.to_string());
|
||||
}
|
||||
/// Return the test system clipboard's last text.
|
||||
fn clipboard_get_text(&mut self) -> Option<String> {
|
||||
self.0.lock().unwrap().last_text.clone()
|
||||
}
|
||||
/// Count a PNG clipboard write in the test clipboard service.
|
||||
fn clipboard_set_png(&mut self, _w: u32, _h: u32, _rgba: &[u8]) {
|
||||
self.0.lock().unwrap().pngs += 1;
|
||||
}
|
||||
}
|
||||
|
||||
struct Win {
|
||||
ctx: egui::Context,
|
||||
app: FigApp,
|
||||
time: f64,
|
||||
recorded: Arc<Mutex<Recorded>>,
|
||||
}
|
||||
|
||||
impl Win {
|
||||
/// Create a test window over a session containing one selected rectangle.
|
||||
fn new() -> Self {
|
||||
let mut s = Session::new();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
let mut win = Self::with_session(s);
|
||||
let _ = win.app.run("select.all", json!({}));
|
||||
win
|
||||
}
|
||||
|
||||
/// Build a test window around `s` with a recording clipboard service and run three frames.
|
||||
fn with_session(s: Session) -> Self {
|
||||
let recorded = Arc::new(Mutex::new(Recorded::default()));
|
||||
let app = FigApp::new(s, Box::new(Clipboard(recorded.clone())));
|
||||
let mut win = Self { ctx: egui::Context::default(), app, time: 0.0, recorded };
|
||||
for _ in 0..3 {
|
||||
win.frame(vec![]);
|
||||
}
|
||||
win
|
||||
}
|
||||
|
||||
/// Run one production UI frame with `events` at the next 60 Hz test time.
|
||||
fn frame(&mut self, events: Vec<Event>) {
|
||||
self.time += 1.0 / 60.0;
|
||||
self.app.clock.set_test_now(Some(self.time));
|
||||
let input =
|
||||
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), events, ..Default::default() };
|
||||
let app = &mut self.app;
|
||||
let mut out = self.ctx.run_ui(input, |ui| app.ui(ui));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Return the recorded `(text writes, PNG writes)` count.
|
||||
fn writes(&self) -> (usize, usize) {
|
||||
let r = self.recorded.lock().unwrap();
|
||||
(r.text.len(), r.pngs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts that a control-channel copy shortcut writes no system clipboard, still runs the
|
||||
/// command and is acknowledged.
|
||||
#[test]
|
||||
fn a_synthetic_copy_shortcut_leaves_the_system_clipboard_alone() {
|
||||
let mut w = Win::new();
|
||||
assert!(!w.app.session.selection().is_empty(), "something to copy");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
w.app.control_queue.push(ControlRequest {
|
||||
id: json!(1),
|
||||
method: "ui.input".into(),
|
||||
// Shift+Cmd+C: `edit.copyAsPng`, which wrote the OS clipboard directly before the fence.
|
||||
params: json!({"events": [{"key": "C", "shift": true, "cmd": true}]}),
|
||||
reply: tx,
|
||||
state: Default::default(),
|
||||
});
|
||||
w.frame(vec![]);
|
||||
let events = crate::windows::take_input(&mut w.app, egui::ViewportId::ROOT);
|
||||
assert!(!events.is_empty(), "the injected shortcut");
|
||||
w.frame(events);
|
||||
assert_eq!(w.writes(), (0, 0), "a control-channel gesture never replaces the user's clipboard");
|
||||
assert!(
|
||||
w.app.ui.toast.as_ref().is_some_and(|(m, _)| m.contains("Copied")),
|
||||
"the command itself ran (only its OS clipboard write is fenced): {:?}",
|
||||
w.app.ui.toast
|
||||
);
|
||||
assert!(rx.try_recv().is_ok(), "the batch is acknowledged");
|
||||
}
|
||||
|
||||
/// Asserts copy commands run under the synthetic-control fence write nothing, while the same
|
||||
/// command afterwards writes once.
|
||||
#[test]
|
||||
fn a_copy_command_invoked_for_a_synthetic_click_still_keeps_the_clipboard() {
|
||||
let mut w = Win::new();
|
||||
// What a synthetic pointer click on Copy runs, fenced as `control::drain`/`background` fence it.
|
||||
w.app.control_synthetic = true;
|
||||
crate::menus::invoke(&mut w.app, "edit.copyAsCss");
|
||||
crate::menus::invoke(&mut w.app, "edit.copyAsText");
|
||||
assert_eq!(w.writes(), (0, 0));
|
||||
w.app.control_synthetic = false;
|
||||
// A user's own copy still writes.
|
||||
crate::menus::invoke(&mut w.app, "edit.copyAsCss");
|
||||
assert_eq!(w.writes(), (1, 0));
|
||||
}
|
||||
|
||||
/// Return the characters of a text node in the test window.
|
||||
fn edit_text(w: &Win, id: NodeId) -> String {
|
||||
match &w.app.session.doc().unwrap().node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.characters.clone(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts a synthetic Cut deletes the selected text, keeps the edit session active, writes
|
||||
/// no system clipboard, and ends its fence with the frame.
|
||||
#[test]
|
||||
fn a_synthetic_cut_deletes_the_selection_but_leaves_the_users_clipboard_alone() {
|
||||
let mut s = Session::new();
|
||||
let id = NodeId(s.execute("text.create", &json!({"text": "abc", "x": 40, "y": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut w = Win::with_session(s);
|
||||
figcraft_engine::textedit::begin(&mut w.app.session, id, Some(3), false).unwrap();
|
||||
figcraft_engine::textedit::set_caret(&mut w.app.session, 0, true).unwrap();
|
||||
|
||||
// A control-channel gesture is fenced from the OS clipboard, but its Cut still edits the
|
||||
// document: the selection is deleted exactly as a user's Cut would delete it.
|
||||
w.app.push_control_input(vec![Event::Cut]);
|
||||
let events = crate::windows::take_input(&mut w.app, egui::ViewportId::ROOT);
|
||||
assert_eq!(events, [Event::Cut], "the production input path owns the synthetic frame");
|
||||
w.frame(events);
|
||||
assert_eq!(w.writes(), (0, 0), "a synthetic cut never writes the user's clipboard");
|
||||
assert_eq!(edit_text(&w, id), "", "the selected text is deleted");
|
||||
assert!(w.app.session.ds().unwrap().text_edit.is_some(), "the edit session stays active");
|
||||
assert!(!w.app.control_synthetic, "the fence ends with the frame");
|
||||
}
|
||||
|
||||
/// Asserts a programmatic copy leaves the system clipboard alone and invalidates the stale
|
||||
/// mirror, so a later user paste uses the system text rather than the programmatic layers.
|
||||
#[test]
|
||||
fn a_programmatic_copy_does_not_let_a_stale_mirror_hide_the_users_paste() {
|
||||
let mut s = Session::new();
|
||||
let hello = figcraft_doc::NodeId(s.execute("text.create", &json!({"text": "hello", "x": 10, "y": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
let other = figcraft_doc::NodeId(s.execute("text.create", &json!({"text": "other", "x": 10, "y": 80})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [hello]})).unwrap();
|
||||
let mut w = Win::with_session(s);
|
||||
|
||||
// The user copies the "hello" text layer: the OS clipboard and `last_copy` become "hello".
|
||||
crate::menus::invoke(&mut w.app, "edit.copy");
|
||||
assert_eq!(w.app.ui.last_copy.as_deref(), Some("hello"));
|
||||
assert_eq!(w.writes().0, 1, "the user's copy reaches the system clipboard");
|
||||
|
||||
// A control-channel copy changes the engine clipboard to "other" but never writes the system
|
||||
// clipboard. The stale "hello" mirror must not claim the programmatic selection is ours.
|
||||
let _ = w.app.run("select.set", json!({"ids": [other]}));
|
||||
w.app.control_synthetic = true;
|
||||
crate::menus::invoke(&mut w.app, "edit.copy");
|
||||
w.app.control_synthetic = false;
|
||||
assert_eq!(w.writes().0, 1, "the programmatic copy leaves the system clipboard alone");
|
||||
assert_eq!(w.app.ui.last_copy, None, "the old system-clipboard mirror is invalidated");
|
||||
|
||||
// The user pastes: the system clipboard's own text wins over the programmatic layers.
|
||||
crate::menus::paste(&mut w.app, Some("hello"), None);
|
||||
let doc = w.app.session.doc().unwrap();
|
||||
let texts: Vec<String> = doc
|
||||
.pages
|
||||
.iter()
|
||||
.filter_map(|p| doc.node(*p))
|
||||
.flat_map(|p| p.children.iter().copied())
|
||||
.filter_map(|id| doc.node(id).and_then(|n| n.kind.text().map(|t| t.characters.clone())))
|
||||
.collect();
|
||||
assert_eq!(texts.iter().filter(|t| t.as_str() == "hello").count(), 2, "the user's text was pasted");
|
||||
assert_eq!(texts.iter().filter(|t| t.as_str() == "other").count(), 1, "the programmatic selection was not pasted");
|
||||
}
|
||||
@@ -199,7 +199,7 @@ fn finish(app: &mut FigApp) {
|
||||
|
||||
/// The selected gradient stop in the picker (shared with the on-canvas stops).
|
||||
pub fn stop_id() -> Id {
|
||||
Id::new("cp_stop")
|
||||
Id::unique("cp_stop")
|
||||
}
|
||||
|
||||
/// Apply a swatch colour: a solid paint's colour, or the selected gradient stop's.
|
||||
@@ -224,7 +224,7 @@ fn set_color(app: &mut FigApp, target: &PickerTarget, paint: &mut Paint, c: Colo
|
||||
fn page_colors(app: &FigApp, ui: &Ui) -> Vec<Color> {
|
||||
let Ok(ds) = app.session.ds() else { return vec![] };
|
||||
let key = (std::sync::Arc::as_ptr(&ds.doc) as usize, ds.page);
|
||||
let cache_id = Id::new("cp_doc_colors");
|
||||
let cache_id = Id::unique("cp_doc_colors");
|
||||
if let Some((k, colors)) = ui.data(|d| d.get_temp::<((usize, figcraft_doc::NodeId), Vec<Color>)>(cache_id))
|
||||
&& k == key
|
||||
{
|
||||
@@ -241,7 +241,7 @@ const MODELS: [&str; 5] = ["Hex", "RGB", "HSL", "HSB", "CSS"];
|
||||
/// The model dropdown with its fields and the alpha field. Returns a new colour and whether the
|
||||
/// edit is done (false while a field is being scrubbed).
|
||||
fn model_fields(ui: &mut Ui, c: Color) -> Option<(Color, bool)> {
|
||||
let model_id = Id::new("cp_model");
|
||||
let model_id = Id::unique("cp_model");
|
||||
let model: usize = ui.data(|d| d.get_temp(model_id)).unwrap_or(0).min(MODELS.len() - 1);
|
||||
let mut out: Option<Color> = None;
|
||||
let mut done = true;
|
||||
@@ -259,7 +259,7 @@ fn model_fields(ui: &mut Ui, c: Color) -> Option<(Color, bool)> {
|
||||
});
|
||||
let num = |ui: &mut Ui, id: &str, v: f64, w: f32| match widgets::number_field(
|
||||
ui,
|
||||
Id::new(("cp_f", id)),
|
||||
Id::unique(("cp_f", id)),
|
||||
widgets::Lead::None,
|
||||
Some(v.round()),
|
||||
"",
|
||||
@@ -309,19 +309,19 @@ fn model_fields(ui: &mut Ui, c: Color) -> Option<(Color, bool)> {
|
||||
}
|
||||
}
|
||||
"CSS" => {
|
||||
if let Some(text) = widgets::text_field(ui, Id::new("cp_css"), &c.to_css(), 152.0, "") {
|
||||
if let Some(text) = widgets::text_field(ui, Id::unique("cp_css"), &c.to_css(), 152.0, "") {
|
||||
out = Color::parse_css(&text);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(h) = widgets::text_field(ui, Id::new("cp_hex"), &c.to_hex(), 101.0, "") {
|
||||
if let Some(h) = widgets::text_field(ui, Id::unique("cp_hex"), &c.to_hex(), 101.0, "") {
|
||||
out = Color::from_hex_or_name(&h).map(|h| h.with_alpha(if h.a < 1.0 { h.a } else { c.a }));
|
||||
}
|
||||
}
|
||||
}
|
||||
if MODELS.get(model) != Some(&"CSS") {
|
||||
let alpha = Some((f64::from(out.unwrap_or(c).a) * 100.0).round());
|
||||
let edit = match widgets::number_field(ui, Id::new("cp_a"), widgets::Lead::None, alpha, "%", 44.0, 1.0) {
|
||||
let edit = match widgets::number_field(ui, Id::unique("cp_a"), widgets::Lead::None, alpha, "%", 44.0, 1.0) {
|
||||
Some(widgets::FieldEdit::Set(v)) => Some((v, true)),
|
||||
Some(widgets::FieldEdit::Scrub(v, end)) => Some((v, end)),
|
||||
None => None,
|
||||
@@ -339,6 +339,8 @@ fn hue_color(ctx: &egui::Context, h: f32) -> Color32 {
|
||||
doc_c32(ctx, Hsb { h, s: 1.0, b: 1.0 }.to_color())
|
||||
}
|
||||
|
||||
/// Draw the saturation/value square and its knob, updating `hsb.s` and `hsb.b` on click or
|
||||
/// drag; returns `(changed, done)`.
|
||||
fn sv_square(ui: &mut Ui, rect: Rect, hsb: &mut Hsb) -> (bool, bool) {
|
||||
// White → hue horizontally, then transparent → black vertically.
|
||||
let mut m = Mesh::default();
|
||||
@@ -362,7 +364,7 @@ fn sv_square(ui: &mut Ui, rect: Rect, hsb: &mut Hsb) -> (bool, bool) {
|
||||
m2.add_triangle(0, 1, 2);
|
||||
m2.add_triangle(0, 2, 3);
|
||||
ui.painter().add(m2);
|
||||
let resp = ui.interact(rect, Id::new("cp_sv"), Sense::click_and_drag());
|
||||
let resp = ui.interact(rect, Id::unique("cp_sv"), Sense::click_and_drag());
|
||||
let mut changed = false;
|
||||
if (resp.dragged() || resp.clicked() || resp.drag_started())
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
@@ -377,6 +379,8 @@ fn sv_square(ui: &mut Ui, rect: Rect, hsb: &mut Hsb) -> (bool, bool) {
|
||||
(changed, resp.drag_stopped() || resp.clicked())
|
||||
}
|
||||
|
||||
/// Draw the hue gradient and knob, updating `hsb.h` clamped below 360; returns
|
||||
/// `(changed, done)`.
|
||||
fn hue_slider(ui: &mut Ui, rect: Rect, hsb: &mut Hsb) -> (bool, bool) {
|
||||
let n = 12;
|
||||
let mut m = Mesh::default();
|
||||
@@ -393,7 +397,7 @@ fn hue_slider(ui: &mut Ui, rect: Rect, hsb: &mut Hsb) -> (bool, bool) {
|
||||
}
|
||||
}
|
||||
ui.painter().add(m);
|
||||
slider_knob(ui, rect, hsb.h / 360.0, Id::new("cp_hue"))
|
||||
slider_knob(ui, rect, hsb.h / 360.0, Id::unique("cp_hue"))
|
||||
.map(|(t, done)| {
|
||||
hsb.h = (t * 360.0).clamp(0.0, 359.9);
|
||||
(true, done)
|
||||
@@ -417,6 +421,8 @@ fn slider_knob(ui: &mut Ui, rect: Rect, t: f32, id: Id) -> Option<(f32, bool)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Draw the checkerboard and transparent-to-opaque alpha gradient with a knob; returns the
|
||||
/// new alpha and done state, or `None` when the slider is not interacting.
|
||||
fn alpha_slider(ui: &mut Ui, rect: Rect, color: Color) -> Option<(f32, bool)> {
|
||||
widgets::checker(&ui.painter().with_clip_rect(rect), rect, rect.height() / 2.0);
|
||||
let mut m = Mesh::default();
|
||||
@@ -432,15 +438,18 @@ fn alpha_slider(ui: &mut Ui, rect: Rect, color: Color) -> Option<(f32, bool)> {
|
||||
m.add_triangle(0, 1, 2);
|
||||
m.add_triangle(0, 2, 3);
|
||||
ui.painter().add(m);
|
||||
slider_knob(ui, rect, color.a, Id::new("cp_alpha"))
|
||||
slider_knob(ui, rect, color.a, Id::unique("cp_alpha"))
|
||||
}
|
||||
|
||||
/// The colour picker window's area id. A fixed id (not `Window::new`'s, which egui keys by
|
||||
/// `Id::new(Some(title))`) so the style picker can tell a click inside the picker from one outside.
|
||||
/// `Id::unique(Some(title))`) so the style picker can tell a click inside the picker from one outside.
|
||||
pub fn window_id() -> Id {
|
||||
Id::new("color_picker")
|
||||
Id::unique("color_picker")
|
||||
}
|
||||
|
||||
/// Draw the colour picker for the current target: close it when there is no target or the
|
||||
/// target's selection no longer matches, otherwise apply eyedropper, paint-kind, colour and
|
||||
/// gradient-stop edits live, positioned beside a plugin field when applicable.
|
||||
pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let Some(target) = app.ui.picker.clone() else {
|
||||
// A colour sampled for a picker that has closed has no paint to go to.
|
||||
@@ -477,7 +486,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let mut close_now = false;
|
||||
egui::Window::new("color_picker")
|
||||
// A fixed area id so the style picker can tell a click in here from a click outside
|
||||
// (`Window::new` alone would key the area by `Id::new(Some(title))`).
|
||||
// (`Window::new` alone would key the area by `Id::unique(Some(title))`).
|
||||
.id(window_id())
|
||||
.title_bar(false)
|
||||
.fixed_pos(pos)
|
||||
@@ -494,7 +503,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let (hr, _) = ui.allocate_exact_size(vec2(240.0, 40.0), Sense::hover());
|
||||
ui.painter().text(pos2(hr.min.x + 16.0, hr.center().y), Align2::LEFT_CENTER, tr("Custom"), semibold(11.0), t.text);
|
||||
let cr = Rect::from_center_size(pos2(hr.max.x - 20.0, hr.center().y), vec2(24.0, 24.0));
|
||||
let cresp = ui.interact(cr, Id::new("cp_close"), Sense::click());
|
||||
let cresp = ui.interact(cr, Id::unique("cp_close"), Sense::click());
|
||||
icons::paint(ui.painter(), cr.shrink(6.0), Icon::Close, t.icon);
|
||||
if cresp.clicked() {
|
||||
close_now = true;
|
||||
@@ -605,11 +614,11 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let mut changed = false;
|
||||
let mut done = false;
|
||||
// The bar first, so the stops on it take their own clicks.
|
||||
let bresp = ui.interact(bar, Id::new("cp_bar"), Sense::click());
|
||||
let bresp = ui.interact(bar, Id::unique("cp_bar"), Sense::click());
|
||||
for (i, s) in g.stops.clone().iter().enumerate() {
|
||||
let x = bar.min.x + s.position * bar.width();
|
||||
let r = Rect::from_center_size(pos2(x, bar.center().y), vec2(12.0, 18.0));
|
||||
let resp = ui.interact(r, Id::new(("cp_stopk", i)), Sense::click_and_drag());
|
||||
let resp = ui.interact(r, Id::unique(("cp_stopk", i)), Sense::click_and_drag());
|
||||
ui.painter().rect_filled(r, CornerRadius::same(3), doc_c32(ui.ctx(), s.color.with_alpha(1.0)));
|
||||
ui.painter().rect_stroke(
|
||||
r,
|
||||
@@ -773,7 +782,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
}
|
||||
if let Some(color) = edit_color {
|
||||
let mut hsb = ui
|
||||
.data(|d| d.get_temp::<(f32, f32, f32, [u8; 4])>(Id::new("cp_hsb")))
|
||||
.data(|d| d.get_temp::<(f32, f32, f32, [u8; 4])>(Id::unique("cp_hsb")))
|
||||
.filter(|(_, _, _, rgba)| *rgba == color.to_rgba8())
|
||||
.map(|(h, s, b, _)| Hsb { h, s, b })
|
||||
.unwrap_or_else(|| Hsb::from_color(color));
|
||||
@@ -817,7 +826,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
changed = true;
|
||||
done |= d;
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(Id::new("cp_hsb"), (hsb.h, hsb.s, hsb.b, nc.to_rgba8())));
|
||||
ui.data_mut(|d| d.insert_temp(Id::unique("cp_hsb"), (hsb.h, hsb.s, hsb.b, nc.to_rgba8())));
|
||||
// A Display P3 colour sRGB can't show: the canvas (sRGB) shows the nearest one.
|
||||
if app.session.doc().is_ok_and(|d| d.color_profile.conversion_to(figcraft_color::ColorProfile::Srgb).clips(nc)) {
|
||||
gamut_warning(ui, &t);
|
||||
@@ -983,7 +992,7 @@ fn pattern_controls(app: &mut FigApp, ui: &mut Ui, target: &PickerTarget, paint:
|
||||
ui.add_space(16.0);
|
||||
let field = |ui: &mut Ui, key: &str, lead: Lead, value: f64, suffix: &str| match widgets::number_field(
|
||||
ui,
|
||||
Id::new(key),
|
||||
Id::unique(key),
|
||||
lead,
|
||||
Some(value),
|
||||
suffix,
|
||||
@@ -1029,7 +1038,7 @@ fn saved_preset_row(ui: &mut Ui, name: &str) -> Option<PresetAction> {
|
||||
let w = ui.available_width().max(180.0);
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(w, 26.0), Sense::click());
|
||||
let del = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(20.0, 20.0));
|
||||
let del_resp = ui.interact(del, ui.id().with(("cp_preset_del", name)), Sense::click()).tip(tr("Delete preset"));
|
||||
let del_resp = ui.interact(del, ui.scope_id().with(("cp_preset_del", name)), Sense::click()).tip(tr("Delete preset"));
|
||||
let hot = resp.hovered() || del_resp.hovered();
|
||||
if hot {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), t.menu_hover);
|
||||
@@ -1061,7 +1070,7 @@ fn image_presets(app: &mut FigApp, ui: &mut Ui, target: &PickerTarget, paint: &m
|
||||
.find(|(_, f)| *f == filters)
|
||||
.map(|(name, _)| name)
|
||||
.unwrap_or_else(|| if filters.is_identity() { tr("No preset").into() } else { tr("Custom").into() });
|
||||
let name_id = Id::new("cp_preset_name");
|
||||
let name_id = Id::unique("cp_preset_name");
|
||||
let mut naming: Option<String> = ui.data(|d| d.get_temp(name_id));
|
||||
let mut action = None;
|
||||
ui.horizontal(|ui| {
|
||||
|
||||
@@ -476,7 +476,7 @@ pub fn start_draft(app: &mut FigApp, x: f64, y: f64) {
|
||||
|
||||
/// The reply field's id for a thread.
|
||||
fn reply_id(thread: u64) -> Id {
|
||||
Id::new(("comment_reply", thread))
|
||||
Id::unique(("comment_reply", thread))
|
||||
}
|
||||
|
||||
fn set_cursor(ctx: &egui::Context, id: Id, at: usize) {
|
||||
@@ -650,7 +650,7 @@ fn message(
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let ctx = ui.ctx().clone();
|
||||
let id = cx.c.id;
|
||||
let hover_key = Id::new(("comment_msg_hover", id, i));
|
||||
let hover_key = Id::unique(("comment_msg_hover", id, i));
|
||||
let hovered = ctx.data(|d| d.get_temp::<bool>(hover_key)).unwrap_or(false);
|
||||
let indent = 36.0;
|
||||
let block = ui.scope(|ui| {
|
||||
@@ -663,10 +663,10 @@ fn message(
|
||||
ui.label(egui::RichText::new(when).font(regular(11.0)).color(t.text_tertiary));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if m.author == cx.me {
|
||||
let menu = Id::new(("comment_msg_more_menu", id, i));
|
||||
let menu = Id::unique(("comment_msg_more_menu", id, i));
|
||||
let more = hover_button(
|
||||
ui,
|
||||
Id::new(("comment_msg_more", id, i)),
|
||||
Id::unique(("comment_msg_more", id, i)),
|
||||
Icon::Dots,
|
||||
hovered || egui::Popup::is_id_open(&ctx, menu),
|
||||
tr("More"),
|
||||
@@ -682,10 +682,10 @@ fn message(
|
||||
}
|
||||
});
|
||||
}
|
||||
let menu = Id::new(("comment_msg_react_menu", id, i));
|
||||
let menu = Id::unique(("comment_msg_react_menu", id, i));
|
||||
let react = hover_button(
|
||||
ui,
|
||||
Id::new(("comment_msg_react", id, i)),
|
||||
Id::unique(("comment_msg_react", id, i)),
|
||||
Icon::Reaction,
|
||||
hovered || egui::Popup::is_id_open(&ctx, menu),
|
||||
tr("Add reaction"),
|
||||
@@ -715,7 +715,7 @@ fn message(
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(indent);
|
||||
ui.vertical(|ui| {
|
||||
if composer(ui, Id::new(("comment_edit", id, i)), text, tr("Edit comment"), cx.people, cx.me, pick) {
|
||||
if composer(ui, Id::unique(("comment_edit", id, i)), text, tr("Edit comment"), cx.people, cx.me, pick) {
|
||||
let mut p = message_params(id, i);
|
||||
p["text"] = json!(text.trim());
|
||||
*act = Some(Act::Run("comment.edit", p));
|
||||
@@ -828,12 +828,12 @@ pub fn popovers(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let me = me(app);
|
||||
let mut pick = std::mem::take(&mut app.ui.comments.mention);
|
||||
let mut post = false;
|
||||
egui::Area::new(Id::new("comment_draft")).order(egui::Order::Foreground).fixed_pos(popover_pos(app.to_screen(x, y), canvas)).show(
|
||||
egui::Area::new(Id::unique("comment_draft")).order(egui::Order::Foreground).fixed_pos(popover_pos(app.to_screen(x, y), canvas)).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
popover_frame(&t).show(ui, |ui| {
|
||||
ui.set_width(POPOVER_W - 24.0);
|
||||
post = composer(ui, Id::new("comment_draft_text"), &mut text, tr("Add a comment"), &people, &me, &mut pick);
|
||||
post = composer(ui, Id::unique("comment_draft_text"), &mut text, tr("Add a comment"), &people, &me, &mut pick);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -877,7 +877,7 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun
|
||||
let mut pick = std::mem::take(&mut app.ui.comments.mention);
|
||||
let mut act: Option<Act> = None;
|
||||
let cx = ThreadCtx { c: &c, me: &me, people: &people };
|
||||
egui::Area::new(Id::new("comment_thread")).order(egui::Order::Foreground).fixed_pos(popover_pos(anchor, bounds)).show(ctx, |ui| {
|
||||
egui::Area::new(Id::unique("comment_thread")).order(egui::Order::Foreground).fixed_pos(popover_pos(anchor, bounds)).show(ctx, |ui| {
|
||||
popover_frame(&t).show(ui, |ui| {
|
||||
ui.set_width(POPOVER_W - 24.0);
|
||||
// Header: resolve, more, close.
|
||||
@@ -934,7 +934,7 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun
|
||||
}
|
||||
Some(Act::CopyLink) => {
|
||||
if let Some(link) = app.run("comment.link", json!({"id": id})).and_then(|v| v.get("link").and_then(Value::as_str).map(str::to_string)) {
|
||||
app.services.clipboard_set_text(&link);
|
||||
app.clipboard_set_text(&link);
|
||||
app.toast(tr("Link copied"));
|
||||
}
|
||||
}
|
||||
@@ -1051,7 +1051,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(16.0);
|
||||
let w = ui.available_width() - 16.0;
|
||||
if let Some(s) = crate::widgets::text_field(ui, Id::new("comment_search"), &app.ui.comments.search, w, tr("Search comments")) {
|
||||
if let Some(s) = crate::widgets::text_field(ui, Id::unique("comment_search"), &app.ui.comments.search, w, tr("Search comments")) {
|
||||
app.ui.comments.search = s;
|
||||
}
|
||||
});
|
||||
@@ -1178,7 +1178,7 @@ pub fn presenter(app: &mut FigApp, ctx: &egui::Context, frame: NodeId, place: cr
|
||||
let mut clicked = None;
|
||||
for p in &pins {
|
||||
let r = pin_rect(p.at);
|
||||
egui::Area::new(Id::new(("present_comment_pin", p.id))).order(egui::Order::Foreground).fixed_pos(r.min).show(ctx, |ui| {
|
||||
egui::Area::new(Id::unique(("present_comment_pin", p.id))).order(egui::Order::Foreground).fixed_pos(r.min).show(ctx, |ui| {
|
||||
let (rr, resp) = ui.allocate_exact_size(r.size(), Sense::click());
|
||||
paint_pin(ui.painter(), rr, p, open == Some(p.id) || resp.hovered());
|
||||
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
|
||||
|
||||
@@ -79,7 +79,8 @@ fn combine_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
|
||||
fn description_ui(app: &mut FigApp, ui: &mut Ui, id: NodeId, description: &str) {
|
||||
widgets::separator(ui);
|
||||
widgets::sublabels(ui, tr("Description"), None);
|
||||
if let Some(new) = widgets::multiline_field(ui, Id::new(("comp_desc", id)), description, tr("Describe how and when to use this component"), 3) {
|
||||
if let Some(new) = widgets::multiline_field(ui, Id::unique(("comp_desc", id)), description, tr("Describe how and when to use this component"), 3)
|
||||
{
|
||||
app.run("node.set", json!({"id": id, "props": {"description": new.chars().take(10_000).collect::<String>()}}));
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
@@ -91,7 +92,7 @@ fn description_ui(app: &mut FigApp, ui: &mut Ui, id: NodeId, description: &str)
|
||||
pub(crate) fn local_components(app: &FigApp, ui: &Ui, doc: &Document) -> std::sync::Arc<Vec<(NodeId, String)>> {
|
||||
type Cached = ((u64, u64), std::sync::Arc<Vec<(NodeId, String)>>);
|
||||
let key = app.session.ds().map(|d| (d.uid, d.revision)).unwrap_or_default();
|
||||
let id = Id::new("component_panel_local_components");
|
||||
let id = Id::unique("component_panel_local_components");
|
||||
if let Some((k, list)) = ui.data(|d| d.get_temp::<Cached>(id))
|
||||
&& k == key
|
||||
{
|
||||
@@ -267,7 +268,7 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId) {
|
||||
let header = row_rect(ui, 32.0, |ui| {
|
||||
let (ir, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover());
|
||||
icons::paint(ui.painter(), ir, Icon::ComponentSet, COMPONENT);
|
||||
if let Some(nn) = widgets::text_field(ui, Id::new(("vprop_name", owner, k.as_str())), k, 110.0, tr("Name")) {
|
||||
if let Some(nn) = widgets::text_field(ui, Id::unique(("vprop_name", owner, k.as_str())), k, 110.0, tr("Name")) {
|
||||
app.run("component.editProperty", json!({"id": owner, "name": k, "newName": nn}));
|
||||
}
|
||||
let def = defaults.get(k).or(vals.first()).cloned().unwrap_or_default();
|
||||
@@ -292,7 +293,7 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId) {
|
||||
row(ui, 30.0, |ui| {
|
||||
ui.add_space(22.0);
|
||||
for v in &chunk {
|
||||
if let Some(nv) = widgets::text_field(ui, Id::new(("vprop_val", owner, k.as_str(), v.as_str())), v, 62.0, "")
|
||||
if let Some(nv) = widgets::text_field(ui, Id::unique(("vprop_val", owner, k.as_str(), v.as_str())), v, 62.0, "")
|
||||
&& nv != *v
|
||||
{
|
||||
app.run("component.editProperty", json!({"id": owner, "name": k, "value": v, "newValue": nv}));
|
||||
@@ -320,7 +321,7 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId) {
|
||||
row(ui, 32.0, |ui| {
|
||||
let (ir, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover());
|
||||
icons::paint(ui.painter(), ir, type_icon(d), COMPONENT);
|
||||
if let Some(nn) = widgets::text_field(ui, Id::new(("prop_name", owner, k.as_str())), k, 96.0, tr("Name")) {
|
||||
if let Some(nn) = widgets::text_field(ui, Id::unique(("prop_name", owner, k.as_str())), k, 96.0, tr("Name")) {
|
||||
app.run("component.editProperty", json!({"id": owner, "name": k, "newName": nn}));
|
||||
}
|
||||
match d {
|
||||
@@ -330,7 +331,7 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId) {
|
||||
}
|
||||
}
|
||||
PropDef::Text { default } => {
|
||||
if let Some(v) = widgets::text_field(ui, Id::new(("prop_def", owner, k.as_str())), default, 84.0, tr("Default")) {
|
||||
if let Some(v) = widgets::text_field(ui, Id::unique(("prop_def", owner, k.as_str())), default, 84.0, tr("Default")) {
|
||||
app.run("component.editProperty", json!({"id": owner, "name": k, "default": v}));
|
||||
}
|
||||
}
|
||||
@@ -701,7 +702,7 @@ fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node, comps
|
||||
PropDef::Text { .. } => {
|
||||
crate::variable_ui::bindable(app, ui, &[id], &bind_field, VariableType::String, w, |app, ui| {
|
||||
let cur = v.as_str().unwrap_or_default().to_string();
|
||||
if let Some(ns) = widgets::text_field(ui, Id::new(("iprop", id, k.as_str())), &cur, w, "")
|
||||
if let Some(ns) = widgets::text_field(ui, Id::unique(("iprop", id, k.as_str())), &cur, w, "")
|
||||
&& ns != cur
|
||||
{
|
||||
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): ns}}));
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
//! The right-click menu on a layer: the copy commands sit in a Copy as submenu under Paste to
|
||||
//! replace; "Copy link to selection" puts `figcraft://node/<id>` on the clipboard and says so, and
|
||||
//! with nothing selected the command copies nothing.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use egui::Pos2;
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::live_tests::{flat, has_text, text_center};
|
||||
use crate::present_tests::id;
|
||||
|
||||
/// A clipboard that keeps what was copied where the test can read it.
|
||||
struct Copied(Arc<Mutex<Vec<String>>>);
|
||||
|
||||
impl crate::Services for Copied {
|
||||
fn clipboard_set_text(&mut self, s: &str) {
|
||||
if let Ok(mut copied) = self.0.lock() {
|
||||
copied.push(s.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_context_menu_groups_the_copy_commands_under_copy_as() {
|
||||
let mut s = Session::new();
|
||||
let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200, "name": "หน้าแรก"})).unwrap());
|
||||
let copied = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut u = Ui::new(s);
|
||||
u.app.services = Box::new(Copied(copied.clone()));
|
||||
u.frame(vec![]);
|
||||
u.app.ui.context_menu = Some((Pos2::new(700.0, 300.0), vec![f]));
|
||||
u.frame(vec![]);
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
// A row under Paste to replace; the items are in its submenu, not in the menu itself.
|
||||
let y = |s: &str| text_center(&shapes, s).y;
|
||||
assert!(y("Paste to replace") < y("Copy as") && y("Copy as") < y("Bring to front"), "Copy as sits under Paste to replace");
|
||||
for item in ["Copy as CSS", "Copy as SVG", "Copy as PNG", "Copy link to selection"] {
|
||||
assert!(!has_text(&shapes, item), "{item} is inside the submenu");
|
||||
}
|
||||
let at = text_center(&shapes, "Copy as");
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
for item in ["Copy as CSS", "Copy as SVG", "Copy as PNG", "Copy link to selection"] {
|
||||
assert!(has_text(&shapes, item), "{item} is in the submenu");
|
||||
}
|
||||
let at = text_center(&shapes, "Copy link to selection");
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
assert_eq!(*copied.lock().unwrap(), vec![format!("figcraft://node/{}", f.0)], "the link to the frame");
|
||||
assert_eq!(u.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("Link copied"));
|
||||
assert!(u.app.ui.context_menu.is_none(), "the menu closes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copying_a_link_with_nothing_selected_copies_nothing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let copied = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut u = Ui::new(s);
|
||||
u.app.services = Box::new(Copied(copied.clone()));
|
||||
crate::menus::invoke(&mut u.app, "edit.copyLink");
|
||||
assert!(copied.lock().unwrap().is_empty(), "no link to node 0");
|
||||
assert!(u.app.ui.toast.is_none());
|
||||
}
|
||||
+811
-108
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,657 @@
|
||||
//! Screenshot capture (the local completion-slot adapter): per-request identity and reverse
|
||||
//! completion, cancellation/late delivery, budget admission, straight-alpha round-trips and zero
|
||||
//! retained bytes after draining. Driven headless through the real UI pass, so geometry comes from
|
||||
//! the frame that issues the capture, not from a stale logic tick.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_doc::NodeId;
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::control::{CaptureSpec, ControlReply, ControlRequest};
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
/// Queue a `ui.screenshot` request in the test app and return its reply receiver.
|
||||
fn push(u: &mut Ui, id: u64, params: serde_json::Value) -> std::sync::mpsc::Receiver<ControlReply> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
u.app.control_queue.push(ControlRequest { id: json!(id), method: "ui.screenshot".into(), params, reply: tx, state: Default::default() });
|
||||
rx
|
||||
}
|
||||
|
||||
/// Run UI passes until every admitted capture has been issued (settled on real UI passes).
|
||||
fn settle_to_issue(u: &mut Ui, n: usize) {
|
||||
for _ in 0..12 {
|
||||
u.frame(vec![]);
|
||||
if u.app.capture.shots.len() == n && u.app.capture.shots.iter().all(|r| r.issued) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("{n} captures were not issued: {} admitted", u.app.capture.shots.len());
|
||||
}
|
||||
|
||||
/// A real changed viewport size, without allocating a readback image of that size.
|
||||
fn resized_frame(u: &mut Ui, size: egui::Vec2) -> egui::FullOutput {
|
||||
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() };
|
||||
let app = &mut u.app;
|
||||
let mut out = u.ctx.run_ui(input, |ui| app.ui(ui));
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether any viewport in the frame output issues a `Screenshot` command.
|
||||
fn has_screenshot(out: &egui::FullOutput) -> bool {
|
||||
out.viewport_output.values().any(|v| v.commands.iter().any(|c| matches!(c, egui::ViewportCommand::Screenshot(_))))
|
||||
}
|
||||
|
||||
/// Asserts reverse capture completion replies only to the matching request, then drains both
|
||||
/// requests.
|
||||
#[test]
|
||||
fn two_captures_correlate_by_request_across_reverse_completion() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let first = push(&mut u, 1, json!({}));
|
||||
let second = push(&mut u, 2, json!({}));
|
||||
settle_to_issue(&mut u, 2);
|
||||
let [a, b] = [0, 1].map(|i| u.app.capture.shots[i].spec.expect("geometry"));
|
||||
assert_eq!(a.viewport, b.viewport);
|
||||
assert!(a.size_px[0] > 0 && a.size_px[1] > 0);
|
||||
// The second capture arrives first; only its own request is completed.
|
||||
let slot_b = u.app.capture.shots[1].slot.clone().expect("issued");
|
||||
slot_b.complete(Arc::new(egui::ColorImage::filled(b.size_px, egui::Color32::GREEN)));
|
||||
u.frame(vec![]);
|
||||
let got = second.try_recv().expect("the second capture's reply");
|
||||
assert_eq!(got.id, json!(2));
|
||||
assert!(first.try_recv().is_err(), "the first is still in flight");
|
||||
assert_eq!(u.app.capture.shots.len(), 1);
|
||||
let slot_a = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
slot_a.complete(Arc::new(egui::ColorImage::filled(a.size_px, egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
let got = first.try_recv().expect("the first capture's reply");
|
||||
assert_eq!(got.id, json!(1));
|
||||
assert!(u.app.capture.shots.is_empty(), "no retained requests");
|
||||
}
|
||||
|
||||
/// Asserts a cancelled capture gets no reply and its slot is released.
|
||||
#[test]
|
||||
fn a_cancelled_capture_never_replies_or_writes() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 3, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
u.app.capture.shots[0].state.cancel_if_open();
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::BLUE)));
|
||||
u.frame(vec![]);
|
||||
assert!(rx.try_recv().is_err(), "a cancelled transport gets no reply");
|
||||
assert!(u.app.capture.shots.is_empty(), "the slot is released");
|
||||
}
|
||||
|
||||
/// A unique directory for a commit test; the caller removes it.
|
||||
fn commit_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-capture-commit-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
dir
|
||||
}
|
||||
|
||||
/// Asserts cancellation after encoding still prevents the final file write and reply.
|
||||
#[test]
|
||||
fn a_cancellation_after_encoding_prevents_the_final_write() {
|
||||
let dir = commit_dir("cancelled");
|
||||
let path = dir.join("shot.png");
|
||||
let gate = crate::control::RequestGate::new();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let clock = crate::FrameClock::default();
|
||||
let img = egui::ColorImage::filled([2, 2], egui::Color32::RED);
|
||||
// Encoding is complete before the transport cancels: the final gate must still refuse the file.
|
||||
let encoded = super::encode_shot(&img, Some(path.to_str().expect("utf-8 path"))).expect("encoded");
|
||||
assert!(!path.exists(), "encoding alone does not write");
|
||||
assert_eq!(gate.cancel_if_open(), crate::control::RequestState::Cancelled);
|
||||
assert!(!super::commit_shot(&gate, &json!(40), &tx, 100.0, &clock, Ok(encoded)), "a cancelled request does not commit");
|
||||
assert!(!path.exists(), "the cancellation landed before the final write");
|
||||
assert!(rx.try_recv().is_err(), "a cancelled transport gets no reply");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Asserts a capture that arrives past its deadline reports a timeout and writes no PNG.
|
||||
#[test]
|
||||
fn a_real_arrival_that_crosses_the_deadline_does_not_write_its_png() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let dir = commit_dir("settle-expired");
|
||||
let path = dir.join("shot.png");
|
||||
let rx = push(&mut u, 60, json!({"path": path.to_string_lossy()}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
let deadline = u.app.capture.shots[0].deadline;
|
||||
let epoch = u.app.capture.shots[0].epoch;
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
// A frame's saved time may precede encoding; the final write must use a fresh clock.
|
||||
let stale_now = u.app.clock.now();
|
||||
u.app.clock.set_test_now(Some(deadline + 1.0));
|
||||
super::drain_completed(&mut u.app, &u.ctx, egui::ViewportId::ROOT, stale_now, epoch);
|
||||
let reply = rx.try_recv().expect("the late commit reports a timeout");
|
||||
assert!(reply.result.unwrap_err().contains("didn't deliver"));
|
||||
assert!(!path.exists(), "the final deadline check must precede the PNG write");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Asserts an expiry during encoding reports the timeout under the gate, marks the request
|
||||
/// replied and writes no file.
|
||||
#[test]
|
||||
fn an_expiry_during_encoding_prevents_the_final_write_and_reports_timeout() {
|
||||
let dir = commit_dir("expired");
|
||||
let path = dir.join("shot.png");
|
||||
let gate = crate::control::RequestGate::new();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut clock = crate::FrameClock::default();
|
||||
clock.set_test_now(Some(5.0));
|
||||
let img = egui::ColorImage::filled([2, 2], egui::Color32::RED);
|
||||
let encoded = super::encode_shot(&img, Some(path.to_str().expect("utf-8 path"))).expect("encoded");
|
||||
// The gate is open, but the fresh clock read under it is already at the deadline.
|
||||
assert!(super::commit_shot(&gate, &json!(41), &tx, 5.0, &clock, Ok(encoded)), "the open request is settled once");
|
||||
let reply = rx.try_recv().expect("a timeout reply");
|
||||
assert_eq!(reply.id, json!(41));
|
||||
assert!(reply.result.unwrap_err().contains("didn't deliver"), "the late commit reports the same timeout");
|
||||
assert!(!path.exists(), "an expired request never writes its file");
|
||||
assert!(gate.is_replied(), "the timeout reply was committed under the gate");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Asserts a commit before the deadline writes the file and queues one reply, and a second
|
||||
/// commit is refused.
|
||||
#[test]
|
||||
fn a_commit_before_the_deadline_writes_and_queues_its_reply_once() {
|
||||
let dir = commit_dir("committed");
|
||||
let path = dir.join("shot.png");
|
||||
let gate = crate::control::RequestGate::new();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut clock = crate::FrameClock::default();
|
||||
clock.set_test_now(Some(1.0));
|
||||
let img = egui::ColorImage::filled([2, 2], egui::Color32::GREEN);
|
||||
let encoded = super::encode_shot(&img, Some(path.to_str().expect("utf-8 path"))).expect("encoded");
|
||||
assert!(super::commit_shot(&gate, &json!(42), &tx, 10.0, &clock, Ok(encoded)), "an open request commits");
|
||||
let reply = rx.try_recv().expect("the committed reply");
|
||||
assert_eq!(reply.id, json!(42));
|
||||
assert_eq!(reply.result.expect("written")["path"], json!(path.to_string_lossy()));
|
||||
assert!(path.is_file(), "the file is written under the gate");
|
||||
assert!(gate.is_replied(), "a timeout now consumes the committed reply");
|
||||
// A second commit is refused: the gate is no longer open.
|
||||
let again = super::encode_shot(&img, Some(path.to_str().expect("utf-8 path"))).expect("encoded");
|
||||
assert!(!super::commit_shot(&gate, &json!(43), &tx, 10.0, &clock, Ok(again)));
|
||||
assert!(rx.try_recv().is_err(), "no duplicate reply");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Asserts a capture past its deadline sends one timeout reply, releases its slot, and late
|
||||
/// pixels are ignored.
|
||||
#[test]
|
||||
fn a_capture_after_its_deadline_replies_once_and_late_pixels_are_inert() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 4, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
u.advance_clock(crate::control::SHOT_TIMEOUT + 1.0);
|
||||
u.frame(vec![]);
|
||||
let reply = rx.try_recv().expect("timed out");
|
||||
assert_eq!(reply.id, json!(4));
|
||||
assert!(reply.result.unwrap_err().contains("didn't deliver"), "one timeout reply");
|
||||
assert!(u.app.capture.shots.is_empty(), "released");
|
||||
// The renderer finishing afterwards finds a closed slot: no reply, no write, no panic.
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
assert!(rx.try_recv().is_err(), "a late capture is inert");
|
||||
}
|
||||
|
||||
/// Asserts the snapshot count budget rejects an over-budget request before issuing, and every
|
||||
/// admitted capture still completes under its own id.
|
||||
#[test]
|
||||
fn a_snapshot_batch_is_capped_before_issuing_over_the_count_budget() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let mut rxs: Vec<_> = (0..crate::control::MAX_SHOTS as u64).map(|i| push(&mut u, 10 + i, json!({}))).collect();
|
||||
settle_to_issue(&mut u, crate::control::MAX_SHOTS);
|
||||
let over = push(&mut u, 99, json!({}));
|
||||
u.frame(vec![]);
|
||||
let reply = over.try_recv().expect("rejected at admission");
|
||||
assert!(reply.result.unwrap_err().contains("too many screenshots"), "budget error");
|
||||
assert_eq!(u.app.capture.shots.len(), crate::control::MAX_SHOTS);
|
||||
// Every admitted capture still completes with its own identity. Each drain removes its
|
||||
// request, so always complete the first remaining one: the vector shifts under the loop.
|
||||
for (i, rx) in rxs.iter_mut().enumerate() {
|
||||
let spec = u.app.capture.shots.first().expect("one left").spec.expect("geometry");
|
||||
let slot = u.app.capture.shots.first().and_then(|r| r.slot.clone()).expect("issued");
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
assert_eq!(rx.try_recv().expect("answered").id, json!(10 + i as u64), "request {i} keeps its identity");
|
||||
}
|
||||
rxs.clear();
|
||||
}
|
||||
|
||||
/// Asserts an undersized readback is not accepted but reissued with one retry and no reply.
|
||||
#[test]
|
||||
fn an_undersized_readback_is_reissued_instead_of_accepted() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 30, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
assert!(spec.size_px[0] > 2, "room for a two-pixel undersized readback");
|
||||
// Smaller by two pixels on one axis: a scale mismatch, not the admitted surface.
|
||||
slot.complete(Arc::new(egui::ColorImage::filled([spec.size_px[0] - 2, spec.size_px[1]], egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
assert!(rx.try_recv().is_err(), "the undersized pixels are not accepted");
|
||||
let r = u.app.capture.shots.first().expect("reissued");
|
||||
assert_eq!(r.retries, 1, "one retry, not an error");
|
||||
assert!(!r.issued, "waits for the settled geometry again");
|
||||
}
|
||||
|
||||
/// Asserts a one-pixel rounding difference is accepted as the same surface.
|
||||
#[test]
|
||||
fn a_one_pixel_rounding_difference_is_still_the_same_surface() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 31, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
slot.complete(Arc::new(egui::ColorImage::filled([spec.size_px[0] - 1, spec.size_px[1] + 1], egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
let reply = rx.try_recv().expect("a pixel of rounding is accepted");
|
||||
assert_eq!(reply.id, json!(31));
|
||||
assert!(reply.result.is_ok());
|
||||
assert!(u.app.capture.shots.is_empty(), "released");
|
||||
}
|
||||
|
||||
/// Asserts an A→B→A tab switch invalidates the admitted capture with "document changed".
|
||||
#[test]
|
||||
fn a_document_a_to_b_to_a_switch_is_not_the_admitted_capture() {
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.new", &json!({"name": "A"})).unwrap();
|
||||
s.execute("file.new", &json!({"name": "B"})).unwrap();
|
||||
let (a, b) = (s.docs.iter().position(|d| d.doc.name == "A").expect("file A"), s.docs.iter().position(|d| d.doc.name == "B").expect("file B"));
|
||||
let mut u = Ui::new(s);
|
||||
u.app.session.active = a;
|
||||
let rx = push(&mut u, 32, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
// A→B→A before the callback is drained: the final UID is A again, but its pixels were never
|
||||
// what this capture asked for.
|
||||
assert!(u.app.run("doc.switch", json!({"index": b})).is_some());
|
||||
assert!(u.app.run("doc.switch", json!({"index": a})).is_some());
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
let reply = rx.try_recv().expect("answered");
|
||||
assert!(reply.result.unwrap_err().contains("document changed"), "the A→B→A switch invalidates the capture");
|
||||
assert!(u.app.capture.shots.is_empty(), "released");
|
||||
}
|
||||
|
||||
/// Asserts a geometry change bumps the capture epoch and reissues instead of accepting old
|
||||
/// pixels.
|
||||
#[test]
|
||||
fn a_geometry_change_reissues_instead_of_accepting_old_pixels() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 5, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let old = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
// A resize between issuance and arrival bumps the epoch.
|
||||
u.app
|
||||
.capture
|
||||
.geometry
|
||||
.insert(egui::ViewportId::ROOT, (CaptureSpec { size_px: [old.size_px[0] + 1, old.size_px[1]], ..old }, u.app.capture.epoch.wrapping_add(1)));
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(old.size_px, egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
assert!(rx.try_recv().is_err(), "the old pixels are not accepted");
|
||||
let r = u.app.capture.shots.first().expect("reissued");
|
||||
assert_eq!(r.retries, 1, "one retry, not an error");
|
||||
assert!(!r.issued, "waits for the settled geometry again");
|
||||
}
|
||||
|
||||
/// Asserts a translucent pixel round-trips through the PNG as straight RGBA without
|
||||
/// darkening.
|
||||
#[test]
|
||||
fn a_translucent_pixel_round_trips_straight_rgba() {
|
||||
let img = egui::ColorImage::from_rgba_unmultiplied([1, 1], &[128, 64, 32, 128]);
|
||||
let reply = super::shot_reply(&img, None).expect("encoded");
|
||||
use base64::Engine as _;
|
||||
let png = base64::engine::general_purpose::STANDARD.decode(reply["data"].as_str().expect("data")).expect("base64");
|
||||
let decoded = image::load_from_memory(&png).expect("png").to_rgba8();
|
||||
assert_eq!(decoded.get_pixel(0, 0).0, [128, 64, 32, 128], "straight alpha is not darkened");
|
||||
}
|
||||
|
||||
/// Asserts a capture is not issued before three completed real UI frames; the following
|
||||
/// completed frame issues it.
|
||||
#[test]
|
||||
fn a_capture_is_not_issued_before_three_completed_real_ui_frames() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let _rx = push(&mut u, 6, json!({}));
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.capture.shots.len(), 1, "admitted");
|
||||
assert!(!u.app.capture.shots[0].issued, "not on the frame that anchors the count");
|
||||
u.frame(vec![]);
|
||||
assert!(!u.app.capture.shots[0].issued, "not on the second frame");
|
||||
u.frame(vec![]);
|
||||
assert!(!u.app.capture.shots[0].issued, "the third frame has not completed when its pass 0 runs");
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.capture.shots[0].issued, "issued once three frames have presented their layout");
|
||||
}
|
||||
|
||||
/// Asserts a discarded sizing pass does not count toward capture settling, and the next
|
||||
/// completed frame issues it.
|
||||
#[test]
|
||||
fn a_discarded_sizing_pass_does_not_count_as_a_settled_capture_frame() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let _rx = push(&mut u, 33, json!({}));
|
||||
// Each `frame_raw_with_discard` presents a layout after rerunning a discarded first pass.
|
||||
// Only that completed frame counts; the discarded pass must not make the capture look settled.
|
||||
u.frame_raw_with_discard(egui::RawInput::default());
|
||||
u.frame_raw_with_discard(egui::RawInput::default());
|
||||
u.frame_raw_with_discard(egui::RawInput::default());
|
||||
assert!(!u.app.capture.shots[0].issued, "three multipass frames present only two prior layouts here; the third pass 0 is not settled");
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.capture.shots[0].issued, "the next completed frame issues the capture");
|
||||
}
|
||||
|
||||
/// Asserts pixels delivered while hidden force a draining paint and are answered rather than
|
||||
/// timed out.
|
||||
#[test]
|
||||
fn a_hidden_window_that_delivers_pixels_is_asked_to_paint_the_draining_pass() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 7, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
// The renderer completes the readback while the window is hidden; the screenshot command that
|
||||
// produced it is drained, so without a new forced paint the request would only time out.
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
let mut input = egui::RawInput::default();
|
||||
input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { minimized: Some(true), ..Default::default() });
|
||||
let ctx = u.ctx.clone();
|
||||
let out = ctx.run_logic(&input, |ctx| crate::control::background(&mut u.app, ctx));
|
||||
let asked = out
|
||||
.viewport_commands
|
||||
.get(&egui::ViewportId::ROOT)
|
||||
.is_some_and(|cmds| cmds.iter().any(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)));
|
||||
assert!(asked, "the completed pixels keep the hidden window painting");
|
||||
// The forced paint drains the slot; the deadline is untouched.
|
||||
u.frame(vec![]);
|
||||
let reply = rx.try_recv().expect("the completed capture is answered, not timed out");
|
||||
assert_eq!(reply.id, json!(7));
|
||||
assert!(reply.result.unwrap()["width"].as_u64().is_some(), "written or returned");
|
||||
assert!(u.app.capture.shots.is_empty(), "released");
|
||||
}
|
||||
|
||||
/// Asserts a capture for a window with unknown visibility is parked with its deadline and a
|
||||
/// paint request, then times out once.
|
||||
#[test]
|
||||
fn a_capture_for_a_window_with_unknown_visibility_is_admitted_with_a_deadline() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 40, json!({}));
|
||||
// A minimised window may report no `visible` flag at all. The request must still be parked
|
||||
// with its deadline rather than left in `control_queue` waiting for a frame that never draws.
|
||||
let mut input = egui::RawInput::default();
|
||||
// Neither `visible` nor `minimized` is reported: the platform has not said whether the
|
||||
// window draws, so waiting for its frame would leave the request queued indefinitely.
|
||||
input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default());
|
||||
let ctx = u.ctx.clone();
|
||||
let out = ctx.run_logic(&input, |ctx| crate::control::background(&mut u.app, ctx));
|
||||
assert_eq!(u.app.capture.shots.len(), 1, "admitted, not left queued");
|
||||
assert!(u.app.control_queue.is_empty(), "the parked request no longer waits in the input queue");
|
||||
let r = &u.app.capture.shots[0];
|
||||
assert!(!r.issued);
|
||||
let now = u.app.clock.now();
|
||||
assert!((r.deadline - (now + crate::control::SHOT_TIMEOUT)).abs() < 1e-6, "the hidden request has its deadline");
|
||||
let asked = out
|
||||
.viewport_commands
|
||||
.get(&egui::ViewportId::ROOT)
|
||||
.is_some_and(|cmds| cmds.iter().any(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)));
|
||||
assert!(asked, "the parked capture asks the window to paint");
|
||||
// The deadline still answers the transport when no frame draws.
|
||||
u.advance_clock(crate::control::SHOT_TIMEOUT + 2.0);
|
||||
u.frame(vec![]);
|
||||
let reply = rx.try_recv().expect("the parked capture times out");
|
||||
assert_eq!(reply.id, json!(40));
|
||||
assert!(reply.result.unwrap_err().contains("didn't deliver"));
|
||||
assert!(u.app.capture.shots.is_empty(), "released");
|
||||
}
|
||||
|
||||
/// Asserts a completed capture is rejected when current geometry is unavailable, failing
|
||||
/// closed.
|
||||
#[test]
|
||||
fn a_completed_capture_is_rejected_when_current_geometry_is_unavailable() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 41, json!({}));
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
// A surface that cannot represent geometry at all (smaller than one point here). The pixels
|
||||
// may still match the old admitted spec, but they cannot be proven current: fail closed.
|
||||
u.advance_clock(1.0);
|
||||
let input = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(0.0, 0.0))),
|
||||
time: Some(1.0),
|
||||
..Default::default()
|
||||
};
|
||||
let app = &mut u.app;
|
||||
let ctx = u.ctx.clone();
|
||||
let mut out = ctx.run_ui(input, |ui| crate::control::drain(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let reply = rx.try_recv().expect("answered instead of accepted");
|
||||
assert_eq!(reply.id, json!(41));
|
||||
assert!(reply.result.unwrap_err().contains("geometry is unavailable"), "fail closed");
|
||||
assert!(u.app.capture.shots.is_empty(), "released");
|
||||
}
|
||||
|
||||
/// Asserts a tab switch while a capture settles invalidates it with "document changed".
|
||||
#[test]
|
||||
fn a_capture_belongs_to_the_document_admitted_not_the_one_showing_when_it_arrives() {
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.new", &json!({"name": "A"})).unwrap();
|
||||
s.execute("file.new", &json!({"name": "B"})).unwrap();
|
||||
let (a, b) = (s.docs.iter().position(|d| d.doc.name == "A").expect("file A"), s.docs.iter().position(|d| d.doc.name == "B").expect("file B"));
|
||||
let mut u = Ui::new(s);
|
||||
u.app.session.active = a;
|
||||
let rx = push(&mut u, 8, json!({}));
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.capture.shots.len(), 1, "admitted against A");
|
||||
// The tab switches while the capture settles: the pixels that arrive are B's, not A's.
|
||||
u.app.session.active = b;
|
||||
settle_to_issue(&mut u, 1);
|
||||
let spec = u.app.capture.shots[0].spec.expect("geometry");
|
||||
let slot = u.app.capture.shots[0].slot.clone().expect("issued");
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
u.frame(vec![]);
|
||||
let reply = rx.try_recv().expect("answered");
|
||||
assert!(reply.result.unwrap_err().contains("document changed"), "a tab switch invalidates the capture");
|
||||
assert!(u.app.capture.shots.is_empty(), "released");
|
||||
}
|
||||
|
||||
/// Asserts the capture budget covers the encoding and reply peaks, not just pixels, and an
|
||||
/// over-budget resize is rejected before readback.
|
||||
#[test]
|
||||
fn the_capture_budget_counts_the_encoding_peak_not_only_the_pixels() {
|
||||
let fits = CaptureSpec { viewport: egui::ViewportId::ROOT, size_px: [4096, 4096], pixels_per_point: 1.0, zoom: 1.0 };
|
||||
let over = CaptureSpec { viewport: egui::ViewportId::ROOT, size_px: [5000, 5000], pixels_per_point: 1.0, zoom: 1.0 };
|
||||
// The encode phase holds the readback and the straight-RGBA copy while the PNG is built; the
|
||||
// reply phase holds the readback and PNG plus the base64 string after that copy is dropped.
|
||||
let raw = fits.bytes().expect("pixels");
|
||||
let png = raw + super::SHOT_PNG_OVERHEAD;
|
||||
let encode_phase = raw * 2 + png;
|
||||
let reply_phase = raw + png + (png / 3 + 1) * 4;
|
||||
assert_eq!(fits.cost(), Some(encode_phase.max(reply_phase)), "cost covers both live encoding phases");
|
||||
// 5000² × 4 is under the per-image pixel budget but its PNG copy and base64 reply are not.
|
||||
assert!(over.bytes().expect("pixels") <= super::MAX_SHOT_IMAGE_BYTES);
|
||||
assert!(over.cost().expect("cost") > super::MAX_SHOT_TOTAL_BYTES, "the reply is part of the bound");
|
||||
assert!(fits.cost().expect("cost") <= super::MAX_SHOT_TOTAL_BYTES);
|
||||
// The real resize path enforces that bound, even after admission at a smaller size.
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push(&mut u, 9, json!({}));
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.capture.shots.len(), 1, "admitted");
|
||||
let out = resized_frame(&mut u, egui::vec2(5000.0, 5000.0));
|
||||
let reply = rx.try_recv().expect("rejected");
|
||||
assert!(reply.result.unwrap_err().contains("capture budget"), "the encoding peak is refused");
|
||||
assert!(u.app.capture.shots.is_empty(), "nothing retained");
|
||||
assert!(!has_screenshot(&out), "over-budget growth is rejected before any readback command");
|
||||
}
|
||||
|
||||
/// Asserts resizing settling captures rechecks aggregate reserved bytes, rejects the request
|
||||
/// that no longer fits, and makes the survivor reserve its real cost.
|
||||
#[test]
|
||||
fn resizing_settling_captures_rechecks_the_aggregate_reserved_bytes() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let a = push(&mut u, 81, json!({}));
|
||||
let b = push(&mut u, 82, json!({}));
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.capture.shots.len(), 2, "both fit at the original size");
|
||||
let out = resized_frame(&mut u, egui::vec2(3200.0, 3200.0));
|
||||
let replies: Vec<_> = [a.try_recv(), b.try_recv()].into_iter().filter_map(Result::ok).collect();
|
||||
assert_eq!(replies.len(), 1, "each resized request fits alone, but not both together");
|
||||
assert!(replies[0].result.as_ref().unwrap_err().contains("capture budget"));
|
||||
assert_eq!(u.app.capture.shots.len(), 1);
|
||||
let remaining = &u.app.capture.shots[0];
|
||||
assert_eq!(remaining.spec.unwrap().size_px, [3200, 3200]);
|
||||
assert_eq!(remaining.reserved, remaining.spec.unwrap().cost().unwrap(), "the survivor reserves its real current cost");
|
||||
assert!(!remaining.issued);
|
||||
assert!(!has_screenshot(&out), "neither request was read back using the old small reservation");
|
||||
}
|
||||
|
||||
/// Asserts an allowed resize restarts settling, issues only after three new-size frames, and
|
||||
/// reserves the current cost.
|
||||
#[test]
|
||||
fn an_allowed_resize_restarts_settling_and_issues_with_the_current_reservation() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let _rx = push(&mut u, 83, json!({}));
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.capture.shots[0].settle, 2);
|
||||
let size = egui::vec2(2000.0, 1200.0);
|
||||
let out = resized_frame(&mut u, size);
|
||||
assert!(!has_screenshot(&out), "the third old-size frame cannot issue a newly resized surface");
|
||||
assert_eq!(u.app.capture.shots[0].settle, 0);
|
||||
for _ in 0..2 {
|
||||
assert!(!has_screenshot(&resized_frame(&mut u, size)), "wait for three completed new-size frames");
|
||||
}
|
||||
let out = resized_frame(&mut u, size);
|
||||
assert!(has_screenshot(&out), "a valid settled capture still issues");
|
||||
let request = &u.app.capture.shots[0];
|
||||
assert!(request.issued);
|
||||
assert_eq!(request.spec.unwrap().size_px, [2000, 1200]);
|
||||
assert_eq!(request.reserved, request.spec.unwrap().cost().unwrap());
|
||||
}
|
||||
|
||||
/// Queue an injected-input request (the desktop app's `raw_input_hook` is simulated by
|
||||
/// `windows::take_input` in these tests).
|
||||
fn push_input(u: &mut Ui, id: u64) -> std::sync::mpsc::Receiver<ControlReply> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
u.app.control_queue.push(ControlRequest {
|
||||
id: json!(id),
|
||||
method: "ui.input".into(),
|
||||
params: json!({"events": [{"move": [10.0, 10.0]}]}),
|
||||
reply: tx,
|
||||
state: Default::default(),
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
/// Asserts injected input is queued, applied by the presenting pass, and acknowledged once
|
||||
/// after that pass.
|
||||
#[test]
|
||||
fn injected_input_is_acknowledged_only_after_the_pass_that_applies_it() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push_input(&mut u, 20);
|
||||
u.frame(vec![]);
|
||||
assert!(rx.try_recv().is_err(), "queued, not applied yet");
|
||||
let events = crate::windows::take_input(&mut u.app, egui::ViewportId::ROOT);
|
||||
assert!(!events.is_empty(), "the batch the window draws with");
|
||||
assert!(u.app.control_synthetic, "the applying frame is fenced from the system clipboard");
|
||||
u.frame(vec![]);
|
||||
let reply = rx.try_recv().expect("acknowledged by the presented pass");
|
||||
assert_eq!(reply.id, json!(20));
|
||||
assert!(reply.result.is_ok());
|
||||
assert!(!u.app.control_synthetic, "the fence ends with the frame");
|
||||
}
|
||||
|
||||
/// Asserts a discarded pass neither acknowledges nor replays an injected batch; the presented
|
||||
/// pass acknowledges once.
|
||||
#[test]
|
||||
fn a_discarded_pass_does_not_acknowledge_or_lose_an_injected_batch() {
|
||||
let mut u = Ui::new(Session::empty());
|
||||
let rx = push_input(&mut u, 21);
|
||||
u.frame(vec![]);
|
||||
let events = crate::windows::take_input(&mut u.app, egui::ViewportId::ROOT);
|
||||
assert!(!events.is_empty());
|
||||
let input = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))),
|
||||
time: Some(1.0),
|
||||
..Default::default()
|
||||
};
|
||||
let app = &mut u.app;
|
||||
let ctx = u.ctx.clone();
|
||||
let mut passes = 0;
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
passes += 1;
|
||||
app.ui(ui);
|
||||
if passes == 1 {
|
||||
ui.ctx().request_discard("test sizing pass");
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(passes, 2);
|
||||
// The batch's side effects already happened; it is never replayed. Its acknowledgement waits
|
||||
// for the pass whose output is actually presented.
|
||||
assert_eq!(rx.try_recv().expect("acknowledged by the presented pass").id, json!(21));
|
||||
assert!(app.control_input.is_empty(), "the batch is not replayed");
|
||||
assert!(app.input_acks.is_empty() && app.applied_acks.is_empty());
|
||||
}
|
||||
|
||||
/// Asserts injected text is applied once across a discarded sizing pass and acknowledged
|
||||
/// once.
|
||||
#[test]
|
||||
fn injected_text_lands_once_across_a_discarded_sizing_pass() {
|
||||
// egui reruns a discarded pass with the same `RawInput`. The custom editor applied the text in
|
||||
// the first pass; the rerun must not insert it a second time.
|
||||
let mut s = Session::new();
|
||||
let id = NodeId(s.execute("text.create", &json!({"text": "X", "x": 40, "y": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, id, Some(1), false).unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
u.app.control_queue.push(ControlRequest {
|
||||
id: json!(22),
|
||||
method: "ui.input".into(),
|
||||
params: json!({"events": [{"text": "abc"}]}),
|
||||
reply: tx,
|
||||
state: Default::default(),
|
||||
});
|
||||
u.frame(vec![]);
|
||||
let events = crate::windows::take_input(&mut u.app, egui::ViewportId::ROOT);
|
||||
assert!(!events.is_empty(), "the applying frame's batch");
|
||||
let input = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))),
|
||||
time: Some(1.0),
|
||||
events,
|
||||
..Default::default()
|
||||
};
|
||||
let app = &mut u.app;
|
||||
let ctx = u.ctx.clone();
|
||||
let mut passes = 0;
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
passes += 1;
|
||||
app.ui(ui);
|
||||
if passes == 1 {
|
||||
ui.ctx().request_discard("a grid-like sizing pass");
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(passes, 2, "egui reran the frame");
|
||||
let typed = match &app.session.doc().expect("a file").node(id).expect("the text layer").kind {
|
||||
figcraft_doc::NodeKind::Text(t) => t.characters.clone(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(typed, "Xabc", "the discarded pass's text was not applied twice");
|
||||
assert_eq!(rx.try_recv().expect("acknowledged once").id, json!(22));
|
||||
assert!(app.input_acks.is_empty() && app.applied_acks.is_empty());
|
||||
}
|
||||
@@ -52,7 +52,7 @@ fn named_button(u: &mut Ui, label: &str) -> Pos2 {
|
||||
|
||||
/// Corner field `k` (an index into the radii).
|
||||
fn field(u: &Ui, k: usize) -> Rect {
|
||||
u.ctx.read_response(Id::new(("corner", k)).with("field")).expect("corner field shows").rect
|
||||
u.ctx.read_response(Id::unique(("corner", k)).with("field")).expect("corner field shows").rect
|
||||
}
|
||||
|
||||
/// The iOS button next to Corner smoothing sets 60% in one undo step, as the help page's "click
|
||||
@@ -103,8 +103,8 @@ fn polygons_and_stars_take_corner_smoothing() {
|
||||
// With no corners of their own, the button is named for what it opens.
|
||||
let t = named_button(&mut u, "Corner smoothing");
|
||||
click(&mut u, t);
|
||||
assert!((0..4).all(|k| u.ctx.read_response(Id::new(("corner", k)).with("field")).is_none()), "{cmd}: one radius, no corner fields");
|
||||
let smoothing = u.ctx.read_response(Id::new("smoothing").with("field")).expect("the smoothing field shows").rect.center();
|
||||
assert!((0..4).all(|k| u.ctx.read_response(Id::unique(("corner", k)).with("field")).is_none()), "{cmd}: one radius, no corner fields");
|
||||
let smoothing = u.ctx.read_response(Id::unique("smoothing").with("field")).expect("the smoothing field shows").rect.center();
|
||||
let history = u.app.session.undo_depth().0;
|
||||
click(&mut u, smoothing);
|
||||
u.frame(vec![Event::Text("60".into())]);
|
||||
|
||||
@@ -256,7 +256,7 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
|
||||
/// [`contributors_ui`] over a given list (tests pass their own).
|
||||
fn contributors_in(ui: &mut egui::Ui, contributors: &[Contributor], total_commits: u64) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let id = egui::Id::new("credits_view");
|
||||
let id = egui::Id::unique("credits_view");
|
||||
let mut v = ui.data_mut(|d| d.get_temp::<View>(id)).unwrap_or_default();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new(tr("Show")).color(t.text_secondary));
|
||||
@@ -446,7 +446,7 @@ fn cell(ui: &mut egui::Ui, numeric: bool, text: &str) {
|
||||
fn header_cell(ui: &mut egui::Ui, t: &Tokens, label: &str, numeric: bool, sort: Option<Option<bool>>) -> egui::Response {
|
||||
let rect = ui.max_rect();
|
||||
let resp = ui.allocate_rect(rect, if sort.is_some() { egui::Sense::click() } else { egui::Sense::hover() });
|
||||
let kind = if sort.is_some() { egui::WidgetType::Button } else { egui::WidgetType::Label };
|
||||
let kind = if sort.is_some() { egui::Role::Button } else { egui::Role::Label };
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(kind, true, label));
|
||||
let resp = if sort.is_some() { resp.on_hover_cursor(egui::CursorIcon::PointingHand) } else { resp };
|
||||
let current = sort.flatten();
|
||||
|
||||
@@ -51,12 +51,14 @@ impl Ui {
|
||||
u
|
||||
}
|
||||
|
||||
/// Store the About table's current view in test context data.
|
||||
fn set_view(&self, v: View) {
|
||||
self.ctx.data_mut(|d| d.insert_temp(egui::Id::new("credits_view"), v));
|
||||
self.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("credits_view"), v));
|
||||
}
|
||||
|
||||
/// Read the stored About table view, defaulting when unset.
|
||||
fn view(&self) -> View {
|
||||
self.ctx.data(|d| d.get_temp::<View>(egui::Id::new("credits_view"))).unwrap_or_default()
|
||||
self.ctx.data(|d| d.get_temp::<View>(egui::Id::unique("credits_view"))).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// One frame; returns the rect `draw` filled.
|
||||
|
||||
@@ -121,7 +121,7 @@ impl Shown {
|
||||
pub fn show(self, ctx: &egui::Context, at: Pos2) {
|
||||
ctx.set_cursor_icon(self.icon());
|
||||
if let Shown::Drawn(g) = self {
|
||||
paint(&ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("canvas_cursor"))), at, g);
|
||||
paint(&ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("canvas_cursor"))), at, g);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut action = None;
|
||||
egui::Window::new("Compare changes")
|
||||
.id(Id::new("dev_compare_window"))
|
||||
.id(Id::unique("dev_compare_window"))
|
||||
.title_bar(false)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
@@ -277,7 +277,7 @@ pub(crate) fn header(ui: &mut Ui, t: &Tokens, title: &str, name: &str, mode: &mu
|
||||
for (m, label) in modes.iter().rev() {
|
||||
let g = ui.painter().layout_no_wrap((*label).into(), regular(11.0), t.text);
|
||||
let cell = Rect::from_min_max(pos2(x - g.size().x - 20.0, r.center().y - 12.0), pos2(x, r.center().y + 12.0));
|
||||
let resp = ui.interact(cell, Id::new(("compare_mode", label)), Sense::click());
|
||||
let resp = ui.interact(cell, Id::unique(("compare_mode", label)), Sense::click());
|
||||
let on = *mode == *m;
|
||||
crate::a11y::tab(&resp, label, on);
|
||||
if on {
|
||||
@@ -294,7 +294,7 @@ pub(crate) fn header(ui: &mut Ui, t: &Tokens, title: &str, name: &str, mode: &mu
|
||||
}
|
||||
if widgets::icon_button_at(
|
||||
ui,
|
||||
Id::new("compare_close"),
|
||||
Id::unique("compare_close"),
|
||||
Rect::from_center_size(pos2(r.max.x - 24.0, r.center().y), vec2(24.0, 24.0)),
|
||||
Icon::Close,
|
||||
tr("Close"),
|
||||
@@ -344,7 +344,7 @@ pub(crate) fn images(ui: &mut Ui, t: &Tokens, r: Rect, shots: [(&Shot, &str); 2]
|
||||
p.text(pos2(img.min.x, label_y), Align2::LEFT_CENTER, before_label, semibold(11.0), t.text_secondary);
|
||||
p.text(pos2(img.max.x, label_y), Align2::RIGHT_CENTER, after_label, semibold(11.0), t.text_secondary);
|
||||
// The slider: a line with a knob, dragged (or clicked) anywhere over the images.
|
||||
let resp = ui.interact(img, Id::new("compare_split"), Sense::click_and_drag());
|
||||
let resp = ui.interact(img, Id::unique("compare_split"), Sense::click_and_drag());
|
||||
if let Some(pos) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
|
||||
*split = ((pos.x - img.min.x) / img.width().max(1.0)).clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
@@ -291,7 +291,7 @@ impl Callout {
|
||||
|
||||
/// Where the template being edited in Connect to code keeps its draft.
|
||||
fn template_id(owner: NodeId, lang: CodeLang) -> Id {
|
||||
Id::new(("code_connect_template", owner, lang.id()))
|
||||
Id::unique(("code_connect_template", owner, lang.id()))
|
||||
}
|
||||
|
||||
/// Layer `id`'s code in `lang`, generated again only when the document or the choice change (a
|
||||
@@ -390,7 +390,7 @@ pub fn playground_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod
|
||||
"text" => row(ui, 32.0, |ui| {
|
||||
widgets::label(ui, name, t.text_secondary);
|
||||
let cur = value.as_str().unwrap_or("");
|
||||
let field = Id::new(("playground_text", id, name));
|
||||
let field = Id::unique(("playground_text", id, name));
|
||||
if let Some(new) = widgets::text_field_named(ui, field, cur, ui.available_width().max(60.0), name)
|
||||
&& new != cur
|
||||
{
|
||||
@@ -471,10 +471,10 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId
|
||||
let col = widgets::col_width(ui.available_width());
|
||||
row(ui, 32.0, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
if let Some(v) = widgets::text_field(ui, Id::new(("code_connect_import", owner, lang.id())), &link.import_path, col, tr("Import path")) {
|
||||
if let Some(v) = widgets::text_field(ui, Id::unique(("code_connect_import", owner, lang.id())), &link.import_path, col, tr("Import path")) {
|
||||
edit = Some(("importPath", v));
|
||||
}
|
||||
if let Some(v) = widgets::text_field(ui, Id::new(("code_connect_name", owner, lang.id())), &link.name, col, tr("Component name")) {
|
||||
if let Some(v) = widgets::text_field(ui, Id::unique(("code_connect_name", owner, lang.id())), &link.name, col, tr("Component name")) {
|
||||
edit = Some(("name", v));
|
||||
}
|
||||
});
|
||||
@@ -585,13 +585,13 @@ pub fn annotations_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: No
|
||||
t.text_secondary,
|
||||
);
|
||||
let del = Rect::from_center_size(pos2(r.max.x - PAD - 4.0, r.center().y), vec2(22.0, 22.0));
|
||||
if widgets::icon_button_at(ui, Id::new(("annot_del", id, k)), del, Icon::Minus, tr("Remove annotation")) {
|
||||
if widgets::icon_button_at(ui, Id::unique(("annot_del", id, k)), del, Icon::Minus, tr("Remove annotation")) {
|
||||
app.run("annotation.remove", json!({"id": id, "index": k}));
|
||||
}
|
||||
if let Some(cat) = category_menu(ui, doc, Id::new(("annot_cat", id, k)), a) {
|
||||
if let Some(cat) = category_menu(ui, doc, Id::unique(("annot_cat", id, k)), a) {
|
||||
app.run("annotation.edit", json!({"id": id, "index": k, "category": cat}));
|
||||
}
|
||||
if let Some(label) = widgets::multiline_field(ui, Id::new(("annot_note", id, k)), &a.label, tr("Add a note for developers"), 2) {
|
||||
if let Some(label) = widgets::multiline_field(ui, Id::unique(("annot_note", id, k)), &a.label, tr("Add a note for developers"), 2) {
|
||||
if label.trim().is_empty() && a.properties.is_empty() {
|
||||
app.run("annotation.remove", json!({"id": id, "index": k}));
|
||||
} else {
|
||||
@@ -602,7 +602,7 @@ pub fn annotations_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: No
|
||||
for (p, v) in annotations::pinned(doc, id, a) {
|
||||
prop_row(app, ui, &v.unwrap_or_else(|| Prop { label: p.label.to_string(), value: "—".into(), color: None, token: None }));
|
||||
}
|
||||
if let Some(p) = pin_menu(ui, Id::new(("annot_pin", id, k)), §ions, &a.properties) {
|
||||
if let Some(p) = pin_menu(ui, Id::unique(("annot_pin", id, k)), §ions, &a.properties) {
|
||||
let mut props = a.properties.clone();
|
||||
match props.iter().position(|q| q == p.id) {
|
||||
Some(i) => {
|
||||
@@ -620,7 +620,7 @@ pub fn annotations_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: No
|
||||
}
|
||||
// A new annotation starts as a note; properties are pinned to it afterwards.
|
||||
if n.annotations.len() < annotations::MAX_PER_LAYER
|
||||
&& let Some(label) = widgets::multiline_field(ui, Id::new(("annot_new", id)), "", tr("Add an annotation for developers"), 1)
|
||||
&& let Some(label) = widgets::multiline_field(ui, Id::unique(("annot_new", id)), "", tr("Add an annotation for developers"), 1)
|
||||
&& !label.trim().is_empty()
|
||||
{
|
||||
app.run("annotation.add", json!({"id": id, "label": label}));
|
||||
@@ -636,7 +636,7 @@ pub fn dev_resources_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id:
|
||||
let Some(n) = doc.node(id).filter(|n| !n.is_page()) else { return };
|
||||
let list = dev_resources::list(doc, id);
|
||||
let can_add = !components::inside_instance(doc, id) && n.dev_resources.len() < dev_resources::MAX_PER_LAYER;
|
||||
let (adding_id, editing_id) = (Id::new(("devres_adding", id)), Id::new(("devres_editing", id)));
|
||||
let (adding_id, editing_id) = (Id::unique(("devres_adding", id)), Id::unique(("devres_editing", id)));
|
||||
let mut adding = can_add && ui.data(|d| d.get_temp::<bool>(adding_id)).unwrap_or(false);
|
||||
let mut editing = ui.data(|d| d.get_temp::<usize>(editing_id)).filter(|i| *i < n.dev_resources.len());
|
||||
widgets::separator(ui);
|
||||
@@ -652,10 +652,10 @@ pub fn dev_resources_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id:
|
||||
let mut edit = None;
|
||||
row(ui, 32.0, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
if let Some(v) = widgets::text_field(ui, Id::new(("devres_name", id, i)), name, col, tr("Name")) {
|
||||
if let Some(v) = widgets::text_field(ui, Id::unique(("devres_name", id, i)), name, col, tr("Name")) {
|
||||
edit = Some(json!({"id": id, "index": i, "name": v}));
|
||||
}
|
||||
if let Some(v) = widgets::text_field(ui, Id::new(("devres_url", id, i)), url, col, "https://…") {
|
||||
if let Some(v) = widgets::text_field(ui, Id::unique(("devres_url", id, i)), url, col, "https://…") {
|
||||
edit = Some(json!({"id": id, "index": i, "url": v}));
|
||||
}
|
||||
if widgets::icon_button(ui, Icon::Check, tr("Done")) {
|
||||
@@ -692,10 +692,10 @@ pub fn dev_resources_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id:
|
||||
if let Some(i) = item.index {
|
||||
let del = Rect::from_center_size(pos2(r.max.x - PAD - 4.0, r.center().y), vec2(22.0, 22.0));
|
||||
let pen = del.translate(vec2(-26.0, 0.0));
|
||||
if widgets::icon_button_at(ui, Id::new(("devres_edit", id, i)), pen, Icon::Pencil, tr("Edit dev resource")) {
|
||||
if widgets::icon_button_at(ui, Id::unique(("devres_edit", id, i)), pen, Icon::Pencil, tr("Edit dev resource")) {
|
||||
editing = Some(i);
|
||||
}
|
||||
if widgets::icon_button_at(ui, Id::new(("devres_del", id, i)), del, Icon::Minus, tr("Remove dev resource")) {
|
||||
if widgets::icon_button_at(ui, Id::unique(("devres_del", id, i)), del, Icon::Minus, tr("Remove dev resource")) {
|
||||
app.run("devResource.remove", json!({"id": id, "index": i}));
|
||||
editing = None;
|
||||
}
|
||||
@@ -704,7 +704,7 @@ pub fn dev_resources_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id:
|
||||
if adding {
|
||||
let w = ui.available_width() - PAD * 2.0;
|
||||
let mut added = None;
|
||||
row(ui, 32.0, |ui| added = widgets::text_field(ui, Id::new(("devres_new", id)), "", w, tr("Paste a link (https://…)")));
|
||||
row(ui, 32.0, |ui| added = widgets::text_field(ui, Id::unique(("devres_new", id)), "", w, tr("Paste a link (https://…)")));
|
||||
if let Some(url) = added.filter(|u| !u.trim().is_empty())
|
||||
&& app.run("devResource.add", json!({"id": id, "url": url})).is_some()
|
||||
{
|
||||
@@ -810,7 +810,7 @@ fn measurement_row(ui: &mut Ui, t: &Tokens, doc: &Document, m: &Placed) -> Optio
|
||||
if resp.clicked() {
|
||||
action = Some(("select.set", json!({"ids": [m.from]})));
|
||||
}
|
||||
if widgets::icon_button_at(ui, Id::new(("measure_del", m.from, m.index)), del, Icon::Minus, tr("Remove measurement")) {
|
||||
if widgets::icon_button_at(ui, Id::unique(("measure_del", m.from, m.index)), del, Icon::Minus, tr("Remove measurement")) {
|
||||
action = Some(("devMode.removeMeasurement", json!({"from": m.from, "index": m.index})));
|
||||
}
|
||||
action
|
||||
@@ -886,7 +886,7 @@ pub fn categories_section(app: &mut FigApp, ui: &mut Ui) {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::hover());
|
||||
// The colour: click for the palette.
|
||||
let sw = Rect::from_center_size(pos2(r.min.x + PAD + 8.0, r.center().y), vec2(16.0, 16.0));
|
||||
let sw_resp = ui.interact(sw, Id::new(("cat_color", &c.id)), Sense::click()).tip(tr("Colour"));
|
||||
let sw_resp = ui.interact(sw, Id::unique(("cat_color", &c.id)), Sense::click()).tip(tr("Colour"));
|
||||
crate::a11y::color(&sw_resp, &c.name, &c.color.to_css_hex());
|
||||
ui.painter().rect_filled(sw, CornerRadius::same(4), doc_c32(ui.ctx(), c.color));
|
||||
if sw_resp.hovered() {
|
||||
@@ -909,14 +909,14 @@ pub fn categories_section(app: &mut FigApp, ui: &mut Ui) {
|
||||
});
|
||||
});
|
||||
let name_r = Rect::from_min_max(pos2(sw.max.x + 8.0, r.min.y + 3.0), pos2(r.max.x - PAD - 28.0, r.max.y - 3.0));
|
||||
if let Some(name) = widgets::text_field_inline(ui, Id::new(("cat_name", &c.id)), &c.name, name_r, regular(11.0))
|
||||
if let Some(name) = widgets::text_field_inline(ui, Id::unique(("cat_name", &c.id)), &c.name, name_r, regular(11.0))
|
||||
&& name.trim() != c.name
|
||||
&& !name.trim().is_empty()
|
||||
{
|
||||
action = Some(("annotation.editCategory", json!({"id": c.id, "name": name.trim()})));
|
||||
}
|
||||
let del = Rect::from_center_size(pos2(r.max.x - PAD - 8.0, r.center().y), vec2(22.0, 22.0));
|
||||
if widgets::icon_button_at(ui, Id::new(("cat_del", &c.id)), del, Icon::Minus, tr("Delete category (its annotations stay)")) {
|
||||
if widgets::icon_button_at(ui, Id::unique(("cat_del", &c.id)), del, Icon::Minus, tr("Delete category (its annotations stay)")) {
|
||||
action = Some(("annotation.removeCategory", json!({"id": c.id})));
|
||||
}
|
||||
}
|
||||
@@ -1014,7 +1014,7 @@ pub fn ready_list(app: &mut FigApp, ui: &mut Ui) {
|
||||
CornerRadius::same(5),
|
||||
t.hover,
|
||||
);
|
||||
if widgets::icon_button_at(ui, Id::new(("ready_focus", item.id)), focus_r, Icon::Frame, tr("Open in focus view")) {
|
||||
if widgets::icon_button_at(ui, Id::unique(("ready_focus", item.id)), focus_r, Icon::Frame, tr("Open in focus view")) {
|
||||
focus = Some(item.id);
|
||||
}
|
||||
}
|
||||
@@ -1058,7 +1058,7 @@ pub fn focus_bar(app: &mut FigApp, ctx: &egui::Context, canvas: Rect) {
|
||||
// Somewhere to go: another ready frame, or into the list from outside it.
|
||||
let can_step = list.len() > usize::from(at.is_some());
|
||||
let t = Tokens::get(ctx);
|
||||
let action = widgets::canvas_banner(ctx, Id::new("dev_focus_bar"), canvas, |ui| {
|
||||
let action = widgets::canvas_banner(ctx, Id::unique("dev_focus_bar"), canvas, |ui| {
|
||||
let mut out = None;
|
||||
let icon = crate::layers::node_icon(&doc, id);
|
||||
icons::paint(ui.painter(), Rect::from_center_size(ui.cursor().min + vec2(7.0, 12.0), vec2(14.0, 14.0)), icon, t.icon_secondary);
|
||||
|
||||
@@ -126,8 +126,13 @@ fn playground_combo(u: &mut crate::layers_drag_tests::Ui, name: &str) -> Option<
|
||||
if centre(&combo).y < 860.0 {
|
||||
return Some(combo);
|
||||
}
|
||||
let wheel =
|
||||
Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, -100.0), phase: TouchPhase::Move, modifiers: Default::default() };
|
||||
let wheel = Event::MouseWheel {
|
||||
unit: MouseWheelUnit::Point,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
delta: vec2(0.0, -100.0),
|
||||
phase: TouchPhase::Move,
|
||||
modifiers: Default::default(),
|
||||
};
|
||||
u.frame(vec![Event::PointerMoved(pos2(1300.0, 500.0)), wheel]);
|
||||
for _ in 0..30 {
|
||||
u.frame(vec![]);
|
||||
|
||||
@@ -105,7 +105,7 @@ pub(crate) fn tab_strip<T: Copy + PartialEq>(ui: &mut egui::Ui, t: &Tokens, tabs
|
||||
let active = *current == tab;
|
||||
let galley = ui.painter().layout_no_wrap(label.into(), semibold(11.0), if active { t.text } else { t.text_secondary });
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(galley.size().x + 16.0, 24.0), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, active, label));
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, label));
|
||||
if active || resp.hovered() {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
@@ -179,6 +179,10 @@ pub fn keys(app: &mut FigApp, ctx: &Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the app's dialogs and cards: pending opens/imports/missing fonts, About,
|
||||
/// Preferences, shortcuts, find/replace, batch rename, menu input, variables, dev compare,
|
||||
/// branch, export preview, colour profile, plugin, live join/publish, online dialogs and
|
||||
/// close confirmation.
|
||||
pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
// Dropped files waiting to open: their card, then (once it has shown) the files.
|
||||
crate::pending_open::pending_opens(app, ctx);
|
||||
@@ -246,7 +250,7 @@ pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Your name in comments"));
|
||||
if let Some(name) = crate::widgets::text_field(ui, egui::Id::new("pref_user_name"), &prefs.user_name, 160.0, tr("You")) {
|
||||
if let Some(name) = crate::widgets::text_field(ui, egui::Id::unique("pref_user_name"), &prefs.user_name, 160.0, tr("You")) {
|
||||
app.run("pref.userName", json!({"name": name}));
|
||||
}
|
||||
});
|
||||
@@ -256,7 +260,7 @@ pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
// Where Share ▸ Online keeps files and join codes are asked; no key here
|
||||
// (preferences are saved as text).
|
||||
let name = tr("Server for online sharing");
|
||||
if let Some(url) = crate::widgets::text_field_named(ui, egui::Id::new("pref_publish_server"), &prefs.publish_server, 220.0, name) {
|
||||
if let Some(url) = crate::widgets::text_field_named(ui, egui::Id::unique("pref_publish_server"), &prefs.publish_server, 220.0, name) {
|
||||
app.run("pref.publishServer", json!({"url": url}));
|
||||
}
|
||||
let usual = prefs.publish_server == figcraft_engine::live::DEFAULT_SERVER;
|
||||
@@ -329,7 +333,7 @@ pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
let mut open = true;
|
||||
let mut action = None;
|
||||
egui::Window::new(tr("Find and replace"))
|
||||
.id(egui::Id::new("Find and replace"))
|
||||
.id(egui::Id::unique("Find and replace"))
|
||||
.open(&mut open)
|
||||
.anchor(Align2::LEFT_TOP, vec2(260.0, 120.0))
|
||||
.resizable(false)
|
||||
@@ -396,7 +400,7 @@ fn menu_input_dialog(app: &mut FigApp, ctx: &Context) {
|
||||
match &mut input {
|
||||
MenuInput::Link(url) => {
|
||||
ui.horizontal(|ui| {
|
||||
let field = crate::widgets::text_input(ui, egui::Id::new("menu_input_link"), url, 250.0, "https://");
|
||||
let field = crate::widgets::text_input(ui, egui::Id::unique("menu_input_link"), url, 250.0, "https://");
|
||||
let enter = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
let ok = !url.trim().is_empty();
|
||||
if (crate::widgets::button(ui, tr("Done"), true, ok).clicked() || enter) && ok {
|
||||
@@ -406,7 +410,7 @@ fn menu_input_dialog(app: &mut FigApp, ctx: &Context) {
|
||||
}
|
||||
MenuInput::Offset(offset) => {
|
||||
ui.horizontal(|ui| {
|
||||
let id = egui::Id::new("menu_input_offset");
|
||||
let id = egui::Id::unique("menu_input_offset");
|
||||
if let Some(crate::widgets::FieldEdit::Set(v) | crate::widgets::FieldEdit::Scrub(v, _)) =
|
||||
crate::widgets::number_field(ui, id, crate::widgets::Lead::None, Some(*offset), "", 120.0, 1.0)
|
||||
{
|
||||
@@ -573,7 +577,7 @@ fn batch_rename_dialog(app: &mut FigApp, ctx: &Context) {
|
||||
let mut open = true;
|
||||
let mut cancel = false;
|
||||
let mut apply = false;
|
||||
window(tr("Rename layers"), ctx).id(egui::Id::new("Rename layers")).open(&mut open).show(ctx, |ui| {
|
||||
window(tr("Rename layers"), ctx).id(egui::Id::unique("Rename layers")).open(&mut open).show(ctx, |ui| {
|
||||
ui.set_width(320.0);
|
||||
ui.label(RichText::new(trn("{n} layers", n, &[])).color(t.text_secondary));
|
||||
ui.add_space(6.0);
|
||||
@@ -802,7 +806,7 @@ fn export_dialog(app: &mut FigApp, ctx: &Context) {
|
||||
// The PDF preset's print options.
|
||||
ui.add_space(6.0);
|
||||
caption(ui, tr("PDF print options"));
|
||||
if let Some(next) = crate::export_panel::print_options(ui, egui::Id::new("export_dialog_print"), &print) {
|
||||
if let Some(next) = crate::export_panel::print_options(ui, egui::Id::unique("export_dialog_print"), &print) {
|
||||
app.ui.pdf_print = next;
|
||||
}
|
||||
divider(ui);
|
||||
|
||||
@@ -74,13 +74,13 @@ fn setting_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, e: &Expo
|
||||
if let Some(size_w) = size_w {
|
||||
let presets: Vec<String> =
|
||||
ExportSize::SCALES.iter().map(|value| ExportSize::Scale { value: *value }.label()).chain(["512w".into(), "512h".into()]).collect();
|
||||
if let Some(s) = widgets::combo_field(ui, Id::new(("export_size", i)), &e.size.label(), size_w, &presets)
|
||||
if let Some(s) = widgets::combo_field(ui, Id::unique(("export_size", i)), &e.size.label(), size_w, &presets)
|
||||
&& ExportSize::parse(&s) != Some(e.size)
|
||||
{
|
||||
app.run("export.update", json!({"ids": ids, "index": i, "size": s}));
|
||||
}
|
||||
}
|
||||
if let Some(sfx) = widgets::text_field(ui, Id::new(("export_suffix", i)), &e.suffix, suffix_w, tr("Suffix"))
|
||||
if let Some(sfx) = widgets::text_field(ui, Id::unique(("export_suffix", i)), &e.suffix, suffix_w, tr("Suffix"))
|
||||
&& sfx != e.suffix
|
||||
{
|
||||
app.run("export.update", json!({"ids": ids, "index": i, "suffix": sfx}));
|
||||
@@ -96,7 +96,7 @@ fn setting_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, e: &Expo
|
||||
});
|
||||
let more = icons::button(ui, Icon::Dots, button, false, tr("Export settings"));
|
||||
egui::Popup::from_toggle_button_response(&more)
|
||||
.id(Id::new(("export_more", i)))
|
||||
.id(Id::unique(("export_more", i)))
|
||||
.width(216.0)
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
.show(|ui| {
|
||||
@@ -142,7 +142,7 @@ fn advanced_options(ui: &mut Ui, e: &ExportSetting, text: bool) -> Option<Value>
|
||||
fn print_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &PrintSettings) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
row(ui, 26.0, |ui| {
|
||||
let open_id = Id::new(("export_print", i));
|
||||
let open_id = Id::unique(("export_print", i));
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), open_id);
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), FIELD_H), Sense::click());
|
||||
if resp.hovered() || open {
|
||||
@@ -156,7 +156,7 @@ fn print_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &PrintS
|
||||
.width(216.0)
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
.show(|ui| {
|
||||
if let Some(next) = print_options(ui, Id::new(("export_print_fields", i)), p) {
|
||||
if let Some(next) = print_options(ui, Id::unique(("export_print_fields", i)), p) {
|
||||
let mut params = print_params(&next);
|
||||
params["ids"] = json!(ids);
|
||||
params["index"] = json!(i);
|
||||
@@ -264,7 +264,7 @@ fn preview(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId) {
|
||||
}
|
||||
let revision = app.session.ds().map(|d| d.revision).unwrap_or(0);
|
||||
let now = ui.input(|i| i.time);
|
||||
let cache_id = Id::new("export_preview_tex");
|
||||
let cache_id = Id::unique("export_preview_tex");
|
||||
let cached: Option<PreviewTex> = ui.data(|d| d.get_temp(cache_id));
|
||||
let stale = cached.as_ref().is_none_or(|c| c.id != id || c.revision != revision);
|
||||
let due = cached.as_ref().is_none_or(|c| c.id != id || now - c.at >= PREVIEW_REFRESH);
|
||||
|
||||
@@ -77,7 +77,7 @@ fn export_rows_offer_a_size_for_images_only() {
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("export.add", &json!({"ids": [r]})).unwrap();
|
||||
let mut u = crate::layers_drag_tests::Ui::new(s);
|
||||
let size_menu = |u: &crate::layers_drag_tests::Ui| u.ctx.read_response(egui::Id::new(("export_size", 0)).with("menu")).is_some();
|
||||
let size_menu = |u: &crate::layers_drag_tests::Ui| u.ctx.read_response(egui::Id::unique(("export_size", 0)).with("menu")).is_some();
|
||||
u.frame(vec![]);
|
||||
assert!(size_menu(&u), "PNG has sizes");
|
||||
for format in ["svg", "pdf"] {
|
||||
@@ -108,7 +108,7 @@ fn advanced_options_offer_the_bounding_box_for_text_layers() {
|
||||
let options = |u: &mut crate::layers_drag_tests::Ui, id: NodeId| {
|
||||
u.app.run("select.set", json!({"ids": [id]}));
|
||||
u.frame(vec![]);
|
||||
egui::Popup::open_id(&u.ctx, egui::Id::new(("export_more", 0)));
|
||||
egui::Popup::open_id(&u.ctx, egui::Id::unique(("export_more", 0)));
|
||||
u.frame(vec![]);
|
||||
crate::import_report_tests::shown_texts(u.frame_output(vec![]).shapes)
|
||||
};
|
||||
|
||||
@@ -102,7 +102,15 @@ impl Parser<'_> {
|
||||
}
|
||||
let v = digits.parse::<f64>().ok().filter(|v| v.is_finite())?;
|
||||
// The unit: letters (px, pt, ms, x), a degree sign, and a percent sign where that is one.
|
||||
while self.chars.next_if(|c| c.is_ascii_alphabetic() || *c == '°' || (*c == '%' && self.percent_unit)).is_some() {}
|
||||
// It may follow spaces ("3 px").
|
||||
let percent_unit = self.percent_unit;
|
||||
let is_unit = |c: &char| c.is_ascii_alphabetic() || *c == '°' || (*c == '%' && percent_unit);
|
||||
let mut ahead = self.chars.clone();
|
||||
while ahead.next_if(|c| c.is_whitespace()).is_some() {}
|
||||
if ahead.peek().is_some_and(is_unit) {
|
||||
self.space();
|
||||
}
|
||||
while self.chars.next_if(is_unit).is_some() {}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
@@ -161,3 +169,17 @@ pub fn stepped(from: f64, steps: f64, step: f64) -> f64 {
|
||||
let v = from + steps * step;
|
||||
if v.is_finite() { (v * 1e6).round() / 1e6 } else { from }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unit_after_a_space() {
|
||||
assert_eq!(parse("3px", true), Some(Typed::Value(3.0)));
|
||||
assert_eq!(parse("3 px", true), Some(Typed::Value(3.0)));
|
||||
assert_eq!(parse("10 °", true), Some(Typed::Value(10.0)));
|
||||
assert_eq!(parse("50 %", true), Some(Typed::Value(50.0)));
|
||||
assert_eq!(parse("3 px + 2 px", true), Some(Typed::Value(5.0)));
|
||||
}
|
||||
}
|
||||
@@ -467,29 +467,33 @@ fn lead(u: &Ui, id: Id) -> Pos2 {
|
||||
u.ctx.read_response(id.with("lead")).unwrap_or_else(|| panic!("no field {id:?}")).rect.center()
|
||||
}
|
||||
|
||||
/// Asserts scrubbing the colour picker's R and alpha fields updates the colour live, each
|
||||
/// scrub adding one undo step.
|
||||
#[test]
|
||||
fn scrubbing_colour_picker_fields_is_live_and_one_undo_step() {
|
||||
let (mut u, a, _) = setup();
|
||||
let rgba = |u: &Ui| u.app.session.doc().unwrap().node(a).unwrap().fills[0].solid_color().unwrap().to_rgba8();
|
||||
let [r0, .., a0] = rgba(&u);
|
||||
u.ctx.data_mut(|d| d.insert_temp(Id::new("cp_model"), 1usize));
|
||||
u.ctx.data_mut(|d| d.insert_temp(Id::unique("cp_model"), 1usize));
|
||||
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![a] });
|
||||
// The picker window takes a frame to size itself.
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let steps = undo_steps(&u);
|
||||
let from = lead(&u, Id::new(("cp_f", "r")));
|
||||
let from = lead(&u, Id::unique(("cp_f", "r")));
|
||||
drag(&mut u, from, -20.0, Modifiers::NONE);
|
||||
assert_eq!((rgba(&u)[0], undo_steps(&u)), (r0 - 20, steps + 1), "R");
|
||||
// The alpha field: a scrub moves it too.
|
||||
let from = lead(&u, Id::new("cp_a"));
|
||||
let from = lead(&u, Id::unique("cp_a"));
|
||||
drag(&mut u, from, -30.0, Modifiers::NONE);
|
||||
let [.., alpha] = rgba(&u);
|
||||
assert!(alpha < a0, "alpha {a0} → {alpha}");
|
||||
assert_eq!(undo_steps(&u), steps + 2, "alpha");
|
||||
}
|
||||
|
||||
/// Asserts scrubbing a prototype delay sets the value once when released and adds one undo
|
||||
/// step.
|
||||
#[test]
|
||||
fn scrubbing_a_prototype_delay_sets_it_once_when_let_go() {
|
||||
let mut s = Session::new();
|
||||
@@ -505,7 +509,7 @@ fn scrubbing_a_prototype_delay_sets_it_once_when_let_go() {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let steps = undo_steps(&u);
|
||||
let from = lead(&u, Id::new(("proto_delay", f1, 0usize)));
|
||||
let from = lead(&u, Id::unique(("proto_delay", f1, 0usize)));
|
||||
drag(&mut u, from, 30.0, Modifiers::NONE);
|
||||
let ms = match u.app.session.doc().unwrap().node(f1).unwrap().interactions[0].trigger {
|
||||
figcraft_doc::proto::Trigger::AfterDelay { ms } => ms,
|
||||
@@ -514,13 +518,14 @@ fn scrubbing_a_prototype_delay_sets_it_once_when_let_go() {
|
||||
assert_eq!((ms, undo_steps(&u)), (800, steps + 1));
|
||||
}
|
||||
|
||||
/// Asserts scrubbing the scale panel's width scales the layer live in one undo step.
|
||||
#[test]
|
||||
fn scrubbing_the_scale_panel_width_scales_live_in_one_undo_step() {
|
||||
let (mut u, a, _) = setup();
|
||||
u.app.run("tool.set", json!({"tool": "scale"}));
|
||||
u.frame(vec![]);
|
||||
let steps = undo_steps(&u);
|
||||
let from = lead(&u, Id::new("scale_w"));
|
||||
let from = lead(&u, Id::unique("scale_w"));
|
||||
drag(&mut u, from, 20.0, Modifiers::NONE);
|
||||
let (_, _, w, h) = geom(&u, a);
|
||||
assert_eq!((w, h, undo_steps(&u)), (60.0, 45.0, steps + 1), "40×30 scaled to a width of 60");
|
||||
@@ -550,14 +555,14 @@ fn the_glass_light_intensity_field_has_a_label() {
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("effect.add", &json!({"type": "glass"})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.ctx.data_mut(|d| d.insert_temp(Id::new(("fx_open", 0usize)), true));
|
||||
u.ctx.data_mut(|d| d.insert_temp(Id::unique(("fx_open", 0usize)), true));
|
||||
u.frame(vec![]);
|
||||
let shapes = u.frame_output(vec![]).shapes;
|
||||
let lead = u.ctx.read_response(Id::new(("fx_gi", 0usize)).with("lead")).expect("the intensity field is shown").rect;
|
||||
let lead = u.ctx.read_response(Id::unique(("fx_gi", 0usize)).with("lead")).expect("the intensity field is shown").rect;
|
||||
let labels: Vec<(String, bool)> =
|
||||
painted_texts(&shapes).into_iter().filter(|(_, _, at)| lead.contains(at.center())).map(|(text, cut, _)| (text, cut)).collect();
|
||||
assert_eq!(labels, [("Intensity".to_string(), false)], "labelled, and not cut short");
|
||||
let field = u.ctx.read_response(Id::new(("fx_gi", 0usize)).with("field")).expect("its value").rect;
|
||||
let field = u.ctx.read_response(Id::unique(("fx_gi", 0usize)).with("field")).expect("its value").rect;
|
||||
assert_eq!(field.max.x - lead.min.x, GLASS_FIELD_W, "the width the next test measures against");
|
||||
}
|
||||
|
||||
@@ -584,13 +589,15 @@ fn the_intensity_label_fits_whole_in_every_language() {
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Asserts a label too long for its number field is elided before the value, while the value
|
||||
/// stays whole and both remain inside the field.
|
||||
#[test]
|
||||
fn a_label_too_long_for_its_field_ends_in_an_ellipsis_before_the_value() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut field = egui::Rect::NOTHING;
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| {
|
||||
let lead = crate::widgets::Lead::Text("A label much wider than its field");
|
||||
let _ = crate::widgets::number_field(ui, Id::new("long"), lead, Some(80.0), "%", 60.0, 1.0);
|
||||
let _ = crate::widgets::number_field(ui, Id::unique("long"), lead, Some(80.0), "%", 60.0, 1.0);
|
||||
field = ui.min_rect();
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
@@ -623,7 +630,7 @@ fn grid_ui(grid: serde_json::Value) -> (Ui, NodeId) {
|
||||
s.execute("node.set", &json!({"ids": [f], "props": {"grids": [grid]}})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [f]})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.ctx.data_mut(|d| d.insert_temp(Id::new(("grid_open", 0usize)), true));
|
||||
u.ctx.data_mut(|d| d.insert_temp(Id::unique(("grid_open", 0usize)), true));
|
||||
u.frame(vec![]);
|
||||
(u, f)
|
||||
}
|
||||
@@ -633,6 +640,7 @@ fn grid_ui(grid: serde_json::Value) -> (Ui, NodeId) {
|
||||
fn scroll_to(u: &mut Ui, id: Id) {
|
||||
let wheel = Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
delta: egui::vec2(0.0, -300.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Modifiers::NONE,
|
||||
@@ -655,7 +663,7 @@ fn scroll_to(u: &mut Ui, id: Id) {
|
||||
/// placeholder said 0 everywhere, which turned the gap's mode off.
|
||||
#[test]
|
||||
fn typing_auto_is_zero_only_where_zero_is_the_automatic_value() {
|
||||
let count_id = Id::new(("grid_field", "count", 0usize));
|
||||
let count_id = Id::unique(("grid_field", "count", 0usize));
|
||||
let (mut u, f) = grid_ui(json!({"kind": "columns", "align": "min", "count": 3, "size": 8, "gutter": 10}));
|
||||
let count = |u: &Ui| u.app.session.doc().unwrap().node(f).unwrap().grids[0].count;
|
||||
scroll_to(&mut u, count_id);
|
||||
@@ -665,7 +673,7 @@ fn typing_auto_is_zero_only_where_zero_is_the_automatic_value() {
|
||||
assert_eq!(count(&u), 4, "and a number is that count");
|
||||
// A stretched grid works its width out from the frame: the field shows Auto and takes no edit.
|
||||
let (mut u, f) = grid_ui(json!({"kind": "columns", "align": "stretch", "count": 3, "size": 0}));
|
||||
let size_id = Id::new(("grid_field", "size", 0usize));
|
||||
let size_id = Id::unique(("grid_field", "size", 0usize));
|
||||
scroll_to(&mut u, size_id);
|
||||
type_at(&mut u, size_id, "40");
|
||||
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().grids[0].size, 0.0, "a stretched grid's width isn't set");
|
||||
@@ -683,6 +691,336 @@ fn typing_auto_is_zero_only_where_zero_is_the_automatic_value() {
|
||||
u.frame(vec![]);
|
||||
let gap = |u: &Ui| u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().gap;
|
||||
let before = gap(&u);
|
||||
type_at(&mut u, Id::new("al_gap"), "Auto");
|
||||
type_at(&mut u, Id::unique("al_gap"), "Auto");
|
||||
assert_eq!(gap(&u), before, "the word isn't a value where Auto is a mode");
|
||||
}
|
||||
|
||||
/// Save starts after the field commits, even if the next raw input releases a tab click first.
|
||||
#[test]
|
||||
fn a_deferred_field_save_keeps_its_document_when_the_next_input_switches_tabs() {
|
||||
for (save_as, same_batch, discard) in
|
||||
[(false, false, false), (true, false, false), (false, true, false), (true, true, false), (false, true, true), (true, true, true)]
|
||||
{
|
||||
let (mut u, a, _) = setup();
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-deferred-field-tab-{}-{save_as}-{same_batch}-{discard}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (path, copy, other) = (dir.join("a.figcraft"), dir.join("copy.figcraft"), dir.join("b.figcraft"));
|
||||
u.app.session.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let owner = u.app.session.ds().unwrap().uid;
|
||||
u.app.session.execute("file.new", &json!({"name": "Deferred B"})).unwrap();
|
||||
u.app.session.execute("shape.rectangle", &json!({"x": 200, "y": 0, "width": 30, "height": 30})).unwrap();
|
||||
u.app.session.execute("file.saveAs", &json!({"path": other.to_string_lossy()})).unwrap();
|
||||
u.app.session.execute("shape.rectangle", &json!({"x": 300, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let other_uid = u.app.session.ds().unwrap().uid;
|
||||
let other_name = u.app.session.doc().unwrap().name.clone();
|
||||
let other_bytes = std::fs::read(&other).unwrap();
|
||||
let index = u.app.session.docs.iter().position(|d| d.uid == owner).unwrap();
|
||||
u.app.session.execute("doc.switch", &json!({"index": index})).unwrap();
|
||||
let asked = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
u.app.services = Box::new(SaveAsPicker { path: Some(copy.clone()), asked: asked.clone() });
|
||||
u.frame(vec![]);
|
||||
let output = u.frame_output(vec![]);
|
||||
let nodes = output.platform_output.accesskit_update.unwrap().nodes;
|
||||
let tab = nodes
|
||||
.iter()
|
||||
.map(|(_, node)| node)
|
||||
.find(|node| node.role() == Role::Tab && node.label() == Some(other_name.as_str()))
|
||||
.expect("the actual B tab");
|
||||
let bounds = tab.bounds().unwrap();
|
||||
let at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32);
|
||||
let (field_at, _) = field(&mut u, "X");
|
||||
click(&mut u, field_at);
|
||||
assert!(crate::a11y::field_focused(&u.ctx));
|
||||
assert!(u.ctx.text_edit_focused(), "the actual field editor owns raw text");
|
||||
assert_eq!(u.ctx.memory(|m| m.focused()), Some(Id::unique("pos_x").with("te")), "X owns the keyboard");
|
||||
if !same_batch {
|
||||
u.frame(vec![Event::Text("77".into())]);
|
||||
assert_eq!(u.ctx.data(|d| d.get_temp::<String>(Id::unique("pos_x").with("editing"))), Some("77".into()), "raw text reached X's draft");
|
||||
}
|
||||
assert_eq!(geom(&u, a).0, 10.0, "the field has not committed before the shortcut");
|
||||
let mut modifiers = if cfg!(target_os = "macos") { Modifiers::COMMAND } else { Modifiers::COMMAND.plus(Modifiers::CTRL) };
|
||||
if save_as {
|
||||
modifiers = modifiers.plus(Modifiers::SHIFT);
|
||||
}
|
||||
let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
// Pressing the tab relinquishes the real field; its release switches documents in the
|
||||
// next frame, before shortcuts::handle consumes the deferred request.
|
||||
let mut events = vec![
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: true, repeat: false, modifiers },
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers },
|
||||
Event::PointerMoved(at),
|
||||
button(true),
|
||||
];
|
||||
if same_batch {
|
||||
events.insert(0, Event::Text("77".into()));
|
||||
}
|
||||
if discard {
|
||||
events.insert(0, Event::ModifiersChanged(modifiers));
|
||||
u.frame_raw_with_discard(egui::RawInput { events, ..Default::default() });
|
||||
} else {
|
||||
u.frame_with(events, modifiers);
|
||||
}
|
||||
assert!(u.app.ui.after_field.is_some(), "the real shortcut deferred a save");
|
||||
if !discard {
|
||||
assert!(
|
||||
!u.ctx.input(|i| i.events.iter().any(|e| matches!(e, Event::Key { key: Key::S, pressed: true, .. }))),
|
||||
"the save press was consumed once"
|
||||
);
|
||||
}
|
||||
// A discarded presented pass sees the original RawInput but does not dispatch it again;
|
||||
// pending/picker/write assertions below also prove that pass did not duplicate the save.
|
||||
assert_eq!(u.app.session.ds().unwrap().uid, owner, "press alone did not switch tabs");
|
||||
assert_eq!(geom(&u, a).0, 77.0, "the original field committed before delivery");
|
||||
u.frame(vec![button(false)]);
|
||||
assert_eq!(u.app.session.ds().unwrap().uid, other_uid, "the real tab release switched to B");
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(u.app.session.ds().unwrap().uid, other_uid, "saving A restores the front tab B");
|
||||
assert!(u.app.session.ds().unwrap().is_dirty(), "B was not saved");
|
||||
assert_eq!(std::fs::read(&other).unwrap(), other_bytes, "B's file was not overwritten");
|
||||
assert_eq!(asked.get(), usize::from(save_as), "only the original Save as asks for a path");
|
||||
assert_eq!(saved_x(if save_as { © } else { &path }, a), 77.0, "A's typed field is saved");
|
||||
assert_eq!(saved_x(&path, a), if save_as { 10.0 } else { 77.0 });
|
||||
assert!(u.app.ui.after_field.is_none());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts a deferred field save does not retarget a closed, moved or foreign owner: the other
|
||||
/// file stays untouched, Save as is not opened, and the stale request is consumed once.
|
||||
#[test]
|
||||
fn a_deferred_field_save_does_not_retarget_a_closed_moved_or_foreign_owner() {
|
||||
for change in ["closed", "moved", "foreign"] {
|
||||
for save_as in [false, true] {
|
||||
let (mut u, a, _) = setup();
|
||||
u.ctx.set_embed_viewports(false);
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-deferred-field-invalid-{}-{change}-{save_as}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (path, other, copy) = (dir.join("a.figcraft"), dir.join("b.figcraft"), dir.join("copy.figcraft"));
|
||||
u.app.session.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let owner = u.app.session.ds().unwrap().uid;
|
||||
u.app.session.execute("file.new", &json!({"name": "Deferred B"})).unwrap();
|
||||
u.app.session.execute("file.saveAs", &json!({"path": other.to_string_lossy()})).unwrap();
|
||||
u.app.session.execute("shape.rectangle", &json!({"x": 200, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let other_uid = u.app.session.ds().unwrap().uid;
|
||||
let other_bytes = std::fs::read(&other).unwrap();
|
||||
let index = u.app.session.docs.iter().position(|d| d.uid == owner).unwrap();
|
||||
u.app.session.execute("doc.switch", &json!({"index": index})).unwrap();
|
||||
let asked = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
u.app.services = Box::new(SaveAsPicker { path: Some(copy.clone()), asked: asked.clone() });
|
||||
let (at, _) = field(&mut u, "X");
|
||||
click(&mut u, at);
|
||||
assert!(crate::a11y::field_focused(&u.ctx));
|
||||
assert!(u.ctx.text_edit_focused(), "the actual field editor owns raw text");
|
||||
assert_eq!(u.ctx.memory(|m| m.focused()), Some(Id::unique("pos_x").with("te")), "X owns the keyboard");
|
||||
u.frame(vec![Event::Text("77".into())]);
|
||||
assert_eq!(u.ctx.data(|d| d.get_temp::<String>(Id::unique("pos_x").with("editing"))), Some("77".into()), "raw text reached X's draft");
|
||||
assert_eq!(geom(&u, a).0, 10.0, "typed field text is not committed before Save");
|
||||
let mut modifiers = if cfg!(target_os = "macos") { Modifiers::COMMAND } else { Modifiers::COMMAND.plus(Modifiers::CTRL) };
|
||||
if save_as {
|
||||
modifiers = modifiers.plus(Modifiers::SHIFT);
|
||||
}
|
||||
u.frame_with(
|
||||
vec![
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: true, repeat: false, modifiers },
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers },
|
||||
],
|
||||
modifiers,
|
||||
);
|
||||
assert!(u.app.ui.after_field.is_some());
|
||||
assert_eq!(geom(&u, a).0, 77.0, "field commit is still before the save");
|
||||
let owner_index = u.app.session.docs.iter().position(|d| d.uid == owner).unwrap();
|
||||
if change == "closed" {
|
||||
u.app.session.execute("file.close", &json!({"index": owner_index, "force": true})).unwrap();
|
||||
} else if change == "moved" {
|
||||
let window = crate::windows::open(&mut u.app, &u.ctx, Some(owner_index), None, None).unwrap();
|
||||
assert_ne!(window, 0);
|
||||
assert_eq!(u.app.windows.of(owner), window);
|
||||
} else {
|
||||
// An impossible/misrouted pane must fail closed too; no real window has this id.
|
||||
u.app.windows.current = u64::MAX;
|
||||
}
|
||||
let other_index = u.app.session.docs.iter().position(|d| d.uid == other_uid).unwrap();
|
||||
u.app.session.execute("doc.switch", &json!({"index": other_index})).unwrap();
|
||||
if change == "foreign" {
|
||||
// Exercise the actual consumer without begin() resetting this deliberate invalid
|
||||
// scope; the valid input/field producer above was the real app path.
|
||||
// Match this direct pass and the harness clock; egui's default predicted_dt is f32.
|
||||
let time = u.ctx.input(|i| i.time) + 1.0 / 60.0;
|
||||
u.advance_clock(time);
|
||||
u.ctx
|
||||
.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| {
|
||||
crate::shortcuts::handle(&mut u.app, ui.ctx(), false, Default::default())
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
u.app.windows.current = 0;
|
||||
} else {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(u.app.session.ds().unwrap().uid, other_uid);
|
||||
assert!(u.app.session.ds().unwrap().is_dirty(), "stale delivery must not save B");
|
||||
assert_eq!(std::fs::read(&other).unwrap(), other_bytes);
|
||||
assert_eq!(saved_x(&path, a), 10.0, "a cancelled owner is not saved");
|
||||
assert_eq!(asked.get(), 0, "a stale Save as must not open for B");
|
||||
assert!(!copy.exists());
|
||||
assert!(u.app.ui.after_field.is_none(), "consume stale requests once");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A save prepared for A must not force its cached X editor into B when routing changes the
|
||||
/// presented document before the fields draw, even though both panels use the same widget ID.
|
||||
#[test]
|
||||
fn a_prepared_field_save_cannot_commit_into_a_same_pass_replacement_document() {
|
||||
for route in ["control", "tab"] {
|
||||
for save_as in [false, true] {
|
||||
for discard in [false, true] {
|
||||
prepared_save_cannot_enter_a_replacement(route, save_as, discard);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One route/save-as/discard combination of the same-pass replacement test: a save prepared for A
|
||||
/// must not commit A's cached X editor into B when routing presents B before the fields draw,
|
||||
/// even though both panels use the same widget ID.
|
||||
fn prepared_save_cannot_enter_a_replacement(route: &str, save_as: bool, discard: bool) {
|
||||
let (mut u, a, _) = setup();
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-field-save-owner-{}-{route}-{save_as}-{discard}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (path, other, copy) = (dir.join("a.figcraft"), dir.join("b.figcraft"), dir.join("copy.figcraft"));
|
||||
u.app.session.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let owner = u.app.session.ds().unwrap().uid;
|
||||
let owner_bytes = std::fs::read(&path).unwrap();
|
||||
u.app.session.execute("file.new", &json!({"name": "Same-pass B"})).unwrap();
|
||||
let b = id(u.app.session.execute("shape.rectangle", &json!({"x": 200, "y": 40, "width": 30, "height": 30})).unwrap());
|
||||
u.app.session.execute("file.saveAs", &json!({"path": other.to_string_lossy()})).unwrap();
|
||||
u.app.session.execute("shape.rectangle", &json!({"x": 300, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
u.app.session.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let other_index = u.app.session.active;
|
||||
let other_uid = u.app.session.ds().unwrap().uid;
|
||||
let other_name = u.app.session.doc().unwrap().name.clone();
|
||||
let other_model = u.app.session.ds().unwrap().doc.clone();
|
||||
let before_switch_revision = u.app.session.ds().unwrap().revision;
|
||||
let other_history = u.app.session.undo_depth();
|
||||
let other_selection = u.app.session.ds().unwrap().selection.clone();
|
||||
let other_dirty = u.app.session.ds().unwrap().is_dirty();
|
||||
let other_bytes = std::fs::read(&other).unwrap();
|
||||
assert!(other_dirty, "B has independent unsaved content");
|
||||
let owner_index = u.app.session.docs.iter().position(|d| d.uid == owner).unwrap();
|
||||
u.app.session.execute("doc.switch", &json!({"index": owner_index})).unwrap();
|
||||
// Every command bumps the outgoing document's revision, even a nonediting switch.
|
||||
let other_revision = u.app.session.docs.iter().find(|d| d.uid == other_uid).unwrap().revision;
|
||||
assert_eq!(other_revision, before_switch_revision + 1, "the setup switch advances only B's command revision");
|
||||
let asked = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
u.app.services = Box::new(SaveAsPicker { path: Some(copy.clone()), asked: asked.clone() });
|
||||
let output = u.frame_output(vec![]);
|
||||
let nodes = output.platform_output.accesskit_update.unwrap().nodes;
|
||||
let tab = nodes
|
||||
.iter()
|
||||
.map(|(_, node)| node)
|
||||
.find(|node| node.role() == Role::Tab && node.label() == Some(other_name.as_str()))
|
||||
.expect("the actual B tab");
|
||||
let bounds = tab.bounds().unwrap();
|
||||
let tab_at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32);
|
||||
let (at, _) = field(&mut u, "X");
|
||||
click(&mut u, at);
|
||||
assert_eq!(u.ctx.memory(|m| m.focused()), Some(Id::unique("pos_x").with("te")));
|
||||
assert!(u.ctx.text_edit_focused());
|
||||
u.frame(vec![Event::Text("77".into())]);
|
||||
assert_eq!(u.ctx.data(|d| d.get_temp::<String>(Id::unique("pos_x").with("editing"))), Some("77".into()));
|
||||
assert_eq!(geom(&u, a).0, 10.0, "A's raw draft is not committed yet");
|
||||
assert_eq!(u.app.session.ds().unwrap().uid, owner, "the save begins with A presented");
|
||||
let reply = if route == "control" {
|
||||
let (reply, rx) = std::sync::mpsc::channel();
|
||||
u.app.control_queue.push(crate::ControlRequest {
|
||||
id: json!("same-pass-switch"),
|
||||
method: "engine.execute".into(),
|
||||
params: json!({"command": "doc.switch", "params": {"index": other_index}, "window": 0}),
|
||||
reply,
|
||||
state: Default::default(),
|
||||
});
|
||||
Some(rx)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut modifiers = if cfg!(target_os = "macos") { Modifiers::COMMAND } else { Modifiers::COMMAND.plus(Modifiers::CTRL) };
|
||||
if save_as {
|
||||
modifiers = modifiers.plus(Modifiers::SHIFT);
|
||||
}
|
||||
let mut events = vec![
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: true, repeat: false, modifiers },
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers },
|
||||
];
|
||||
if route == "tab" {
|
||||
events.push(Event::PointerMoved(tab_at));
|
||||
for pressed in [true, false] {
|
||||
events.push(Event::PointerButton { pos: tab_at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
|
||||
}
|
||||
}
|
||||
if discard {
|
||||
events.insert(0, Event::ModifiersChanged(modifiers));
|
||||
u.frame_raw_with_discard(egui::RawInput { events, ..Default::default() });
|
||||
} else {
|
||||
u.frame_with(events, modifiers);
|
||||
}
|
||||
if let Some(reply) = reply {
|
||||
let reply = reply.try_recv().expect("real control::drain acknowledged doc.switch in this pass");
|
||||
assert!(reply.result.is_ok(), "{:?}", reply.result);
|
||||
}
|
||||
let unchanged = |u: &Ui| {
|
||||
assert_eq!(u.app.session.ds().unwrap().uid, other_uid, "the real same-pass route presents B");
|
||||
assert_eq!(geom(u, b), (200.0, 40.0, 30.0, 30.0), "A's draft cannot enter B's field: route={route}, save_as={save_as}, discard={discard}");
|
||||
assert!(std::sync::Arc::ptr_eq(&u.app.session.ds().unwrap().doc, &other_model), "B's model is untouched");
|
||||
assert_eq!(u.app.session.ds().unwrap().revision, other_revision);
|
||||
assert_eq!(u.app.session.undo_depth(), other_history, "B's undo/redo history is unchanged");
|
||||
assert_eq!(u.app.session.ds().unwrap().selection, other_selection);
|
||||
assert_eq!(u.app.session.ds().unwrap().is_dirty(), other_dirty);
|
||||
assert_eq!(std::fs::read(&other).unwrap(), other_bytes);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), owner_bytes);
|
||||
assert_eq!(u.app.session.docs.iter().find(|d| d.uid == owner).unwrap().doc.world_bounds(a).unwrap().x0, 10.0);
|
||||
assert_eq!(asked.get(), 0, "the cancelled request never asks for a path");
|
||||
assert!(!copy.exists());
|
||||
assert!(u.app.ui.after_field.is_none(), "cancel before late fallback or queueing");
|
||||
};
|
||||
unchanged(&u);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
unchanged(&u);
|
||||
}
|
||||
// A cancelled draft is not a permanent veto: B accepts a later real field edit
|
||||
// and saves its own value through the same focused-field shortcut path.
|
||||
let (at, _) = field(&mut u, "X");
|
||||
click(&mut u, at);
|
||||
assert_eq!(u.ctx.memory(|m| m.focused()), Some(Id::unique("pos_x").with("te")));
|
||||
u.frame(vec![Event::Text("88".into())]);
|
||||
assert_eq!(geom(&u, b).0, 200.0, "fresh B text still waits for a normal commit");
|
||||
assert_eq!(u.ctx.data(|d| d.get_temp::<String>(Id::unique("pos_x").with("editing"))), Some("88".into()));
|
||||
u.frame_with(
|
||||
vec![
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: true, repeat: false, modifiers },
|
||||
Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers },
|
||||
],
|
||||
modifiers,
|
||||
);
|
||||
assert_eq!(geom(&u, b).0, 88.0, "a fresh B field commits normally");
|
||||
assert!(u.app.ui.after_field.is_some());
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(u.app.session.ds().unwrap().uid, other_uid);
|
||||
assert_eq!(saved_x(if save_as { © } else { &other }, b), 88.0, "a later valid save belongs to B");
|
||||
if save_as {
|
||||
assert_eq!(std::fs::read(&other).unwrap(), other_bytes);
|
||||
}
|
||||
assert_eq!(std::fs::read(&path).unwrap(), owner_bytes, "A stays unsaved");
|
||||
assert_eq!(asked.get(), usize::from(save_as));
|
||||
assert!(u.app.ui.after_field.is_none());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
@@ -32,7 +32,7 @@ fn key(style: &TextStyle, text: &str, ppp: f32) -> u64 {
|
||||
pub fn texture(ctx: &egui::Context, style: &TextStyle, text: &str, budget: &mut usize) -> Option<egui::TextureHandle> {
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let k = key(style, text, ppp);
|
||||
let cache = ctx.data_mut(|d| d.get_temp_mut_or_default::<Cache>(Id::new("font_previews")).clone());
|
||||
let cache = ctx.data_mut(|d| d.get_temp_mut_or_default::<Cache>(Id::unique("font_previews")).clone());
|
||||
if let Some(t) = cache.0.lock().ok()?.get(&k) {
|
||||
return t.clone();
|
||||
}
|
||||
|
||||
@@ -156,3 +156,23 @@ fn a_sections_label_renames_it_and_a_click_elsewhere_commits() {
|
||||
assert!(u.app.ui.rename_label.is_none());
|
||||
assert_eq!(u.app.session.ds().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sections_pill_is_above_the_labels_of_frames_inside_it() {
|
||||
// A frame near the section's top-left puts its label over the section's pill (#1150): the pill
|
||||
// draws last, so pressing where they overlap selects the section.
|
||||
let mut s = Session::new();
|
||||
let sec = id(s.execute("node.create", &json!({"type": "section", "x": 0, "y": 0, "width": 300, "height": 200, "name": "Marketing"})).unwrap());
|
||||
let f = id(s.execute("frame.create", &json!({"x": 10, "y": 22, "width": 100, "height": 80, "name": "Icon card", "parent": sec})).unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.frame(vec![]);
|
||||
let at = mid(&label(&u, sec));
|
||||
let frame_label = egui::Rect::from_points(&label(&u, f));
|
||||
assert!(frame_label.contains(at), "the frame's label {frame_label:?} overlaps the pill at {at:?}");
|
||||
let order: Vec<NodeId> = u.app.session.tool.labels.iter().map(|(id, _)| *id).collect();
|
||||
assert_eq!(order, vec![f, sec], "the section's label comes after (above) its frames'");
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
assert_eq!(u.app.session.selection(), vec![sec]);
|
||||
}
|
||||
@@ -58,10 +58,16 @@ pub fn turn_since(painter: &Painter, from: ShapeIdx, pivot: Pos2, angle: f32) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Recursively rotate shape geometry by `rot`/`angle` about `pivot`: leaves
|
||||
/// no-op/callback/band shapes alone, rotates points and centers, adds the angle to
|
||||
/// ellipses/rects/text, and rotates meshes.
|
||||
fn turn(shape: &mut Shape, rot: Rot2, angle: f32, pivot: Pos2) {
|
||||
let at = |p: &mut Pos2| *p = pivot + rot * (*p - pivot);
|
||||
match shape {
|
||||
Shape::Noop | Shape::Callback(_) => {}
|
||||
// Bands are not drawn by this UI; if one ever arrives, rotate it via its own `angle`
|
||||
// rather than approximating the samples as points.
|
||||
Shape::Band(_) => {}
|
||||
Shape::Vec(v) => v.iter_mut().for_each(|s| turn(s, rot, angle, pivot)),
|
||||
Shape::Circle(c) => at(&mut c.center),
|
||||
Shape::Ellipse(e) => {
|
||||
@@ -166,7 +172,7 @@ pub fn rename_field(app: &mut FigApp, ui: &mut egui::Ui) {
|
||||
let font = regular(11.0);
|
||||
let text_w = ui.painter().layout_no_wrap(name.clone(), font.clone(), Color32::WHITE).size().x;
|
||||
let rect = Rect::from_min_size(pos2(area.min.x, area.max.y - 16.0), vec2((text_w + 24.0).max(area.width()).clamp(80.0, 480.0), 16.0));
|
||||
let (done, open) = crate::widgets::rename_field(ui, egui::Id::new(("frame_label_rename", r.id)), &name, rect, font, r.start);
|
||||
let (done, open) = crate::widgets::rename_field(ui, egui::Id::unique(("frame_label_rename", r.id)), &name, rect, font, r.start);
|
||||
app.ui.rename_label = open.then_some(crate::layers::Rename { id: r.id, start: false });
|
||||
if let Some(new) = done {
|
||||
app.run("object.rename", serde_json::json!({"ids": [r.id], "name": new}));
|
||||
|
||||
@@ -10,6 +10,8 @@ use crate::icons::{self, Icon};
|
||||
use crate::theme::{Tokens, regular, semibold};
|
||||
use crate::widgets::{self, PAD};
|
||||
|
||||
/// Draw the expandable frame-preset categories; choosing a preset runs `frame.create`,
|
||||
/// switches to the Move tool and zooms to the new selection.
|
||||
pub fn panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
widgets::section_header(ui, tr("Frame"), &[], false);
|
||||
@@ -22,7 +24,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
let mut chosen = None;
|
||||
for cat in cats {
|
||||
let open_id = Id::new(("preset_cat", cat));
|
||||
let open_id = Id::unique(("preset_cat", cat));
|
||||
// The first category starts open.
|
||||
let open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(cat == "Phone");
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(w, 32.0), Sense::click());
|
||||
|
||||
@@ -49,13 +49,14 @@ struct Placed {
|
||||
line: Option<[Point; 2]>,
|
||||
}
|
||||
|
||||
/// Stable egui id for guide dragging.
|
||||
fn drag_id() -> Id {
|
||||
Id::new("guide_drag")
|
||||
Id::unique("guide_drag")
|
||||
}
|
||||
|
||||
/// The dragged guide as it would land.
|
||||
fn preview_id() -> Id {
|
||||
Id::new("guide_preview")
|
||||
Id::unique("guide_preview")
|
||||
}
|
||||
|
||||
/// The page's guides and those of its top-level frames (frames last, so they're found first).
|
||||
@@ -268,6 +269,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
app.run("guide.select", owned(g.owner, page, json!({"index": g.index})));
|
||||
if secondary {
|
||||
app.ui.context_menu = Some((pos, Vec::new()));
|
||||
app.ui.context_menu_shown = false;
|
||||
} else {
|
||||
ctx.data_mut(|d| {
|
||||
d.insert_temp(drag_id(), GuideDrag::Move { owner: g.owner, index: g.index, vertical: g.vertical, copy: alt, frame })
|
||||
|
||||
@@ -67,8 +67,9 @@ fn crop_corners(app: &FigApp, id: NodeId, r: (f64, f64, f64, f64)) -> Option<[Po
|
||||
])
|
||||
}
|
||||
|
||||
/// Stable egui id for handle dragging.
|
||||
fn drag_id() -> Id {
|
||||
Id::new("figcraft_handle_drag")
|
||||
Id::unique("figcraft_handle_drag")
|
||||
}
|
||||
|
||||
/// The gradient being edited (single node, picker open on a gradient paint).
|
||||
|
||||
+19
-10
@@ -188,6 +188,8 @@ fn dropped(app: &mut FigApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the Home sidebar: app icon and wordmark, file/template search (Escape clears it)
|
||||
/// and section tabs; choosing a section clears the file query.
|
||||
fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
|
||||
let mut y = left.min.y + 20.0;
|
||||
crate::theme::paint_app_icon(ui, Rect::from_min_size(pos2(left.min.x + 12.0, y - 4.0), vec2(32.0, 32.0)));
|
||||
@@ -195,8 +197,13 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
|
||||
y += 52.0;
|
||||
let search = Rect::from_min_size(pos2(left.min.x + 8.0, y), vec2(SIDEBAR - 16.0, widgets::FIELD_H));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(search), |ui| {
|
||||
let response =
|
||||
widgets::text_input(ui, Id::new("home_file_search"), &mut app.ui.home_view.file_query, search.width(), tr("Search files and templates"));
|
||||
let response = widgets::text_input(
|
||||
ui,
|
||||
Id::unique("home_file_search"),
|
||||
&mut app.ui.home_view.file_query,
|
||||
search.width(),
|
||||
tr("Search files and templates"),
|
||||
);
|
||||
a11y::text(&response, tr("Search files and templates"), &app.ui.home_view.file_query);
|
||||
if (response.has_focus() || response.lost_focus()) && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.ui.home_view.file_query.clear();
|
||||
@@ -205,7 +212,7 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
|
||||
y += widgets::FIELD_H + 12.0;
|
||||
for (section, icon, label) in Section::ALL {
|
||||
let r = Rect::from_min_size(pos2(left.min.x + 8.0, y), vec2(SIDEBAR - 16.0, 32.0));
|
||||
let resp = ui.interact(r, ui.id().with(("home_section", label)), Sense::click());
|
||||
let resp = ui.interact(r, ui.scope_id().with(("home_section", label)), Sense::click());
|
||||
let current = app.ui.home_view.file_query.trim().is_empty() && app.ui.home_view.section == section;
|
||||
a11y::tab(&resp, tr(label), current);
|
||||
if current || resp.hovered() {
|
||||
@@ -250,7 +257,7 @@ fn search_results(app: &mut FigApp, ui: &mut Ui, t: &Tokens) {
|
||||
detail_size: 11.0,
|
||||
detail_ink: t.text_secondary,
|
||||
};
|
||||
if listed(ui, t, ui.id().with(("search_online", &f.server, &f.file)), 36.0, &row) {
|
||||
if listed(ui, t, ui.scope_id().with(("search_online", &f.server, &f.file)), 36.0, &row) {
|
||||
open_online = Some(f.clone());
|
||||
}
|
||||
}
|
||||
@@ -385,7 +392,7 @@ fn open_files(app: &mut FigApp, ui: &mut Ui, t: &Tokens, query: &str) -> usize {
|
||||
detail_size: 11.0,
|
||||
detail_ink: t.text_secondary,
|
||||
};
|
||||
if listed(ui, t, ui.id().with(("open", d.uid)), 36.0, &row) {
|
||||
if listed(ui, t, ui.scope_id().with(("open", d.uid)), 36.0, &row) {
|
||||
switch = Some(i);
|
||||
}
|
||||
}
|
||||
@@ -423,7 +430,7 @@ fn getting_started(app: &mut FigApp, ui: &mut Ui, t: &Tokens) {
|
||||
let close = Rect::from_min_size(pos2(rect.max.x - 36.0, rect.min.y + 12.0), vec2(24.0, 24.0));
|
||||
if widgets::icon_button_at(
|
||||
ui,
|
||||
ui.id().with("tips_close"),
|
||||
ui.scope_id().with("tips_close"),
|
||||
close,
|
||||
Icon::Close,
|
||||
tr("Hide these tips (Getting started in the Help menu shows them again)"),
|
||||
@@ -470,10 +477,12 @@ fn matches(template: &Template, query: &str, kind: Option<Kind>) -> bool {
|
||||
|| has(template.size))
|
||||
}
|
||||
|
||||
/// Draw template search and kind filter, show no-match guidance and a "Show all templates"
|
||||
/// button that clears the query and kind, and lay matching templates out in a grid.
|
||||
fn templates(app: &mut FigApp, ui: &mut Ui, t: &Tokens) {
|
||||
heading(ui, t, tr("Templates"));
|
||||
ui.horizontal(|ui| {
|
||||
let search = widgets::text_input(ui, Id::new("home_template_search"), &mut app.ui.home_view.query, 260.0, tr("Search templates"));
|
||||
let search = widgets::text_input(ui, Id::unique("home_template_search"), &mut app.ui.home_view.query, 260.0, tr("Search templates"));
|
||||
a11y::text(&search, tr("Search templates"), &app.ui.home_view.query);
|
||||
let labels: Vec<&str> = std::iter::once(tr("All")).chain(Kind::ALL.iter().map(|k| tr(k.label()))).collect();
|
||||
let active = app.ui.home_view.kind.and_then(|k| Kind::ALL.iter().position(|x| *x == k)).map_or(0, |i| i + 1);
|
||||
@@ -506,7 +515,7 @@ fn templates(app: &mut FigApp, ui: &mut Ui, t: &Tokens) {
|
||||
fn template_grid(app: &mut FigApp, ui: &mut Ui, t: &Tokens, list: &[&Template]) {
|
||||
let columns = (((ui.available_width() + GAP) / (CARD_W + GAP)).floor() as usize).max(1);
|
||||
let dark = ui.visuals().dark_mode;
|
||||
let mut thumbs: Thumbs = ui.data(|d| d.get_temp(Id::new("template_thumbs"))).unwrap_or_default();
|
||||
let mut thumbs: Thumbs = ui.data(|d| d.get_temp(Id::unique("template_thumbs"))).unwrap_or_default();
|
||||
let mut chosen = None;
|
||||
let mut rendered = false;
|
||||
for row in list.chunks(columns) {
|
||||
@@ -529,7 +538,7 @@ fn template_grid(app: &mut FigApp, ui: &mut Ui, t: &Tokens, list: &[&Template])
|
||||
});
|
||||
ui.add_space(GAP);
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(Id::new("template_thumbs"), thumbs));
|
||||
ui.data_mut(|d| d.insert_temp(Id::unique("template_thumbs"), thumbs));
|
||||
if let Some(template) = chosen
|
||||
&& app.run("file.newFromTemplate", json!({"template": template.id, "name": tr(template.name)})).is_some()
|
||||
{
|
||||
@@ -601,6 +610,6 @@ fn thumbnail(ctx: &egui::Context, template: &Template, background: figcraft_colo
|
||||
/// Tests: the templates whose pictures are cached for the light or dark theme.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cached_thumbnails(ctx: &egui::Context, dark: bool) -> Vec<&'static str> {
|
||||
let thumbs: Thumbs = ctx.data(|d| d.get_temp(Id::new("template_thumbs"))).unwrap_or_default();
|
||||
let thumbs: Thumbs = ctx.data(|d| d.get_temp(Id::unique("template_thumbs"))).unwrap_or_default();
|
||||
thumbs.0.iter().filter(|((_, d), thumb)| *d == dark && thumb.is_some()).map(|((id, _), _)| *id).collect()
|
||||
}
|
||||
@@ -685,7 +685,7 @@ fn heading(ui: &mut Ui, t: &Tokens, text: &str) {
|
||||
|
||||
/// The id of `path`'s card or row (stable, so the keyboard stays on it as the order changes).
|
||||
fn card_id(path: &str) -> Id {
|
||||
Id::new(("home_recent_file", path))
|
||||
Id::unique(("home_recent_file", path))
|
||||
}
|
||||
|
||||
/// Clicks, keys and the context menu on a card or row: a click selects, a double-click or Enter
|
||||
@@ -909,7 +909,7 @@ fn list(ui: &mut Ui, t: &Tokens, recents: &mut Recents, files: &[Shown], now: u6
|
||||
let x0 = if i == 0 { header.min.x } else { header.min.x + date_x(i) };
|
||||
let x1 = if i + 1 < columns.len() { header.min.x + date_x(i + 1) } else { header.max.x };
|
||||
let cell = Rect::from_min_max(pos2(x0, header.min.y), pos2(x1, header.max.y));
|
||||
let resp = ui.interact(cell, Id::new(("home_recents_header", key.id())), Sense::click());
|
||||
let resp = ui.interact(cell, Id::unique(("home_recents_header", key.id())), Sense::click());
|
||||
a11y::button(&resp, &trf("Sort by {column}", &[("column", label)]));
|
||||
let on = sort.key == *key;
|
||||
if resp.hovered() {
|
||||
|
||||
@@ -1283,7 +1283,7 @@ pub fn paint_outlines(painter: &Painter, rect: Rect, size: f64, parts: &[(&figcr
|
||||
/// Every icon at the sizes the UI uses, labelled: for reviewing the set (`ui.set {iconGallery}`).
|
||||
pub fn gallery(ctx: &egui::Context) {
|
||||
let t = crate::theme::Tokens::get(ctx);
|
||||
egui::Area::new(egui::Id::new("icon_gallery")).order(egui::Order::Foreground).fixed_pos(Pos2::ZERO).show(ctx, |ui| {
|
||||
egui::Area::new(egui::Id::unique("icon_gallery")).order(egui::Order::Foreground).fixed_pos(Pos2::ZERO).show(ctx, |ui| {
|
||||
let screen = ctx.content_rect();
|
||||
let (r, _) = ui.allocate_exact_size(screen.size(), egui::Sense::click());
|
||||
ui.painter().rect_filled(r, 0.0, t.panel);
|
||||
@@ -1381,7 +1381,7 @@ mod tests {
|
||||
let mut u = crate::layers_drag_tests::Ui::new(s);
|
||||
u.frame(vec![]);
|
||||
let shapes = u.frame_output(vec![]).shapes;
|
||||
let lead = |name: &str| u.ctx.read_response(egui::Id::new(name).with("lead")).map(|r| r.rect).unwrap_or_else(|| panic!("{name} is shown"));
|
||||
let lead = |name: &str| u.ctx.read_response(egui::Id::unique(name).with("lead")).map(|r| r.rect).unwrap_or_else(|| panic!("{name} is shown"));
|
||||
let (rotation, radius) = (marks(&shapes, lead("pos_rot")), marks(&shapes, lead("ap_rad")));
|
||||
assert!(!rotation.is_empty() && !radius.is_empty(), "both draw an icon");
|
||||
assert_ne!(rotation, radius);
|
||||
|
||||
@@ -36,6 +36,7 @@ impl Harness {
|
||||
/// One frame with `events`, 1/60 s after the last; returns the repaint delay it asked for.
|
||||
fn frame(&mut self, events: Vec<Event>) -> Duration {
|
||||
self.time += 1.0 / 60.0;
|
||||
self.app.clock.set_test_now(Some(self.time));
|
||||
let input =
|
||||
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), events, ..Default::default() };
|
||||
let app = &mut self.app;
|
||||
@@ -247,6 +248,8 @@ fn a_finished_background_render_wakes_the_ui() {
|
||||
assert!(worker.poll().is_some(), "the woken frame finds the image");
|
||||
}
|
||||
|
||||
/// Asserts a control request wakes an idle UI and is answered, and screenshots keep frames
|
||||
/// coming until delivered before the UI rests again.
|
||||
#[test]
|
||||
fn control_requests_and_screenshots_wake_an_idle_ui() {
|
||||
let (mut h, _) = document();
|
||||
@@ -258,7 +261,7 @@ fn control_requests_and_screenshots_wake_an_idle_ui() {
|
||||
method: "ui.inspect".into(),
|
||||
params: json!({}),
|
||||
reply: tx.clone(),
|
||||
cancelled: Default::default(),
|
||||
state: Default::default(),
|
||||
});
|
||||
assert_eq!(h.frame(vec![]), Duration::ZERO);
|
||||
assert!(rx.try_recv().unwrap().result.is_ok());
|
||||
@@ -266,15 +269,20 @@ fn control_requests_and_screenshots_wake_an_idle_ui() {
|
||||
// A screenshot keeps frames coming until the window delivers it, then the UI rests again.
|
||||
let path = std::env::temp_dir().join(format!("figcraft-idle-shot-{}.png", std::process::id()));
|
||||
let params = json!({"path": path.to_string_lossy()});
|
||||
h.app.control_queue.push(ControlRequest { id: json!(2), method: "ui.screenshot".into(), params, reply: tx, cancelled: Default::default() });
|
||||
h.app.control_queue.push(ControlRequest { id: json!(2), method: "ui.screenshot".into(), params, reply: tx, state: Default::default() });
|
||||
for _ in 0..5 {
|
||||
assert_eq!(h.frame(vec![]), Duration::ZERO, "waiting for the screenshot");
|
||||
let delay = h.frame(vec![]);
|
||||
assert!(delay <= Duration::from_secs_f64(crate::control::SHOT_TIMEOUT), "waiting for the screenshot");
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "not delivered yet");
|
||||
let image = Arc::new(egui::ColorImage::filled([4, 4], egui::Color32::RED));
|
||||
h.frame(vec![Event::Screenshot { viewport_id: ViewportId::ROOT, user_data: egui::UserData::default(), image }]);
|
||||
// The settled UI issued the viewport capture command; the renderer completes its one-shot
|
||||
// slot, and the next UI pass writes the reply.
|
||||
let spec = h.app.capture.shots.first().and_then(|r| r.spec).expect("admitted against real geometry");
|
||||
let slot = h.app.capture.shots.first().and_then(|r| r.slot.clone()).expect("issued after settling");
|
||||
slot.complete(Arc::new(egui::ColorImage::filled(spec.size_px, egui::Color32::RED)));
|
||||
h.frame(vec![]);
|
||||
let reply = rx.try_recv().unwrap();
|
||||
assert_eq!(reply.result.unwrap()["width"], json!(4));
|
||||
assert_eq!(reply.result.unwrap()["width"], json!(spec.size_px[0]));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
h.assert_idle("after a screenshot");
|
||||
}
|
||||
@@ -335,41 +343,52 @@ fn cjk_names_are_looked_for_in_edits_not_on_every_pan() {
|
||||
assert_eq!(h.app.cjk_needed(&ctx, 0), crate::cjk::HANGUL);
|
||||
}
|
||||
|
||||
/// Asserts a hidden window answers edits and inspection at once, while a screenshot is
|
||||
/// parked with a deadline and times out once instead of waiting for a frame.
|
||||
#[test]
|
||||
fn a_hidden_window_answers_at_once() {
|
||||
// #269, #720: minimised or covered, the window draws no frames, but the app's logic still runs:
|
||||
// it answers edits, inspection, saves and the interface's state; what needs a frame (a capture
|
||||
// of the window) is an error at once instead of waiting for the window to show.
|
||||
// of the window) queues for a forced hidden paint and otherwise expires at its deadline.
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-hidden-save-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("hidden.figcraft");
|
||||
let (mut h, _) = document();
|
||||
h.settle();
|
||||
// Exercise admission well after startup, independently of settling speed.
|
||||
h.time += 120.0;
|
||||
h.app.clock.set_test_now(Some(h.time));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let request = |id: u64, method: &str, params: Value| ControlRequest {
|
||||
id: json!(id),
|
||||
method: method.into(),
|
||||
params,
|
||||
reply: tx.clone(),
|
||||
cancelled: Default::default(),
|
||||
state: Default::default(),
|
||||
};
|
||||
h.app.control_queue.push(request(1, "engine.execute", json!({"command": "file.save", "params": {"path": path.to_string_lossy()}})));
|
||||
h.app.control_queue.push(request(2, "ui.inspect", json!({})));
|
||||
h.app.control_queue.push(request(3, "ui.screenshot", json!({"path": dir.join("shot.png").to_string_lossy()})));
|
||||
let mut hidden = RawInput::default();
|
||||
hidden.viewports.insert(ViewportId::ROOT, egui::ViewportInfo { minimized: Some(true), ..Default::default() });
|
||||
let app = &mut h.app;
|
||||
let _ = h.ctx.run_logic(&hidden, |ctx| crate::control::drain_hidden(app, ctx));
|
||||
let ctx = h.ctx.clone();
|
||||
let _ = ctx.run_logic(&hidden, |ctx| crate::control::background(&mut h.app, ctx));
|
||||
let saved = rx.try_recv().unwrap();
|
||||
assert_eq!(saved.id, json!(1));
|
||||
assert!(saved.result.is_ok() && path.exists(), "saved while hidden: {:?}", saved.result);
|
||||
let inspected = rx.try_recv().unwrap();
|
||||
assert_eq!(inspected.id, json!(2));
|
||||
assert!(inspected.result.is_ok(), "the interface's state: {:?}", inspected.result);
|
||||
let shot = rx.try_recv().unwrap();
|
||||
assert_eq!(shot.id, json!(3));
|
||||
assert!(shot.result.unwrap_err().contains("minimised or hidden"), "a capture needs the window on screen");
|
||||
assert!(rx.try_recv().is_err(), "a capture queues for a forced hidden paint");
|
||||
assert_eq!(h.app.capture.shots.len(), 1, "one admitted capture");
|
||||
assert!(h.app.control_queue.is_empty(), "nothing waits for the window");
|
||||
// Its deadline expires it once, with the same error the transport used to get.
|
||||
h.app.clock.set_test_now(Some(h.time + crate::control::SHOT_TIMEOUT + 1.0));
|
||||
let _ = ctx.run_logic(&hidden, |ctx| crate::control::background(&mut h.app, ctx));
|
||||
let shot = rx.try_recv().expect("expired");
|
||||
assert_eq!(shot.id, json!(3));
|
||||
assert!(shot.result.unwrap_err().contains("didn't deliver a screenshot"), "a capture needs paint");
|
||||
assert!(h.app.capture.shots.is_empty(), "released after its deadline");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -408,3 +427,47 @@ fn auto_save_writes_a_changed_file_then_rests() {
|
||||
h.assert_idle("an auto-saved file");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Asserts a hidden logic tick runs background work and advances the autosave deadline
|
||||
/// without counting a UI frame, and is idempotent at the same time.
|
||||
#[test]
|
||||
fn a_hidden_logic_tick_runs_background_work_but_counts_no_ui_frame() {
|
||||
let (mut h, _) = document();
|
||||
h.settle();
|
||||
let frames = h.app.frame_stats.frames;
|
||||
let deadline_before = h.app.ui.next_autosave;
|
||||
h.time += crate::AUTOSAVE_SECS + 1.0;
|
||||
h.app.clock.set_test_now(Some(h.time));
|
||||
let mut input = RawInput::default();
|
||||
input.viewports.insert(ViewportId::ROOT, egui::ViewportInfo { minimized: Some(true), ..Default::default() });
|
||||
let ctx = h.ctx.clone();
|
||||
let _ = ctx.run_logic(&input, |ctx| h.app.background_tick(ctx));
|
||||
assert_eq!(h.app.frame_stats.frames, frames, "a logic-only tick is not a UI frame");
|
||||
let deadline = h.app.ui.next_autosave;
|
||||
assert!(deadline > deadline_before + crate::AUTOSAVE_SECS - 1.0, "the autosave deadline advanced");
|
||||
// Repeating the same due instant does not advance it again (consumed/deadline-driven work).
|
||||
let _ = ctx.run_logic(&input, |ctx| h.app.background_tick(ctx));
|
||||
assert_eq!(h.app.ui.next_autosave, deadline, "idempotent at the same monotonic time");
|
||||
}
|
||||
|
||||
/// Asserts a discarded sizing pass counts one drawn frame, not one per pass.
|
||||
#[test]
|
||||
fn a_discarded_sizing_pass_sets_up_and_counts_one_frame_only() {
|
||||
let (mut h, _) = document();
|
||||
h.settle();
|
||||
let frames = h.app.frame_stats.frames;
|
||||
let input =
|
||||
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(h.time + 1.0 / 60.0), ..Default::default() };
|
||||
let mut passes = 0;
|
||||
let app = &mut h.app;
|
||||
let mut out = h.ctx.run_ui(input, |ui| {
|
||||
passes += 1;
|
||||
app.ui(ui);
|
||||
if passes == 1 {
|
||||
ui.ctx().request_discard("test sizing pass");
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(passes, 2, "egui reran the frame");
|
||||
assert_eq!(app.frame_stats.frames, frames + 1, "one frame was drawn, not one per pass");
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! edit (an idle frame too) with the candidate window at the caret, the composition shows without
|
||||
//! entering the document, keys pressed while composing are the IME's, and the commit lands once.
|
||||
|
||||
use egui::output::{IMEOutput, IMESurroundingText, IMESurroundingTextPayload, ImeChangeCause};
|
||||
use egui::{Event, ImeEvent, Key, Modifiers, RawInput, Rect};
|
||||
use figcraft_doc::{NodeId, NodeKind};
|
||||
use figcraft_engine::Session;
|
||||
@@ -42,6 +43,24 @@ fn composing(u: &Ui) -> Option<String> {
|
||||
u.app.session.ds().unwrap().text_edit.as_ref().expect("still editing").preedit.as_ref().map(|p| p.text.clone())
|
||||
}
|
||||
|
||||
/// The whole IME descriptor one frame leaves for the platform.
|
||||
fn ime_descriptor(u: &mut Ui, events: Vec<Event>) -> IMEOutput {
|
||||
u.frame_raw(RawInput { events, ..Default::default() }).platform_output.ime.expect("the IME stays on while editing")
|
||||
}
|
||||
|
||||
/// Return the available surrounding-text payload of an IME output, panicking when unavailable.
|
||||
fn available(ime: &IMEOutput) -> &IMESurroundingTextPayload {
|
||||
match &ime.surrounding_text {
|
||||
IMESurroundingText::Available(payload) => payload,
|
||||
IMESurroundingText::Unavailable => panic!("expected available surrounding text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a text layer with `text` and return its node id.
|
||||
fn text_layer(s: &mut Session, text: &str) -> NodeId {
|
||||
NodeId(s.execute("text.create", &json!({"text": text, "x": 40, "y": 40})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinyin_composes_inline_and_commits_once_with_the_ime_on_every_frame() {
|
||||
// The text is measured with a font: without craft-fonts a system one, scanned here rather than
|
||||
@@ -85,3 +104,543 @@ fn pinyin_composes_inline_and_commits_once_with_the_ime_on_every_frame() {
|
||||
ime(&mut u, vec![key(Key::Enter, true), key(Key::Enter, false), Event::Text("!".into())]);
|
||||
assert_eq!(text(&u, t), "Hi你好\n!");
|
||||
}
|
||||
|
||||
/// Asserts an empty IME commit ends the composition, inserts nothing, keeps the editor
|
||||
/// focused, and the next pass observes the committed text.
|
||||
#[test]
|
||||
fn an_empty_ime_commit_ends_the_composition_without_inserting_text() {
|
||||
// Safari's egui web integration sends `Commit("")` (not `Preedit("")`) when the last
|
||||
// composition character is deleted. It ends the composition; it must not leave the pre-edit
|
||||
// rendering or insert anything.
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hello");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(5), false).unwrap();
|
||||
ime(&mut u, vec![preedit("にほ")]);
|
||||
assert_eq!(composing(&u).as_deref(), Some("にほ"));
|
||||
let after = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit(String::new()))]);
|
||||
assert_eq!(composing(&u), None, "the empty commit ends the composition");
|
||||
assert_eq!(text(&u, t), "Hello", "and inserts nothing");
|
||||
assert!(matches!(after.surrounding_text, IMESurroundingText::Available(_)));
|
||||
// The editor is still focused, and the next pass observes committed text only.
|
||||
let next = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(composing(&u), None);
|
||||
assert_eq!(available(&next).text, "Hello");
|
||||
assert_eq!(text(&u, t), "Hello");
|
||||
}
|
||||
|
||||
/// Asserts byte deletion before the paired commit replaces the exact UTF-8 range, and one undo
|
||||
/// restores the pre-IME text.
|
||||
#[test]
|
||||
fn an_ime_replacing_text_deletes_in_bytes_before_the_paired_commit() {
|
||||
// 0.37 sends `DeleteSurroundingBytes` immediately before the commit that replaces it. The
|
||||
// custom engine editor deletes the exact UTF-8 range (never display-bidi text) and keeps the
|
||||
// whole edit as one undo step.
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = NodeId(s.execute("text.create", &json!({"text": "ab\u{4F60}\u{597D}cd", "x": 40, "y": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(4), false).unwrap();
|
||||
ime(&mut u, vec![]);
|
||||
// Compose, then replace "你好c" with "X".
|
||||
ime(&mut u, vec![preedit("x")]);
|
||||
ime(&mut u, vec![Event::Ime(ImeEvent::DeleteSurroundingBytes { before_bytes: 6, after_bytes: 1 }), Event::Ime(ImeEvent::Commit("X".into()))]);
|
||||
assert_eq!(text(&u, t), "abXd");
|
||||
figcraft_engine::textedit::end(&mut u.app.session).unwrap();
|
||||
u.app.session.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&u, t), "ab\u{4F60}\u{597D}cd", "one undo restores the pre-IME text");
|
||||
}
|
||||
|
||||
/// Asserts a caret click invalidates the whole stale IME batch (both byte and character
|
||||
/// deletions) while a later direct commit still works.
|
||||
#[test]
|
||||
fn a_caret_click_rejects_the_stale_delete_and_commit_in_the_same_input_batch() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
for delete in
|
||||
[ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 1 }, ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 1 }]
|
||||
{
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "abcdef");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(6), false).unwrap();
|
||||
ime(&mut u, vec![preedit("z")]);
|
||||
let p = u.app.to_screen(42.0, 45.0);
|
||||
// Real canvas pointer handling moves the caret and cancels preedit before text_keys.
|
||||
ime(
|
||||
&mut u,
|
||||
vec![
|
||||
Event::PointerMoved(p),
|
||||
Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
|
||||
Event::Ime(delete),
|
||||
Event::Ime(ImeEvent::Commit("Q".into())),
|
||||
],
|
||||
);
|
||||
let edit = u.app.session.ds().unwrap().text_edit.as_ref().unwrap();
|
||||
assert!(edit.caret < 6, "the production canvas click actually moved the caret");
|
||||
assert!(edit.preedit.is_none(), "the click ended the composition");
|
||||
assert_eq!(text(&u, t), "abcdef", "neither stale deletion nor its Commit may mutate the clicked caret");
|
||||
u.frame(vec![Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]);
|
||||
// A later direct commit without an active composition is legitimate.
|
||||
let caret = u.app.session.ds().unwrap().text_edit.as_ref().unwrap().caret;
|
||||
ime(&mut u, vec![Event::Ime(ImeEvent::Commit("X".into()))]);
|
||||
let mut expected = "abcdef".to_string();
|
||||
expected.insert(caret, 'X');
|
||||
assert_eq!(text(&u, t), expected, "the interrupted batch does not poison a later direct commit");
|
||||
figcraft_engine::textedit::end(&mut u.app.session).unwrap();
|
||||
u.app.session.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&u, t), "abcdef", "the valid edit retains one-session undo");
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts a control-channel document switch rejects the old composition's delete and commit
|
||||
/// batch, while a direct commit to the new target remains valid.
|
||||
#[test]
|
||||
fn a_document_switch_rejects_the_old_compositions_delete_and_commit_batch() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let a = text_layer(&mut s, "Alpha");
|
||||
s.execute("file.new", &json!({"name": "B"})).unwrap();
|
||||
let b = text_layer(&mut s, "Bravo");
|
||||
figcraft_engine::textedit::begin(&mut s, b, Some(5), false).unwrap();
|
||||
s.execute("doc.switch", &json!({"index": 0})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, a, Some(5), false).unwrap();
|
||||
ime(&mut u, vec![preedit("z")]);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
u.app.control_queue.push(crate::control::ControlRequest {
|
||||
id: json!(91),
|
||||
method: "engine.execute".into(),
|
||||
params: json!({"window": 0, "command": "doc.switch", "params": {"index": 1}}),
|
||||
reply: tx,
|
||||
state: Default::default(),
|
||||
});
|
||||
ime(&mut u, vec![Event::Ime(ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 }), Event::Ime(ImeEvent::Commit("Q".into()))]);
|
||||
assert!(rx.try_recv().unwrap().result.is_ok(), "production control drain switched the document");
|
||||
assert_eq!(u.app.session.active, 1);
|
||||
assert_eq!(text(&u, b), "Bravo", "the new target cannot inherit the old composition's mutations");
|
||||
assert_eq!(u.app.session.docs[0].doc.node(a).unwrap().kind.text().unwrap().characters, "Alpha");
|
||||
ime(&mut u, vec![Event::Ime(ImeEvent::Commit("X".into()))]);
|
||||
assert_eq!(text(&u, b), "BravoX", "a direct commit to the new noncomposing target remains valid");
|
||||
}
|
||||
|
||||
/// Asserts the first observation and ordinary typing are `Other`, while an accepted commit is
|
||||
/// `InputMethod` with UTF-8 offsets, the same owner and generation.
|
||||
#[test]
|
||||
fn ime_cause_is_input_method_only_for_an_accepted_commit() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
|
||||
let first = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(first.change_cause, ImeChangeCause::Other, "the first focused observation starts a context");
|
||||
assert_eq!(available(&first).text, "Hi");
|
||||
assert_eq!((available(&first).cursor, available(&first).anchor), (2, 2));
|
||||
|
||||
let commit = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("你好".into()))]);
|
||||
assert_eq!(commit.change_cause, ImeChangeCause::InputMethod);
|
||||
assert_eq!(available(&commit).text, "Hi你好");
|
||||
assert_eq!(available(&commit).cursor, 8, "UTF-8 bytes, not characters");
|
||||
assert_eq!(commit.context_generation, first.context_generation, "a commit is not a context change");
|
||||
assert_eq!(commit.owner, first.owner);
|
||||
|
||||
let typed = ime_descriptor(&mut u, vec![Event::Text("x".into())]);
|
||||
assert_eq!(typed.change_cause, ImeChangeCause::Other, "ordinary typing is an application edit");
|
||||
assert_eq!(available(&typed).text, "Hi你好x");
|
||||
assert_eq!(text(&u, t), "Hi你好x");
|
||||
}
|
||||
|
||||
/// Asserts a frame mixing IME and application edits is `Other`, and a later pure commit is
|
||||
/// `InputMethod` without lingering state.
|
||||
#[test]
|
||||
fn ime_cause_reports_mixed_application_and_ime_mutations_as_other() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
ime(&mut u, vec![]);
|
||||
|
||||
let mixed = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("あ".into())), Event::Text("b".into())]);
|
||||
assert_eq!(mixed.change_cause, ImeChangeCause::Other, "an application edit in the same frame dominates");
|
||||
assert_eq!(available(&mixed).text, "Hiあb");
|
||||
|
||||
// The next frame is only an accepted commit: the frame-scoped `Other` does not linger.
|
||||
let pure = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("う".into()))]);
|
||||
assert_eq!(pure.change_cause, ImeChangeCause::InputMethod);
|
||||
assert_eq!(available(&pure).text, "Hiあbう");
|
||||
|
||||
// An application edit before the IME receipt, and IME → application → IME, are both Other.
|
||||
let before = ime_descriptor(&mut u, vec![Event::Text("c".into()), Event::Ime(ImeEvent::Commit("え".into()))]);
|
||||
assert_eq!(before.change_cause, ImeChangeCause::Other);
|
||||
let sandwiched =
|
||||
ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("お".into())), Event::Text("d".into()), Event::Ime(ImeEvent::Commit("か".into()))]);
|
||||
assert_eq!(sandwiched.change_cause, ImeChangeCause::Other);
|
||||
assert_eq!(text(&u, t), "Hiあbうcえおdか");
|
||||
}
|
||||
|
||||
/// Asserts a control-channel text edit is an application change (`Other`).
|
||||
#[test]
|
||||
fn a_control_channel_text_edit_is_an_application_change() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
ime(&mut u, vec![]);
|
||||
|
||||
// A command from the control channel (not an ImeEvent) changes committed text.
|
||||
u.app.session.execute("text.edit.insert", &json!({"text": "z"})).unwrap();
|
||||
let out = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(out.change_cause, ImeChangeCause::Other);
|
||||
assert_eq!(available(&out).text, "Hiz");
|
||||
}
|
||||
|
||||
/// Asserts a byte delete followed by a commit is `InputMethod` and describes the
|
||||
/// post-mutation text and caret.
|
||||
#[test]
|
||||
fn ime_delete_then_commit_is_input_method_and_describes_the_post_mutation_text() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "ab\u{4F60}\u{597D}cd");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(4), false).unwrap();
|
||||
ime(&mut u, vec![]);
|
||||
|
||||
let out = ime_descriptor(
|
||||
&mut u,
|
||||
vec![Event::Ime(ImeEvent::DeleteSurroundingBytes { before_bytes: 6, after_bytes: 1 }), Event::Ime(ImeEvent::Commit("X".into()))],
|
||||
);
|
||||
assert_eq!(out.change_cause, ImeChangeCause::InputMethod);
|
||||
assert_eq!(available(&out).text, "abXd", "the snapshot is observed after both mutations");
|
||||
assert_eq!(available(&out).cursor, 3);
|
||||
assert_eq!(text(&u, t), "abXd");
|
||||
}
|
||||
|
||||
/// Asserts preedit text is excluded from surrounding text and earns no receipt, while the
|
||||
/// following commit is `InputMethod`.
|
||||
#[test]
|
||||
fn preedit_is_not_surrounding_text_but_the_commit_that_follows_is_input_method() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
ime(&mut u, vec![]);
|
||||
|
||||
let composing = ime_descriptor(&mut u, vec![preedit("にほ")]);
|
||||
assert_eq!(available(&composing).text, "Hi", "the composition is excluded");
|
||||
assert_eq!((available(&composing).cursor, available(&composing).anchor), (2, 2));
|
||||
assert_eq!(composing.change_cause, ImeChangeCause::Other, "preedit alone earns no receipt");
|
||||
|
||||
let committed = ime_descriptor(&mut u, vec![preedit(""), Event::Ime(ImeEvent::Commit("にほ".into()))]);
|
||||
assert_eq!(committed.change_cause, ImeChangeCause::InputMethod);
|
||||
assert_eq!(available(&committed).text, "Hiにほ");
|
||||
assert_eq!(available(&committed).cursor, 8);
|
||||
}
|
||||
|
||||
/// Asserts surrounding text is logical UTF-8 with byte offsets and keeps a reversed
|
||||
/// selection.
|
||||
#[test]
|
||||
fn ime_surrounding_text_is_logical_utf8_and_keeps_a_reversed_selection() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "café😀e\u{301}x");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(8), false).unwrap();
|
||||
figcraft_engine::textedit::set_caret(&mut u.app.session, 8, false).unwrap();
|
||||
figcraft_engine::textedit::set_caret(&mut u.app.session, 5, true).unwrap();
|
||||
|
||||
let out = ime_descriptor(&mut u, vec![]);
|
||||
let payload = available(&out);
|
||||
assert_eq!(payload.text, "café😀e\u{301}x");
|
||||
assert_eq!((payload.cursor, payload.anchor), (9, 13));
|
||||
assert!(payload.cursor < payload.anchor, "the reversed selection is not sorted");
|
||||
}
|
||||
|
||||
/// Asserts empty text is available while a selection wider than the 4000-byte budget is
|
||||
/// explicitly unavailable but still has a nonzero IME context generation.
|
||||
#[test]
|
||||
fn empty_text_is_available_while_a_too_wide_selection_is_explicitly_unavailable() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(0), false).unwrap();
|
||||
let empty = ime_descriptor(&mut u, vec![]);
|
||||
let payload = available(&empty);
|
||||
assert_eq!((payload.text.as_str(), payload.cursor, payload.anchor), ("", 0, 0));
|
||||
|
||||
// The same editor over a selection wider than the 4000-byte budget cannot describe it.
|
||||
let mut s = Session::new();
|
||||
let long = "a".repeat(5000);
|
||||
let t = text_layer(&mut s, &long);
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, None, false).unwrap();
|
||||
let wide = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(wide.surrounding_text, IMESurroundingText::Unavailable);
|
||||
assert!(wide.context_generation > 0, "the owner stays known when only the text is unavailable");
|
||||
}
|
||||
|
||||
/// Asserts replacing a too-wide selection with a commit is still an `InputMethod` receipt.
|
||||
#[test]
|
||||
fn a_commit_replacing_a_too_wide_selection_is_still_an_input_method_receipt() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let long = "a".repeat(5000);
|
||||
let t = text_layer(&mut s, &long);
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, None, false).unwrap();
|
||||
let wide = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(wide.surrounding_text, IMESurroundingText::Unavailable);
|
||||
|
||||
// The unavailable baseline and the pre-mutation stamp carry the engine's document revision,
|
||||
// so replacing the over-wide selection with a normal commit is a provable IME receipt rather
|
||||
// than an unproven `Other` change.
|
||||
let out = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("X".into()))]);
|
||||
assert_eq!(out.change_cause, ImeChangeCause::InputMethod);
|
||||
assert_eq!(text(&u, t), "X");
|
||||
assert_eq!(available(&out).text, "X");
|
||||
assert_eq!((available(&out).cursor, available(&out).anchor), (1, 1));
|
||||
}
|
||||
|
||||
/// Asserts another text node is another owner, and re-entering the same node changes the
|
||||
/// context generation while keeping the owner key.
|
||||
#[test]
|
||||
fn a_new_edit_session_and_another_text_node_are_new_ime_owners() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let a = text_layer(&mut s, "A");
|
||||
let b = text_layer(&mut s, "B");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, a, Some(1), false).unwrap();
|
||||
let first = ime_descriptor(&mut u, vec![]);
|
||||
|
||||
figcraft_engine::textedit::end(&mut u.app.session).unwrap();
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, b, Some(1), false).unwrap();
|
||||
let other = ime_descriptor(&mut u, vec![]);
|
||||
assert_ne!(other.owner, first.owner, "another text node is another owner");
|
||||
assert_ne!(other.context_generation, first.context_generation);
|
||||
|
||||
figcraft_engine::textedit::end(&mut u.app.session).unwrap();
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, a, Some(1), false).unwrap();
|
||||
let again = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(again.owner, first.owner, "the owner key is the document and node");
|
||||
assert_ne!(again.context_generation, first.context_generation, "re-entering is a replaced target");
|
||||
}
|
||||
|
||||
/// Asserts an accepted commit survives a discarded rerun without inserting twice and keeps
|
||||
/// its `InputMethod` cause, while a mixed rerun is `Other`.
|
||||
#[test]
|
||||
fn an_accepted_commit_survives_a_discarded_pass_without_reapplying_or_losing_its_cause() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
let first = ime_descriptor(&mut u, vec![]);
|
||||
|
||||
let out = u.frame_raw_with_discard(RawInput { events: vec![Event::Ime(ImeEvent::Commit("あ".into()))], ..Default::default() });
|
||||
let ime = out.platform_output.ime.expect("the presented pass keeps the IME on");
|
||||
assert_eq!(text(&u, t), "Hiあ", "the discarded rerun must not insert twice");
|
||||
assert_eq!(available(&ime).text, "Hiあ");
|
||||
assert_eq!(ime.change_cause, ImeChangeCause::InputMethod, "the unchanged second pass keeps the first pass's cause");
|
||||
assert_eq!(ime.context_generation, first.context_generation);
|
||||
|
||||
let mixed = u
|
||||
.frame_raw_with_discard(RawInput { events: vec![Event::Ime(ImeEvent::Commit("い".into())), Event::Text("x".into())], ..Default::default() });
|
||||
let mixed = mixed.platform_output.ime.expect("still editing");
|
||||
assert_eq!(text(&u, t), "Hiあいx");
|
||||
assert_eq!(mixed.change_cause, ImeChangeCause::Other);
|
||||
}
|
||||
|
||||
/// Asserts IME context state is scoped per viewport: each viewport has its own generation,
|
||||
/// the root keeps its context across an aux pass, and a closed aux viewport does not inherit
|
||||
/// the old generation.
|
||||
#[test]
|
||||
fn ime_context_state_is_scoped_per_viewport() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
figcraft_engine::textedit::begin(&mut s, t, Some(2), false).unwrap();
|
||||
let mut app = crate::FigApp::new(s, Box::new(crate::NoServices));
|
||||
// No window drew here, so give the canvas a finite rect for the caret geometry.
|
||||
app.canvas.rect = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_embed_viewports(false);
|
||||
let aux = egui::ViewportId::from_hash_of("figcraft-ime-aux");
|
||||
|
||||
let mut raw = RawInput { viewport_id: egui::ViewportId::ROOT, ..Default::default() };
|
||||
raw.viewports.entry(egui::ViewportId::ROOT).or_default();
|
||||
let root_out = ctx.run_ui(raw, |ui| {
|
||||
ui.ctx().show_viewport_deferred(aux, egui::ViewportBuilder::default(), |_, _| {});
|
||||
crate::shortcuts::ime_output(&mut app, ui.ctx());
|
||||
});
|
||||
let root = root_out.platform_output.ime.clone().expect("root descriptor");
|
||||
root_out.drop_without_applying_deltas();
|
||||
|
||||
let mut raw = RawInput { viewport_id: aux, ..Default::default() };
|
||||
raw.viewports.entry(aux).or_default();
|
||||
let aux_out = ctx.run_ui(raw, |ui| crate::shortcuts::ime_output(&mut app, ui.ctx()));
|
||||
let aux_ime = aux_out.platform_output.ime.clone().expect("aux descriptor");
|
||||
aux_out.drop_without_applying_deltas();
|
||||
assert_eq!(aux_ime.owner, root.owner, "the same edit is the same owner");
|
||||
assert_ne!(aux_ime.context_generation, root.context_generation, "each viewport gets its own generation");
|
||||
assert_eq!(available(&aux_ime).text, "Hi");
|
||||
|
||||
// The root's next consecutive pass keeps its context even though the aux pass ran between.
|
||||
let mut raw = RawInput { viewport_id: egui::ViewportId::ROOT, ..Default::default() };
|
||||
raw.viewports.entry(egui::ViewportId::ROOT).or_default();
|
||||
let root_out = ctx.run_ui(raw, |ui| {
|
||||
ui.ctx().show_viewport_deferred(aux, egui::ViewportBuilder::default(), |_, _| {});
|
||||
crate::shortcuts::ime_output(&mut app, ui.ctx());
|
||||
});
|
||||
let root_again = root_out.platform_output.ime.clone().expect("root descriptor");
|
||||
root_out.drop_without_applying_deltas();
|
||||
assert_eq!(root_again.context_generation, root.context_generation);
|
||||
|
||||
// Closing the aux viewport releases its state; it never inherits the old context.
|
||||
app.ime.end_viewport(aux);
|
||||
let mut raw = RawInput { viewport_id: aux, ..Default::default() };
|
||||
raw.viewports.entry(aux).or_default();
|
||||
let aux_out = ctx.run_ui(raw, |ui| crate::shortcuts::ime_output(&mut app, ui.ctx()));
|
||||
let aux_again = aux_out.platform_output.ime.clone().expect("aux descriptor");
|
||||
aux_out.drop_without_applying_deltas();
|
||||
assert_ne!(aux_again.context_generation, aux_ime.context_generation);
|
||||
}
|
||||
|
||||
/// Asserts the engine's IME surrounding-text byte limit equals egui's wire limit.
|
||||
#[test]
|
||||
fn the_engine_surrounding_limit_matches_the_wire_limit() {
|
||||
// A divergence would truncate or overrun the bounded payload silently.
|
||||
let engine = figcraft_engine::textedit::MAX_IME_SURROUNDING_BYTES;
|
||||
let wire = egui::output::MAX_IME_SURROUNDING_TEXT_BYTES;
|
||||
assert_eq!(engine, wire);
|
||||
}
|
||||
|
||||
/// Asserts a frame observes the IME exactly once in both the editor pass and the Home
|
||||
/// early-return pass.
|
||||
#[test]
|
||||
fn a_frame_observes_the_ime_once_even_when_it_ends_early() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
let before = u.app.ime_observations;
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.ime_observations - before, 1, "one final observation for the editor pass");
|
||||
|
||||
// The home/present early returns make the same single idle observation.
|
||||
u.app.ui.home = true;
|
||||
let before = u.app.ime_observations;
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.ime_observations - before, 1, "one idle observation on the home screen");
|
||||
}
|
||||
|
||||
/// Asserts a double-click inside an existing edit selects the word without changing the IME
|
||||
/// owner or generation.
|
||||
#[test]
|
||||
fn a_double_click_inside_the_edit_keeps_the_ime_generation() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hello world");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
let (p, zoom) = {
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let node = doc.node(t).unwrap();
|
||||
let Some((layout, dy)) = figcraft_text::layout_node(node) else { return };
|
||||
if layout.glyphs.is_empty() || layout.lines.is_empty() {
|
||||
return; // no fonts
|
||||
}
|
||||
let (x0, x1) = (layout.caret(7).0, layout.caret(8).0);
|
||||
let line = &layout.lines[0];
|
||||
let world = doc.world_transform(t);
|
||||
let p = world * figcraft_geom::Point::new((x0 + x1) / 2.0, line.top + line.height / 2.0 + dy);
|
||||
(p, u.app.session.ds().unwrap().view.zoom)
|
||||
};
|
||||
let first = ime_descriptor(&mut u, vec![]);
|
||||
let ev = figcraft_engine::PointerEvent::at(figcraft_engine::PointerKind::DoubleClick, p.x, p.y, zoom);
|
||||
u.app.session.pointer(&ev).unwrap();
|
||||
|
||||
let after = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(after.owner, first.owner, "the same text node is the same owner");
|
||||
assert_eq!(after.context_generation, first.context_generation, "a word-select inside the edit is not a replaced target");
|
||||
assert_eq!(available(&after).text, "Hello world");
|
||||
}
|
||||
|
||||
/// Asserts a `window.new` that moves the edited file leaves the root window emitting no IME
|
||||
/// descriptor.
|
||||
#[test]
|
||||
fn a_window_new_that_moves_the_edited_file_leaves_the_root_ime_idle() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.new", &json!({"name": "A"})).unwrap();
|
||||
let uid = s.ds().unwrap().uid;
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
figcraft_engine::textedit::begin(&mut s, t, Some(2), false).unwrap();
|
||||
s.execute("file.new", &json!({"name": "B"})).unwrap();
|
||||
let a = s.docs.iter().position(|d| d.uid == uid).unwrap();
|
||||
s.execute("doc.switch", &json!({"index": a})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.ctx.set_embed_viewports(false);
|
||||
let first = ime_descriptor(&mut u, vec![]);
|
||||
assert_eq!(available(&first).text, "Hi");
|
||||
|
||||
// A `window.new` queued before the pass is applied after `windows::begin` picked the file
|
||||
// for the root: the root no longer shows the edited file when the pass ends.
|
||||
u.app.window_requests.push(figcraft_engine::UiRequest { kind: "window.new".into(), data: json!({"index": a}) });
|
||||
let out = u.frame_raw(RawInput::default());
|
||||
assert_ne!(u.app.windows.of(uid), 0, "the file moved to its own window");
|
||||
assert!(out.platform_output.ime.is_none(), "the root must not emit a descriptor for a file it no longer shows");
|
||||
}
|
||||
|
||||
/// Asserts a CRLF-normalized commit is application-origin (`Other`), and bare-newline and
|
||||
/// control-only commits insert nothing.
|
||||
#[test]
|
||||
fn a_transformed_commit_is_application_origin_and_a_bare_newline_does_nothing() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "Hi");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
ime(&mut u, vec![]);
|
||||
|
||||
let normalized = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("a\r\nb".into()))]);
|
||||
assert_eq!(normalized.change_cause, ImeChangeCause::Other, "CRLF normalisation is an application transformation");
|
||||
assert_eq!(text(&u, t), "Hia\nb");
|
||||
assert_eq!(available(&normalized).text, "Hia\nb");
|
||||
|
||||
let newline = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("\n".into()))]);
|
||||
assert_eq!(text(&u, t), "Hia\nb", "stock TextEdit ignores a bare newline commit");
|
||||
assert!(matches!(newline.surrounding_text, IMESurroundingText::Available(_)));
|
||||
let control = ime_descriptor(&mut u, vec![Event::Ime(ImeEvent::Commit("\u{0}\u{7}".into()))]);
|
||||
assert_eq!(text(&u, t), "Hia\nb", "a control-only commit inserts nothing");
|
||||
assert!(matches!(control.surrounding_text, IMESurroundingText::Available(_)));
|
||||
}
|
||||
|
||||
/// Asserts character deletion keeps the selection for the paired commit, which replaces it
|
||||
/// and reports `InputMethod`.
|
||||
#[test]
|
||||
fn ime_delete_surrounding_chars_keeps_the_selection_for_the_paired_commit() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
let mut s = Session::new();
|
||||
let t = text_layer(&mut s, "ab\u{4F60}\u{597D}cd");
|
||||
let mut u = Ui::new(s);
|
||||
figcraft_engine::textedit::begin(&mut u.app.session, t, Some(2), false).unwrap();
|
||||
figcraft_engine::textedit::set_caret(&mut u.app.session, 4, true).unwrap(); // "你好"
|
||||
ime(&mut u, vec![]);
|
||||
|
||||
let out = ime_descriptor(
|
||||
&mut u,
|
||||
vec![Event::Ime(ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 1 }), Event::Ime(ImeEvent::Commit("X".into()))],
|
||||
);
|
||||
// The delete removes "b" and "c"; the selected "你好" stays for the commit, which replaces it.
|
||||
assert_eq!(text(&u, t), "aXd");
|
||||
assert_eq!(available(&out).text, "aXd");
|
||||
assert_eq!(available(&out).cursor, 2);
|
||||
assert_eq!(out.change_cause, ImeChangeCause::InputMethod);
|
||||
}
|
||||
@@ -81,7 +81,7 @@ pub fn rail(app: &mut FigApp, ui: &mut Ui) {
|
||||
let mut y = r.min.y + 8.0;
|
||||
// Main menu (logo).
|
||||
let lr = Rect::from_center_size(pos2(r.center().x, y + 16.0), vec2(36.0, 32.0));
|
||||
let lresp = ui.interact(lr, ui.id().with("rail_menu"), Sense::click()).tip(tr("Main menu"));
|
||||
let lresp = ui.interact(lr, ui.scope_id().with("rail_menu"), Sense::click()).tip(tr("Main menu"));
|
||||
if lresp.hovered() || app.ui.main_menu {
|
||||
ui.painter().rect_filled(lr, CornerRadius::same(6), t.hover);
|
||||
}
|
||||
@@ -100,7 +100,7 @@ pub fn rail(app: &mut FigApp, ui: &mut Ui) {
|
||||
for (icon, label, tab) in items {
|
||||
let ir = Rect::from_center_size(pos2(r.center().x, y + 14.0), vec2(36.0, 28.0));
|
||||
let hit = Rect::from_min_max(pos2(r.min.x, y), pos2(r.max.x, y + 48.0));
|
||||
let resp = ui.interact(hit, ui.id().with(("rail", label)), Sense::click()).tip(label);
|
||||
let resp = ui.interact(hit, ui.scope_id().with(("rail", label)), Sense::click()).tip(label);
|
||||
let active = tab.is_some_and(|tb| tb == app.ui.left_tab && !app.ui.left_collapsed && !app.ui.versions.open);
|
||||
if tab.is_some() {
|
||||
a11y::tab(&resp, label, active);
|
||||
@@ -134,6 +134,8 @@ pub fn rail(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the left panel: versions when open, otherwise the file/Assets header with in-place
|
||||
/// file rename and collapse control, followed by Pages and Layers or the Assets panel.
|
||||
pub fn left_panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
if app.ui.versions.open {
|
||||
crate::versions::panel(app, ui);
|
||||
@@ -149,13 +151,13 @@ pub fn left_panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
let name = app.session.doc().map(|d| d.name.clone()).unwrap_or_default();
|
||||
let nr = Rect::from_min_max(pos2(head.min.x + 14.0, head.min.y + 14.0), pos2(head.max.x - 48.0, head.min.y + 34.0));
|
||||
let start = std::mem::take(&mut app.ui.rename_file);
|
||||
if let (Some(new), _) = crate::widgets::rename_field(ui, Id::new("filename"), &name, nr, semibold(13.0), start) {
|
||||
if let (Some(new), _) = crate::widgets::rename_field(ui, Id::unique("filename"), &name, nr, semibold(13.0), start) {
|
||||
app.run("file.rename", json!({"name": new}));
|
||||
}
|
||||
ui.painter().text(pos2(head.min.x + 16.0, head.min.y + 46.0), Align2::LEFT_CENTER, tr("Drafts"), regular(11.0), t.text_secondary);
|
||||
}
|
||||
let hr = Rect::from_center_size(pos2(head.max.x - 24.0, head.min.y + 24.0), vec2(24.0, 24.0));
|
||||
let hresp = ui.interact(hr, ui.id().with("hideui"), Sense::click()).tip(tr("Collapse panel"));
|
||||
let hresp = ui.interact(hr, ui.scope_id().with("hideui"), Sense::click()).tip(tr("Collapse panel"));
|
||||
if hresp.hovered() {
|
||||
ui.painter().rect_filled(hr, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
@@ -173,6 +175,8 @@ pub fn left_panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the page list with open/search/add controls, filtering, selection, rename,
|
||||
/// reorder/drag and layer drop-to-page; Dev Mode allows opening pages but blocks mutations.
|
||||
fn pages(app: &mut FigApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
// Dev Mode only inspects: rows open pages, but don't add, rename, reorder, duplicate or delete.
|
||||
@@ -182,19 +186,19 @@ fn pages(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
let w = ui.available_width();
|
||||
let (hr, _) = ui.allocate_exact_size(vec2(w, 40.0), Sense::hover());
|
||||
let tresp = ui.interact(Rect::from_min_size(hr.min, vec2(w - 40.0, 40.0)), ui.id().with("pages_toggle"), Sense::click());
|
||||
let tresp = ui.interact(Rect::from_min_size(hr.min, vec2(w - 40.0, 40.0)), ui.scope_id().with("pages_toggle"), Sense::click());
|
||||
a11y::toggle(&tresp, tr("Pages"), app.ui.pages_open);
|
||||
ui.painter().text(pos2(hr.min.x + 16.0, hr.center().y), Align2::LEFT_CENTER, tr("Pages"), semibold(11.0), t.text);
|
||||
if tresp.clicked() {
|
||||
app.ui.pages_open = !app.ui.pages_open;
|
||||
}
|
||||
let sr = Rect::from_center_size(pos2(hr.max.x - 50.0, hr.center().y), vec2(24.0, 24.0));
|
||||
let sresp = ui.interact(sr, ui.id().with("lsearch"), Sense::click()).tip(tr("Search pages"));
|
||||
let sresp = ui.interact(sr, ui.scope_id().with("lsearch"), Sense::click()).tip(tr("Search pages"));
|
||||
if sresp.hovered() || app.ui.page_search {
|
||||
ui.painter().rect_filled(sr, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
icons::paint(ui.painter(), sr.shrink(5.0), Icon::Search, t.icon);
|
||||
let search_id = Id::new("page_search_field");
|
||||
let search_id = Id::unique("page_search_field");
|
||||
if sresp.clicked() {
|
||||
app.ui.page_search = !app.ui.page_search;
|
||||
app.ui.page_filter.clear();
|
||||
@@ -203,7 +207,7 @@ fn pages(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
let ar = Rect::from_center_size(pos2(hr.max.x - 22.0, hr.center().y), vec2(24.0, 24.0));
|
||||
let aresp = ui.interact(ar, ui.id().with("addpage"), Sense::click()).tip(tr("Add new page"));
|
||||
let aresp = ui.interact(ar, ui.scope_id().with("addpage"), Sense::click()).tip(tr("Add new page"));
|
||||
if aresp.hovered() {
|
||||
ui.painter().rect_filled(ar, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
@@ -285,7 +289,7 @@ fn pages(app: &mut FigApp, ui: &mut Ui) {
|
||||
let tr = Rect::from_min_max(pos2(r.min.x + 8.0, r.min.y + 4.0), pos2(r.max.x - 4.0, r.max.y - 4.0));
|
||||
let start = ui.data_mut(|d| d.remove_temp::<bool>(page_rename_start_id())).unwrap_or(false);
|
||||
let font = if id == cur { semibold(11.0) } else { regular(11.0) };
|
||||
if let (Some(new), _) = crate::widgets::rename_field(ui, Id::new(("pagename", id)), &name, tr, font, start) {
|
||||
if let (Some(new), _) = crate::widgets::rename_field(ui, Id::unique(("pagename", id)), &name, tr, font, start) {
|
||||
rename_done = Some((id, new));
|
||||
}
|
||||
} else if !divider {
|
||||
@@ -391,8 +395,9 @@ fn pages_edge(app: &mut FigApp, ui: &mut Ui, shown: f32) {
|
||||
let w = ui.available_width();
|
||||
let (line, _) = ui.allocate_exact_size(vec2(w, 1.0), Sense::hover());
|
||||
let grab = ui.style().interaction.resize_grab_radius_side;
|
||||
let id = Id::new("pages_edge");
|
||||
let resp = ui.interact(line.expand2(vec2(0.0, grab)), id, Sense::click_and_drag());
|
||||
let id = Id::unique("pages_edge");
|
||||
// Not focusable, like the side panels' edges: Tab/F6 must not stop on an unnamed drag handle.
|
||||
let resp = ui.interact(line.expand2(vec2(0.0, grab)), id, Sense::CLICK | Sense::DRAG);
|
||||
let active = resp.hovered() || resp.dragged();
|
||||
if active {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
|
||||
@@ -425,12 +430,12 @@ fn pages_edge(app: &mut FigApp, ui: &mut Ui, shown: f32) {
|
||||
|
||||
/// A page rename just asked for by a double click: its field takes the focus when drawn (temp data).
|
||||
fn page_rename_start_id() -> Id {
|
||||
Id::new("page_rename_start")
|
||||
Id::unique("page_rename_start")
|
||||
}
|
||||
|
||||
/// The layer row being dragged in the panel (temp data).
|
||||
fn layer_drag_id() -> Id {
|
||||
Id::new("layer_drag")
|
||||
Id::unique("layer_drag")
|
||||
}
|
||||
|
||||
/// A press on a row's eye or padlock dragged across other rows: every row passed gets the state the
|
||||
@@ -443,8 +448,9 @@ struct Sweep {
|
||||
ids: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// Stable egui id for the eye/padlock sweep state.
|
||||
fn sweep_id() -> Id {
|
||||
Id::new("layer_toggle_sweep")
|
||||
Id::unique("layer_toggle_sweep")
|
||||
}
|
||||
|
||||
/// What a drag of row `dragging` moves: the selection when the row is in it, else the row.
|
||||
@@ -489,7 +495,7 @@ fn hash_expanded(expanded: &BTreeSet<NodeId>) -> u64 {
|
||||
pub(crate) fn rows_for(ui: &Ui, doc: &Arc<Document>, page: NodeId, expanded: &BTreeSet<NodeId>, filter: &str) -> Arc<Vec<Row>> {
|
||||
let ex = if filter.is_empty() { hash_expanded(expanded) } else { 0 };
|
||||
ui.data_mut(|d| {
|
||||
let c = d.get_temp_mut_or_default::<RowCache>(Id::new("layer_rows"));
|
||||
let c = d.get_temp_mut_or_default::<RowCache>(Id::unique("layer_rows"));
|
||||
let fresh = c.doc.as_ref().is_some_and(|d| Arc::ptr_eq(d, doc)) && c.page == Some(page) && c.expanded == ex && c.filter == filter;
|
||||
if !fresh {
|
||||
let rows = listed_rows(doc, page, expanded, filter);
|
||||
@@ -653,8 +659,9 @@ fn rename_layer(app: &mut FigApp, id: NodeId) {
|
||||
app.ui.layers_seen_sel = app.session.selection();
|
||||
}
|
||||
|
||||
/// Stable egui id for a layer row's rename field.
|
||||
fn rename_id(id: NodeId) -> Id {
|
||||
Id::new(("rename", id))
|
||||
Id::unique(("rename", id))
|
||||
}
|
||||
|
||||
/// Left edge of a row's contents (disclosure triangle) in the row's inner rect `rr`.
|
||||
@@ -704,7 +711,7 @@ fn search_field(ui: &mut Ui, t: &Tokens, w: f32, id: Id, hint: &str, text: &mut
|
||||
.frame(egui::Frame::NONE)
|
||||
.font(regular(11.0))
|
||||
.hint_text(hint)
|
||||
.vertical_align(egui::Align::Center)
|
||||
.align(egui::Align2::LEFT_CENTER)
|
||||
.desired_width(te_rect.width()),
|
||||
);
|
||||
// After the field: the click that opened it ends elsewhere, which would take the focus back.
|
||||
@@ -721,6 +728,8 @@ fn search_field(ui: &mut Ui, t: &Tokens, w: f32, id: Id, hint: &str, text: &mut
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the layer tree with search, cached rows, reveal-selection expansion and scrolling,
|
||||
/// rename/Tab navigation, selection and drag/drop, sweep toggles and Dev Mode restrictions.
|
||||
fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
// Dev Mode only inspects: rows select and expand, but don't rename, reorder, hide or lock.
|
||||
@@ -732,12 +741,12 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
let (hr, _) = ui.allocate_exact_size(vec2(w, 40.0), Sense::hover());
|
||||
ui.painter().text(pos2(hr.min.x + 16.0, hr.center().y), Align2::LEFT_CENTER, tr("Layers"), semibold(11.0), t.text);
|
||||
let sr = Rect::from_center_size(pos2(hr.max.x - 22.0, hr.center().y), vec2(24.0, 24.0));
|
||||
let sresp = ui.interact(sr, ui.id().with("layer_search_btn"), Sense::click()).tip(tr("Search layers"));
|
||||
let sresp = ui.interact(sr, ui.scope_id().with("layer_search_btn"), Sense::click()).tip(tr("Search layers"));
|
||||
if sresp.hovered() || app.ui.layer_search {
|
||||
ui.painter().rect_filled(sr, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
icons::paint(ui.painter(), sr.shrink(5.0), Icon::Search, t.icon);
|
||||
let search_id = Id::new("layer_search_field");
|
||||
let search_id = Id::unique("layer_search_field");
|
||||
if sresp.clicked() {
|
||||
app.ui.layer_search = !app.ui.layer_search;
|
||||
app.ui.layer_filter.clear();
|
||||
@@ -889,7 +898,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
// Expand triangle.
|
||||
if row.has_kids {
|
||||
let tri = Rect::from_center_size(pos2(x0 + 6.0, r.center().y), vec2(14.0, 14.0));
|
||||
let tresp = ui.interact(tri, ui.id().with(("tri", row.id)), Sense::click());
|
||||
let tresp = ui.interact(tri, ui.scope_id().with(("tri", row.id)), Sense::click());
|
||||
let open = app.ui.expanded.contains(&row.id);
|
||||
a11y::button(&tresp, if open { tr("Collapse") } else { tr("Expand") });
|
||||
icons::paint(ui.painter(), tri.shrink(1.0), if open { Icon::Chevron } else { Icon::ChevronRight }, t.icon_secondary);
|
||||
@@ -956,7 +965,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
icons::paint(ui.painter(), er.shrink(3.0), if hidden { Icon::EyeOff } else { Icon::Eye }, t.icon_secondary);
|
||||
}
|
||||
if show_eye && !dev {
|
||||
let eresp = ui.interact(er, ui.id().with(("eye", row.id)), Sense::click_and_drag());
|
||||
let eresp = ui.interact(er, ui.scope_id().with(("eye", row.id)), Sense::click_and_drag());
|
||||
a11y::toggle(&eresp, tr("Hidden"), hidden);
|
||||
if eresp.clicked() {
|
||||
vis = Some(row.id);
|
||||
@@ -970,7 +979,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
icons::paint(ui.painter(), lr.shrink(3.0), if locked || row.locked_above { Icon::Lock } else { Icon::Unlock }, col);
|
||||
}
|
||||
if show_lock && !dev {
|
||||
let lresp = ui.interact(lr, ui.id().with(("lock", row.id)), Sense::click_and_drag());
|
||||
let lresp = ui.interact(lr, ui.scope_id().with(("lock", row.id)), Sense::click_and_drag());
|
||||
a11y::toggle(&lresp, tr("Locked"), locked || row.locked_above);
|
||||
if lresp.clicked() {
|
||||
lock = Some(row.id);
|
||||
@@ -991,6 +1000,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
let pos = ui.input(|i| i.pointer.hover_pos()).unwrap_or(r.center());
|
||||
app.ui.context_menu = Some((pos, vec![row.id]));
|
||||
app.ui.context_menu_shown = false;
|
||||
}
|
||||
// Drag to reorder.
|
||||
if resp.drag_started() && !crate::menus::dev_mode_refuses(app, "node.reparent") {
|
||||
@@ -1024,7 +1034,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
ui.painter().rect_stroke(rr, CornerRadius::same(5), Stroke::new(2.0, ACCENT), egui::StrokeKind::Inside);
|
||||
// Holding over a collapsed group or frame opens it, to drop deeper inside.
|
||||
if row.has_kids && !app.ui.expanded.contains(&row.id) {
|
||||
let hold_id = Id::new("layer_drag_hold");
|
||||
let hold_id = Id::unique("layer_drag_hold");
|
||||
let now = ui.input(|i| i.time);
|
||||
match ui.data(|d| d.get_temp::<(NodeId, f64)>(hold_id)) {
|
||||
Some((id, since)) if id == row.id => {
|
||||
@@ -1059,7 +1069,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
// Empty space below clears selection.
|
||||
let rest = Rect::from_x_y_ranges(band.x_range(), (top + total)..=(top + total.max(viewport.max.y)));
|
||||
// A click target for the pointer only (no stop for the keyboard).
|
||||
if rest.height() > 0.0 && ui.interact(rest, Id::new("layers_empty_space"), Sense::CLICK).clicked() {
|
||||
if rest.height() > 0.0 && ui.interact(rest, Id::unique("layers_empty_space"), Sense::CLICK).clicked() {
|
||||
app.run("select.none", json!({}));
|
||||
}
|
||||
});
|
||||
@@ -1095,7 +1105,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
if ui.input(|i| i.pointer.any_released()) {
|
||||
ui.data_mut(|d| {
|
||||
d.remove::<NodeId>(drag_id);
|
||||
d.remove::<(NodeId, f64)>(Id::new("layer_drag_hold"));
|
||||
d.remove::<(NodeId, f64)>(Id::unique("layer_drag_hold"));
|
||||
});
|
||||
// A drag started in the design can end after a switch to Dev Mode.
|
||||
if let (Some(_), Some((target, zone))) = (dragging, drop)
|
||||
|
||||
@@ -312,6 +312,7 @@ fn pages_down_to(u: &mut Ui, to: f32) -> Vec<NodeId> {
|
||||
opened
|
||||
}
|
||||
|
||||
/// Asserts a 60-page list scrolls with the wheel to its last page, past its first pages.
|
||||
#[test]
|
||||
fn a_long_pages_list_scrolls_and_leaves_room_for_the_layers() {
|
||||
let mut s = Session::new();
|
||||
@@ -330,6 +331,7 @@ fn a_long_pages_list_scrolls_and_leaves_room_for_the_layers() {
|
||||
// The wheel over the pages list scrolls it to its last page.
|
||||
let wheel = Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
delta: egui::vec2(0.0, -400.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Default::default(),
|
||||
@@ -382,6 +384,8 @@ fn double_click_checking_focus(u: &mut Ui, p: Pos2) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts double-clicking a page selects and renames it, with the keyboard in its name
|
||||
/// field for the screen-reader tree.
|
||||
#[test]
|
||||
fn double_clicking_a_page_renames_it_with_the_focus_in_the_screen_reader_tree() {
|
||||
let mut s = Session::new();
|
||||
@@ -394,10 +398,10 @@ fn double_clicking_a_page_renames_it_with_the_focus_in_the_screen_reader_tree()
|
||||
double_click_checking_focus(&mut u, r2);
|
||||
assert_eq!(u.app.session.page().unwrap(), p2);
|
||||
assert_eq!(u.app.ui.rename_page.as_ref().map(|r| r.0), Some(p2), "a double click renames the page");
|
||||
assert!(u.ctx.memory(|m| m.has_focus(Id::new(("pagename", p2)).with("te"))), "with the keyboard in its name");
|
||||
assert!(u.ctx.memory(|m| m.has_focus(Id::unique(("pagename", p2)).with("te"))), "with the keyboard in its name");
|
||||
// The page that's open.
|
||||
u.app.ui.rename_page = None;
|
||||
u.ctx.memory_mut(|m| m.surrender_focus(Id::new(("pagename", p2)).with("te")));
|
||||
u.ctx.memory_mut(|m| m.surrender_focus(Id::unique(("pagename", p2)).with("te")));
|
||||
u.app.session.execute("page.select", &json!({"id": p1})).unwrap();
|
||||
for _ in 0..30 {
|
||||
u.frame(vec![]);
|
||||
|
||||
@@ -43,6 +43,7 @@ impl Ui {
|
||||
/// screen and clock.
|
||||
pub(crate) fn frame_raw(&mut self, raw: RawInput) -> egui::FullOutput {
|
||||
self.time += 1.0 / 60.0;
|
||||
self.app.clock.set_test_now(Some(self.time));
|
||||
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), ..raw };
|
||||
let app = &mut self.app;
|
||||
let mut out = self.ctx.run_ui(input, |ui| app.ui(ui));
|
||||
@@ -50,6 +51,32 @@ impl Ui {
|
||||
out
|
||||
}
|
||||
|
||||
/// One frame that egui reruns as a discarded pass (the returned output is the presented pass).
|
||||
///
|
||||
/// The rerun sees the same `RawInput`; the custom text editor must not apply its events twice,
|
||||
/// and the IME descriptor of the presented pass must still describe the first pass's result.
|
||||
pub(crate) fn frame_raw_with_discard(&mut self, raw: RawInput) -> egui::FullOutput {
|
||||
self.time += 1.0 / 60.0;
|
||||
self.app.clock.set_test_now(Some(self.time));
|
||||
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), ..raw };
|
||||
let Ui { ctx, app, .. } = self;
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
app.ui(ui);
|
||||
if ui.ctx().current_pass_index() == 0 {
|
||||
ui.ctx().request_discard("ime test: exercise a discarded pass");
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
}
|
||||
|
||||
/// Move the harness time (and the app's monotonic clock) forward, e.g. past a deadline; the
|
||||
/// next frame continues from here.
|
||||
pub(crate) fn advance_clock(&mut self, secs: f64) {
|
||||
self.time = secs;
|
||||
self.app.clock.set_test_now(Some(secs));
|
||||
}
|
||||
|
||||
/// The middle of `id`'s row in the layers panel (found by hovering down the panel).
|
||||
pub(crate) fn row_at(&mut self, id: NodeId) -> Pos2 {
|
||||
let mut hits = Vec::new();
|
||||
|
||||
@@ -144,6 +144,8 @@ fn rename_without_a_name_renames_one_row_or_opens_the_dialog() {
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.ds().unwrap().doc));
|
||||
}
|
||||
|
||||
/// Asserts a layer rename continues after its row is scrolled out of view and commits on
|
||||
/// Enter.
|
||||
#[test]
|
||||
fn a_rename_scrolled_out_of_view_goes_on() {
|
||||
let mut s = Session::new();
|
||||
@@ -158,6 +160,7 @@ fn a_rename_scrolled_out_of_view_goes_on() {
|
||||
let p = egui::pos2(150.0, 400.0);
|
||||
let wheel = Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
delta: egui::vec2(0.0, -400.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Modifiers::NONE,
|
||||
|
||||
@@ -156,9 +156,9 @@ fn dimensions(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], has
|
||||
let col = widgets::col_width(ui.available_width());
|
||||
widgets::sublabels(ui, tr("Dimensions"), None);
|
||||
row(ui, 32.0, |ui| {
|
||||
let e = crate::variable_ui::number_field_mixed(app, ui, &ids, "width", Id::new("lay_w"), Lead::Text("W"), w, "", col);
|
||||
let e = crate::variable_ui::number_field_mixed(app, ui, &ids, "width", Id::unique("lay_w"), Lead::Text("W"), w, "", col);
|
||||
app.field_of(&ids, "width", e, w_of, |v| json!(v.max(0.0)));
|
||||
let e = crate::variable_ui::number_field_mixed(app, ui, &ids, "height", Id::new("lay_h"), Lead::Text("H"), h, "", col);
|
||||
let e = crate::variable_ui::number_field_mixed(app, ui, &ids, "height", Id::unique("lay_h"), Lead::Text("H"), h, "", col);
|
||||
app.field_of(&ids, "height", e, h_of, |v| json!(v.max(0.0)));
|
||||
let locked = common(doc, sel, |n| n.constrain_proportions).unwrap_or(false);
|
||||
let link = ui
|
||||
@@ -259,7 +259,7 @@ fn limit_row(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], hori
|
||||
let (lead, add) = if is_min { (tr(axis.min_lead), tr(axis.add_min)) } else { (tr(axis.max_lead), tr(axis.add_max)) };
|
||||
if has(is_min) {
|
||||
let v = common(doc, sel, |n| limit(n, horizontal, is_min).map(|v| (v * 100.0).round() / 100.0)).flatten();
|
||||
let e = crate::variable_ui::number_field(app, ui, &ids, key, Id::new(("lay_limit", key)), Lead::Text(lead), v, "", col);
|
||||
let e = crate::variable_ui::number_field(app, ui, &ids, key, Id::unique(("lay_limit", key)), Lead::Text(lead), v, "", col);
|
||||
app.field(&ids, key, e, |v| json!(v.max(0.0)));
|
||||
} else if add_slot(ui, lead, add, col).clicked() {
|
||||
app.set_props(&ids, json!({key: current}));
|
||||
@@ -283,6 +283,8 @@ fn add_slot(ui: &mut Ui, label: &str, tip: &str, width: f32) -> egui::Response {
|
||||
resp
|
||||
}
|
||||
|
||||
/// Draw the 3×3 main/cross alignment grid, auto-gap modes, grid column/row gaps and the
|
||||
/// horizontal baseline checkbox.
|
||||
fn alignment(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let grid_mode = l.mode == LayoutMode::Grid;
|
||||
@@ -309,7 +311,7 @@ fn alignment(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
for xi in 0..3 {
|
||||
let c = pos2(grid.min.x + 12.0 + xi as f32 * 24.0, grid.min.y + 10.0 + yi as f32 * 22.0);
|
||||
let r = Rect::from_center_size(c, vec2(22.0, 20.0));
|
||||
let resp = ui.interact(r, Id::new(("al_grid", xi, yi)), Sense::click());
|
||||
let resp = ui.interact(r, Id::unique(("al_grid", xi, yi)), Sense::click());
|
||||
let (main_i, cross_i) = if horizontal { (xi, yi) } else { (yi, xi) };
|
||||
let on = (cur_main == main_i || cur_main == 9) && (cur_cross == cross_i || cur_cross == 9);
|
||||
if on {
|
||||
@@ -338,7 +340,7 @@ fn alignment(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
ui,
|
||||
ids,
|
||||
"columnGap",
|
||||
Id::new("al_gap"),
|
||||
Id::unique("al_gap"),
|
||||
Lead::Icon(Icon::Gap, tr("Column gap")),
|
||||
Some(l.gap),
|
||||
"",
|
||||
@@ -351,7 +353,7 @@ fn alignment(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
ui,
|
||||
ids,
|
||||
"rowGap",
|
||||
Id::new("al_rowgap"),
|
||||
Id::unique("al_rowgap"),
|
||||
Lead::Icon(Icon::DistributeV, tr("Row gap")),
|
||||
Some(l.cross_gap),
|
||||
"",
|
||||
@@ -363,7 +365,7 @@ fn alignment(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
let auto = l.main_align.is_auto_gap();
|
||||
let gap_icon = if l.mode == LayoutMode::Vertical { Icon::DistributeV } else { Icon::Gap };
|
||||
let (shown, lead) = ((!auto).then_some(l.gap), Lead::Icon(gap_icon, tr("Gap between items")));
|
||||
let e = crate::variable_ui::number_field_or(app, ui, ids, "gap", Id::new("al_gap"), shown, 96.0, tr("Auto"), lead, "");
|
||||
let e = crate::variable_ui::number_field_or(app, ui, ids, "gap", Id::unique("al_gap"), shown, 96.0, tr("Auto"), lead, "");
|
||||
app.field(ids, "gap", e, |v| json!(v));
|
||||
ui.add_space(8.0);
|
||||
let label = match l.main_align {
|
||||
@@ -406,10 +408,10 @@ fn alignment(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
let col = widgets::col_width(ui.available_width());
|
||||
let [pt, pr, pb, pl] = l.padding;
|
||||
let open = ui.data(|d| d.get_temp::<bool>(Id::new("indep_padding"))).unwrap_or(false);
|
||||
let open = ui.data(|d| d.get_temp::<bool>(Id::unique("indep_padding"))).unwrap_or(false);
|
||||
let toggle = |ui: &mut Ui| {
|
||||
if icons::button(ui, Icon::IndependentPadding, 24.0, open, tr("Individual padding")).clicked() {
|
||||
ui.data_mut(|d| d.insert_temp(Id::new("indep_padding"), !open));
|
||||
ui.data_mut(|d| d.insert_temp(Id::unique("indep_padding"), !open));
|
||||
}
|
||||
};
|
||||
if open {
|
||||
@@ -424,7 +426,8 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
for (r, pair) in sides.chunks(2).enumerate() {
|
||||
row(ui, 32.0, |ui| {
|
||||
for (key, name, icon, v, k) in pair {
|
||||
let e = crate::variable_ui::number_field(app, ui, ids, key, Id::new(("padding", *k)), Lead::Icon(*icon, name), Some(*v), "", col);
|
||||
let e =
|
||||
crate::variable_ui::number_field(app, ui, ids, key, Id::unique(("padding", *k)), Lead::Icon(*icon, name), Some(*v), "", col);
|
||||
app.field(ids, key, e, |v| json!(v.max(0.0)));
|
||||
}
|
||||
if r == 0 {
|
||||
@@ -439,7 +442,7 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
ui,
|
||||
ids,
|
||||
"paddingHorizontal",
|
||||
Id::new("al_padh"),
|
||||
Id::unique("al_padh"),
|
||||
Lead::Icon(Icon::PaddingH, tr("Horizontal padding")),
|
||||
(pl == pr).then_some(pl),
|
||||
"",
|
||||
@@ -451,7 +454,7 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
ui,
|
||||
ids,
|
||||
"paddingVertical",
|
||||
Id::new("al_padv"),
|
||||
Id::unique("al_padv"),
|
||||
Lead::Icon(Icon::PaddingV, tr("Vertical padding")),
|
||||
(pt == pb).then_some(pt),
|
||||
"",
|
||||
@@ -475,7 +478,7 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
ui,
|
||||
ids,
|
||||
"crossGap",
|
||||
Id::new("al_crossgap"),
|
||||
Id::unique("al_crossgap"),
|
||||
shown,
|
||||
col,
|
||||
tr("Auto"),
|
||||
@@ -500,9 +503,9 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) {
|
||||
if l.mode == LayoutMode::Grid {
|
||||
widgets::sublabels(ui, tr("Columns"), Some(tr("Rows")));
|
||||
row(ui, 32.0, |ui| {
|
||||
let e = widgets::number_field(ui, Id::new("al_cols"), Lead::None, Some(f64::from(l.grid_columns)), "", col, 1.0);
|
||||
let e = widgets::number_field(ui, Id::unique("al_cols"), Lead::None, Some(f64::from(l.grid_columns)), "", col, 1.0);
|
||||
app.field(ids, "gridColumns", e, |v| json!(v.max(1.0)));
|
||||
let e = widgets::number_field(ui, Id::new("al_rows"), Lead::None, Some(f64::from(l.grid_rows)), "", col, 1.0);
|
||||
let e = widgets::number_field(ui, Id::unique("al_rows"), Lead::None, Some(f64::from(l.grid_rows)), "", col, 1.0);
|
||||
app.field(ids, "gridRows", e, |v| json!(v.max(1.0)));
|
||||
});
|
||||
}
|
||||
@@ -571,7 +574,7 @@ fn tracks(app: &mut FigApp, ui: &mut Ui, doc: &Document, ids: &[NodeId]) {
|
||||
let (value, suffix) = if track.sizing == Sizing::Fill { (track.value, "fr") } else { (size, "") };
|
||||
let e = widgets::number_field(
|
||||
ui,
|
||||
Id::new(("al_track", axis, i)),
|
||||
Id::unique(("al_track", axis, i)),
|
||||
Lead::Text(&label),
|
||||
Some(value),
|
||||
suffix,
|
||||
@@ -614,9 +617,9 @@ fn grid_cell(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
|
||||
// Moving on one axis pins the other where it is, so the child doesn't jump.
|
||||
let at = |c: f64, r: f64| json!({"ids": [id], "props": {"gridColumn": (c - 1.0).max(0.0), "gridRow": (r - 1.0).max(0.0)}});
|
||||
let (c0, r0) = ((cell.column + 1) as f64, (cell.row + 1) as f64);
|
||||
let e = widgets::number_field(ui, Id::new("al_cell_col"), Lead::None, Some(c0), "", col, 1.0);
|
||||
let e = widgets::number_field(ui, Id::unique("al_cell_col"), Lead::None, Some(c0), "", col, 1.0);
|
||||
app.field_run(e, "node.set", |v| at(v, r0));
|
||||
let e = widgets::number_field(ui, Id::new("al_cell_row"), Lead::None, Some(r0), "", col, 1.0);
|
||||
let e = widgets::number_field(ui, Id::unique("al_cell_row"), Lead::None, Some(r0), "", col, 1.0);
|
||||
app.field_run(e, "node.set", |v| at(c0, v));
|
||||
if anchored && icons::button(ui, Icon::Reset, 24.0, false, tr("Place automatically")).clicked() {
|
||||
app.set_props(&ids, json!({"gridColumn": null, "gridRow": null}));
|
||||
@@ -627,9 +630,9 @@ fn grid_cell(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
|
||||
let rs = common(doc, sel, |n| f64::from(n.child_layout.row_span()));
|
||||
widgets::sublabels(ui, tr("Column span"), Some(tr("Row span")));
|
||||
row(ui, 32.0, |ui| {
|
||||
let e = widgets::number_field(ui, Id::new("al_span_c"), Lead::None, cs, "", col, 1.0);
|
||||
let e = widgets::number_field(ui, Id::unique("al_span_c"), Lead::None, cs, "", col, 1.0);
|
||||
app.field(&ids, "gridColumnSpan", e, |v| json!(v.max(1.0)));
|
||||
let e = widgets::number_field(ui, Id::new("al_span_r"), Lead::None, rs, "", col, 1.0);
|
||||
let e = widgets::number_field(ui, Id::unique("al_span_r"), Lead::None, rs, "", col, 1.0);
|
||||
app.field(&ids, "gridRowSpan", e, |v| json!(v.max(1.0)));
|
||||
});
|
||||
// Alignment in the cell; Auto follows the frame's alignment.
|
||||
|
||||
+337
-35
@@ -63,6 +63,7 @@ pub mod theme;
|
||||
pub mod toolbar;
|
||||
pub mod typography;
|
||||
pub mod ui_scale;
|
||||
pub mod updates_ui;
|
||||
pub mod variable_ui;
|
||||
pub mod variables_panel;
|
||||
pub mod vector_panel;
|
||||
@@ -90,6 +91,8 @@ mod canvas_fixes_tests;
|
||||
#[cfg(test)]
|
||||
mod canvas_image_rect_tests;
|
||||
#[cfg(test)]
|
||||
mod clipboard_fence_tests;
|
||||
#[cfg(test)]
|
||||
mod colorpicker_eyedropper_tests;
|
||||
#[cfg(test)]
|
||||
mod colorpicker_selection_tests;
|
||||
@@ -98,6 +101,8 @@ mod comments_tests;
|
||||
#[cfg(test)]
|
||||
mod component_props_reorder_tests;
|
||||
#[cfg(test)]
|
||||
mod context_menu_tests;
|
||||
#[cfg(test)]
|
||||
mod corner_individual_tests;
|
||||
#[cfg(test)]
|
||||
mod cursors_tests;
|
||||
@@ -252,7 +257,7 @@ use figcraft_doc::NodeId;
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use control::{ControlReply, ControlRequest};
|
||||
pub use control::{ControlReply, ControlRequest, RequestGate, RequestState};
|
||||
|
||||
/// Platform services the app crate provides (file dialogs, clipboard, URLs).
|
||||
pub trait Services {
|
||||
@@ -475,6 +480,35 @@ pub(crate) fn repaint_in(ctx: &egui::Context, secs: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A monotonic clock for background work (autosave, recovery, capture deadlines).
|
||||
///
|
||||
/// `Context::input(|i| i.time)` is the UI pass's time and is stale in `run_logic`; wall-clock time
|
||||
/// can jump. `web_time::Instant` is monotonic on native and in the browser. Tests drive deadlines
|
||||
/// directly with [`FrameClock::set_test_now`].
|
||||
pub struct FrameClock {
|
||||
origin: web_time::Instant,
|
||||
test_now: Option<f64>,
|
||||
}
|
||||
|
||||
impl Default for FrameClock {
|
||||
/// Start the frame clock at the current web time with no injected test time.
|
||||
fn default() -> Self {
|
||||
Self { origin: web_time::Instant::now(), test_now: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameClock {
|
||||
/// Seconds since the app started (or the injected test time).
|
||||
pub fn now(&self) -> f64 {
|
||||
self.test_now.unwrap_or_else(|| self.origin.elapsed().as_secs_f64())
|
||||
}
|
||||
|
||||
/// Set a fake monotonic time (tests); `None` returns to the real clock.
|
||||
pub fn set_test_now(&mut self, secs: Option<f64>) {
|
||||
self.test_now = secs;
|
||||
}
|
||||
}
|
||||
|
||||
/// The side panels' widths: the least and most a drag of their edge gives, what a double-click on
|
||||
/// the edge puts back, and how much of the window they leave the canvas.
|
||||
pub const LEFT_PANEL: std::ops::RangeInclusive<f32> = 200.0..=480.0;
|
||||
@@ -528,6 +562,8 @@ pub struct UiState {
|
||||
pub palette_hi: usize,
|
||||
/// The palette ignores one outside click after opening (the click that opened it).
|
||||
pub palette_armed: bool,
|
||||
/// The context menu has been drawn at least once (its opening frame's press is spared).
|
||||
pub context_menu_shown: bool,
|
||||
/// This frame's Actions toolbar button rect: presses on it toggle, never dismiss.
|
||||
pub actions_rect: Option<egui::Rect>,
|
||||
/// The Variables editor, when open.
|
||||
@@ -641,7 +677,13 @@ pub struct UiState {
|
||||
|
||||
/// What FigCraft last put on the system clipboard: when the clipboard still holds it, a paste
|
||||
/// uses our copied layers; anything else there (an image, SVG, text) came from another app.
|
||||
/// `None` also means a programmatic copy changed the engine clipboard without writing the OS
|
||||
/// clipboard, so the system text is no longer known to be ours.
|
||||
pub last_copy: Option<String>,
|
||||
/// The engine clipboard's layers generation when `last_copy` was mirrored. A programmatic
|
||||
/// copy changes the engine clipboard without writing the OS clipboard; the generation then
|
||||
/// no longer matches, so the stale mirror is not mistaken for the user's own copy.
|
||||
pub last_copy_generation: u64,
|
||||
/// Since the last V key release: whether its press arrived, and whether a paste event did
|
||||
/// (`shortcuts::swallowed_paste`).
|
||||
pub v_pressed: bool,
|
||||
@@ -649,14 +691,14 @@ pub struct UiState {
|
||||
/// The window got the focus back since the last V release.
|
||||
pub refocused: bool,
|
||||
/// A save shortcut pressed while a panel field had the keyboard: the field lets go (which
|
||||
/// commits what was typed) and the command runs the next frame (`shortcuts::handle`).
|
||||
pub after_field: Option<&'static str>,
|
||||
/// commits what was typed) and the command runs next frame for that document/window.
|
||||
pub after_field: Option<shortcuts::AfterFieldSave>,
|
||||
/// The modifiers held, as of the last modifier change in the raw events: a paste event doesn't
|
||||
/// carry them.
|
||||
pub held: egui::Modifiers,
|
||||
/// When (UI clock, seconds) open documents next get an autosave checkpoint.
|
||||
/// When (monotonic [`FrameClock`], seconds) open documents next get an autosave checkpoint.
|
||||
pub next_autosave: f64,
|
||||
/// With auto-save on: when (UI clock, seconds) files with unsaved changes are next saved, and
|
||||
/// With auto-save on: when (monotonic [`FrameClock`], seconds) files with unsaved changes are next saved, and
|
||||
/// the revisions of those files it waits on (a change restarts the wait).
|
||||
pub auto_save_at: Option<(f64, u64)>,
|
||||
/// Files being encoded for auto-save on threads of their own (tab `uid`).
|
||||
@@ -686,6 +728,9 @@ pub struct UiState {
|
||||
}
|
||||
|
||||
impl Default for UiState {
|
||||
/// Seed the default UI state (panel widths, tabs, pages, Home, presenters, pickers and
|
||||
/// dialogs off, and the rest of the transient UI fields); `FigApp::new` overrides panel
|
||||
/// widths and the pages height from preferences.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
left_width: PANEL_DEFAULT,
|
||||
@@ -707,6 +752,7 @@ impl Default for UiState {
|
||||
palette_tab: menus::PaletteTab::All,
|
||||
palette_hi: 0,
|
||||
palette_armed: false,
|
||||
context_menu_shown: false,
|
||||
actions_rect: None,
|
||||
variables: None,
|
||||
about: false,
|
||||
@@ -773,6 +819,7 @@ impl Default for UiState {
|
||||
dev: dev_mode::DevUi::default(),
|
||||
|
||||
last_copy: None,
|
||||
last_copy_generation: 0,
|
||||
v_pressed: false,
|
||||
paste_event: false,
|
||||
refocused: false,
|
||||
@@ -795,6 +842,14 @@ impl Default for UiState {
|
||||
}
|
||||
}
|
||||
|
||||
/// A control reply waiting for the pass that presents an injected input batch. The viewport keeps
|
||||
/// one window's batch from acknowledging (or erroring) another window's request.
|
||||
pub(crate) struct PendingAck {
|
||||
pub(crate) viewport: egui::ViewportId,
|
||||
pub(crate) tx: std::sync::mpsc::Sender<ControlReply>,
|
||||
pub(crate) reply: ControlReply,
|
||||
}
|
||||
|
||||
/// The whole FigCraft UI.
|
||||
pub struct FigApp {
|
||||
pub session: Session,
|
||||
@@ -833,12 +888,48 @@ pub struct FigApp {
|
||||
/// The automation roots the app was started with: every frame and control request runs
|
||||
/// confined to them ([`windows::guard`]).
|
||||
pub automation_roots: Option<Arc<figcraft_engine::file_access::Roots>>,
|
||||
/// The active-document id when synthetic input was queued: a batch is dropped when the file
|
||||
/// changed before a UI pass applied it.
|
||||
pub(crate) control_input_doc: Option<u64>,
|
||||
/// This frame applies events injected through the control channel: no system clipboard
|
||||
/// read or write may happen for them.
|
||||
pub(crate) control_synthetic: bool,
|
||||
/// `ui.input` replies waiting for the pass that actually presents the injected batch (a
|
||||
/// discarded sizing pass must not acknowledge it).
|
||||
pub(crate) input_acks: Vec<PendingAck>,
|
||||
/// Replies whose batch this frame took into its raw input: sent only if the pass is presented.
|
||||
pub(crate) applied_acks: Vec<PendingAck>,
|
||||
/// The batch taken into this frame's raw input, kept so a discarded pass gives it back.
|
||||
pub(crate) applied_input: Option<Vec<egui::Event>>,
|
||||
/// `handle("ui.input")` queued raw events whose acknowledgement waits for the applied pass
|
||||
/// (controller-only input is applied at once and needs no fence).
|
||||
pub(crate) control_input_queued: bool,
|
||||
/// The viewport whose batch this frame took into its raw input (`applied_input`/`applied_acks`).
|
||||
pub(crate) applied_frame: Option<egui::ViewportId>,
|
||||
/// Monotonic time for background work and capture deadlines.
|
||||
pub(crate) clock: FrameClock,
|
||||
/// Screenshot requests admitted, settling and awaiting readback.
|
||||
pub(crate) capture: control::CaptureState,
|
||||
/// [`Self::background_tick`] ran for this pass (so [`Self::ui`] does not repeat it).
|
||||
logic_ticked: bool,
|
||||
/// The last frame whose UI setup ran (multi-pass frames set up once).
|
||||
ui_frame_stamp: Option<(egui::ViewportId, u64)>,
|
||||
/// IME owner/generation/change-cause state for the on-canvas text editor, per viewport.
|
||||
pub(crate) ime: egui::ime_context::ImeContextTracker,
|
||||
/// The check for a newer release and its prompt (desktop; [`updates_ui`]).
|
||||
pub(crate) updates_rt: updates_ui::Runtime,
|
||||
/// Test-only count of the one IME observation each viewport pass makes.
|
||||
#[cfg(test)]
|
||||
pub(crate) ime_observations: u32,
|
||||
}
|
||||
|
||||
/// What to do with the result of a command run in the background.
|
||||
pub type Done = Box<dyn FnOnce(&mut FigApp, &egui::Context, Value)>;
|
||||
|
||||
impl FigApp {
|
||||
/// Construct `FigApp` from a session and services, taking panel widths and pages height
|
||||
/// from preferences and initializing UI, canvas, clocks, capture/IME and transient channel
|
||||
/// state.
|
||||
pub fn new(session: Session, services: Box<dyn Services>) -> Self {
|
||||
// The main window's panels open as wide as they were left.
|
||||
let (left_width, right_width) = session.prefs.panel_widths;
|
||||
@@ -864,6 +955,21 @@ impl FigApp {
|
||||
pending_dialog: None,
|
||||
ui_context: None,
|
||||
automation_roots: None,
|
||||
control_input_doc: None,
|
||||
control_synthetic: false,
|
||||
input_acks: Vec::new(),
|
||||
applied_acks: Vec::new(),
|
||||
applied_input: None,
|
||||
control_input_queued: false,
|
||||
applied_frame: None,
|
||||
clock: FrameClock::default(),
|
||||
capture: control::CaptureState::default(),
|
||||
logic_ticked: false,
|
||||
ui_frame_stamp: None,
|
||||
ime: egui::ime_context::ImeContextTracker::new(),
|
||||
updates_rt: updates_ui::Runtime::default(),
|
||||
#[cfg(test)]
|
||||
ime_observations: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -876,12 +982,34 @@ impl FigApp {
|
||||
|
||||
/// Run a command, surfacing errors as a toast. Returns the result.
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
|
||||
let layers_generation = self.session.clipboard.layers_generation;
|
||||
let r = self.session.execute(id, ¶ms);
|
||||
self.clear_comment_draft_after_tool_set(id, r.is_ok());
|
||||
self.handle_ui_requests();
|
||||
self.invalidate_synthetic_copy(layers_generation);
|
||||
// A command may change the file the window shows (`doc.switch`, `doc.nextTab`,
|
||||
// `file.open`/`file.close`). Record that presentation before returning, so an in-flight
|
||||
// screenshot admitted on the old file cannot accept pixels from the new one.
|
||||
self.observe_presentation();
|
||||
r.map_err(|e| self.failed(id, &e)).ok()
|
||||
}
|
||||
|
||||
/// A programmatic command that changed the engine clipboard never wrote the system clipboard:
|
||||
/// forget the old system mirror so a later user paste does not trust it as our own copy.
|
||||
/// `before` is the layers generation captured before the command ran.
|
||||
pub(crate) fn invalidate_synthetic_copy(&mut self, before: u64) {
|
||||
if self.control_synthetic && self.session.clipboard.layers_generation != before {
|
||||
self.ui.last_copy = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the file the window drawing now shows, with a monotonic generation that changes on
|
||||
/// every switch (an A→B→A switch is two generations, never the admitted one again).
|
||||
pub(crate) fn observe_presentation(&mut self) {
|
||||
let window = self.windows.current;
|
||||
self.windows.presentation(&self.session, window);
|
||||
}
|
||||
|
||||
/// [`run`](Self::run) for something the user did (a dialog, a drop, a paste, a recent file):
|
||||
/// a file it imports shows its import report. Programmatic calls use `run` and never open one.
|
||||
pub fn run_user(&mut self, id: &str, params: Value) -> Option<Value> {
|
||||
@@ -1004,6 +1132,83 @@ impl FigApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Finish the frame that applies an injected batch: acknowledge it once the pass is presented,
|
||||
/// and stop fencing the system clipboard. Only the viewport whose batch this frame took acts.
|
||||
pub(crate) fn end_input_frame(&mut self, ctx: &egui::Context) {
|
||||
if self.applied_frame != Some(ctx.viewport_id()) {
|
||||
return;
|
||||
}
|
||||
self.applied_input = None;
|
||||
if ctx.will_discard() {
|
||||
// Keep `applied_frame`/`applied_acks`: the rerun pass must present (and acknowledge)
|
||||
// the same frame without replaying the input.
|
||||
return;
|
||||
}
|
||||
self.applied_frame = None;
|
||||
for ack in self.applied_acks.drain(..) {
|
||||
let _ = ack.tx.send(ack.reply);
|
||||
}
|
||||
self.control_synthetic = false;
|
||||
}
|
||||
|
||||
/// The app's monotonic clock in seconds, also usable from logic-only callbacks (recovery,
|
||||
/// control deadlines). Never `ctx.input(i.time)`, which is stale there.
|
||||
pub fn now_secs(&self) -> f64 {
|
||||
self.clock.now()
|
||||
}
|
||||
|
||||
/// Queue raw input injected through the control channel for the window drawing next, tagged
|
||||
/// with the document it belongs to (a batch is dropped if another file is active by then).
|
||||
pub(crate) fn push_control_input(&mut self, events: Vec<egui::Event>) -> bool {
|
||||
if events.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let doc = self.session.docs.get(self.session.active).map(|d| d.uid);
|
||||
if !self.control_input.is_empty() && self.control_input_doc != doc {
|
||||
// A queued batch belongs to the file that was open when it was injected; it cannot be
|
||||
// merged with one for the file showing now. Its acknowledgement says so.
|
||||
self.control_input.clear();
|
||||
let viewport = crate::windows::viewport(self.windows.current);
|
||||
crate::windows::fail_input_acks(self, viewport);
|
||||
}
|
||||
// Always the live pane vector: while a child window draws, `windows::enter` has swapped
|
||||
// its pane into the app, and `leave` swaps these events back into that pane.
|
||||
self.control_input.extend(events);
|
||||
self.control_input_doc = doc;
|
||||
self.control_synthetic = true;
|
||||
true
|
||||
}
|
||||
|
||||
/// The acknowledgements waiting for `viewport`'s input batch (other windows keep theirs).
|
||||
pub(crate) fn take_input_acks(&mut self, viewport: egui::ViewportId) -> Vec<PendingAck> {
|
||||
let mut mine = Vec::new();
|
||||
for ack in std::mem::take(&mut self.input_acks) {
|
||||
if ack.viewport == viewport {
|
||||
mine.push(ack);
|
||||
} else {
|
||||
self.input_acks.push(ack);
|
||||
}
|
||||
}
|
||||
mine
|
||||
}
|
||||
|
||||
/// Put `text` on the system clipboard. Input injected through the control channel never
|
||||
/// replaces what the user copied: this is the one write path every copy command goes through.
|
||||
pub(crate) fn clipboard_set_text(&mut self, text: &str) {
|
||||
if self.control_synthetic {
|
||||
return;
|
||||
}
|
||||
self.services.clipboard_set_text(text);
|
||||
}
|
||||
|
||||
/// [`Self::clipboard_set_text`] for an image (straight RGBA).
|
||||
pub(crate) fn clipboard_set_png(&mut self, width: u32, height: u32, rgba: &[u8]) {
|
||||
if self.control_synthetic {
|
||||
return;
|
||||
}
|
||||
self.services.clipboard_set_png(width, height, rgba);
|
||||
}
|
||||
|
||||
pub fn toast(&mut self, msg: impl Into<String>) {
|
||||
self.ui.toast = Some((msg.into(), ToastClock::Raised));
|
||||
}
|
||||
@@ -1169,8 +1374,10 @@ impl FigApp {
|
||||
fn panel_edge(ui: &mut egui::Ui, name: &str, x: f32, rows: egui::Rangef, width: f32, grows: f32) -> Option<f32> {
|
||||
let grab = ui.style().interaction.resize_grab_radius_side;
|
||||
let rect = egui::Rect::from_x_y_ranges(x - grab..=x + grab, rows);
|
||||
let id = egui::Id::new(("panel_edge", name));
|
||||
let resp = ui.interact(rect, id, egui::Sense::click_and_drag());
|
||||
let id = egui::Id::unique(("panel_edge", name));
|
||||
// Not focusable: an edge is a pointer target, so it must not take Tab/F6 focus from the
|
||||
// panels' controls (see `a11y::focusables`).
|
||||
let resp = ui.interact(rect, id, egui::Sense::CLICK | egui::Sense::DRAG);
|
||||
if resp.hovered() || resp.dragged() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
|
||||
ui.painter().vline(x, rows, egui::Stroke::new(2.0, theme::ACCENT));
|
||||
@@ -1412,18 +1619,56 @@ impl FigApp {
|
||||
need
|
||||
}
|
||||
|
||||
/// Per-frame logic that doesn't draw (control requests, theme, language).
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
/// Work safe from a logic-only callback (`App::logic`, which also runs while hidden) and from
|
||||
/// a normal UI pass: consumed control work, live polling, background completions, autosave and
|
||||
/// recovery deadlines. It never reads UI input, so it must not scan events, run shortcuts or
|
||||
/// lay out anything.
|
||||
pub fn background_tick(&mut self, ctx: &egui::Context) {
|
||||
control::background(self, ctx);
|
||||
// What happened in a live session (the network woke us for it).
|
||||
if self.session.live_poll() {
|
||||
if let Some(m) = self.session.message.take() {
|
||||
self.toast(live::failure_text(&m));
|
||||
}
|
||||
self.background_done(ctx);
|
||||
}
|
||||
// Files that arrived without a command (joined, recovered) take the kept View toggles too.
|
||||
self.session.apply_view_prefs();
|
||||
let now = self.clock.now();
|
||||
self.autosave_tick(ctx, now);
|
||||
self.auto_save_tick(ctx, now);
|
||||
updates_ui::tick(self, ctx);
|
||||
self.logic_ticked = true;
|
||||
}
|
||||
|
||||
/// UI-phase setup that needs a real current `Ui`: fonts/language/theme, interface zoom and the
|
||||
/// render worker. Runs once per frame (pass 0) for the main window, and once per frame for
|
||||
/// every child window (`windows::draw`), never on a logic-only tick.
|
||||
fn ui_setup(&mut self, ctx: &egui::Context) {
|
||||
self.viewport_setup(ctx);
|
||||
}
|
||||
|
||||
/// The app-global part of [`Self::ui_setup`] that every window's frame needs: language, fonts,
|
||||
/// theme and `ui.dark`, the render worker, and the interface zoom plan. eframe only calls
|
||||
/// `App::ui` for the root window, so a child must run this itself before it draws; a child that
|
||||
/// only runs while the root is minimised still gets theme switches, CJK faces for its own
|
||||
/// document, and the right `ui.dark` for its tabs and dialogs.
|
||||
pub(crate) fn viewport_setup(&mut self, ctx: &egui::Context) {
|
||||
if self.language.as_ref() != Some(&self.session.prefs.language) {
|
||||
i18n::set(&self.session.prefs.language, self.services.system_language().as_deref());
|
||||
self.language = Some(self.session.prefs.language.clone());
|
||||
}
|
||||
// Screen-reader and bidi language of the UI (fork E17).
|
||||
ctx.set_language(i18n::current().map(|l| l.code.to_string()));
|
||||
if !self.fonts_installed {
|
||||
// Cmd/Ctrl+= / - / 0 zoom the canvas (view.zoomIn, view.zoomOut, view.zoom100): egui's
|
||||
// own keyboard zoom would scale the whole interface on the same keys.
|
||||
ctx.options_mut(|o| o.zoom_with_keyboard = false);
|
||||
theme::install_fonts(ctx, false, 0);
|
||||
self.fonts_installed = true;
|
||||
// Installed fonts apply from the next frame; a child window draws on here, so ask for
|
||||
// that frame (the root draws nothing on the frame it installs them).
|
||||
ctx.request_repaint();
|
||||
} else if figcraft_text::system_fonts_scanned() {
|
||||
// Once the system fonts are indexed: faces for names in scripts the UI fonts lack, and
|
||||
// for each CJK script once something shows it.
|
||||
@@ -1438,12 +1683,15 @@ impl FigApp {
|
||||
}
|
||||
// egui's zoom is for the whole app and multiplies each window's own system scale, so the
|
||||
// size is the same relative to every screen; the main window, whose size can hold a size
|
||||
// back, sets it. The browser keeps its own zoom.
|
||||
if ctx.viewport_id() == egui::ViewportId::ROOT {
|
||||
// back, sets it. The browser keeps its own zoom. Every window records its own plan (the
|
||||
// Preferences warning and `ui.inspect` read it), from its own size.
|
||||
{
|
||||
let window_px = ctx.content_rect().size() * ctx.pixels_per_point();
|
||||
let size = if cfg!(target_arch = "wasm32") { 1.0 } else { self.session.prefs.ui_scale };
|
||||
let plan = ui_scale::plan(size, ctx.native_pixels_per_point(), Some((window_px.x, window_px.y)));
|
||||
ctx.set_zoom_factor(plan.zoom);
|
||||
if ctx.viewport_id() == egui::ViewportId::ROOT {
|
||||
ctx.set_zoom_factor(plan.zoom);
|
||||
}
|
||||
self.ui.ui_scale = plan;
|
||||
}
|
||||
let dark = match self.session.prefs.theme.as_str() {
|
||||
@@ -1464,8 +1712,7 @@ impl FigApp {
|
||||
|
||||
/// Every [`AUTOSAVE_SECS`], each open document with unsaved changes since its last version
|
||||
/// gets an autosave checkpoint in its version history.
|
||||
fn autosave_tick(&mut self, ctx: &egui::Context) {
|
||||
let now = ctx.input(|i| i.time);
|
||||
fn autosave_tick(&mut self, ctx: &egui::Context, now: f64) {
|
||||
if now < self.ui.next_autosave {
|
||||
// Wake up for it even if nothing else draws a frame by then.
|
||||
repaint_in(ctx, self.ui.next_autosave - now);
|
||||
@@ -1486,8 +1733,7 @@ impl FigApp {
|
||||
/// With auto-save on, files that have a path are saved [`AUTO_SAVE_SECS`] after they last
|
||||
/// changed (not during a gesture, a live preview or while a version is shown). The file is
|
||||
/// encoded on a thread of its own, so a big one doesn't hold up the window, and written here.
|
||||
fn auto_save_tick(&mut self, ctx: &egui::Context) {
|
||||
let now = ctx.input(|i| i.time);
|
||||
fn auto_save_tick(&mut self, ctx: &egui::Context, now: f64) {
|
||||
let mut failed = self.auto_save_done();
|
||||
// The browser has no files to save to.
|
||||
let on = !cfg!(target_arch = "wasm32") && self.session.prefs.auto_save;
|
||||
@@ -1562,25 +1808,36 @@ impl FigApp {
|
||||
let t0 = std::time::Instant::now();
|
||||
let ctx = ui.ctx().clone();
|
||||
self.ui_context = Some(ctx.clone());
|
||||
self.frame_stats.record(&ctx);
|
||||
// `App::logic` already ticked this pass; direct harnesses do not call it. The marker only
|
||||
// covers the tick that shares this pass: clearing it here keeps a direct `App::ui` harness
|
||||
// ticking on every frame (it used to tick every other frame).
|
||||
if !std::mem::take(&mut self.logic_ticked) {
|
||||
self.background_tick(&ctx);
|
||||
self.logic_ticked = false;
|
||||
}
|
||||
// Setup once per frame (pass 0), not once per pass and never on a logic-only tick.
|
||||
let stamp = (ctx.viewport_id(), ctx.cumulative_frame_nr());
|
||||
let first = !self.fonts_installed;
|
||||
self.logic(&ctx);
|
||||
self.autosave_tick(&ctx);
|
||||
self.auto_save_tick(&ctx);
|
||||
if first {
|
||||
// New fonts apply from the next frame; draw nothing until then.
|
||||
if ctx.current_pass_index() == 0 && self.ui_frame_stamp != Some(stamp) {
|
||||
self.ui_frame_stamp = Some(stamp);
|
||||
self.frame_stats.record(&ctx);
|
||||
self.ui_setup(&ctx);
|
||||
}
|
||||
if first && self.fonts_installed {
|
||||
// New fonts apply from the next frame; draw nothing until then. Anything taken into
|
||||
// this frame's (undrawn) input waits for the first drawn frame.
|
||||
ctx.request_repaint();
|
||||
if let Some(events) = self.applied_input.take() {
|
||||
self.push_control_input(events);
|
||||
}
|
||||
self.input_acks.append(&mut self.applied_acks);
|
||||
self.applied_frame = None;
|
||||
self.control_synthetic = false;
|
||||
// The next (drawn) frame ticks for itself in a direct harness.
|
||||
self.logic_ticked = false;
|
||||
self.observe_ime(&ctx, false);
|
||||
return;
|
||||
}
|
||||
// What happened in a live session (the network woke us for it).
|
||||
if self.session.live_poll() {
|
||||
if let Some(m) = self.session.message.take() {
|
||||
self.toast(live::failure_text(&m));
|
||||
}
|
||||
self.background_done(&ctx);
|
||||
}
|
||||
// Files that arrived without a command (joined, recovered) take the kept View toggles too.
|
||||
self.session.apply_view_prefs();
|
||||
windows::begin(self, &ctx);
|
||||
let (files, prefs) = (self.session.docs.len(), self.session.prefs.clone());
|
||||
self.frame(ui);
|
||||
@@ -1589,6 +1846,10 @@ impl FigApp {
|
||||
windows::repaint_others(self, &ctx);
|
||||
}
|
||||
windows::show(self, &ctx);
|
||||
// The injected batch was applied by the frame that took it. A discarded sizing pass keeps
|
||||
// its acknowledgement for the presented pass but never replays the input (its side effects
|
||||
// already happened and would otherwise duplicate).
|
||||
self.end_input_frame(&ctx);
|
||||
// Plugins installed, removed or set up are kept at once: a crash doesn't lose them.
|
||||
// So are the owner tokens of files put online.
|
||||
if std::mem::take(&mut self.session.plugins.unsaved) | std::mem::take(&mut self.session.live.unsaved) {
|
||||
@@ -1613,11 +1874,17 @@ impl FigApp {
|
||||
/// One frame of the window drawing now.
|
||||
pub(crate) fn frame(&mut self, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
// Bind this input batch before controls or pointer input can replace its composing
|
||||
// target/caret. Outgoing IME receipts run after mutation and cannot authorize it.
|
||||
let ime_input = shortcuts::ImeInputBaseline::capture(self);
|
||||
let t = theme::Tokens::get(&ctx);
|
||||
// A field that had the keyboard when the frame began keeps its keys from the shortcuts
|
||||
// even if it lets go during the frame (Enter commits it), or as it began (egui drops the
|
||||
// focus on Escape before the frame, which cancels the field's edit and nothing else).
|
||||
let typing = std::mem::take(&mut self.field_focus) || a11y::field_focused(&ctx);
|
||||
// Bind the originating field/file before tabs can switch. Its widget commits only after
|
||||
// processing this batch; delivery remains deferred until the following frame.
|
||||
let field_save = shortcuts::prepare_field_save(self, &ctx);
|
||||
let swallowed = shortcuts::swallowed_paste(self, &ctx);
|
||||
// A dialog that closed acts first, in the window it was opened from.
|
||||
self.poll_dialog(&ctx);
|
||||
@@ -1626,7 +1893,7 @@ impl FigApp {
|
||||
windows::requests(self, &ctx);
|
||||
selection_spacing::sync(self, &ctx);
|
||||
// Before any widget: the navigation keys (F6, Tab, arrows, Escape) move the keyboard.
|
||||
a11y::begin(self, &ctx);
|
||||
a11y::begin(self, &ctx, ui.scope_id());
|
||||
if self.ui.title_bar == TitleBar::Custom {
|
||||
tabs::resize_edges(&ctx);
|
||||
}
|
||||
@@ -1639,15 +1906,21 @@ impl FigApp {
|
||||
self.end_pen_outside_design();
|
||||
tabs::relink_presents(self);
|
||||
tabs::tab_bar(self, ui);
|
||||
// Control/window work and this pass's physical tab click may have replaced the owner.
|
||||
// A shared field ID in that replacement must never consume the old commit marker.
|
||||
let field_save = shortcuts::revalidate_field_save(self, &ctx, field_save);
|
||||
if self.ui.present.is_some() {
|
||||
// A close request can arrive while the presenter fills the window. Let its unsaved
|
||||
// changes dialog take Escape and draw above the player just as it does in the editor.
|
||||
dialogs::keys(self, &ctx);
|
||||
present::show(self, ui);
|
||||
dialogs::show(self, &ctx);
|
||||
updates_ui::show(self, &ctx);
|
||||
// What went wrong while presenting (a widget's plugin failing) shows over it.
|
||||
self.toast_ui(&ctx);
|
||||
windows::requests(self, &ctx);
|
||||
shortcuts::clear_field_save_marker(&ctx);
|
||||
self.observe_ime(&ctx, false);
|
||||
return;
|
||||
}
|
||||
if !self.has_files() || self.ui.home {
|
||||
@@ -1657,8 +1930,11 @@ impl FigApp {
|
||||
self.ui.shortcuts_panel = false;
|
||||
dialogs::keys(self, &ctx);
|
||||
dialogs::show(self, &ctx);
|
||||
updates_ui::show(self, &ctx);
|
||||
self.toast_ui(&ctx);
|
||||
windows::requests(self, &ctx);
|
||||
shortcuts::clear_field_save_marker(&ctx);
|
||||
self.observe_ime(&ctx, false);
|
||||
return;
|
||||
}
|
||||
let hidden = self.session.ds().map(|d| d.view.ui_hidden).unwrap_or(false);
|
||||
@@ -1743,13 +2019,14 @@ impl FigApp {
|
||||
branch_ui::keys(self, &ctx);
|
||||
live::dialog_keys(self, &ctx);
|
||||
dialogs::keys(self, &ctx);
|
||||
shortcuts::handle(self, &ctx, typing, swallowed);
|
||||
shortcuts::handle_input(self, &ctx, typing, swallowed, ime_input, field_save);
|
||||
menus::popups(self, &ctx);
|
||||
variable_ui::picker(self, &ctx);
|
||||
style_picker::show(self, &ctx);
|
||||
self.end_unwanted_text_preview(&ctx);
|
||||
self.end_pen_outside_design();
|
||||
dialogs::show(self, &ctx);
|
||||
updates_ui::show(self, &ctx);
|
||||
self.toast_ui(&ctx);
|
||||
// A rename started after the layers panel drew (Cmd/Ctrl+R, a double-click) opens its field
|
||||
// next frame.
|
||||
@@ -1763,8 +2040,33 @@ impl FigApp {
|
||||
// changed), from the window with its file.
|
||||
let windows = &self.windows;
|
||||
self.session.live_sync_in(|uid| uid.map_or(0, |u| windows.of(u)) == windows.current);
|
||||
// The canvas editor's IME context is observed exactly once per pass, after every command
|
||||
// this pass ran (shortcuts, menus, dialogs, window requests and live sync). A focused panel
|
||||
// field or an open palette owns the platform IME instead; the early `home`/present paths
|
||||
// above make the same single idle observation.
|
||||
self.observe_ime(&ctx, !typing && !self.field_focus && self.ui.palette.is_none());
|
||||
}
|
||||
|
||||
/// The pass's one IME observation: the focused on-canvas editor, or an explicit idle.
|
||||
///
|
||||
/// Calling `ImeContextTracker::observe` more than once in a pass would treat an idle followed
|
||||
/// by a focused observation as a context change (dropping the frame's receipts) and bump the
|
||||
/// generation. Keeping this in one place makes the fork contract structural.
|
||||
fn observe_ime(&mut self, ctx: &egui::Context, focused: bool) {
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.ime_observations = self.ime_observations.saturating_add(1);
|
||||
}
|
||||
if focused {
|
||||
shortcuts::ime_output(self, ctx);
|
||||
} else {
|
||||
let _ = self.ime.observe(ctx.viewport_id(), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the toast: start its lifetime on the frame **after** the first drawn frame, request
|
||||
/// that frame and the frame that hides it, expire and remove it at the deadline, and place it
|
||||
/// at the bottom centre.
|
||||
fn toast_ui(&mut self, ctx: &egui::Context) {
|
||||
let Some((msg, clock)) = &mut self.ui.toast else { return };
|
||||
let now = ctx.input(|i| i.time);
|
||||
@@ -1793,7 +2095,7 @@ impl FigApp {
|
||||
repaint_in(ctx, left);
|
||||
}
|
||||
let screen = ctx.content_rect();
|
||||
egui::Area::new(egui::Id::new("toast"))
|
||||
egui::Area::new(egui::Id::unique("toast"))
|
||||
.fixed_pos(egui::pos2(screen.center().x, screen.max.y - 96.0))
|
||||
.pivot(egui::Align2::CENTER_BOTTOM)
|
||||
.order(egui::Order::Tooltip)
|
||||
@@ -1923,7 +2225,7 @@ pub(crate) fn drop_overlay(ctx: &egui::Context, rect: egui::Rect, label: &str) {
|
||||
return;
|
||||
}
|
||||
let t = theme::Tokens::get(ctx);
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("drop_overlay")));
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("drop_overlay")));
|
||||
let area = rect.shrink(4.0);
|
||||
painter.rect_filled(area, egui::CornerRadius::same(8), t.accent.gamma_multiply(0.12));
|
||||
painter.rect_stroke(area, egui::CornerRadius::same(8), egui::Stroke::new(2.0, theme::ACCENT), egui::StrokeKind::Inside);
|
||||
|
||||
@@ -6,15 +6,15 @@
|
||||
//! lists bottom first; other lists (an interaction's actions, pages) show their items in model
|
||||
//! order.
|
||||
|
||||
use egui::{AsId, Id, Rect, Sense, Ui, pos2, vec2};
|
||||
use egui::{AsIdSalt, Id, Rect, Sense, Ui, pos2, vec2};
|
||||
|
||||
use crate::icons::{self, Icon};
|
||||
use crate::theme::{Tokens, regular};
|
||||
use crate::widgets::{self, PAD};
|
||||
|
||||
/// The id of list `list` (any hashable key, e.g. `"fills"`).
|
||||
fn list_id(list: impl AsId) -> Id {
|
||||
Id::new(("list_drag", list))
|
||||
fn list_id(list: impl AsIdSalt) -> Id {
|
||||
Id::unique(("list_drag", list))
|
||||
}
|
||||
|
||||
/// The row of list `list` being dragged (its model index; temp data).
|
||||
@@ -24,7 +24,7 @@ fn drag_id(list: Id) -> Id {
|
||||
|
||||
/// The grip of item `index` of list `list` (tests find rows by it).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn grip_id(list: impl AsId, index: usize) -> Id {
|
||||
pub(crate) fn grip_id(list: impl AsIdSalt, index: usize) -> Id {
|
||||
grip_of(list_id(list), index)
|
||||
}
|
||||
|
||||
@@ -49,12 +49,12 @@ pub struct ListDrag {
|
||||
|
||||
impl ListDrag {
|
||||
/// A list shown topmost item (the model's last) first, as the Design panel shows paints.
|
||||
pub fn new(ui: &Ui, list: impl AsId) -> Self {
|
||||
pub fn new(ui: &Ui, list: impl AsIdSalt) -> Self {
|
||||
Self::with_order(ui, list_id(list), true)
|
||||
}
|
||||
|
||||
/// A list shown in model order, first item on top (an interaction's actions).
|
||||
pub fn in_order(ui: &Ui, list: impl AsId) -> Self {
|
||||
pub fn in_order(ui: &Ui, list: impl AsIdSalt) -> Self {
|
||||
Self::with_order(ui, list_id(list), false)
|
||||
}
|
||||
|
||||
@@ -164,34 +164,34 @@ fn drop_slot(rows: &[(usize, Rect)], from: usize, p: egui::Pos2, reversed: bool)
|
||||
Some((if reversed { n - 1 - at } else { at }, y))
|
||||
}
|
||||
|
||||
/// Keep per-row flags (`Id::new((salt, index))`, e.g. an open settings section) with their rows
|
||||
/// Keep per-row flags (`Id::unique((salt, index))`, e.g. an open settings section) with their rows
|
||||
/// when item `from` of a `len`-long list moves to `to`.
|
||||
pub fn move_flags(ui: &Ui, salt: &'static str, len: usize, from: usize, to: usize) {
|
||||
ui.data_mut(|d| {
|
||||
let flags: Vec<Option<bool>> = (0..len).map(|i| d.get_temp::<bool>(Id::new((salt, i)))).collect();
|
||||
let flags: Vec<Option<bool>> = (0..len).map(|i| d.get_temp::<bool>(Id::unique((salt, i)))).collect();
|
||||
for (i, f) in flags.into_iter().enumerate() {
|
||||
let j = figcraft_engine::cmd::lists::moved_index(i, from, to);
|
||||
match f {
|
||||
Some(v) => {
|
||||
d.insert_temp(Id::new((salt, j)), v);
|
||||
d.insert_temp(Id::unique((salt, j)), v);
|
||||
}
|
||||
None => d.remove::<bool>(Id::new((salt, j))),
|
||||
None => d.remove::<bool>(Id::unique((salt, j))),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Keep per-row flags (`Id::new((salt, index))`) with their rows when item `removed` of a
|
||||
/// Keep per-row flags (`Id::unique((salt, index))`) with their rows when item `removed` of a
|
||||
/// `len`-long list goes; its own flag goes with it.
|
||||
pub fn remove_flags(ui: &Ui, salt: &'static str, len: usize, removed: usize) {
|
||||
ui.data_mut(|d| {
|
||||
let flags: Vec<Option<bool>> = (0..len).map(|i| d.get_temp::<bool>(Id::new((salt, i)))).collect();
|
||||
let flags: Vec<Option<bool>> = (0..len).map(|i| d.get_temp::<bool>(Id::unique((salt, i)))).collect();
|
||||
for i in 0..len {
|
||||
d.remove::<bool>(Id::new((salt, i)));
|
||||
d.remove::<bool>(Id::unique((salt, i)));
|
||||
}
|
||||
for (i, f) in flags.into_iter().enumerate() {
|
||||
if let (Some(j), Some(v)) = (figcraft_engine::cmd::lists::removed_index(i, removed), f) {
|
||||
d.insert_temp(Id::new((salt, j)), v);
|
||||
d.insert_temp(Id::unique((salt, j)), v);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
+20
-20
@@ -354,7 +354,7 @@ pub fn chat_box(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let _ = app.session.live_chat("");
|
||||
return;
|
||||
}
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("live_chat")));
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("live_chat")));
|
||||
chat_bubble(&painter, tip, None, &chat.text, fill, alpha);
|
||||
app.ui.live.chat = Some(chat);
|
||||
return;
|
||||
@@ -366,7 +366,7 @@ pub fn chat_box(app: &mut FigApp, ctx: &egui::Context) {
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(CHAT_HOLD + CHAT_FADE - idle));
|
||||
let fg = text_on(fill);
|
||||
let resp = egui::Area::new(egui::Id::new("live_chat_box"))
|
||||
let resp = egui::Area::new(egui::Id::unique("live_chat_box"))
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(tip + vec2(12.0, 16.0))
|
||||
.show(ctx, |ui| {
|
||||
@@ -378,7 +378,7 @@ pub fn chat_box(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let w = ui.painter().layout_no_wrap(chat.text.clone(), regular(12.0), fg).size().x + 8.0;
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut chat.text)
|
||||
.id(egui::Id::new("live_chat_text"))
|
||||
.id(egui::Id::unique("live_chat_text"))
|
||||
.frame(egui::Frame::NONE)
|
||||
.font(regular(12.0))
|
||||
.text_color(fg)
|
||||
@@ -425,7 +425,7 @@ pub fn spotlight_banner(app: &mut FigApp, ctx: &egui::Context, canvas: Rect) {
|
||||
return;
|
||||
};
|
||||
let t = Tokens::get(ctx);
|
||||
let clicked = widgets::canvas_banner(ctx, egui::Id::new("live_spotlight"), canvas, |ui| {
|
||||
let clicked = widgets::canvas_banner(ctx, egui::Id::unique("live_spotlight"), canvas, |ui| {
|
||||
ui.label(egui::RichText::new(text).font(regular(11.0)).color(t.text));
|
||||
widgets::button(ui, button, true, true).clicked()
|
||||
});
|
||||
@@ -473,7 +473,7 @@ pub fn people_bar(app: &mut FigApp, ui: &mut Ui, area: Rect) {
|
||||
let mut spotlight = false;
|
||||
if in_session {
|
||||
let c = pos2(x, cy);
|
||||
let resp = ui.interact(Rect::from_center_size(c, vec2(2.0 * R, 2.0 * R)), ui.id().with("live_me"), Sense::click());
|
||||
let resp = ui.interact(Rect::from_center_size(c, vec2(2.0 * R, 2.0 * R)), ui.scope_id().with("live_me"), Sense::click());
|
||||
a11y::menu_button(&resp, tr("You"), a11y::menu_open(&resp));
|
||||
if spotlighting || resp.hovered() {
|
||||
ui.painter().circle_stroke(c, R + 2.5, Stroke::new(2.0, me_fill));
|
||||
@@ -491,7 +491,7 @@ pub fn people_bar(app: &mut FigApp, ui: &mut Ui, area: Rect) {
|
||||
let c = pos2(x, cy);
|
||||
let following = follow == Some(*id);
|
||||
let tip = if following { trf("Stop following {name}", &[("name", name)]) } else { trf("Follow {name}", &[("name", name)]) };
|
||||
let resp = ui.interact(Rect::from_center_size(c, vec2(2.0 * R, 2.0 * R)), ui.id().with(("live_avatar", id)), Sense::click()).tip(tip);
|
||||
let resp = ui.interact(Rect::from_center_size(c, vec2(2.0 * R, 2.0 * R)), ui.scope_id().with(("live_avatar", id)), Sense::click()).tip(tip);
|
||||
ring(ui, c);
|
||||
avatar(ui.painter(), c, R, name, *fill);
|
||||
if following || resp.hovered() {
|
||||
@@ -517,7 +517,7 @@ pub fn people_bar(app: &mut FigApp, ui: &mut Ui, area: Rect) {
|
||||
ui.painter().text(c, Align2::CENTER_CENTER, format!("+{more}"), semibold(10.0), t.text);
|
||||
}
|
||||
let chev = Rect::from_center_size(pos2(x + R + 10.0, cy), vec2(16.0, 24.0));
|
||||
let cresp = ui.interact(chev, ui.id().with("live_people"), Sense::click());
|
||||
let cresp = ui.interact(chev, ui.scope_id().with("live_people"), Sense::click());
|
||||
a11y::menu_button(&cresp, tr("People in this file"), a11y::menu_open(&cresp));
|
||||
if cresp.hovered() {
|
||||
ui.painter().rect_filled(chev, CornerRadius::same(4), t.hover);
|
||||
@@ -665,7 +665,7 @@ fn online_note(app: &mut FigApp, ui: &mut Ui, t: &Tokens, server: &str) {
|
||||
/// home screen is closed. The session of the join that started, if one did.
|
||||
pub fn join_row(app: &mut FigApp, ui: &mut Ui, width: f32) -> Option<SessionId> {
|
||||
let mut typed = std::mem::take(&mut app.ui.live.code);
|
||||
let joined = ui.horizontal(|ui| join_field(app, ui, &mut typed, egui::Id::new("live_join_code"), width, false)).inner;
|
||||
let joined = ui.horizontal(|ui| join_field(app, ui, &mut typed, egui::Id::unique("live_join_code"), width, false)).inner;
|
||||
app.ui.live.code = typed;
|
||||
joined
|
||||
}
|
||||
@@ -714,7 +714,7 @@ fn start_ui(app: &mut FigApp, ui: &mut Ui, t: &Tokens) {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::label(ui, tr("Your name"), t.text);
|
||||
let name = app.session.prefs.user_name.clone();
|
||||
if let Some(n) = widgets::text_field(ui, egui::Id::new("live_name"), &name, 160.0, tr("Your name")) {
|
||||
if let Some(n) = widgets::text_field(ui, egui::Id::unique("live_name"), &name, 160.0, tr("Your name")) {
|
||||
app.run("pref.userName", json!({"name": n}));
|
||||
}
|
||||
});
|
||||
@@ -755,7 +755,7 @@ fn start_ui(app: &mut FigApp, ui: &mut Ui, t: &Tokens) {
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
widgets::label(ui, tr("Port"), t.text);
|
||||
if let Some(port) = widgets::text_field_named(ui, egui::Id::new("live_port"), &app.ui.live.port, 70.0, tr("Port")) {
|
||||
if let Some(port) = widgets::text_field_named(ui, egui::Id::unique("live_port"), &app.ui.live.port, 70.0, tr("Port")) {
|
||||
// Digits only; empty: the usual port, or any free one.
|
||||
app.ui.live.port = port.trim().parse::<u16>().map(|p| p.to_string()).unwrap_or_default();
|
||||
}
|
||||
@@ -885,11 +885,11 @@ fn share_ui(app: &mut FigApp, ui: &mut Ui, t: &Tokens, share: &Share) {
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::button(ui, tr("Copy code"), true, true).clicked() {
|
||||
app.services.clipboard_set_text(&code);
|
||||
app.clipboard_set_text(&code);
|
||||
app.toast(tr("Join code copied"));
|
||||
}
|
||||
if widgets::button(ui, tr("Copy link"), false, true).on_hover_text(tr("An invite link that opens FigCraft and joins")).clicked() {
|
||||
app.services.clipboard_set_text(&link);
|
||||
app.clipboard_set_text(&link);
|
||||
app.toast(tr("Invite link copied"));
|
||||
}
|
||||
});
|
||||
@@ -1007,7 +1007,7 @@ fn report_ui(app: &mut FigApp, ui: &mut Ui, t: &Tokens) {
|
||||
.hint_text(tr("Spam, stolen work, abuse…"))
|
||||
.char_limit(figcraft_engine::live::MAX_REPORT)
|
||||
.desired_width(ui.available_width())
|
||||
.id(egui::Id::new("live_report_reason")),
|
||||
.id(egui::Id::unique("live_report_reason")),
|
||||
);
|
||||
a11y::text(&resp, tr("Report"), &reason);
|
||||
crate::widgets::select_all_on_focus(ui, &resp, &reason);
|
||||
@@ -1042,7 +1042,7 @@ fn link_rows(app: &mut FigApp, ui: &mut Ui, rows: &[(&str, &String, &str)]) {
|
||||
ui.label(egui::RichText::new(widgets::elide(ui, value, w)).font(regular(10.5)).monospace());
|
||||
});
|
||||
if widgets::button(ui, tr("Copy"), false, true).on_hover_text(trf("Copy the {label}", &[("label", &label.to_lowercase())])).clicked() {
|
||||
app.services.clipboard_set_text(value);
|
||||
app.clipboard_set_text(value);
|
||||
app.toast(*what);
|
||||
}
|
||||
});
|
||||
@@ -1085,11 +1085,11 @@ pub fn join_dialog(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let mut cancel = false;
|
||||
let mut go = false;
|
||||
let focus = std::mem::take(&mut app.ui.live.focus_join);
|
||||
crate::dialogs::window(tr("Join live session"), ctx).id(egui::Id::new("Join live session")).open(&mut open).show(ctx, |ui| {
|
||||
crate::dialogs::window(tr("Join live session"), ctx).id(egui::Id::unique("Join live session")).open(&mut open).show(ctx, |ui| {
|
||||
ui.set_width(380.0);
|
||||
widgets::label(ui, tr("Type the join code you were given, or paste an invite link."), t.text);
|
||||
ui.horizontal(|ui| {
|
||||
go = join_field(app, ui, &mut link, egui::Id::new("live_join_link"), 300.0, focus).is_some();
|
||||
go = join_field(app, ui, &mut link, egui::Id::unique("live_join_link"), 300.0, focus).is_some();
|
||||
cancel = widgets::button(ui, tr("Cancel"), false, true).clicked();
|
||||
});
|
||||
widgets::label(ui, tr("You'll get the shared file as a new tab and edit it together."), t.text_secondary);
|
||||
@@ -1158,7 +1158,7 @@ pub fn publish_dialog(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let open_server = info.as_ref().is_some_and(|v| v["open"] == true);
|
||||
// A first look at an address already filled in.
|
||||
ask |= focus && !address.is_empty() && !keyed && info.is_none();
|
||||
crate::dialogs::window(tr("Publish to server"), ctx).id(egui::Id::new("Publish to server")).open(&mut open).show(ctx, |ui| {
|
||||
crate::dialogs::window(tr("Publish to server"), ctx).id(egui::Id::unique("Publish to server")).open(&mut open).show(ctx, |ui| {
|
||||
ui.set_width(380.0);
|
||||
widgets::label(
|
||||
ui,
|
||||
@@ -1170,7 +1170,7 @@ pub fn publish_dialog(app: &mut FigApp, ctx: &egui::Context) {
|
||||
egui::TextEdit::singleline(&mut form.server)
|
||||
.hint_text("wss://server/ or ws://server:47900/?key=…")
|
||||
.desired_width(380.0)
|
||||
.id(egui::Id::new("live_publish_server")),
|
||||
.id(egui::Id::unique("live_publish_server")),
|
||||
);
|
||||
// The address may carry the server key: it isn't read out.
|
||||
a11y::text(&resp, tr("Server address"), "");
|
||||
@@ -1202,7 +1202,7 @@ pub fn publish_dialog(app: &mut FigApp, ctx: &egui::Context) {
|
||||
),
|
||||
}
|
||||
widgets::label(ui, tr("File name"), t.text_secondary);
|
||||
let nresp = ui.add(egui::TextEdit::singleline(&mut form.name).desired_width(380.0).id(egui::Id::new("live_publish_name")));
|
||||
let nresp = ui.add(egui::TextEdit::singleline(&mut form.name).desired_width(380.0).id(egui::Id::unique("live_publish_name")));
|
||||
a11y::text(&nresp, tr("File name"), &form.name);
|
||||
crate::widgets::select_all_on_focus(ui, &nresp, &form.name);
|
||||
go |= nresp.lost_focus() && enter(ui) && (keyed || open_server);
|
||||
@@ -1249,7 +1249,7 @@ fn published_dialog(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let t = Tokens::get(ctx);
|
||||
let mut open = true;
|
||||
let mut done = false;
|
||||
crate::dialogs::window(tr("File published"), ctx).id(egui::Id::new("File published")).open(&mut open).show(ctx, |ui| {
|
||||
crate::dialogs::window(tr("File published"), ctx).id(egui::Id::unique("File published")).open(&mut open).show(ctx, |ui| {
|
||||
ui.set_width(400.0);
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
|
||||
widgets::label(ui, &trf("{name} is on the server.", &[("name", &p.name)]), t.text);
|
||||
|
||||
@@ -14,8 +14,9 @@ fn escape(h: &mut Harness) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the Join link field currently has focus.
|
||||
fn link_focused(h: &Harness) -> bool {
|
||||
h.ctx.memory(|m| m.has_focus(egui::Id::new("live_join_link")))
|
||||
h.ctx.memory(|m| m.has_focus(egui::Id::unique("live_join_link")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -20,8 +20,9 @@ fn key(h: &mut Harness, key: Key) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the widget with the given id currently has focus.
|
||||
fn focused(h: &Harness, id: &str) -> bool {
|
||||
h.ctx.memory(|m| m.has_focus(egui::Id::new(id)))
|
||||
h.ctx.memory(|m| m.has_focus(egui::Id::unique(id)))
|
||||
}
|
||||
|
||||
/// Joined through a server's link with `access`: the welcome and the document (a new tab).
|
||||
|
||||
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user