canvas-w25: net change of 2 commits

- canvas-w25: written from its sheet
- canvas-w25: repair 1
This commit is contained in:
bflatastic
2026-11-21 23:26:56 +07:00
parent 0f854066af
commit 82ed6e4630
11 changed files with 236 additions and 2176 deletions
+2 -2
View File
@@ -80,7 +80,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts.
- Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns). If the provenance of an asset is unclear, don't add it.
- Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets.
- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input.
- Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort.
@@ -91,7 +91,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net.
- Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them.
- **Adding a cursor.** The app decides which cursors exist; whoever draws them works from the list. For a new tool state with a cursor of its own: add the `Cursor` variant (`crates/tools/src/lib.rs`, with a doc comment), return it from the tool's `cursor()` with a tool test, cover it in `cursor_icon` (`crates/ui-egui/src/canvas.rs`), draw it in `crates/ui-egui/src/cursors.rs` or give it a stand-in in `Cursor::stand_in()` until it's drawn, and add its `[[cursor]]` entry to `crates/tools/src/cursors.toml` (when it shows, in plain behaviour terms, and its hotspot; never another app's look). A missing entry only warns (`cargo xtask cursors`): the cursor still works.
- **Adding a cursor.** The app decides which cursors exist; whoever draws them works from the list. For a new tool state with a cursor of its own: add the `Cursor` variant (`crates/tools/src/lib.rs`, with a doc comment), return it from the tool's `cursor()` with a tool test, map it in `cursors::tool_cursor` (`crates/ui-egui/src/cursors.rs`), using a catalog icon or an SVG in `assets/cursors/` (with its `ASSETS.md` row and `CURSOR_ICONS` entry), or give it a stand-in in `Cursor::stand_in()` until it's drawn, and add its `[[cursor]]` entry to `crates/tools/src/cursors.toml` (when it shows, in plain behaviour terms, and its hotspot; never another app's look). A missing entry only warns (`cargo xtask cursors`): the cursor still works.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
+22 -1
View File
@@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`).
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`).
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
@@ -58,6 +58,23 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `packaging/macos/dmg/background.svg` | Xus Badia (contributed in #493) | Original artwork for VectorCraft's DMG window; links the app icon `assets/app-icon/vectorcraft-small.svg` | MIT OR Apache-2.0 (licensed by the contributor under the project licence) | DMG background source. Text in Inter and JetBrains Mono (OFL-1.1, `assets/fonts`), not embedded; paper grain generated by an SVG `feTurbulence` filter |
| `packaging/macos/dmg/background.tiff` | Xus Badia (contributed in #493) | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 | 1x + 2x DMG background; includes the app icon (see its rows), text rendered from OFL-1.1 fonts and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
| `packaging/macos/dmg/DS_Store` | Xus Badia (layout, #493) | Written by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 | Finder view settings for the DMG (window, icon size and positions, background alias); no machine data |
| `assets/cursors/cursor-anchor-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-direct-anchor-selected.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-direct-anchor.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-loaded-text-link.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-loaded-text.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-bracket.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-edge.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-line-level.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-line-rising.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-ring.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-star.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-convert.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-curvature.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-new.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-reshape-segment.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
@@ -95,6 +112,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/chevrons-left.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC; derived from Feather, also MIT (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/chevrons-right.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC; derived from Feather, also MIT (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/circle.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC; derived from Feather, also MIT (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/circle-off.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/clipboard-paste.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/cloud.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/combine.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
@@ -124,6 +142,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-artboard-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-artboards.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-blend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-blend-align-page.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-blend-align-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-bloat.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cap-butt.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cap-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -160,6 +180,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-filter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-flare.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-folder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-free-distort.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: a quadrilateral with a handle on each corner | MIT OR Apache-2.0 | |
| `assets/icons/dc-free-transform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-fx.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-gamut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
-238
View File
@@ -1,238 +0,0 @@
//! AppKit delivery of the UI's existing cursor artwork, independent of canvas presentation.
#![forbid(unsafe_code)]
// Interim #2292: remove when pinned winit correctly handles macOS cursor image and hotspot sizing.
use egui::{Context, FullOutput, Plugin, ViewportId};
use objc2::{AllocAnyThread, MainThreadMarker, rc::Retained};
use objc2_app_kit::{NSApplication, NSBitmapImageRep, NSCursor, NSImage, NSWindow};
use objc2_foundation::{NSData, NSPoint, NSSize};
use std::cell::RefCell;
use vectorcraft_ui_egui::cursors::native_request::{self, Bitmap, Key, Request};
const CAPACITY: usize = 128;
fn build(bitmap: &Bitmap) -> Option<Retained<NSCursor>> {
let one = &bitmap.representations[0];
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
let image = NSImage::initWithSize(NSImage::alloc(), size);
for bitmap in &bitmap.representations {
let pixels = image::RgbaImage::from_raw(u32::from(bitmap.size[0]), u32::from(bitmap.size[1]), bitmap.rgba.to_vec())?;
let mut png = std::io::Cursor::new(Vec::new());
pixels.write_to(&mut png, image::ImageFormat::Png).ok()?;
let rep = NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(png.get_ref()))?;
rep.setSize(size);
image.addRepresentation(&rep);
}
Some(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1]))))
}
/// The ownership protocol also runs against a headless backend in tests.
trait Backend {
type Window: Clone + PartialEq;
type Cursor: Clone + PartialEq;
fn window(&self) -> Option<Self::Window>;
fn enabled(&self, window: &Self::Window) -> bool;
fn suspend(&mut self, window: &Self::Window);
fn restore(&mut self, window: &Self::Window);
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
fn set(&mut self, cursor: &Self::Cursor);
}
struct State<B: Backend> {
backend: B,
candidate: Option<B::Window>,
cache: Vec<(Key, Option<B::Cursor>)>,
// Retain the active object independently of cache eviction.
active: Option<(Key, B::Window, B::Cursor)>,
}
impl<B: Backend> State<B> {
fn new(backend: B) -> Self {
Self { backend, candidate: None, cache: Vec::new(), active: None }
}
fn begin(&mut self) {
self.candidate = self.backend.window();
}
fn release(&mut self) {
self.candidate = None;
if let Some((_, window, _)) = self.active.take() {
self.backend.restore(&window);
}
}
fn finish(&mut self, request: Option<Request>) {
let window = self.candidate.take().filter(|w| self.backend.window().as_ref() == Some(w));
let (Some(request), Some(window)) = (request, window) else {
self.release();
return;
};
if let Some((key, owned, cursor)) = &self.active
&& *key == request.key
&& *owned == window
{
// AppKit can show the system arrow when the pointer moves while
// `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a
// comparison would keep the arrow. Setting the cursor again costs nothing.
self.backend.set(cursor);
return;
}
self.release();
// Never take another component's suspension (a sheet or native tracking session).
if !self.backend.enabled(&window) {
return;
}
let cursor = if let Some((_, cursor)) = self.cache.iter().find(|(key, _)| *key == request.key) {
cursor.clone()
} else {
let cursor = self.backend.build(&request);
if self.cache.len() >= CAPACITY {
self.cache.clear();
}
self.cache.push((request.key, cursor.clone()));
cursor
};
if let Some(cursor) = cursor {
self.backend.suspend(&window);
self.backend.set(&cursor);
self.active = Some((request.key, window, cursor));
}
}
}
#[derive(Default)]
struct AppKit {
root: std::sync::Weak<winit::window::Window>,
}
impl Backend for AppKit {
type Window = Retained<NSWindow>;
type Cursor = Retained<NSCursor>;
fn window(&self) -> Option<Self::Window> {
let mtm = MainThreadMarker::new()?;
// Bind the candidate to the host's actual root window without converting raw pointers.
// A floating native panel may be key while egui still has stale root focus input.
let root = self.root.upgrade()?;
if !root.has_focus() || root.is_visible() == Some(false) || root.is_minimized() == Some(true) {
return None;
}
NSApplication::sharedApplication(mtm).keyWindow().filter(|w| w.isVisible() && w.isKeyWindow())
}
fn enabled(&self, window: &Self::Window) -> bool {
window.areCursorRectsEnabled()
}
fn suspend(&mut self, window: &Self::Window) {
window.disableCursorRects();
}
fn restore(&mut self, window: &Self::Window) {
window.enableCursorRects();
window.resetCursorRects();
// egui-winit may skip an unchanged fallback icon. Rebuild its stored rectangle anyway.
if let Some(view) = window.contentView() {
window.invalidateCursorRectsForView(&view);
}
}
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
build(&request.bitmap)
}
fn set(&mut self, cursor: &Self::Cursor) {
cursor.set();
}
}
thread_local! { static STATE: RefCell<State<AppKit>> = RefCell::new(State::new(AppKit::default())); }
fn with_state(f: impl FnOnce(&mut State<AppKit>)) {
// All production AppKit access, including restoration, stays on the main thread.
if MainThreadMarker::new().is_some() {
STATE.with(|state| {
if let Ok(mut state) = state.try_borrow_mut() {
f(&mut state);
}
});
}
}
/// Also called synchronously when native menu tracking begins and before process teardown.
pub(crate) fn release() {
with_state(State::release);
}
struct EndedPass {
viewport: ViewportId,
discarded: bool,
request: Option<Request>,
}
struct Delivery {
begin: fn(),
finish: fn(Option<Request>),
release: fn(),
tracking: fn() -> bool,
ended: Vec<EndedPass>,
}
impl Plugin for Delivery {
fn debug_name(&self) -> &'static str {
"macOS canvas cursor"
}
fn on_begin_pass(&mut self, ui: &mut egui::Ui) {
native_request::clear(ui.ctx());
// Floating panels must not acquire or release the main canvas's window.
if ui.ctx().viewport_id() == ViewportId::ROOT {
(self.begin)();
}
}
fn on_end_pass(&mut self, ui: &mut egui::Ui) {
// egui restores the parent viewport before output_hook. Capture this pass here so
// a floating panel's output cannot consume or release its parent's cursor.
self.ended.push(EndedPass { viewport: ui.ctx().viewport_id(), discarded: ui.ctx().will_discard(), request: native_request::take(ui.ctx()) });
}
fn input_hook(&mut self, _: &Context, input: &mut egui::RawInput) {
if input.viewport_id == ViewportId::ROOT
&& (!input.focused || input.viewports.get(&ViewportId::ROOT).is_some_and(|v| v.minimized == Some(true)))
{
(self.release)();
}
}
fn output_hook(&mut self, ctx: &Context, output: &mut FullOutput) {
let Some(ended) = self.ended.pop() else { return };
if ended.viewport != ViewportId::ROOT {
return;
}
if ended.discarded
|| (output.platform_output.requested_discard() && output.platform_output.num_completed_passes < ctx.options(|o| o.max_passes.get()))
{
return;
}
let request = ended.request.filter(|r| {
r.viewport == ended.viewport
&& r.pass.checked_add(1) == Some(ctx.cumulative_pass_nr_for(ended.viewport))
&& ctx.input(|i| i.focused && i.pointer.hover_pos().is_some())
&& output.platform_output.cursor_icon == r.fallback
&& output.platform_output.cursor_image.is_none()
&& !(self.tracking)()
});
// This is BEFORE egui-winit's platform output. In pinned winit, fallback changes update
// the view's stored cursor and invalidate rectangles. Our owned suspension is intended
// to keep that update from replacing the native cursor; native timing needs hand testing.
(self.finish)(request);
}
fn on_exit(&mut self, _: &Context) {
(self.release)();
}
}
pub(crate) fn install(ctx: &Context, window: Option<&std::sync::Arc<winit::window::Window>>) {
with_state(|state| state.backend.root = window.map(std::sync::Arc::downgrade).unwrap_or_default());
ctx.add_plugin(Delivery {
begin: || with_state(State::begin),
finish: |request| with_state(|state| state.finish(request)),
release,
tracking: super::mac_menu::is_tracking,
ended: Vec::new(),
});
}
#[cfg(test)]
mod tests;
-227
View File
@@ -1,227 +0,0 @@
use super::*;
use egui::{CursorIcon, RawInput};
use std::cell::Cell;
#[derive(Default)]
struct Fake {
window: Option<u8>,
suspended: Vec<u8>,
sets: usize,
builds: usize,
restores: Vec<u8>,
fail: bool,
}
impl Backend for Fake {
type Window = u8;
type Cursor = Key;
fn window(&self) -> Option<u8> {
self.window
}
fn enabled(&self, w: &u8) -> bool {
!self.suspended.contains(w)
}
fn suspend(&mut self, w: &u8) {
self.suspended.push(*w);
}
fn restore(&mut self, w: &u8) {
self.suspended.retain(|v| v != w);
self.restores.push(*w);
}
fn build(&mut self, r: &Request) -> Option<Key> {
self.builds += 1;
(!self.fail).then_some(r.key)
}
fn set(&mut self, _: &Key) {
self.sets += 1;
}
}
fn fake_state() -> State<Fake> {
State::new(Fake { window: Some(1), ..Default::default() })
}
fn raw(id: ViewportId, focused: bool) -> RawInput {
let mut input = RawInput { viewport_id: id, focused, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() };
input.viewports.entry(id).or_default();
input
}
fn publish(ctx: &Context, scale: f32) {
let mut session = vectorcraft_engine::Session::new();
let cursor = session.cursor(Default::default(), Default::default(), Default::default());
let fallback = native_request::request(ctx, cursor, CursorIcon::Default, true, scale);
ctx.set_cursor_icon(fallback);
}
fn request(scale: f32) -> Request {
let ctx = Context::default();
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| publish(ui.ctx(), scale));
native_request::take(&ctx).unwrap()
}
fn deliver(state: &mut State<Fake>, request: Option<Request>) {
state.begin();
state.finish(request);
}
#[test]
fn mac_cursor_ownership_reasserts_every_pass_and_restores() {
let req = request(1.0);
let mut state = fake_state();
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.suspended, [1]);
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
// The pointer moves and AppKit shows the system arrow, but the app's current cursor
// still reads as ours. The next pass sets it again without rebuilding or re-suspending.
deliver(&mut state, Some(req.clone()));
assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1));
deliver(&mut state, None);
assert_eq!(state.backend.restores, [1]);
deliver(&mut state, Some(req.clone()));
state.backend.window = None;
deliver(&mut state, Some(req.clone()));
assert!(state.active.is_none());
state.backend.window = Some(1);
deliver(&mut state, Some(req.clone()));
state.begin();
state.backend.window = Some(2);
state.finish(Some(req));
assert!(state.active.is_none(), "never acquire a different key window mid-pass");
assert_eq!(state.backend.restores, [1, 1, 1]);
}
#[test]
fn mac_cursor_respects_other_suspensions_failures_and_cache_eviction() {
let mut state = fake_state();
state.backend.suspended.push(1);
deliver(&mut state, Some(request(1.0)));
assert_eq!(state.backend.builds, 0);
state.release();
assert_eq!(state.backend.suspended, [1]);
assert!(state.backend.restores.is_empty());
state.backend.suspended.clear();
state.backend.fail = true;
for _ in 0..2 {
deliver(&mut state, Some(request(1.0)));
}
assert_eq!(state.backend.builds, 1, "cache failed constructions");
state.backend.fail = false;
for i in 1..140 {
deliver(&mut state, Some(request(1.0 + i as f32 / 1000.0)));
}
assert!(state.cache.len() <= CAPACITY);
let active = state.active.unwrap();
state.cache.clear();
assert_eq!(state.active, Some(active));
state.release();
assert!(state.backend.suspended.is_empty());
}
thread_local! {
static FAKE: RefCell<State<Fake>> = RefCell::new(fake_state());
static TRACKING: Cell<bool> = const { Cell::new(false) };
}
fn install_fake(ctx: &Context) {
ctx.add_plugin(Delivery {
begin: || FAKE.with(|s| s.borrow_mut().begin()),
finish: |r| FAKE.with(|s| s.borrow_mut().finish(r)),
release: || FAKE.with(|s| s.borrow_mut().release()),
tracking: || TRACKING.with(Cell::get),
ended: Vec::new(),
});
}
#[test]
fn mac_cursor_plugin_consumes_passes_and_releases_for_menu_focus_and_overrides() {
FAKE.with(|s| *s.borrow_mut() = fake_state());
TRACKING.with(|t| t.set(false));
let ctx = Context::default();
install_fake(&ctx);
install_fake(&ctx);
let root = ViewportId::ROOT;
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 1, "one installed plugin consumes the request"));
let _ = headless(&ctx, raw(ViewportId::from_hash_of("floating-panel"), true), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_some()));
let _ = headless(&ctx, raw(root, true), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_none(), "empty pass hands back even an unchanged Default icon"));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
let _ = headless(&ctx, raw(root, true), |ui| {
publish(ui.ctx(), 1.0);
ui.ctx().set_cursor_icon(CursorIcon::Text);
});
FAKE.with(|s| assert!(s.borrow().active.is_none(), "changed-icon handback"));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
// The notification calls release without waiting for another UI pass.
TRACKING.with(|t| t.set(true));
FAKE.with(|s| s.borrow_mut().release());
FAKE.with(|s| assert!(s.borrow().active.is_none()));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert!(s.borrow().active.is_none()));
TRACKING.with(|t| t.set(false));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
let _ = headless(&ctx, raw(root, false), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_none()));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert!(s.borrow().active.is_some()));
}
#[test]
fn mac_cursor_discarded_pass_does_not_commit_and_installation_does_not_repaint() {
FAKE.with(|s| *s.borrow_mut() = fake_state());
TRACKING.with(|t| t.set(false));
let ctx = Context::default();
install_fake(&ctx);
let mut passes = 0;
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| {
passes += 1;
if passes == 1 {
publish(ui.ctx(), 1.0);
ui.ctx().request_discard("cursor regression");
}
});
assert_eq!(passes, 2);
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 0));
let idle = || {
let mut input = raw(ViewportId::ROOT, true);
input.events.clear();
input.time = Some(ctx.input(|i| i.time) + 0.1);
input
};
for _ in 0..3 {
let _ = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
}
let out = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
assert!(out.viewport_output[&ViewportId::ROOT].repaint_delay > std::time::Duration::ZERO);
}
#[test]
fn mac_cursor_appkit_representations_have_pixel_sizes_and_point_hotspots() {
// Only construct and inspect image/cursor objects: no NSApplication, window or cursor.set().
for scale in [0.75, 1.0, 1.25, 1.5, 2.0] {
let request = request(scale);
let cursor = build(&request.bitmap).unwrap();
let image = cursor.image();
let one = &request.bitmap.representations[0];
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
assert_eq!(image.size(), size);
assert_eq!(cursor.hotSpot(), NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1])));
let reps = image.representations();
assert_eq!(reps.len(), 2);
let mut dimensions: Vec<_> = reps
.iter()
.map(|rep| {
assert_eq!(rep.size(), size);
(rep.pixelsWide(), rep.pixelsHigh())
})
.collect();
dimensions.sort_unstable();
assert_eq!(
dimensions,
[
(isize::try_from(one.size[0]).unwrap(), isize::try_from(one.size[1]).unwrap()),
(isize::try_from(one.size[0]).unwrap() * 2, isize::try_from(one.size[1]).unwrap() * 2)
]
);
}
}
fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput {
let mut output = ctx.run_ui(input, draw);
output.textures_delta.clear();
output
}
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 4.8L18.7 1.4L22.6 21.6L4.8 18.2Z"/>
<rect x="0.8" y="3.6" width="2.4" height="2.4" fill="currentColor"/>
<rect x="17.5" y="0.2" width="2.4" height="2.4" fill="currentColor"/>
<rect x="21.4" y="20.4" width="2.4" height="2.4" fill="currentColor"/>
<rect x="3.6" y="17" width="2.4" height="2.4" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 525 B

+9 -44
View File
@@ -6,7 +6,7 @@ use vectorcraft_geom::Point;
use vectorcraft_tools::distort::perspective::widget::WidgetPlace;
use vectorcraft_tools::draw2::FEEDBACK;
use vectorcraft_tools::shape::MAX_CORNER_RADIUS;
use vectorcraft_tools::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, settings};
use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, settings};
use crate::{EngineError, Prefs, Result, Session};
@@ -42,6 +42,9 @@ pub struct ViewInfo {
pub screen: Option<vectorcraft_tools::ScreenFrame>,
/// The view's active artboard (an index): artboard rulers measure from it.
pub artboard: usize,
/// Precise cursors in this call: the canvas's `CanvasSpace::precise`, the preference toggled by
/// Caps Lock. The one source for the tools' crosshair and for hiding the brush tip.
pub precise: bool,
}
impl Default for ViewInfo {
@@ -61,6 +64,7 @@ impl Default for ViewInfo {
shape_widgets: true,
screen: None,
artboard: 0,
precise: false,
}
}
}
@@ -483,7 +487,7 @@ impl Session {
screen: view.screen,
plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position),
plane_targets: self.prefs.perspective_widget.targets(),
precise_cursors: self.precise_cursors(),
precise_cursors: view.precise,
global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()),
interaction_doc: st.interaction.as_ref().map(|it| &*it.doc),
};
@@ -1076,30 +1080,6 @@ impl Session {
r
}
/// Would [`Session::tool_text`] insert `text` unchanged (no control-character filtering,
/// newline normalization or document formatting such as Typographer's Quotes)? An IME commit
/// the application rewrites is an application edit, not an accepted IME insertion.
pub fn tool_text_is_verbatim(&mut self, text: &str, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.text_input_is_verbatim(cx, text))
}
/// [`Session::tool_text_is_verbatim`] for text typed on the keyboard, as
/// [`Session::tool_typed_text`] would insert it: a lone typed `”` that Typographer's Quotes
/// turns into an opening quote is not verbatim.
pub fn tool_typed_text_is_verbatim(&mut self, text: &str, view: ViewInfo) -> bool {
self.keyboard_text = true;
let v = self.tool_text_is_verbatim(text, view);
self.keyboard_text = false;
v
}
/// Does the active tool's open typing session still match the document? An IME commit after
/// an external edit starts a fresh session (an application-side reset), so its receipt must
/// not be accepted as an unchanged IME insertion.
pub fn tool_ime_session_matches(&mut self, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.ime_session_matches_document(cx))
}
/// Whether the active tool currently owns keyboard text input, as the Type tool does while editing.
pub fn tool_wants_text(&self) -> bool {
self.tool.wants_text()
@@ -1136,14 +1116,6 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.ime_target(cx))
}
/// The committed logical text around the IME cursor (UTF-8 byte offsets), with any pre-edit
/// removed and at most `max_bytes` bytes copied: the app's outgoing surrounding-text producer
/// (egui E21b) reads it. An explicit [`ImeSurrounding::Unavailable`] carries the narrow reason
/// (no editor, invalid offsets, or a selection wider than the limit).
pub fn tool_ime_surrounding(&mut self, max_bytes: usize, view: ViewInfo) -> ImeSurrounding {
self.with_tool_cx(view, |t, cx| t.ime_surrounding(cx, max_bytes))
}
/// Is the active tool showing uncommitted IME text?
pub fn tool_composing(&self) -> bool {
self.tool.composing()
@@ -1304,13 +1276,12 @@ impl Session {
v
}
/// The pointer the active tool shows at `p` (General › Use Precise Cursors, or Caps Lock while
/// it is on, makes the drawing tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
/// The pointer the active tool shows at `p`. With Cmd held, the pointer of the selection tool a
/// press would borrow ([`Self::lend_selection_tool`]).
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
// While an edit is computed, a Cmd press is held for the active tool, which shows it is busy.
let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None };
let c = match lent {
match lent {
Some(id) => {
let lent = self.make_tool(id);
let own = std::mem::replace(&mut self.tool, lent);
@@ -1319,13 +1290,7 @@ impl Session {
c
}
None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)),
};
if self.precise_cursors() { c.precise() } else { c }
}
/// General › Use Precise Cursors is on, or Caps Lock is.
fn precise_cursors(&self) -> bool {
self.prefs.use_precise_cursors || self.caps_lock
}
}
pub fn tool_options(&self) -> Value {
File diff suppressed because it is too large Load Diff
@@ -1,136 +0,0 @@
//! Prepared, platform-neutral requests. The desktop host alone owns native cursor state.
use super::{Cursor, rasterize};
use egui::{Context, CursorIcon, CustomCursorImage, Id, ViewportId};
use std::sync::Arc;
const CAPACITY: usize = 128;
const MAX_PADDED_SIDE: u16 = 258;
/// Opaque identity: the resolved tool cursor and logical scale, independent of display scale.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Key(Cursor, u32);
/// The same artwork at one and two pixels per logical point, aligned without resampling.
#[derive(Clone, Debug)]
pub struct Bitmap {
/// Straight-alpha RGBA representations; the second size/hotspot is exactly twice the first.
pub representations: [CustomCursorImage; 2],
}
/// One canvas request, valid only for its viewport and pass.
#[derive(Clone, Debug)]
pub struct Request {
/// Identity owned by the UI; the host need not depend on the tools crate.
pub key: Key,
/// Shared prepared pixels, retained independently of cache eviction.
pub bitmap: Arc<Bitmap>,
/// Visible fallback, also used to detect a later UI override.
pub fallback: CursorIcon,
/// Viewport that selected this cursor.
pub viewport: ViewportId,
/// Cumulative pass number when the request was made.
pub pass: u64,
}
#[derive(Clone, Default)]
struct Cache(Vec<(Key, Option<Arc<Bitmap>>)>);
impl Cache {
fn get(&mut self, cursor: Cursor, scale: f32) -> Option<(Key, Arc<Bitmap>)> {
// Bound before tessellation, including malicious/non-finite preference values.
if !scale.is_finite() || !(0.125..=4.0).contains(&scale) {
return None;
}
let key = Key(cursor, scale.to_bits());
if let Some((_, bitmap)) = self.0.iter().find(|(k, _)| *k == key) {
return bitmap.clone().map(|bitmap| (key, bitmap));
}
let bitmap = prepare(cursor, scale).map(Arc::new);
if self.0.len() >= CAPACITY {
self.0.clear();
}
self.0.push((key, bitmap.clone()));
bitmap.map(|bitmap| (key, bitmap))
}
}
fn prepare(cursor: Cursor, scale: f32) -> Option<Bitmap> {
align([rasterize(cursor, scale)?, rasterize(cursor, scale * 2.0)?])
}
fn valid(image: &CustomCursorImage) -> bool {
let [w, h] = image.size;
w > 0 && h > 0 && w <= 256 && h <= 256 && image.hotspot[0] < w && image.hotspot[1] < h && image.rgba.len() == usize::from(w) * usize::from(h) * 4
}
fn align(source: [CustomCursorImage; 2]) -> Option<Bitmap> {
if !source.iter().all(valid) {
return None;
}
let [one, two] = &source;
let mut size = [0; 2];
let mut hotspot = [0; 2];
for axis in 0..2 {
hotspot[axis] = one.hotspot[axis].max(two.hotspot[axis].div_ceil(2));
let after = (one.size[axis] - one.hotspot[axis]).max((two.size[axis] - two.hotspot[axis]).div_ceil(2));
size[axis] = hotspot[axis].checked_add(after)?;
if size[axis].checked_mul(2)? > MAX_PADDED_SIDE {
return None;
}
}
Some(Bitmap { representations: [pad(one, size, hotspot, 1)?, pad(two, size, hotspot, 2)?] })
}
fn pad(source: &CustomCursorImage, size: [u16; 2], hotspot: [u16; 2], factor: u16) -> Option<CustomCursorImage> {
let size = [size[0].checked_mul(factor)?, size[1].checked_mul(factor)?];
let hotspot = [hotspot[0].checked_mul(factor)?, hotspot[1].checked_mul(factor)?];
let x = usize::from(hotspot[0].checked_sub(source.hotspot[0])?);
let y = usize::from(hotspot[1].checked_sub(source.hotspot[1])?);
let stride = usize::from(size[0]) * 4;
let row = usize::from(source.size[0]) * 4;
let mut rgba = vec![0; stride.checked_mul(usize::from(size[1]))?];
for (i, pixels) in source.rgba.chunks_exact(row).enumerate() {
let start = (y + i) * stride + x * 4;
rgba.get_mut(start..start + row)?.copy_from_slice(pixels);
}
Some(CustomCursorImage { rgba: rgba.into(), size, hotspot })
}
fn pending_id(ctx: &Context) -> Id {
Id::unique(("native-canvas-cursor", ctx.viewport_id()))
}
/// Expire the current viewport's request at the start of every host pass.
pub fn clear(ctx: &Context) {
let id = pending_id(ctx);
ctx.data_mut(|data| data.remove::<Request>(id));
}
/// Consume only this viewport's request. The host validates its pass at finalization.
pub fn take(ctx: &Context) -> Option<Request> {
let id = pending_id(ctx);
ctx.data_mut(|data| {
let request = data.get_temp::<Request>(id);
data.remove::<Request>(id);
request
})
}
/// Publish eligible pixels and always return a visible system fallback, even without a host.
pub fn request(ctx: &Context, cursor: Cursor, fallback: CursorIcon, custom: bool, scale: f32) -> CursorIcon {
clear(ctx);
let fallback = if fallback == CursorIcon::None { CursorIcon::Default } else { fallback };
if custom && ctx.input(|i| i.focused && i.pointer.hover_pos().is_some()) {
let prepared = ctx.data_mut(|data| data.get_temp_mut_or_default::<Cache>(Id::unique("native-cursor-bitmaps")).get(cursor, scale));
if let Some((key, bitmap)) = prepared {
let request = Request { key, bitmap, fallback, viewport: ctx.viewport_id(), pass: ctx.cumulative_pass_nr() };
let id = pending_id(ctx);
ctx.data_mut(|data| data.insert_temp(id, request));
}
}
fallback
}
#[cfg(test)]
mod tests;
@@ -1,98 +0,0 @@
use super::*;
#[test]
fn every_glyph_and_rotation_preserves_pixels_and_logical_hotspots() {
let cursors = super::super::GLYPHS.into_iter().chain((0..8).map(Cursor::RotateToward));
for cursor in cursors {
for scale in [0.75, 1.0, 1.25, 1.5, 2.0] {
let bitmap = prepare(cursor, scale).unwrap();
let [one, two] = &bitmap.representations;
assert_eq!(two.size, one.size.map(|x| x * 2));
assert_eq!(two.hotspot, one.hotspot.map(|x| x * 2));
for (i, dest) in bitmap.representations.iter().enumerate() {
let source = rasterize(cursor, scale * (i + 1) as f32).unwrap();
let dx = dest.hotspot[0] - source.hotspot[0];
let dy = dest.hotspot[1] - source.hotspot[1];
for y in 0..dest.size[1] {
for x in 0..dest.size[0] {
let offset = (usize::from(y) * usize::from(dest.size[0]) + usize::from(x)) * 4;
let actual = &dest.rgba[offset..offset + 4];
if x >= dx && x < dx + source.size[0] && y >= dy && y < dy + source.size[1] {
let at = (usize::from(y - dy) * usize::from(source.size[0]) + usize::from(x - dx)) * 4;
assert_eq!(actual, &source.rgba[at..at + 4], "{cursor:?}, {scale}");
} else {
assert_eq!(actual, [0; 4]);
}
}
}
}
}
}
}
#[test]
fn invalid_inputs_and_system_states_are_bounded_and_cached() {
let mut cache = Cache::default();
for scale in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::MAX, 100.0] {
assert!(cache.get(Cursor::Arrow, scale).is_none());
}
for cursor in [Cursor::Busy, Cursor::NotAllowed, Cursor::ScissorsNotAllowed] {
assert!(cache.get(cursor, 1.0).is_none());
assert!(cache.get(cursor, 1.0).is_none());
}
assert_eq!(cache.0.len(), 3);
let good = rasterize(Cursor::Pen, 1.0).unwrap();
for bad in [
CustomCursorImage { rgba: Arc::from([]), ..good.clone() },
CustomCursorImage { size: [u16::MAX, 1], ..good.clone() },
CustomCursorImage { hotspot: good.size, ..good.clone() },
] {
assert!(align([bad, good.clone()]).is_none());
}
let (_, retained) = cache.get(Cursor::Pen, 1.0).unwrap();
assert!(Arc::ptr_eq(&retained, &cache.get(Cursor::Pen, 1.0).unwrap().1));
for i in 0..140 {
cache.get(Cursor::Pen, 1.0 + i as f32 / 1000.0);
}
assert!(cache.0.len() <= CAPACITY);
assert!(valid(&retained.representations[0]));
}
#[test]
fn requests_are_consumed_per_viewport_and_expire_on_empty_passes() {
let ctx = Context::default();
let raw = |id| {
let mut input = egui::RawInput { viewport_id: id, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() };
input.viewports.entry(id).or_default();
input
};
let root = ViewportId::ROOT;
let panel = ViewportId::from_hash_of("panel");
let _ = headless(&ctx, raw(root), |ui| {
request(ui.ctx(), Cursor::Pen, CursorIcon::Crosshair, true, 1.0);
});
let _ = headless(&ctx, raw(panel), |ui| {
clear(ui.ctx());
assert!(take(ui.ctx()).is_none());
});
assert!(ctx.data(|d| d.get_temp::<Request>(Id::unique(("native-canvas-cursor", root)))).is_some());
let _ = headless(&ctx, raw(root), |ui| {
clear(ui.ctx());
assert!(take(ui.ctx()).is_none());
});
let _ = headless(&ctx, raw(root), |ui| {
request(ui.ctx(), Cursor::Pen, CursorIcon::Crosshair, true, 1.25);
let req = take(ui.ctx()).unwrap();
assert_eq!(req.viewport, root);
assert_eq!(req.pass, ui.ctx().cumulative_pass_nr());
assert!(take(ui.ctx()).is_none());
request(ui.ctx(), Cursor::Pen, CursorIcon::Crosshair, false, 1.0);
assert!(take(ui.ctx()).is_none());
});
}
fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput {
let mut output = ctx.run_ui(input, draw);
output.textures_delta.clear();
output
}
+10 -602
View File
@@ -1,614 +1,22 @@
use std::sync::Arc;
use super::*;
use serde_json::json;
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
/// The straight RGBA of pixel (x, y).
fn pixel(img: &CustomCursorImage, x: usize, y: usize) -> [u8; 4] {
let i = (y * img.size[0] as usize + x) * 4;
[img.rgba[i], img.rgba[i + 1], img.rgba[i + 2], img.rgba[i + 3]]
}
/// The Anchor Point caret's hotspot is the middle of its hollow square: white there, with the
/// square's ink a few points above it.
/// A hotspot is data a typo moves off the glyph: every painted tool cursor's lies in its icon's box.
#[test]
fn anchor_point_hotspot_is_inside_its_square() {
for ppp in [1.0f32, 2.0] {
let img = rasterize(Cursor::AnchorPoint, ppp).expect("anchor point has a bitmap");
let [hx, hy] = img.hotspot.map(usize::from);
assert_eq!(pixel(&img, hx, hy), [255, 255, 255, 255], "hollow at the hotspot at {ppp}x");
let reach = (4.0 * ppp).round() as usize;
let inked = (1..=reach.min(hy)).any(|d| {
let p = pixel(&img, hx, hy - d);
p[0] < 64 && p[3] > 200
});
assert!(inked, "ink on the square's top edge within 4 points above the hotspot at {ppp}x");
}
}
/// Direct Selection's anchor square is hollow over an unselected path and filled over a
/// selected one; the arrow stays white. The Reshape Segment and copy arrowheads are black and
/// Group Selection's arrow white, just inside their tips.
#[test]
fn selection_arrows_are_white_or_black() {
let at = |img: &CustomCursorImage, x: f32, y: f32, ppp: f32| {
let [hx, hy] = img.hotspot.map(usize::from);
pixel(img, hx + (x * ppp).round() as usize, hy + (y * ppp).round() as usize)
};
for ppp in [1.0f32, 2.0] {
for c in [Cursor::DirectAnchor, Cursor::DirectAnchorSelected] {
let img = rasterize(c, ppp).expect("a bitmap");
let tip = at(&img, 1.5, 6.0, ppp);
assert!(tip[0] > 192 && tip[3] > 200, "{c:?}'s arrow is white at {ppp}x: {tip:?}");
}
// Same arrow, so the filled square shows as more ink than the hollow one.
let ink = |c| {
let img = rasterize(c, ppp).expect("a bitmap");
img.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 64 && p[3] > 200).count()
};
let (hollow, filled) = (ink(Cursor::DirectAnchor), ink(Cursor::DirectAnchorSelected));
assert!(filled > hollow, "the selected path's square is filled at {ppp}x: {filled} vs {hollow}");
for (c, white) in [(Cursor::ReshapeSegment, false), (Cursor::SelectionCopy, false), (Cursor::GroupSelection, true)] {
let img = rasterize(c, ppp).expect("a bitmap");
let tip = at(&img, 1.5, 6.0, ppp);
assert_eq!(tip[0] > 192, white, "{c:?} at {ppp}x: {tip:?}");
assert!(tip[3] > 200, "{c:?} at {ppp}x: {tip:?}");
}
}
}
#[test]
fn a_cursor_not_drawn_yet_looks_like_the_one_it_borrows() {
fn every_tool_cursors_hotspot_lies_inside_its_icon_box() {
for c in GLYPHS {
let Some(stand_in) = c.stand_in() else { continue };
assert_eq!(rasterize(c, 2.0), rasterize(stand_in, 2.0), "{c:?} borrows {stand_in:?}");
}
}
/// Loaded text after a click on the overflow out port is a text-block glyph, not the I-beam.
#[test]
fn loaded_text_cursor_is_not_the_text_i_beam() {
assert!(Cursor::LoadedText.stand_in().is_none());
let loaded = rasterize(Cursor::LoadedText, 2.0).expect("loaded text bitmap");
let ibeam = rasterize(Cursor::Text, 2.0).expect("text bitmap");
assert_ne!(loaded.rgba, ibeam.rgba);
let [hx, hy] = loaded.hotspot.map(usize::from);
assert!(pixel(&loaded, hx, hy)[3] > 200, "hotspot lies on the drawn frame");
}
/// Loaded text over an object a click threads it into is drawn as its own glyph: the loaded
/// text's block with a link badge below right, so it has more ink than the plain loaded text.
#[test]
fn loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge() {
assert!(Cursor::LoadedTextLink.stand_in().is_none());
for ppp in [1.0f32, 2.0] {
let link = rasterize(Cursor::LoadedTextLink, ppp).expect("link bitmap");
let loaded = rasterize(Cursor::LoadedText, ppp).expect("loaded text bitmap");
assert_ne!(link, loaded, "a glyph of its own at {ppp}x");
let ink = |img: &CustomCursorImage| img.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 64 && p[3] > 200).count();
assert!(ink(&link) > ink(&loaded), "the badge adds ink at {ppp}x");
let [hx, hy] = link.hotspot.map(usize::from);
assert!(pixel(&link, hx, hy)[3] > 200, "hotspot lies on the drawn frame at {ppp}x");
}
}
#[test]
fn every_glyph_becomes_a_bitmap_with_its_hotspot_inside() {
for ppp in [1.0, 1.25, 1.5, 2.0, 3.0] {
for c in GLYPHS {
let img = rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let [w, h] = img.size.map(usize::from);
assert_eq!(img.rgba.len(), w * h * 4, "{c:?}");
assert!(img.hotspot[0] < img.size[0] && img.hotspot[1] < img.size[1], "{c:?} at {ppp}: {img:?}");
assert!(w as f32 <= 50.0 * ppp && h as f32 <= 50.0 * ppp, "{c:?} at {ppp}: {img:?}");
assert!(img.rgba.as_chunks::<4>().0.iter().any(|p| p[3] == 255), "{c:?}: nothing opaque");
}
// #1269: the normal Eyedropper is a pipette, with its tip at the hotspot; only
// Use Precise Cursors turns it into a crosshair.
let dropper = rasterize(Cursor::Eyedropper, ppp).unwrap();
let precise = rasterize(Cursor::Eyedropper.precise(), ppp).unwrap();
assert_ne!(dropper, precise, "Eyedropper must be distinguishable from its precise cursor at {ppp}");
let [hx, hy] = dropper.hotspot.map(usize::from);
let halo = (3.0 * ppp).ceil(); // The bitmap bounds round out to whole physical pixels.
assert!(hx as f32 <= halo && f32::from(dropper.size[1]) - hy as f32 <= halo, "the tip is at the lower-left: {dropper:?}");
assert!(pixel(&dropper, hx, hy)[3] > 0, "the tip covers the hotspot at {ppp}");
}
assert!(rasterize(Cursor::NotAllowed, 1.0).is_none(), "the busy states stay system cursors");
assert!(rasterize(Cursor::Busy, 1.0).is_none());
assert!(rasterize(Cursor::ScissorsNotAllowed, 1.0).is_none(), "until it's drawn it borrows the system not-allowed cursor");
for ppp in [0.0, -1.0, f32::NAN, f32::INFINITY, 1e9] {
assert!(rasterize(Cursor::Arrow, ppp).is_none(), "{ppp}");
}
}
#[test]
fn the_arrow_bitmap_is_black_in_a_white_halo_with_the_tip_on_the_hotspot() {
let img = rasterize(Cursor::Arrow, 1.0).unwrap();
let [hx, hy] = img.hotspot.map(usize::from);
// The tip covers the hotspot's pixel; the body is solid black, the outline's halo white.
assert!(pixel(&img, hx, hy)[3] > 0, "{:?}", pixel(&img, hx, hy));
let body = pixel(&img, hx + 2, hy + 8);
assert!(body[3] == 255 && body[..3].iter().all(|&c| c < 40), "{body:?}");
assert!(img.rgba.as_chunks::<4>().0.iter().any(|p| p[3] == 255 && p[..3].iter().all(|&c| c > 215)), "no white halo");
// Nothing left of or above the tip but the halo.
assert!((0..img.size[1] as usize).all(|y| pixel(&img, 0, y)[..3].iter().all(|&c| c > 100) || pixel(&img, 0, y)[3] < 128));
// At twice the pixels per point, twice the pixels.
let big = rasterize(Cursor::Arrow, 2.0).unwrap();
for i in 0..2 {
let ratio = f32::from(big.size[i]) / f32::from(img.size[i]);
assert!((1.8..=2.2).contains(&ratio), "{:?} vs {:?}", big.size, img.size);
}
let [bx, by] = big.hotspot.map(usize::from);
let body = pixel(&big, bx + 4, by + 16);
assert!(body[3] == 255 && body[..3].iter().all(|&c| c < 40), "{body:?}");
}
/// The pen nib is a fountain pen's lying along the selection arrow's axis: its point on the
/// hotspot, the slit running back along it into the round breather hole, the heel clipped
/// at the back.
#[test]
fn the_pen_nib_has_a_slit_and_a_breather_hole() {
for ppp in [1.0f32, 2.0] {
let img = rasterize(Cursor::PenDrawing, ppp).expect("a bitmap");
let [hx, hy] = img.hotspot.map(usize::from);
let at = |x: f32, y: f32| {
let (px, py) = ((hx as f32 + x * ppp) as usize, (hy as f32 + y * ppp) as usize);
if px < img.size[0] as usize && py < img.size[1] as usize { pixel(&img, px, py) } else { [0; 4] }
};
// The breather hole, ~12 points along the axis ((4.6, 10.9) on screen): fully white.
let hole = at(4.6, 10.9);
assert!(hole[3] > 200 && hole[0] > 192, "the breather hole at {ppp}: {hole:?}");
// The slit on the way to the hole: white over a black field.
let slit = at(2.4, 5.5);
assert!(slit[3] > 40 && slit[0] > 128, "the slit at {ppp}: {slit:?}");
// The body past the hole is solid ink.
let body = at(5.5, 12.9);
assert!(body[3] > 200 && body[0] < 64, "the nib's body at {ppp}: {body:?}");
// The heel's corners carry ink out near the bitmap's edge.
for (x, y) in [(8.8f32, 13.1), (3.3, 15.4)] {
let corner = at(x, y);
assert!(corner[3] > 0, "a heel corner at {ppp} ({x}, {y}): {corner:?}");
if let cb::Cursor::Painted(PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) {
assert!((0.0..=24.0).contains(&hotspot.x) && (0.0..=24.0).contains(&hotspot.y), "{c:?}: {hotspot:?}");
}
}
}
/// The Pen drawing a path is the same nib as the new-path Pen, without the asterisk.
/// A `cursor-` icon name a cursor uses must be in the set the host registers.
#[test]
fn the_drawing_pen_has_no_new_path_asterisk() {
for ppp in [1.0, 2.0] {
let (new, drawing) = (rasterize(Cursor::Pen, ppp).unwrap(), rasterize(Cursor::PenDrawing, ppp).unwrap());
assert_eq!(new.hotspot, drawing.hotspot, "at {ppp}");
// The asterisk's center, 16 × 15 points from the hotspot.
let at = |img: &CustomCursorImage| {
let [hx, hy] = img.hotspot.map(usize::from);
let (x, y) = (hx + (16.0 * ppp) as usize, hy + (15.0 * ppp) as usize);
if x < img.size[0] as usize && y < img.size[1] as usize { pixel(img, x, y)[3] } else { 0 }
};
assert_eq!(at(&new), 255, "the new-path Pen has its asterisk at {ppp}");
assert_eq!(at(&drawing), 0, "the drawing Pen has no badge at {ppp}");
// The nib is the same.
let [hx, hy] = drawing.hotspot.map(usize::from);
let nib = (hx + (8.0 * ppp) as usize, hy + (8.0 * ppp) as usize);
assert_eq!(pixel(&new, nib.0, nib.1), pixel(&drawing, nib.0, nib.1), "at {ppp}");
}
}
/// The Pencil's and the Paintbrush's closing cursors are the crosshair those tools show, with a
/// ring below right.
#[test]
fn the_closing_cursors_are_the_crosshair_with_a_ring() {
for ppp in [1.0, 2.0] {
let cross = rasterize(Cursor::Crosshair, ppp).unwrap();
for c in [Cursor::PencilClose, Cursor::PaintbrushClose] {
let img = rasterize(c, ppp).unwrap();
assert_eq!(img.hotspot, cross.hotspot, "{c:?} at {ppp}");
let [hx, hy] = img.hotspot.map(usize::from);
let at = |img: &CustomCursorImage, dx: f32, dy: f32| {
let (x, y) = ((hx as f32 + dx * ppp) as usize, (hy as f32 + dy * ppp) as usize);
if x < img.size[0] as usize && y < img.size[1] as usize { pixel(img, x, y) } else { [0; 4] }
};
// Black pixels in the square 4 to 12 points right of and below the hotspot, clear of the arms.
let ring_ink = |img: &CustomCursorImage| {
let steps = (8.0 * ppp) as usize;
(0..steps * steps)
.filter(|i| {
let p = at(img, 4.0 + (i % steps) as f32 / ppp, 4.0 + (i / steps) as f32 / ppp);
p[3] > 200 && p[0] < 64
})
.count()
};
assert!(ring_ink(&img) > 0, "{c:?} has its ring at {ppp}");
assert_eq!(ring_ink(&cross), 0, "the crosshair has no ring at {ppp}");
assert_eq!(at(&img, 8.0, 8.0)[3], 0, "{c:?}'s ring is hollow at {ppp}");
// The arms are the crosshair's.
assert_eq!(at(&img, -6.0, 0.0), at(&cross, -6.0, 0.0), "{c:?} at {ppp}");
fn every_cursor_icon_the_app_names_is_in_its_set() {
for c in GLYPHS {
let (cb::Cursor::Painted(PaintedCursor::Tool { icon, .. } | PaintedCursor::PointerTool { icon, .. })) = tool_cursor(c) else { continue };
if icon.name().starts_with("cursor-") {
assert!(CURSOR_ICONS.icons.iter().any(|(name, _)| *name == icon.name()), "{c:?} names {}", icon.name());
}
}
}
/// The Pencil's new-path cursor is the crosshair with a small star below right, where the
/// closing cursor's ring is hollow and the straight-line cursor has a single line.
#[test]
fn the_pencil_new_path_cursor_is_the_crosshair_with_a_star() {
for ppp in [1.0, 2.0] {
let cross = rasterize(Cursor::Crosshair, ppp).unwrap();
let img = rasterize(Cursor::PencilNew, ppp).unwrap();
let ring = rasterize(Cursor::PencilClose, ppp).unwrap();
let straight = rasterize(Cursor::PencilStraight, ppp).unwrap();
assert_eq!(img.hotspot, cross.hotspot, "at {ppp}");
let at = |img: &CustomCursorImage, dx: f32, dy: f32| {
let [hx, hy] = img.hotspot.map(usize::from);
let (x, y) = ((hx as f32 + dx * ppp) as usize, (hy as f32 + dy * ppp) as usize);
if x < img.size[0] as usize && y < img.size[1] as usize { pixel(img, x, y) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
assert!(inked(at(&img, 8.5, 8.5)), "the star's middle at {ppp}");
assert_eq!(at(&ring, 8.5, 8.5)[3], 0, "the closing ring is hollow there at {ppp}");
assert_eq!(at(&cross, 8.5, 8.5)[3], 0, "the crosshair has no badge at {ppp}");
// Three strokes cross at the middle: the diagonal the straight-line cursor lacks, and the
// upright one.
assert!(inked(at(&img, 5.5, 5.5)) && !inked(at(&straight, 5.5, 5.5)), "the second diagonal at {ppp}");
// At 1 point per pixel the upright stroke covers two pixel columns in gray.
let dark = |p: [u8; 4]| p[3] > 200 && p[0] < 128;
let upright = |img: &CustomCursorImage, dy: f32| [7.5, 8.0, 8.5].iter().any(|&dx| dark(at(img, dx, dy)));
assert!(upright(&img, 4.5) && upright(&img, 11.5), "the upright stroke at {ppp}");
assert!(!upright(&straight, 4.5) && !upright(&straight, 11.5), "the straight line has none at {ppp}");
assert_eq!(at(&img, -6.0, 0.0), at(&cross, -6.0, 0.0), "the arms are the crosshair's at {ppp}");
}
}
/// The Pencil's straight-line cursor is the crosshair with a short level line below right,
/// through the point where the closing cursor's ring is hollow.
#[test]
fn the_pencil_straight_line_cursor_is_the_crosshair_with_a_line() {
for ppp in [1.0, 2.0] {
let cross = rasterize(Cursor::Crosshair, ppp).unwrap();
let img = rasterize(Cursor::PencilStraight, ppp).unwrap();
let ring = rasterize(Cursor::PencilClose, ppp).unwrap();
assert_eq!(img.hotspot, cross.hotspot, "at {ppp}");
let at = |img: &CustomCursorImage, dx: f32, dy: f32| {
let [hx, hy] = img.hotspot.map(usize::from);
let (x, y) = ((hx as f32 + dx * ppp) as usize, (hy as f32 + dy * ppp) as usize);
if x < img.size[0] as usize && y < img.size[1] as usize { pixel(img, x, y) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
assert!(inked(at(&img, 8.5, 8.5)), "the line crosses the badge's middle at {ppp}");
assert_eq!(at(&ring, 8.5, 8.5)[3], 0, "the closing ring is hollow there at {ppp}");
assert_eq!(at(&cross, 8.5, 8.5)[3], 0, "the crosshair has no badge at {ppp}");
// Along the line, not across it: no ink off its ends.
assert!(!inked(at(&img, 5.0, 5.0)) && !inked(at(&img, 12.0, 12.0)), "a line, not a cross, at {ppp}");
// Level: inked at both ends of it, and not where the continuation cursor's line rises.
assert!(inked(at(&img, 4.5, 8.5)) && inked(at(&img, 12.5, 8.5)), "a level line at {ppp}");
assert!(!inked(at(&img, 6.0, 11.0)) && !inked(at(&img, 11.0, 6.0)), "not a rising one at {ppp}");
assert_ne!(img, ring, "at {ppp}");
assert_eq!(at(&img, -6.0, 0.0), at(&cross, -6.0, 0.0), "the arms are the crosshair's at {ppp}");
}
}
/// The Pencil's continuation cursor is the crosshair with a short line rising to the right below
/// right, where the straight-line cursor's line is level.
#[test]
fn the_pencil_continuation_cursor_is_the_crosshair_with_a_rising_line() {
for ppp in [1.0, 2.0] {
let cross = rasterize(Cursor::Crosshair, ppp).unwrap();
let img = rasterize(Cursor::PencilContinue, ppp).unwrap();
let straight = rasterize(Cursor::PencilStraight, ppp).unwrap();
assert_eq!(img.hotspot, cross.hotspot, "at {ppp}");
let at = |img: &CustomCursorImage, dx: f32, dy: f32| {
let [hx, hy] = img.hotspot.map(usize::from);
let (x, y) = ((hx as f32 + dx * ppp) as usize, (hy as f32 + dy * ppp) as usize);
if x < img.size[0] as usize && y < img.size[1] as usize { pixel(img, x, y) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
assert!(inked(at(&img, 8.5, 8.5)), "the line crosses the badge's middle at {ppp}");
assert!(inked(at(&img, 5.0, 11.0)) && inked(at(&img, 10.0, 6.0)), "the line rises to the right at {ppp}");
assert!(!inked(at(&straight, 6.0, 11.0)), "the straight-line cursor's line is level at {ppp}");
assert!(!inked(at(&img, 4.5, 8.5)) && !inked(at(&img, 12.5, 8.5)), "not a level one at {ppp}");
assert!(!inked(at(&img, 3.5, 13.5)), "no end point square at {ppp}");
assert!(!inked(at(&img, 12.0, 12.0)), "a line, not a cross, at {ppp}");
assert_eq!(at(&img, -6.0, 0.0), at(&cross, -6.0, 0.0), "the arms are the crosshair's at {ppp}");
}
}
/// The Live Paint Bucket's cursors are drawn, not the crosshair: an empty bucket where a click
/// paints nothing, a filled bucket with a larger drop on the hotspot where it fills a face, and a
/// brush with its tip on the hotspot where it paints an edge.
#[test]
fn the_live_paint_bucket_shows_a_bucket_or_a_brush() {
for ppp in [1.0f32, 2.0] {
let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let (cross, empty, filled, brush) =
(img(Cursor::Crosshair), img(Cursor::LivePaintBucket), img(Cursor::LivePaintBucketFace), img(Cursor::LivePaintBucketEdge));
// The pixel nearest the point `u` points up-right of the hotspot and `v` down-right across.
let at = |img: &CustomCursorImage, u: f32, v: f32| {
let s = std::f32::consts::FRAC_1_SQRT_2;
let [hx, hy] = img.hotspot.map(f32::from);
let (x, y) = ((hx + (u + v) * s * ppp - 0.5).round(), (hy + (v - u) * s * ppp - 0.5).round());
let inside = x >= 0.0 && y >= 0.0 && x < f32::from(img.size[0]) && y < f32::from(img.size[1]);
if inside { pixel(img, x as usize, y as usize) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
let white = |p: [u8; 4]| p[3] > 200 && p[0] > 192;
assert!(white(at(&empty, 11.0, 2.0)), "the empty bucket's body is white at {ppp}");
assert!(inked(at(&filled, 11.0, 2.0)), "the filled bucket's body is ink at {ppp}");
assert!(at(&empty, 0.0, 0.0)[3] > 0 && inked(at(&filled, 0.0, 0.0)), "a drop on the hotspot at {ppp}");
if ppp == 2.0 {
assert!(inked(at(&filled, 1.4, 0.0)) && !inked(at(&empty, 2.0, 0.0)), "the filled bucket's drop is larger");
}
assert!(inked(at(&brush, 3.0, 0.0)), "the bristles by the hotspot at {ppp}");
assert!(white(at(&brush, 7.5, 0.0)), "the white ferrule at {ppp}");
assert!(inked(at(&brush, 14.0, 0.0)), "the handle at {ppp}");
assert!(!inked(at(&brush, 11.0, 4.0)), "the brush is thin where the bucket is wide at {ppp}");
assert!(white(at(&empty, 14.0, 0.0)), "the empty bucket has no handle there at {ppp}");
for (c, i) in [(Cursor::LivePaintBucket, &empty), (Cursor::LivePaintBucketFace, &filled), (Cursor::LivePaintBucketEdge, &brush)] {
assert!(c.stand_in().is_none(), "{c:?} is drawn");
assert_ne!(i, &cross, "{c:?} is not the crosshair at {ppp}");
assert_eq!(rasterize(c.precise(), ppp).as_ref(), Some(&cross), "{c:?} with Use Precise Cursors at {ppp}");
}
assert!(empty != filled && filled != brush && empty != brush, "three looks at {ppp}");
}
}
/// The Knife's cursor, which the Trim at Crossings Tool shows too, is drawn, not the crosshair: a
/// knife with the blade's point on the hotspot, the white blade, then the black handle up-right.
#[test]
fn the_knife_shows_a_knife_with_its_point_on_the_hotspot() {
for ppp in [1.0f32, 2.0] {
let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let (cross, knife, brush) = (img(Cursor::Crosshair), img(Cursor::Knife), img(Cursor::LivePaintBucketEdge));
// The pixel nearest the point `u` points up-right of the hotspot and `v` down-right across.
let at = |img: &CustomCursorImage, u: f32, v: f32| {
let s = std::f32::consts::FRAC_1_SQRT_2;
let [hx, hy] = img.hotspot.map(f32::from);
let (x, y) = ((hx + (u + v) * s * ppp - 0.5).round(), (hy + (v - u) * s * ppp - 0.5).round());
let inside = x >= 0.0 && y >= 0.0 && x < f32::from(img.size[0]) && y < f32::from(img.size[1]);
if inside { pixel(img, x as usize, y as usize) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
let white = |p: [u8; 4]| p[3] > 200 && p[0] > 192;
assert!(at(&knife, 0.0, 0.0)[3] > 0, "the point covers the hotspot at {ppp}");
assert!(white(at(&knife, 8.0, 0.5)), "the white blade at {ppp}");
assert!(inked(at(&knife, 16.0, 0.2)), "the black handle at {ppp}");
assert!(!inked(at(&knife, -4.0, 0.0)), "nothing beyond the point at {ppp}");
assert!(Cursor::Knife.stand_in().is_none(), "the Knife is drawn");
assert_ne!(knife, cross, "the Knife is not the crosshair at {ppp}");
assert_ne!(knife, brush, "the Knife is not the Live Paint brush at {ppp}");
assert_eq!(rasterize(Cursor::Knife.precise(), ppp).as_ref(), Some(&cross), "with Use Precise Cursors at {ppp}");
}
}
/// Live Paint Selection's cursors are the solid arrow, its tip on the hotspot, with a badge at its
/// lower right: a filled square over a face, a line between two anchor marks over an edge, and an x
/// where a click selects nothing.
#[test]
fn live_paint_selection_shows_the_arrow_with_a_face_edge_or_x_badge() {
for ppp in [2.0f32, 3.0] {
let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let (arrow, cross) = (img(Cursor::Arrow), img(Cursor::Crosshair));
let (face, edge, out) = (img(Cursor::LivePaintSelectFace), img(Cursor::LivePaintSelectEdge), img(Cursor::LivePaintSelectOutside));
// The pixel at (dx, dy) points from the hotspot.
let at = |img: &CustomCursorImage, dx: f32, dy: f32| {
let [hx, hy] = img.hotspot.map(usize::from);
let (x, y) = ((hx as f32 + dx * ppp) as usize, (hy as f32 + dy * ppp) as usize);
if x < img.size[0] as usize && y < img.size[1] as usize { pixel(img, x, y) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
// Inside the square, away from the x's strokes and the edge's line.
let square = (15.0, 14.0);
// The edge's upper anchor mark, beyond the square and the x.
let mark = (19.0, 13.0);
// On the x's stroke from top left to bottom right, away from the edge's line.
let x_stroke = (13.0, 14.0);
for (c, i, want) in [
(Cursor::LivePaintSelectFace, &face, [true, false, true]),
(Cursor::LivePaintSelectEdge, &edge, [false, true, false]),
(Cursor::LivePaintSelectOutside, &out, [false, false, true]),
] {
assert_eq!(i.hotspot, arrow.hotspot, "{c:?} has the arrow's hotspot at {ppp}");
assert!(inked(at(i, 1.5, 6.0)), "{c:?} is the solid arrow at {ppp}");
let got = [square, mark, x_stroke].map(|(x, y)| inked(at(i, x, y)));
assert_eq!(got, want, "{c:?} at {ppp}");
assert!(c.stand_in().is_none(), "{c:?} is drawn");
assert_ne!(i, &arrow, "{c:?} is not the plain arrow at {ppp}");
assert_eq!(rasterize(c.precise(), ppp).as_ref(), Some(&cross), "{c:?} with Use Precise Cursors at {ppp}");
}
assert!(face != edge && edge != out && face != out, "three looks at {ppp}");
}
}
#[test]
fn each_bitmap_is_made_once_so_the_os_cursor_is_kept() {
let mut images = Images::default();
let a = images.get(Cursor::Pen, 1.5).unwrap();
let b = images.get(Cursor::Pen, 1.5).unwrap();
assert!(Arc::ptr_eq(&a.rgba, &b.rgba));
assert!(!Arc::ptr_eq(&a.rgba, &images.get(Cursor::Pen, 2.0).unwrap().rgba));
assert!(images.get(Cursor::NotAllowed, 1.5).is_none());
assert!(images.get(Cursor::Arrow, f32::NAN).is_none());
assert_eq!(images.0.len(), 2);
}
/// One headless 800×600 frame of the whole window, a tenth of a second after the last.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::FullOutput {
let time = Some(ctx.input(|i| i.time) + 0.1);
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), time, events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
});
out.textures_delta.clear();
out
}
/// One [`frame`] with `focused` set: true for a window that has the focus, false while another app
/// or a sheet has it.
fn focus_frame(app: &mut VectorcraftApp, ctx: &egui::Context, focused: bool, events: Vec<egui::Event>) -> egui::FullOutput {
let time = Some(ctx.input(|i| i.time) + 0.1);
let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)));
let raw = egui::RawInput { screen_rect, time, focused, events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
});
out.textures_delta.clear();
out
}
#[test]
fn the_canvas_hands_the_tool_cursor_to_the_os_and_idles_while_the_pointer_rests() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
// Every frame renders on this thread, however long it takes: a frame finished by the render
// worker during the idle frames asks for a repaint.
app.canvas.worker_started = true;
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
let canvas = app.canvas_rect.unwrap();
let over = canvas.center();
let out = frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]);
if OS_CURSORS {
let img = out.platform_output.cursor_image.as_ref().expect("the Selection tool's arrow as an OS cursor");
assert_eq!(img, &app.canvas.cursors.get(Cursor::Arrow, 1.0).unwrap());
// Where the OS can't show the bitmap, its system cursor.
assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::Default);
} else if cfg!(target_os = "macos") {
assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::Default);
assert!(out.platform_output.cursor_image.is_none());
} else {
assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::None);
}
// The same bitmap while the pointer moves (the OS keeps its cursor), and an idle window
// once it rests: no frame is asked for.
let next = frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over + vec2(5.0, 3.0))]);
if OS_CURSORS {
assert!(Arc::ptr_eq(&next.platform_output.cursor_image.unwrap().rgba, &out.platform_output.cursor_image.unwrap().rgba));
}
let mut idle = frame(&mut app, &ctx, vec![]);
for _ in 0..3 {
idle = frame(&mut app, &ctx, vec![]);
}
let delay = idle.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.repaint_delay).unwrap();
assert!(delay > std::time::Duration::from_millis(100), "{delay:?} {:?}", ctx.repaint_causes());
// Off the canvas, the panels' cursors.
let off = frame(&mut app, &ctx, vec![egui::Event::PointerMoved(Pos2::new(canvas.left() - 20.0, canvas.center().y))]);
assert!(off.platform_output.cursor_image.is_none());
}
/// On Wayland the glyph is painted and the pointer hidden over the canvas, on every build (#1645).
#[test]
fn a_wayland_window_paints_the_tool_cursor() {
let mut app = VectorcraftApp::new(Session::new(), crate::Services { wayland: true, ..Default::default() });
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
let over = app.canvas_rect.unwrap().center();
let out = frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]);
assert!(out.platform_output.cursor_image.is_none());
assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::None);
}
/// Without a cursor theme the canvas keeps the system pointer visible (#2450).
#[test]
fn no_cursor_theme_keeps_the_system_pointer() {
let mut app = VectorcraftApp::new(Session::new(), crate::Services { wayland: true, no_cursor_theme: true, ..Default::default() });
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
let over = app.canvas_rect.unwrap().center();
let out = frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]);
assert_ne!(out.platform_output.cursor_icon, egui::CursorIcon::None);
}
/// On macOS a window without the focus shows the system pointer over the canvas, and the glyph
/// is not painted next to it (#2020). With the focus back, the canvas sets `CursorIcon::None` again
/// on the next frame, without a pointer move.
#[test]
fn a_window_without_the_focus_shows_the_system_cursor_alone_on_macos() {
// Wayland: every desktop build paints the glyphs.
let mut app = VectorcraftApp::new(Session::new(), crate::Services { wayland: true, ..Default::default() });
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("tool.select", json!({"tool": "rectangle"})).unwrap();
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
let over = app.canvas_rect.unwrap().center();
let key = focus_frame(&mut app, &ctx, true, vec![egui::Event::PointerMoved(over)]);
assert_eq!(key.platform_output.cursor_icon, egui::CursorIcon::None, "with the focus: the glyph alone");
let away = focus_frame(&mut app, &ctx, false, vec![egui::Event::WindowFocused(false), egui::Event::PointerMoved(over + vec2(5.0, 3.0))]);
if HIDES_ONLY_WHEN_KEY {
assert_eq!(away.platform_output.cursor_icon, egui::CursorIcon::Crosshair, "macOS without the focus: the system pointer alone");
} else {
assert_eq!(away.platform_output.cursor_icon, egui::CursorIcon::None, "other platforms: the glyph without the focus too");
}
let back = focus_frame(&mut app, &ctx, true, vec![egui::Event::WindowFocused(true)]);
assert_eq!(back.platform_output.cursor_icon, egui::CursorIcon::None, "the focus back: the glyph alone");
}
/// User Interface › Scale Cursor Proportional to UI (#394): off, the tool cursors keep their
/// size whatever the UI Scaling; on, they grow with it.
#[test]
fn tool_cursors_scale_with_the_ui_only_when_asked() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("prefs.set", json!({"key": "uiScaling", "value": 2.0})).unwrap();
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
assert_eq!(ctx.zoom_factor(), 2.0);
let over = app.canvas_rect.unwrap().center();
let shown =
|app: &mut VectorcraftApp, d: f32| frame(app, &ctx, vec![egui::Event::PointerMoved(over + vec2(d, 0.0))]).platform_output.cursor_image;
if OS_CURSORS {
assert_eq!(shown(&mut app, 0.0).unwrap(), app.canvas.cursors.get(Cursor::Arrow, 1.0).unwrap(), "off: its own size");
app.run("prefs.set", json!({"key": "scaleCursorWithUi", "value": true})).unwrap();
assert_eq!(shown(&mut app, 4.0).unwrap(), app.canvas.cursors.get(Cursor::Arrow, 2.0).unwrap(), "on: twice as big");
}
// Painted into the window (macOS, the web), the glyph is drawn at the scale asked for, its
// hotspot where the pointer is.
let painted = |scale: f32| {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("probe"));
assert!(paint(&ui.ctx().layer_painter(layer), Cursor::Arrow, pos2(100.0, 100.0), scale));
});
out.textures_delta.clear();
out.textures_delta.clear();
out.shapes.iter().fold(egui::Rect::NOTHING, |r, c| r.union(c.shape.visual_bounding_rect()))
};
let (full, half) = (painted(1.0), painted(0.5));
assert!((half.height() * 2.0 - full.height()).abs() < 1.5 && full.height() > 15.0, "{full:?} {half:?}");
assert!(full.contains(pos2(100.0, 100.0)) && half.contains(pos2(100.0, 100.0)), "{full:?} {half:?}");
}
#[test]
fn wayland_windows_paint_the_glyphs() {
assert!(os_cursors(true, false), "Windows, X11");
assert!(!os_cursors(true, true), "Wayland: the compositor would size the bitmap (#1645)");
assert!(!os_cursors(false, false) && !os_cursors(false, true), "macOS, the web");
}
#[test]
fn macos_windows_paint_the_glyphs_only_with_the_focus() {
assert!(paint_glyphs(true, true, false), "macOS with the focus");
assert!(!paint_glyphs(true, false, false), "macOS without the focus: the system pointer shows (#2020)");
assert!(paint_glyphs(false, true, false) && paint_glyphs(false, false, false), "Wayland, the web: painted with the focus or without");
assert!(!paint_glyphs(false, true, true), "without a cursor theme, use the system pointer alone");
}
#[test]
fn arrow_hotspot_is_tip() {
let pts = arrow_points(pos2(10.0, 20.0));
assert_eq!(pts[0], pos2(10.0, 20.0));
assert!(pts.iter().all(|q| q.x >= 10.0 && q.y >= 20.0));
}
+10 -1
View File
@@ -1,6 +1,9 @@
//! Generated icon table (`assets/icons`). Lucide icons are ISC-licensed; `dc-*` icons are VectorCraft's own.
//! Regenerate when icons are added: see crates/ui-egui/README.md.
/// The Selection and Direct Selection arrows' fill, painted black or white under their outline.
pub const DC_ARROW_FILL: &[u8] = include_bytes!("../../../assets/icons/dc-arrow-fill.svg");
pub static ICONS: &[(&str, &[u8])] = &[
("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")),
("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")),
@@ -25,6 +28,8 @@ pub static ICONS: &[(&str, &[u8])] = &[
("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")),
("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")),
("circle", include_bytes!("../../../assets/icons/circle.svg")),
// PLAN: circle-off.svg is plugins-w11's file; the row waits for it.
("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")),
("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")),
("cloud", include_bytes!("../../../assets/icons/cloud.svg")),
("combine", include_bytes!("../../../assets/icons/combine.svg")),
@@ -53,6 +58,9 @@ pub static ICONS: &[(&str, &[u8])] = &[
("dc-artboard-options", include_bytes!("../../../assets/icons/dc-artboard-options.svg")),
("dc-artboards", include_bytes!("../../../assets/icons/dc-artboards.svg")),
("dc-blend", include_bytes!("../../../assets/icons/dc-blend.svg")),
// PLAN: the two blend-align files are object-panels-w4's; the rows wait for them.
("dc-blend-align-page", include_bytes!("../../../assets/icons/dc-blend-align-page.svg")),
("dc-blend-align-path", include_bytes!("../../../assets/icons/dc-blend-align-path.svg")),
("dc-bloat", include_bytes!("../../../assets/icons/dc-bloat.svg")),
("dc-cap-butt", include_bytes!("../../../assets/icons/dc-cap-butt.svg")),
("dc-cap-round", include_bytes!("../../../assets/icons/dc-cap-round.svg")),
@@ -72,7 +80,7 @@ pub static ICONS: &[(&str, &[u8])] = &[
("dc-dir-off", include_bytes!("../../../assets/icons/dc-dir-off.svg")),
("dc-dir-on", include_bytes!("../../../assets/icons/dc-dir-on.svg")),
("dc-direct", include_bytes!("../../../assets/icons/dc-direct.svg")),
("dc-arrow-fill", include_bytes!("../../../assets/icons/dc-arrow-fill.svg")),
("dc-dist-bottom", include_bytes!("../../../assets/icons/dc-dist-bottom.svg")),
("dc-dist-hcenter", include_bytes!("../../../assets/icons/dc-dist-hcenter.svg")),
("dc-dist-hspace", include_bytes!("../../../assets/icons/dc-dist-hspace.svg")),
@@ -90,6 +98,7 @@ pub static ICONS: &[(&str, &[u8])] = &[
("dc-filter", include_bytes!("../../../assets/icons/dc-filter.svg")),
("dc-flare", include_bytes!("../../../assets/icons/dc-flare.svg")),
("dc-folder", include_bytes!("../../../assets/icons/dc-folder.svg")),
("dc-free-distort", include_bytes!("../../../assets/icons/dc-free-distort.svg")),
("dc-free-transform", include_bytes!("../../../assets/icons/dc-free-transform.svg")),
("dc-fx", include_bytes!("../../../assets/icons/dc-fx.svg")),
("dc-gamut", include_bytes!("../../../assets/icons/dc-gamut.svg")),