diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 06be570630..47813f192e 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services { open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), + // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens + // only while the active tool uses the wheel. + #[cfg(all(windows, not(target_vendor = "win7")))] + stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)), ..Default::default() } } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 7c23fe71ba..db055d3246 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -74,6 +74,7 @@ mod windows_cores; mod windows_display_size; mod windows_stylus; mod windows_symbol_chars; +mod windows_wintab; mod xwayland; use std::sync::{Arc, Mutex}; diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 745a5046f5..b8e6b88ee1 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -1,7 +1,8 @@ //! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its //! barrel button and which end of the pen is down. For each pointer message of a pen, //! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its -//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]): +//! pressure, end, tilt and rotation, and an airbrush pen's finger wheel, into the framework's +//! [`PenSource`] ([`start`]): //! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is //! pressed") is the eraser end //! (). Pointer @@ -24,9 +25,12 @@ //! `rotation` in degrees 0..359 clockwise //! (). //! Toward the user is down the screen, so they are the sample's axes and direction as they come, -//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel. +//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which +//! comes from the tablet driver's Wintab interface instead, when it has one +//! ([`crate::windows_wintab`]). #![cfg_attr(not(windows), allow(dead_code))] +use std::cell::Cell; use std::sync::OnceLock; use craft::behavior::PointerSample; @@ -38,6 +42,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020; /// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left /// detection range. const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002; +/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled. +const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000; /// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`. const PEN_FLAG_INVERTED: u32 = 0x0002; const PEN_FLAG_ERASER: u32 = 0x0004; @@ -65,6 +71,13 @@ const WM_POINTERLEAVE: u32 = 0x024A; /// A pen's tilt along x and y and its barrel rotation, in radians. type Pose = ([f32; 2], f32); +thread_local! { + /// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that + /// took them, or the pen whose message last asked for the wheel when none has + /// ([`crate::windows_wintab::wheel_pen`]). + static WHEEL_PEN: Cell> = const { Cell::new(None) }; +} + /// The pen source [`msg_hook`] writes, once [`start`] has made it. static FEED: OnceLock = OnceLock::new(); @@ -89,14 +102,22 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let Some(pen) = FEED.get() else { return false; }; + crate::windows_wintab::msg_hook(msg); + if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) { + crate::windows_wintab::forget(); + } let read_pen = || { let mut info = POINTER_PEN_INFO::default(); + let id = (msg.wParam.0 & 0xffff) as u32; // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. - unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; + unsafe { GetPointerPenInfo(id, &mut info) }.ok()?; let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; + let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; + let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser); + WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id))); let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); - Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) + Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel)) }; // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); @@ -111,8 +132,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { /// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags` /// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen /// in contact that reports none; the eraser end while it is inverted or its eraser button is -/// pressed; and how it is held, `pose` ([`pen_pose`]). -fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample { +/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet +/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept +/// within 0..1 and none when it is not a number. +fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option) -> PointerSample { let pressure = match pressure { 1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0, _ if in_contact => 1.0, @@ -122,6 +145,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (t sample.tilt = tilt; sample.rotation = rotation; sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; + sample.wheel = wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0)); sample } @@ -134,6 +158,43 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose { ([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn) } +/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message +/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the +/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another +/// pen leaving keeps the readings. +fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + if pen != Some((wparam & 0xffff) as u32) { + return false; + } + let flags = wparam >> 16; + match message { + WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => { + flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0 + } + WM_POINTERLEAVE => true, + _ => false, + } +} + +/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook +/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and +/// `WM_POINTERLEAVE` are sent +/// (); the posted pointer +/// messages are left to [`msg_hook`]. +fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen) +} + +/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on +/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as +/// [`msg_hook`] does for the messages it sees. +#[cfg(windows)] +pub fn sent_message(message: u32, wparam: usize) { + if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) { + crate::windows_wintab::forget(); + } +} + /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, /// not from a pen or a touch. fn is_mouse(extra_info: u32) -> bool { @@ -175,7 +236,7 @@ mod tests { #[test] fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() { - let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser; + let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT, None).eraser; assert!(!eraser(0), "the tip"); assert!(!eraser(PEN_FLAG_BARREL), "the barrel button"); assert!(eraser(PEN_FLAG_INVERTED), "turned over"); @@ -194,19 +255,77 @@ mod tests { assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel"); assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges"); let pose = pen_pose(all, 10, 20, 180); - let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose); + let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, None); assert_eq!((sample.tilt, sample.rotation), pose); } + #[test] + fn an_airbrush_wheel_goes_into_the_sample() { + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, Some(0.25)).wheel, Some(0.25)); + let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; + let pose = pen_pose(all, 10, 20, 180); + let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, Some(0.75)); + assert_eq!((sample.tilt, sample.rotation, sample.wheel), (pose.0, pose.1, Some(0.75)), "with the tilt and rotation"); + assert_eq!(sample.pressure, 0.5, "the pressure as before"); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).wheel, None, "no wheel"); + assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(f32::NAN)).wheel, None, "not a number"); + assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(1.5)).wheel, Some(1.0), "kept within 0..1"); + } + + #[test] + fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7; + let pen = Some(7); + for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!forgets_wheel(m, in_range, pen), "{m:#x}"); + assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}"); + assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}"); + } + assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen)); + // WM_MOUSEMOVE and WT_PACKET. + assert!(!forgets_wheel(0x0200, 0, Some(0))); + assert!(!forgets_wheel(0x7FF0, 7, pen)); + } + + #[test] + fn another_pointer_leaving_keeps_the_wheel() { + // A touch, pointer 9, leaves the window and detection range while pen 7 hovers. + let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9; + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7))); + assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range"); + let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9; + assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled"); + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel"); + assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself"); + } + + #[test] + fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let pen = Some(7); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window"); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel"); + assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window"); + // Posted messages, which the message hook already sees. + for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}"); + } + // WT_CTXCLOSE. + assert!(!sent_forgets_wheel(0x7FF2, 7, pen)); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { - assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5); - assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0); - assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering"); - assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); - assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one"); - assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0"); - assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5); + assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering"); + assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); + assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one"); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0"); + assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0); } #[test] diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs new file mode 100644 index 0000000000..31da32a1ff --- /dev/null +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -0,0 +1,1595 @@ +//! Windows: an airbrush pen's finger wheel. `POINTER_PEN_INFO` has no field for it +//! (), so +//! [`crate::windows_stylus`] keeps reading the pressure, end, tilt and rotation from pointer +//! messages, and this module reads only the wheel from the tablet driver's Wintab interface, as +//! its tangential pressure (`pkTangentPressure`), when the driver installs one. The Wintab +//! reference describes the context, packet and message calls used here +//! (), and the +//! Windows Ink comparison says the wheel comes only through Wintab +//! (). +//! +//! - Nothing here runs until the active tool draws with a brush or tip that varies with the +//! finger wheel (Stylus Wheel), as the app says through [`set_wheel_used`]: until then pen +//! messages load no library, install no hook and open no context, and when the tool stops +//! using the wheel the context closes ([`unused_context`]). +//! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen +//! comes over a window while the wheel is used. Without it, without one of its exports, or when +//! a call fails, the pens read no wheel and draw as before; the user sees no error. +//! - The context is opened from the driver's default context for the window that owns the pen's +//! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor +//! and makes no press. When the pen comes over another top-level window, such as a separate +//! document window, the context closes and opens again for that window, and the readings start +//! afresh ([`next_context`]). Each `WT_PACKET` for that window and context is read with `WTPacket` into +//! a buffer larger than any packet, and decoded from the fields the context asked for +//! ([`decode`]). +//! - Only a cursor the driver reports as an airbrush (`(CSR_TYPE & 0x0F06) == 0x0902`, from the +//! Wintab basics page: ) +//! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, +//! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 +//! ([`Axis::wheel`]); a value outside it reads as none. +//! - A pointer message of a pen takes the wheel of the airbrush whose latest packet came within +//! [`MAX_SKEW_MS`] of the message, and none when two are that recent or none is +//! ([`Readings::wheel_for`]). The first pen to read a wheel that way after the readings start +//! afresh takes the readings: other pens read none until they start afresh, and that pen keeps +//! reading the one airbrush read, however long ago its last packet came, since a pen held still +//! sends none. As on +//! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the +//! readings start afresh when a cursor +//! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns +//! to its other end, a press of the pen is canceled, the pen leaves the window or detection +//! range, or the context closes. These rules are VectorCraft's own. +//! +//! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's +//! information changes (`WT_INFOCHANGE`) unless the driver closed it too, and dropped when its +//! window no longer exists; a later pen message opens it again. The driver sends those two notices +//! to the window procedure, where a sent message does not pass winit's message hook, so the +//! context's window gets a window procedure in front of its own that notes them ([`Notices`]). +//! When that procedure cannot be put in front, no context is opened for the window +//! ([`hooked_open`]). An open that leaves no context is tried again for the same window by a pen +//! message [`RETRY_MS`] or more later ([`next_context`]). A hook on the messages Windows sends to +//! the thread's windows passes a pen's `WM_POINTERLEAVE` to [`crate::windows_stylus`], and closes +//! the context when another app becomes the active one (`WM_ACTIVATEAPP`). No pen message opens a +//! context while this app is not active, so the context does not sit in front of another app's in +//! the driver's overlap order. A packet that `WTPacket` cannot read starts the readings afresh +//! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed +//! (`TPS_QUEUE_ERR`, [`Readings::packet`]). +#![cfg_attr(not(windows), allow(dead_code))] + +/// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. +const WT_DEFBASE: u32 = 0x7FF0; +/// `WT_PACKET`, `WT_CTXCLOSE`, `WT_PROXIMITY`, `WT_INFOCHANGE` and `WT_CSRCHANGE` at that base. +const WT_PACKET: u32 = WT_DEFBASE; +const WT_CTXCLOSE: u32 = WT_DEFBASE + 2; +const WT_PROXIMITY: u32 = WT_DEFBASE + 5; +const WT_INFOCHANGE: u32 = WT_DEFBASE + 6; +const WT_CSRCHANGE: u32 = WT_DEFBASE + 7; + +/// `CXO_SYSTEM`, `CXO_PEN`, `CXO_MESSAGES` and `CXO_CSRMESSAGES` (`wintab.h`), in `lcOptions`. +const CXO_SYSTEM: u32 = 0x0001; +const CXO_PEN: u32 = 0x0002; +const CXO_MESSAGES: u32 = 0x0004; +const CXO_CSRMESSAGES: u32 = 0x0008; + +/// The packet fields (`PK_*`, `pktdef.h`) in the order a packet holds them, each with its size in +/// bytes: `pkContext` is a handle, `pkOrientation` and `pkRotation` three 32-bit values each, and +/// the others one 32-bit value. +const PK_CONTEXT: u32 = 0x0001; +const PK_STATUS: u32 = 0x0002; +const PK_TIME: u32 = 0x0004; +const PK_CHANGED: u32 = 0x0008; +const PK_SERIAL_NUMBER: u32 = 0x0010; +const PK_CURSOR: u32 = 0x0020; +const PK_BUTTONS: u32 = 0x0040; +const PK_X: u32 = 0x0080; +const PK_Y: u32 = 0x0100; +const PK_Z: u32 = 0x0200; +const PK_NORMAL_PRESSURE: u32 = 0x0400; +const PK_TANGENT_PRESSURE: u32 = 0x0800; +const PK_ORIENTATION: u32 = 0x1000; +const PK_ROTATION: u32 = 0x2000; +const FIELDS: [(u32, usize); 14] = [ + (PK_CONTEXT, std::mem::size_of::()), + (PK_STATUS, 4), + (PK_TIME, 4), + (PK_CHANGED, 4), + (PK_SERIAL_NUMBER, 4), + (PK_CURSOR, 4), + (PK_BUTTONS, 4), + (PK_X, 4), + (PK_Y, 4), + (PK_Z, 4), + (PK_NORMAL_PRESSURE, 4), + (PK_TANGENT_PRESSURE, 4), + (PK_ORIENTATION, 12), + (PK_ROTATION, 12), +]; + +/// The fields the context asks for (`lcPktData`), all absolute: the status, the cursor, the +/// position and the tangential pressure. +const PACKET_DATA: u32 = PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The changes that make a packet (`lcMoveMask`): a move, or a turn of the wheel in place. +const MOVE_MASK: u32 = PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The bytes `WTPacket` writes into: more than a packet of every field. +const PACKET_BUFFER: usize = 256; + +/// `TPS_PROXIMITY` and `TPS_QUEUE_ERR` (`wintab.h`), in `pkStatus`: the cursor is out of the +/// context, and the queue overflowed. +const TPS_PROXIMITY: u32 = 0x0001; +const TPS_QUEUE_ERR: u32 = 0x0002; + +/// The `LOGCONTEXTW` (`wintab.h`) as 32-bit words: a 40-character name, then `lcOptions`, +/// `lcStatus`, `lcLocks`, `lcMsgBase`, `lcDevice`, `lcPktRate`, `lcPktData`, `lcPktMode`, +/// `lcMoveMask`, `lcBtnDnMask` and `lcBtnUpMask`, and 22 words of extents and sensitivities. +const LOGCONTEXT_WORDS: usize = 53; +const _: () = assert!(LOGCONTEXT_WORDS * 4 == 212, "sizeof(LOGCONTEXTW)"); +const LC_OPTIONS: usize = 20; +const LC_MSG_BASE: usize = 23; +const LC_PKT_DATA: usize = 26; +const LC_PKT_MODE: usize = 27; +const LC_MOVE_MASK: usize = 28; +const LC_BTN_DN_MASK: usize = 29; +const LC_BTN_UP_MASK: usize = 30; + +/// `WTInfoW` categories and indexes (`wintab.h`): the interface's device count, the default +/// context, a device's first cursor, cursor count and tangential-pressure range, and a cursor's +/// packet fields and type. +const WTI_INTERFACE: u32 = 1; +const IFC_NDEVICES: u32 = 4; +const WTI_DEFCONTEXT: u32 = 3; +const WTI_DEVICES: u32 = 100; +const DVC_NCSRTYPES: u32 = 3; +const DVC_FIRSTCSR: u32 = 4; +const DVC_TPRESSURE: u32 = 16; +const WTI_CURSORS: u32 = 200; +const CSR_PKTDATA: u32 = 3; +const CSR_TYPE: u32 = 20; +/// Cursor and device numbers stay below the next category's base. +const MAX_INDEX: u32 = 100; +/// At most this many devices are looked through for a cursor's device. +const MAX_DEVICES: u32 = 16; + +/// A packet and a pointer message at most this far apart, in the message clock's milliseconds, +/// belong together. +const MAX_SKEW_MS: u32 = 200; +/// At most this many cursors' readings are kept. +const MAX_READINGS: usize = 4; +/// At most this many pens' ends are kept. +const MAX_PENS: usize = 16; + +/// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, +/// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on +/// a move or a turn of the wheel, and no button events. +fn configure(words: &mut [u32; LOGCONTEXT_WORDS]) { + words[LC_OPTIONS] = (words[LC_OPTIONS] | CXO_MESSAGES | CXO_CSRMESSAGES) & !(CXO_SYSTEM | CXO_PEN); + words[LC_MSG_BASE] = WT_DEFBASE; + words[LC_PKT_DATA] = PACKET_DATA; + words[LC_PKT_MODE] = 0; + words[LC_MOVE_MASK] = MOVE_MASK; + words[LC_BTN_DN_MASK] = 0; + words[LC_BTN_UP_MASK] = 0; +} + +/// The size in bytes of a packet holding the fields of `mask`. +fn packet_size(mask: u32) -> usize { + FIELDS.iter().filter(|(f, _)| mask & f != 0).map(|(_, n)| n).sum() +} + +/// The 32-bit field `field` of a packet holding the fields of `mask`, or `None` when the mask +/// leaves it out, it is not a 32-bit field, or `bytes` is too short. +fn field(bytes: &[u8], mask: u32, field: u32) -> Option { + if mask & field == 0 || bytes.len() < packet_size(mask) { + return None; + } + let mut at = 0; + for &(f, n) in &FIELDS { + if f == field { + let word = bytes.get(at..at + 4).filter(|_| n == 4)?; + return Some(u32::from_ne_bytes(word.try_into().ok()?)); + } + if mask & f != 0 { + at += n; + } + } + None +} + +/// What a packet says about the wheel. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Packet { + status: u32, + cursor: u32, + tangent: u32, +} + +/// The status, cursor and tangential pressure of a packet holding the fields of `mask`. +fn decode(bytes: &[u8], mask: u32) -> Option { + Some(Packet { status: field(bytes, mask, PK_STATUS)?, cursor: field(bytes, mask, PK_CURSOR)?, tangent: field(bytes, mask, PK_TANGENT_PRESSURE)? }) +} + +/// A device's tangential-pressure range (`AXIS`'s `axMin` and `axMax`). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Axis { + min: i32, + max: i32, +} + +impl Axis { + /// The wheel, 0..1, for the absolute value `raw`: 0 at `axMin`, 1 at `axMax`. `pktdef.h` gives + /// an absolute tangential pressure as unsigned; with a range below 0 it is read as signed. A + /// value outside the range reads as none. + fn wheel(self, raw: u32) -> Option { + let (min, max) = (i64::from(self.min), i64::from(self.max)); + if min >= max { + return None; + } + let v = if min < 0 { i64::from(raw as i32) } else { i64::from(raw) }; + (min..=max).contains(&v).then(|| ((v - min) as f64 / (max - min) as f64) as f32) + } +} + +/// Whether a cursor of this `CSR_TYPE` is an airbrush. +fn is_airbrush(csr_type: u32) -> bool { + csr_type & 0x0F06 == 0x0902 +} + +/// The wheel range of a cursor of `csr_type` whose packets carry the fields of `csr_pktdata`, on a +/// device whose `DVC_TPRESSURE` reads as `axis` (`axMin`, `axMax`, `axUnits`, `axResolution`): +/// `None` unless it is an airbrush with a tangential pressure and the range is not empty. +fn wheel_axis(csr_type: u32, csr_pktdata: u32, axis: Option<[u32; 4]>) -> Option { + let [min, max, ..] = axis?; + let axis = Axis { min: min as i32, max: max as i32 }; + (is_airbrush(csr_type) && csr_pktdata & PK_TANGENT_PRESSURE != 0 && axis.min < axis.max).then_some(axis) +} + +/// The device of `cursor`, from each device's first cursor and cursor count (`DVC_FIRSTCSR`, +/// `DVC_NCSRTYPES`), or `None` when no device or more than one has it. +fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { + let mut found = devices.iter().enumerate().filter(|(_, (first, n))| first.checked_add(*n).is_some_and(|end| (*first..end).contains(&cursor))); + let (d, _) = found.next()?; + found.next().is_none().then_some(d) +} + +/// What the driver said about a cursor's wheel range. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Lookup { + /// The range, or `None` for a cursor the driver describes without a wheel. + Known(Option), + /// A `WTInfoW` call failed at this message time. + Failed { at: u32 }, +} + +/// Each cursor's wheel range, as the driver reported it, until the driver's information changes. +#[derive(Clone, Debug, Default)] +struct Cursors(Vec<(u32, Lookup)>); + +impl Cursors { + /// The wheel range of `cursor` for a packet at the message time `time`, asking the driver with + /// `query` the first time, or again once [`retry_due`] after a query that failed (`Err`). + /// Until then a cursor whose query failed reads no wheel. + fn axis(&mut self, cursor: u32, time: u32, query: impl FnOnce() -> Result, ()>) -> Option { + if let Some(i) = self.0.iter().position(|(c, _)| *c == cursor) { + match self.0[i].1 { + Lookup::Known(axis) => return axis, + Lookup::Failed { at } if !retry_due(at, time) => return None, + Lookup::Failed { .. } => { + self.0.remove(i); + } + } + } + let lookup = match query() { + Ok(axis) => Lookup::Known(axis), + Err(()) => Lookup::Failed { at: time }, + }; + if self.0.len() >= MAX_READINGS * 4 { + self.0.remove(0); + } + self.0.push((cursor, lookup)); + match lookup { + Lookup::Known(axis) => axis, + Lookup::Failed { .. } => None, + } + } + + fn clear(&mut self) { + self.0.clear(); + } +} + +/// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. +fn near(a: u32, b: u32) -> bool { + (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS +} + +/// The latest packet of a cursor near the context. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Reading { + cursor: u32, + /// The cursor's wheel range, `None` for a cursor without a wheel. + axis: Option, + raw: u32, + /// The message time of the packet. + time: u32, + /// The cursor has reported a value other than 0 since the readings started afresh. + moved: bool, +} + +/// The latest packet of each cursor near the context, until the readings start afresh. +#[derive(Clone, Debug, Default)] +struct Readings { + list: Vec, + /// The pointer id of each pen whose pointer messages were read since the readings started + /// afresh, with the end its last message read (`true` for the eraser end), at most + /// [`MAX_PENS`] of them. + ends: Vec<(u32, bool)>, + /// The pointer id of the pen whose message first read the wheel since the readings started + /// afresh; another pen's messages read none. + pen: Option, + /// The cursor whose wheel that pen read; the pen reads no other cursor's wheel until the + /// readings start afresh. + cursor: Option, +} + +impl Readings { + /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of + /// a cursor out of the context drops that cursor's reading. A packet sent after the context's + /// queue overflowed starts every reading afresh, until the next packet. + fn packet(&mut self, p: Packet, axis: Option, time: u32) { + if p.status & TPS_QUEUE_ERR != 0 { + self.forget(); + return; + } + let at = self.list.iter().position(|r| r.cursor == p.cursor); + if p.status & TPS_PROXIMITY != 0 { + if let Some(i) = at { + self.list.remove(i); + } + return; + } + let moved = at.is_some_and(|i| self.list[i].moved && self.list[i].axis == axis) || p.tangent != 0; + let reading = Reading { cursor: p.cursor, axis, raw: p.tangent, time, moved }; + match at { + Some(i) => self.list[i] = reading, + None => { + if self.list.len() >= MAX_READINGS { + self.list.remove(0); + } + self.list.push(reading); + } + } + } + + /// A `WT_PACKET` read at the message time `time`: the packet with its cursor's wheel range, or + /// `None` when `WTPacket` failed or the packet could not be decoded. Then no reading is known to + /// be current, and the readings start afresh until the next packet. + fn read(&mut self, read: Option<(Packet, Option)>, time: u32) { + match read { + Some((p, axis)) => self.packet(p, axis, time), + None => self.forget(), + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet + /// could not be read, the context's queue overflowed, or the context closed. + fn forget(&mut self) { + self.list.clear(); + self.ends.clear(); + self.pen = None; + self.cursor = None; + } + + /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took + /// the readings, or `pen` when none has. + fn owner_or(&self, pen: u32) -> u32 { + self.pen.unwrap_or(pen) + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time + /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose + /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the + /// readings, the latest packet of the cursor whose wheel it read, however long ago it came (a + /// pen held still sends none) and whatever other cursors were read since. `None` when no cursor, + /// or more than one, is that recent, or the cursor has read only 0 since the readings started + /// afresh, or another pen's message read a wheel first since then. The same pen's turn to its + /// other end starts them afresh first; another pen's message with another end does not. + fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { + if self.pen.is_some_and(|p| p != pen) { + return None; + } + if self.ends.iter().any(|&(p, e)| p == pen && e != eraser) { + self.forget(); + } + match self.ends.iter_mut().find(|(p, _)| *p == pen) { + Some(end) => end.1 = eraser, + None => { + if self.ends.len() >= MAX_PENS { + self.ends.remove(0); + } + self.ends.push((pen, eraser)); + } + } + let r = if self.pen == Some(pen) { + let cursor = self.cursor?; + self.list.iter().find(|r| r.cursor == cursor)? + } else { + let mut near_time = self.list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; + } + r + }; + if !r.moved { + return None; + } + let wheel = r.axis?.wheel(r.raw)?; + self.pen = Some(pen); + self.cursor = Some(r.cursor); + Some(wheel) + } +} + +/// What a pen message does to the open context before it is opened for the pen's window. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Current { + /// Nothing is open, or the context is the pen window's. + Keep, + /// The context's window is gone: drop the handle without a call on it. + Drop, + /// The context is another window's: close it with `WTClose`. + Close, +} + +/// After an open that left no context, the same window is tried again by the first pen message at +/// least this many milliseconds of the message clock later. +const RETRY_MS: u32 = 2000; + +/// The context step for a pen message to a window owned by `owner` at the message time `time`: +/// what happens to the open context, whose window is `current` with whether that window still +/// exists, and whether a context is opened for `owner`. The context follows the window the pen +/// draws in. While no context is open, the window and time of the last open tried (`tried`) keep +/// pen messages to that window from trying again until [`RETRY_MS`] have passed; another window, +/// or the driver closing or changing the context, tries at once. +/// A pen message to a window of an app that is not the active one (`active` false) opens none, so +/// the context never sits in front of the active app's own in the driver's overlap order. +fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32, active: bool) -> (Current, bool) { + let step = match current { + Some((_, false)) => Current::Drop, + Some((w, true)) if w == owner => return (Current::Keep, false), + Some(_) => Current::Close, + None => Current::Keep, + }; + let due = match tried { + Some((w, at)) if w == owner => retry_due(at, time), + _ => true, + }; + (step, active && (due || step != Current::Keep)) +} + +/// The context step for a pen message while the active tool reads no wheel ([`Wheel::Unused`]): +/// an open context closes, or is dropped when its window is gone (`current` as for +/// [`next_context`]), and none opens. +fn unused_context(current: Option<(usize, bool)>) -> Current { + match current { + Some((_, false)) => Current::Drop, + Some(_) => Current::Close, + None => Current::Keep, + } +} + +/// Whether the active tool draws with a brush or tip that varies with the finger wheel, as the +/// app last said ([`set_wheel_used`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Wheel { + /// No pen message loads `Wintab32.dll`, installs the thread's hook or opens a context, and a + /// context still open closes. + #[default] + Unused, + /// Pen messages open the context as [`next_context`] says. + Used, +} + +/// Whether a pen message calls the driver at all: while the wheel is used, or to close a context +/// still open after it stopped being used. +fn calls_driver(wheel: Wheel, open: bool) -> bool { + wheel == Wheel::Used || open +} + +/// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or +/// more later, on the message clock, which wraps. +fn retry_due(at: u32, time: u32) -> bool { + time.wrapping_sub(at) >= RETRY_MS +} + +/// At most this many contexts' closing notices wait for [`Notices::take`]. +const MAX_NOTICES: usize = 8; + +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`), and another app becoming +/// the active one (`WM_ACTIVATEAPP`), since they were last taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// call of its own, so they are noted here and acted on at the next Wintab or pen message. +#[derive(Clone, Debug, Default, PartialEq)] +struct Notices { + /// The contexts the driver closed or is about to close. + closed: Vec, + /// The driver's information changed. + info_changed: bool, + /// The readings were to start afresh while they were in use ([`Notices::forget_later`]). + forget: bool, + /// Another app became the active one. + deactivated: bool, +} + +/// What the driver's notices do to the open context. Both can come in one batch. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Notice { + /// The driver closed it: drop the handle without `WTClose`, and open a context again at the + /// next pen message. + closed: bool, + /// The driver's information changed: close it if it is still open, forget each cursor's wheel + /// range, and open a context again at the next pen message. + info_changed: bool, + /// Start the readings afresh. + forget: bool, + /// Another app became the active one: close the context, and open one again at the next pen + /// message once this app is active again. + deactivated: bool, +} + +impl Notices { + /// Notes `message` if it is a closing, information-change or deactivation notice. + fn note(&mut self, message: Message) { + match message { + Message::Closed { ctx } if !self.closed.contains(&ctx) => { + if self.closed.len() >= MAX_NOTICES { + self.closed.remove(0); + } + self.closed.push(ctx); + } + Message::InfoChange => self.info_changed = true, + Message::Deactivated => self.deactivated = true, + _ => {} + } + } + + /// The reader closed `ctx` itself: its closing notice is not the driver's, and a context opened + /// later with the same handle value stays open. + fn closed_by_reader(&mut self, ctx: usize) { + self.closed.retain(|&c| c != ctx); + } + + /// The readings are to start afresh, at a time they are in use, for example when the pen leaves + /// the window during a driver call: the next [`Notices::take`] says so. + fn forget_later(&mut self) { + self.forget = true; + } + + /// Takes the notices: what they do to the open context `current`. + fn take(&mut self, current: Option) -> Notice { + let notices = std::mem::take(self); + Notice { + closed: current.is_some_and(|c| notices.closed.contains(&c)), + info_changed: notices.info_changed, + forget: notices.forget, + deactivated: notices.deactivated, + } + } +} + +/// Opens a context with `open` only when `hook` put the window procedure that notes the driver's +/// notices in front of the window's own and, asked after every other driver call, this app is +/// still the active one (`active`); otherwise opens none, and the window is tried again as +/// [`next_context`] says. +fn hooked_open(hook: impl FnOnce() -> bool, active: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() && active() { open() } else { None } +} + +/// What a message does to the readings and the context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Message { + /// A packet with this serial number is waiting for the context `lparam` names. + Packet { + serial: u32, + ctx: usize, + }, + /// The readings start afresh for the context it names. + Forget { + ctx: usize, + }, + /// The context it names has closed. + Closed { + ctx: usize, + }, + /// The driver's information changed: the context closes and opens again. + InfoChange, + /// Another app became the active one: the context closes. + Deactivated, + Other, +} + +/// `WM_ACTIVATEAPP` (`winuser.h`): sent to the app's top-level windows when another app's window +/// is activated (`wParam` false) or one of the app's own is (true) +/// (). +const WM_ACTIVATEAPP: u32 = 0x001C; + +/// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` +/// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. +fn message(message: u32, wparam: usize, lparam: isize) -> Message { + match message { + WM_ACTIVATEAPP if wparam == 0 => Message::Deactivated, + WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, + WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, + WT_PROXIMITY => Message::Forget { ctx: wparam }, + WT_CTXCLOSE => Message::Closed { ctx: wparam }, + WT_INFOCHANGE => Message::InfoChange, + _ => Message::Other, + } +} + +#[cfg(windows)] +pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win { + use std::cell::{Cell, RefCell}; + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; + use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::System::Threading::GetCurrentThreadId; + use windows::Win32::UI::WindowsAndMessaging::{ + CWPSTRUCT, CallNextHookEx, CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetForegroundWindow, GetPropW, + GetWindowLongPtrW, GetWindowThreadProcessId, IsWindow, MSG, RemovePropW, SetPropW, SetWindowLongPtrW, SetWindowsHookExW, WH_CALLWNDPROC, + WM_NCDESTROY, WNDPROC, + }; + use windows::core::{PCWSTR, s, w}; + + use super::{ + Axis, CSR_PKTDATA, CSR_TYPE, Current, Cursors, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, + MAX_INDEX, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, PK_TANGENT_PRESSURE, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, + WTI_INTERFACE, Wheel, calls_driver, configure, decode, device_of, hooked_open, is_airbrush, message, next_context, retry_due, unused_context, + wheel_axis, + }; + + /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). + type WtInfo = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32; + type WtOpen = unsafe extern "system" fn(*mut c_void, *mut c_void, i32) -> *mut c_void; + type WtClose = unsafe extern "system" fn(*mut c_void) -> i32; + type WtPacket = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + + #[derive(Clone, Copy)] + struct Api { + info: WtInfo, + open: WtOpen, + close: WtClose, + packet: WtPacket, + } + + /// The bytes a packet is read into. + #[repr(C, align(8))] + struct PacketBuffer([u8; PACKET_BUFFER]); + + /// An open context and the window that owns it. + struct Context { + handle: *mut c_void, + hwnd: *mut c_void, + } + + #[derive(Default)] + struct State { + context: Option, + /// The window an open was last tried for, and the message time it was tried at + /// ([`next_context`]). + tried: Option<(*mut c_void, u32)>, + cursors: Cursors, + readings: Readings, + } + + thread_local! { + static STATE: RefCell = RefCell::new(State::default()); + /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends + /// while [`STATE`] is borrowed for a driver call. + static NOTICES: RefCell = RefCell::new(Notices::default()); + /// Whether the active tool uses the wheel ([`set_wheel_used`]), kept apart from [`STATE`] so + /// the app can say so while [`STATE`] is borrowed. + static WHEEL: Cell = const { Cell::new(Wheel::Unused) }; + } + + /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. + const PREV_PROC: PCWSTR = w!("VectorCraft.Wintab.PrevProc"); + + /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. + fn note(what: Message) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange | Message::Deactivated) { + return; + } + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.note(what); + } + }); + } + + /// The window procedure put in front of the context window's own: the driver sends + /// `WT_CTXCLOSE` and `WT_INFOCHANGE` (), + /// and a sent message reaches the window procedure without passing winit's message hook. It + /// notes them and passes every message on. + unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + note(message(msg, wparam.0, lparam.0)); + // SAFETY: `GetPropW` takes any handle value and a NUL-terminated name. + let prev = unsafe { GetPropW(hwnd, PREV_PROC) }.0; + if msg == WM_NCDESTROY { + // SAFETY: as above; the window is being destroyed. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } + if prev.is_null() { + // SAFETY: the default procedure takes any message of a window of this thread. + return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }; + } + // SAFETY: the property holds the window procedure `subclass` replaced, which stays valid + // while the window exists. + let prev = unsafe { std::mem::transmute::<*mut c_void, WNDPROC>(prev) }; + // SAFETY: `prev` is the window's own procedure, called with the message it was sent. + unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } + } + + /// Another app became the active one: closes the context now, unless the reader is in a call of + /// its own, when the noted [`Message::Deactivated`] closes it at the next Wintab or pen message. + /// No pen messages come while another app is active, so waiting for one would leave the context + /// in front of that app's own. + fn deactivate() { + let Some(api) = api() else { return }; + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.take_notices(api); + } + }); + } + + /// Whether this app is the active one: the foreground window belongs to this thread, which + /// runs every window of the app. + fn is_active() -> bool { + // SAFETY: `GetForegroundWindow` takes no arguments. + let foreground = unsafe { GetForegroundWindow() }; + // SAFETY: `GetWindowThreadProcessId` takes any handle value, and no process id is asked for. + !foreground.0.is_null() && unsafe { GetWindowThreadProcessId(foreground, None) } == unsafe { GetCurrentThreadId() } + } + + /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's + /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a + /// top-level window of the app, ) + /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` + /// () go to + /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows + /// they are sent to (). + unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code >= 0 { + // SAFETY: for `HC_ACTION` (0), `lParam` points to the message's `CWPSTRUCT`, which + // lives for the call; `as_ref` gives `None` for a null pointer. + if let Some(cwp) = unsafe { (lparam.0 as *const CWPSTRUCT).as_ref() } { + if message(cwp.message, cwp.wParam.0, cwp.lParam.0) == Message::Deactivated { + note(Message::Deactivated); + deactivate(); + } + crate::windows_stylus::sent_message(cwp.message, cwp.wParam.0); + } + } + // SAFETY: every hook procedure passes the call on, with what it was given. + unsafe { CallNextHookEx(None, code, wparam, lparam) } + } + + /// Installs [`call_wnd_proc`] for this thread, for a pen message at the message time `time`, + /// unless it is installed, and returns whether it is. It stays for the life of the thread. After + /// a failed install, a pen message tries again once [`retry_due`]. + fn hook_thread(time: u32) -> bool { + thread_local! { + /// Installed, or the message time of the last failed install. + static HOOK: std::cell::Cell>> = const { std::cell::Cell::new(Err(None)) }; + } + match HOOK.get() { + Ok(()) => return true, + Err(Some(at)) if !retry_due(at, time) => return false, + Err(_) => {} + } + // SAFETY: a hook of this thread, whose procedure is in this executable, so no module + // handle is passed. + let hooked = unsafe { SetWindowsHookExW(WH_CALLWNDPROC, Some(call_wnd_proc), None, GetCurrentThreadId()) }.is_ok(); + HOOK.set(if hooked { Ok(()) } else { Err(Some(time)) }); + hooked + } + + /// Closes the context for a deactivation noted while the reader was in a call of its own + /// ([`deactivate`]), once that call has ended. + fn settle() { + if NOTICES.with(|n| n.try_borrow().is_ok_and(|n| n.deactivated)) { + deactivate(); + } + } + + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns + /// whether it is there. The window's property holds the procedure it replaced, and goes with the + /// window. + fn subclass(hwnd: *mut c_void) -> bool { + let hwnd = HWND(hwnd); + // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. + if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { + return true; + } + // SAFETY: as above. + let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; + if prev == 0 { + return false; + } + // SAFETY: the window is this thread's (winit's), and the property's value is a procedure + // address, not memory the system frees. + if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { + return false; + } + type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; + // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. + if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { + // SAFETY: as for `SetPropW`. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + return false; + } + true + } + + /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. + fn api() -> Option { + static API: OnceLock> = OnceLock::new(); + *API.get_or_init(|| { + // SAFETY: Wintab32.dll is loaded from the system directory only, and stays loaded for + // the process, so the function pointers below stay valid. + let module = unsafe { LoadLibraryExW(w!("Wintab32.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?; + // SAFETY: the names are NUL-terminated, and the module is loaded. + let (info, open, close, packet) = unsafe { + ( + GetProcAddress(module, s!("WTInfoW"))?, + GetProcAddress(module, s!("WTOpenW"))?, + GetProcAddress(module, s!("WTClose"))?, + GetProcAddress(module, s!("WTPacket"))?, + ) + }; + type Proc = unsafe extern "system" fn() -> isize; + // SAFETY: the exports have these signatures (`wintab.h`). + unsafe { + Some(Api { + info: std::mem::transmute::(info), + open: std::mem::transmute::(open), + close: std::mem::transmute::(close), + packet: std::mem::transmute::(packet), + }) + } + }) + } + + /// `WTInfoW`'s answer for `category` and `index`, when it is exactly `N` 32-bit words. + fn info(api: Api, category: u32, index: u32) -> Option<[u32; N]> { + // SAFETY: a null buffer asks for the size only. + let size = unsafe { (api.info)(category, index, std::ptr::null_mut()) } as usize; + if N > 128 || size != N * 4 { + return None; + } + // Room for more than asked, should the driver write more than it said. + let mut buf = [0u32; 128]; + // SAFETY: `buf` holds 512 bytes, more than the size the driver gave. + let wrote = unsafe { (api.info)(category, index, buf.as_mut_ptr().cast()) } as usize; + let mut out = [0u32; N]; + out.copy_from_slice(buf.get(..N)?); + (wrote == N * 4).then_some(out) + } + + /// The wheel range of `cursor`: `Ok(None)` for a cursor the driver describes without one, and + /// `Err` when a `WTInfoW` call it needs fails. + fn cursor_axis(api: Api, cursor: u32) -> Result, ()> { + if cursor >= MAX_INDEX { + return Ok(None); + } + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE).ok_or(())?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA).ok_or(())?; + if !is_airbrush(csr_type) || csr_pktdata & PK_TANGENT_PRESSURE == 0 { + return Ok(None); + } + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES).ok_or(())?; + let mut devices = vec![]; + for d in 0..count.min(MAX_DEVICES) { + let [first] = info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR).ok_or(())?; + let [n] = info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES).ok_or(())?; + devices.push((first, n)); + } + let Some(device) = device_of(cursor, &devices).and_then(|d| u32::try_from(d).ok()) else { return Ok(None) }; + let range = info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE).ok_or(())?; + Ok(wheel_axis(csr_type, csr_pktdata, Some(range))) + } + + /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. + fn context_open() -> bool { + STATE.with(|s| !s.try_borrow().is_ok_and(|s| s.context.is_none())) + } + + fn is_window(hwnd: *mut c_void) -> bool { + // SAFETY: `IsWindow` takes any handle value and reads no caller memory. + unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() + } + + impl State { + fn close(&mut self, api: Api) { + if let Some(c) = self.context.take() { + // SAFETY: the handle came from `WTOpenW` and has not been closed. + unsafe { (api.close)(c.handle) }; + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.closed_by_reader(c.handle as usize); + } + }); + } + self.readings.forget(); + } + + /// Acts on the driver's notices since the last look ([`Notices::take`]). + fn take_notices(&mut self, api: Api) { + let current = self.context.as_ref().map(|c| c.handle as usize); + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::default(), |mut n| n.take(current))); + if notice.closed { + self.context = None; + self.tried = None; + self.readings.forget(); + } + if notice.info_changed { + self.close(api); + self.tried = None; + self.cursors.clear(); + } + if notice.forget { + self.readings.forget(); + } + if notice.deactivated { + self.close(api); + self.tried = None; + } + } + + /// Moves the context to the window that owns `hwnd`, for a pen message at the message time + /// `time` ([`next_context`]), or closes it when the active tool does not use the wheel + /// (`wheel`, [`unused_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32, wheel: Wheel) { + // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. + let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; + let owner = if owner.is_null() { hwnd } else { owner }; + let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); + let tried = self.tried.map(|(w, at)| (w as usize, at)); + let (step, open) = match wheel { + Wheel::Used => next_context(current, tried, owner as usize, time, is_active()), + Wheel::Unused => (unused_context(current), false), + }; + match step { + Current::Keep => {} + Current::Drop => { + self.context = None; + self.readings.forget(); + } + Current::Close => self.close(api), + } + if !open { + return; + } + self.tried = Some((owner, time)); + let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; + configure(&mut words); + // Whether the app is active is asked again here, after the close and `WTInfoW` above. + let handle = hooked_open( + || subclass(owner), + is_active, + || { + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for + // the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + (!handle.is_null()).then_some(handle) + }, + ); + if let Some(handle) = handle { + self.context = Some(Context { handle, hwnd: owner }); + } + } + + fn ours(&self, hwnd: *mut c_void, ctx: usize) -> Option<*mut c_void> { + self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) + } + + fn axis(&mut self, api: Api, cursor: u32, time: u32) -> Option { + self.cursors.axis(cursor, time, || cursor_axis(api, cursor)) + } + } + + /// winit's message hook for the Wintab messages: reads each packet of the context and starts + /// the readings afresh on a cursor's change or proximity. A closing or information-change + /// notice that comes through the queue is noted as [`wnd_proc`] notes a sent one. It never + /// consumes the message. + pub fn msg_hook(msg: &MSG) { + let what = message(msg.message, msg.wParam.0, msg.lParam.0); + if what == Message::Other { + return; + } + if !calls_driver(WHEEL.get(), context_open()) { + return; + } + let Some(api) = api() else { return }; + note(what); + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.take_notices(api); + match what { + Message::Packet { serial, ctx } => { + let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; + let mut buf = PacketBuffer([0; PACKET_BUFFER]); + // SAFETY: the handle is the open context's, and `buf` holds more bytes than a + // packet of every field. + let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor, msg.time))); + s.readings.read(read, msg.time); + } + Message::Forget { ctx } => { + if s.ours(msg.hwnd.0, ctx).is_some() { + s.readings.forget(); + } + } + Message::Closed { .. } | Message::InfoChange | Message::Deactivated | Message::Other => {} + } + }); + settle(); + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message + /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when + /// none is open. While the active tool does not use the wheel ([`set_wheel_used`]), it reads + /// none and calls the driver only to close a context still open ([`calls_driver`]). The first + /// call that opens a context installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// installed, no context opens and the pens read no wheel. + pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { + let used = WHEEL.get(); + if !calls_driver(used, context_open()) { + return None; + } + let api = api()?; + if used == Wheel::Used && !hook_thread(time) { + return None; + } + let wheel = STATE.with(|s| { + let mut s = s.try_borrow_mut().ok()?; + s.take_notices(api); + s.open_for(api, hwnd.0, time, used); + s.readings.wheel_for(time, pen, eraser) + }); + settle(); + wheel.filter(|_| used == Wheel::Used) + } + + /// The app says whether the active tool draws with a brush or tip that varies with the finger + /// wheel (`used`). Until it says so, pen messages read no wheel and leave the driver alone; when + /// it stops, the context closes now, or at the next pen message while the reader is in a call + /// of its own. + pub fn set_wheel_used(used: bool) { + let wheel = if used { Wheel::Used } else { Wheel::Unused }; + if WHEEL.replace(wheel) == wheel { + return; + } + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.tried = None; + if wheel == Wheel::Unused + && s.context.is_some() + && let Some(api) = api() + { + // A context the driver closed is dropped without `WTClose`. + s.take_notices(api); + s.close(api); + } + }); + settle(); + } + + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer + /// id `pen` ([`Readings::owner_or`]). + pub fn wheel_pen(pen: u32) -> u32 { + STATE.with(|s| s.try_borrow().map_or(pen, |s| s.readings.owner_or(pen))) + } + + /// Start the readings afresh: the pen left the window or detection range, or a press was + /// canceled. While the readings are in use, as in a driver call, they start afresh at the next + /// Wintab or pen message ([`Notices::forget_later`]). + pub fn forget() { + STATE.with(|s| match s.try_borrow_mut() { + Ok(mut s) => s.readings.forget(), + Err(_) => NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.forget_later(); + } + }), + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The pointer id of the pen in the tests that use one pen. + const PEN: u32 = 1; + + impl Readings { + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + self.wheel_for(time, PEN, eraser) + } + } + + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler + /// when it has none, and the wider fields hold filler bytes. + fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { + let mut out = vec![]; + for &(f, n) in &FIELDS { + if mask & f == 0 { + continue; + } + let v = values.iter().find(|(k, _)| *k == f).map_or(0xAAAA_AAAA, |&(_, v)| v); + if n == 4 { + out.extend(v.to_ne_bytes()); + } else { + out.extend(std::iter::repeat_n(0xEE, n)); + } + } + out + } + + #[test] + fn the_context_asks_for_the_wheel_without_the_system_cursor() { + let mut words = [0u32; LOGCONTEXT_WORDS]; + words[LC_OPTIONS] = CXO_SYSTEM | CXO_PEN | 0x8000; + words[LC_MSG_BASE] = 0x1234; + words[LC_BTN_DN_MASK] = !0; + words[LC_BTN_UP_MASK] = !0; + words[LC_PKT_MODE] = PK_TANGENT_PRESSURE; + words[31] = 77; + configure(&mut words); + assert_eq!(words[LC_OPTIONS], CXO_MESSAGES | CXO_CSRMESSAGES | 0x8000, "the driver's other options stay"); + assert_eq!(words[LC_MSG_BASE], WT_DEFBASE); + assert_eq!(words[LC_PKT_DATA], PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE); + assert_eq!(words[LC_PKT_MODE], 0, "absolute"); + assert_eq!(words[LC_MOVE_MASK] & PK_TANGENT_PRESSURE, PK_TANGENT_PRESSURE, "a turn in place makes a packet"); + assert_eq!((words[LC_BTN_DN_MASK], words[LC_BTN_UP_MASK]), (0, 0)); + assert_eq!(words[31], 77, "the extents stay the driver's"); + } + + #[test] + fn packets_are_read_in_the_order_of_their_fields() { + let want = Packet { status: 0, cursor: 3, tangent: 600 }; + let p = bytes(PACKET_DATA, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), 20); + assert_eq!(decode(&p, PACKET_DATA), Some(want)); + // Every field before the tangential pressure, the context handle and the orientation + // after it. + let all = FIELDS.iter().fold(0, |m, (f, _)| m | f); + let p = bytes(all, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), packet_size(all)); + assert_eq!(packet_size(all), std::mem::size_of::() + 4 * 11 + 24); + assert_eq!(decode(&p, all), Some(want)); + assert_eq!(decode(&p[..p.len() - 1], all), None, "a short packet"); + assert_eq!(decode(&p, PK_STATUS | PK_CURSOR), None, "no tangential pressure"); + assert_eq!(field(&p, all, PK_ORIENTATION), None, "not a 32-bit field"); + assert!(packet_size(all) <= PACKET_BUFFER); + } + + #[test] + fn only_an_airbrush_with_a_range_reads_a_wheel() { + let range = |min: i32, max: i32| Some([min as u32, max as u32, 0, 0]); + let airbrush = 0x0902; + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 1023)), Some(Axis { min: 0, max: 1023 })); + assert_eq!(wheel_axis(0x090A, PK_TANGENT_PRESSURE, range(-1023, 1023)), Some(Axis { min: -1023, max: 1023 }), "its other end"); + assert_eq!(wheel_axis(0x0802, PACKET_DATA, range(0, 1023)), None, "a general stylus"); + assert_eq!(wheel_axis(0x0804, PACKET_DATA, range(0, 1023)), None, "an Art Pen"); + assert_eq!(wheel_axis(airbrush, PK_X | PK_Y, range(0, 1023)), None, "no tangential pressure"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, None), None, "no range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 0)), None, "an empty range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(1023, 0)), None, "a falling range"); + } + + #[test] + fn the_wheel_is_its_place_in_the_range() { + let axis = Axis { min: 0, max: 1000 }; + assert_eq!(axis.wheel(0), Some(0.0)); + assert_eq!(axis.wheel(250), Some(0.25)); + assert_eq!(axis.wheel(1000), Some(1.0)); + assert_eq!(axis.wheel(1001), None, "past the end"); + assert_eq!(axis.wheel(u32::MAX), None); + let signed = Axis { min: -1000, max: 1000 }; + assert_eq!(signed.wheel(-1000i32 as u32), Some(0.0)); + assert_eq!(signed.wheel(0), Some(0.5)); + assert_eq!(signed.wheel(500), Some(0.75)); + assert_eq!(signed.wheel(i32::MIN as u32), None); + let wide = Axis { min: i32::MIN, max: i32::MAX }; + assert_eq!(wide.wheel(i32::MAX as u32), Some(1.0), "no overflow"); + assert_eq!(Axis { min: 5, max: 5 }.wheel(5), None); + } + + #[test] + fn a_cursor_belongs_to_one_device() { + let devices = [(0, 3), (3, 3)]; + assert_eq!(device_of(1, &devices), Some(0)); + assert_eq!(device_of(4, &devices), Some(1)); + assert_eq!(device_of(6, &devices), None); + assert_eq!(device_of(1, &[(0, 3), (1, 1)]), None, "two devices claim it"); + assert_eq!(device_of(u32::MAX, &[(u32::MAX - 1, 5)]), None, "a range past the end"); + assert_eq!(device_of(0, &[]), None); + } + + const AXIS: Option = Some(Axis { min: 0, max: 1000 }); + + fn packet(cursor: u32, tangent: u32) -> Packet { + Packet { status: 0, cursor, tangent } + } + + #[test] + fn a_pen_message_takes_the_wheel_of_the_recent_airbrush() { + let mut r = Readings::default(); + assert_eq!(r.wheel_at(1000, false), None, "no packet"); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1010, false), Some(0.25)); + assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); + assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.forget(); + r.packet(packet(1, 1000), AXIS, u32::MAX - 5); + r.packet(packet(2, 500), None, u32::MAX); + assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); + r.packet(packet(1, 1000), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); + r.forget(); + r.packet(packet(2, 500), None, 100); + assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); + r.packet(packet(1, 2000), AXIS, 300); + assert_eq!(r.wheel_at(500, false), None, "a value past the range"); + } + + #[test] + fn a_pen_keeps_the_airbrush_whose_wheel_it_read() { + let mut r = Readings::default(); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1000, false), Some(0.25)); + // Another tablet's airbrush moves while the pen is held still. + r.packet(packet(2, 750), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(0.25), "its own cursor's wheel, not the other's"); + assert_eq!(r.wheel_at(9000, false), Some(0.25), "however old both packets are"); + r.packet(packet(1, 500), AXIS, 6000); + assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 500) }, AXIS, 6100); + r.packet(packet(2, 750), AXIS, 6105); + assert_eq!(r.wheel_at(6110, false), None, "its own cursor left; the other's is not taken"); + r.forget(); + r.packet(packet(2, 750), AXIS, 7000); + assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); + } + + #[test] + fn zero_is_no_wheel_until_the_pen_reports_another_value() { + let mut r = Readings::default(); + r.packet(packet(1, 0), AXIS, 100); + assert_eq!(r.wheel_at(100, false), None); + r.packet(packet(1, 300), AXIS, 110); + r.packet(packet(1, 0), AXIS, 120); + assert_eq!(r.wheel_at(120, false), Some(0.0), "a real 0 after another value"); + r.forget(); + r.packet(packet(1, 0), AXIS, 130); + assert_eq!(r.wheel_at(130, false), None, "afresh after the pen came near"); + } + + #[test] + fn the_readings_start_afresh_for_the_other_end_and_out_of_the_context() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_at(100, false), Some(0.3)); + assert_eq!(r.wheel_at(100, true), None, "the other end"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, true), Some(0.3)); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 300) }, AXIS, 120); + assert_eq!(r.wheel_at(120, true), None, "out of the context"); + r.packet(packet(1, 300), AXIS, 130); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(1, 300) }, AXIS, 140); + assert_eq!(r.wheel_at(140, true), None, "the queue overflowed"); + // The eraser end leaves; the tip's first message after it keeps the tip's packet. + r.forget(); + r.packet(packet(1, 300), AXIS, 150); + assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + r.forget(); + for c in 0..10 { + r.packet(packet(c, 300), AXIS, 1000 * c); + } + assert_eq!(r.list.len(), MAX_READINGS, "bounded"); + assert_eq!(r.wheel_at(9000, false), Some(0.3)); + } + + /// [`next_context`] while this app is the active one. + fn step(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32) -> (Current, bool) { + next_context(current, tried, owner, time, true) + } + + #[test] + fn the_context_follows_the_window_the_pen_draws_in() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(step(None, None, main, t), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t), (Current::Keep, false), "the same window keeps it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t + 60_000), (Current::Keep, false), "however long it is open"); + assert_eq!(step(Some((main, true)), Some((main, t)), doc, t), (Current::Close, true), "another document window"); + assert_eq!(step(Some((doc, true)), Some((doc, t)), main, t), (Current::Close, true), "and back"); + assert_eq!(step(Some((main, false)), Some((main, t)), doc, t), (Current::Drop, true), "a window that is gone"); + assert_eq!(step(Some((main, false)), Some((main, t)), main, t), (Current::Drop, true), "its handle reused"); + assert_eq!(step(None, Some((main, t)), main, t + 1), (Current::Keep, false), "an open that failed is not tried at once"); + assert_eq!(step(None, Some((main, t)), doc, t + 1), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn a_window_whose_open_failed_is_tried_again_later() { + let main = 0x10; + let t = 1000; + for dt in [0, 1, 500, RETRY_MS - 1] { + assert_eq!(step(None, Some((main, t)), main, t + dt), (Current::Keep, false), "{dt} ms later"); + } + assert_eq!(step(None, Some((main, t)), main, t + RETRY_MS), (Current::Keep, true), "after the retry interval"); + assert_eq!(step(None, Some((main, t)), main, t + 60_000), (Current::Keep, true), "or long after"); + // The message clock wraps after about 49.7 days. + let late = u32::MAX - 100; + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(50)), (Current::Keep, false), "across the wrap"); + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(RETRY_MS)), (Current::Keep, true), "and due across it"); + } + + #[test] + fn a_failed_step_is_retried_after_the_interval() { + assert!(!retry_due(1000, 1000), "at once"); + assert!(!retry_due(1000, 1000 + RETRY_MS - 1)); + assert!(retry_due(1000, 1000 + RETRY_MS), "after the interval"); + assert!(retry_due(u32::MAX - 10, (u32::MAX - 10).wrapping_add(RETRY_MS)), "across the clock's wrap"); + assert!(!retry_due(u32::MAX - 10, 5), "and not early across it"); + } + + #[test] + fn no_context_opens_while_another_app_is_active() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(next_context(None, None, main, t, false), (Current::Keep, false), "a pen hovering over an inactive window"); + assert_eq!(next_context(None, Some((main, t)), main, t + RETRY_MS, false), (Current::Keep, false), "not even when a retry is due"); + assert_eq!(next_context(Some((main, true)), None, doc, t, false), (Current::Close, false), "another window's context closes"); + assert_eq!(next_context(Some((main, false)), None, main, t, false), (Current::Drop, false), "a gone window's is dropped"); + assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); + } + + #[test] + fn the_driver_is_left_alone_until_the_wheel_is_used() { + assert!(!calls_driver(Wheel::Unused, false), "no brush or tip on Stylus Wheel"); + assert!(calls_driver(Wheel::Used, false), "one is: the context opens"); + assert!(calls_driver(Wheel::Unused, true), "none any more: the open context closes"); + assert_eq!(Wheel::default(), Wheel::Unused, "at start-up"); + let main = 0x10; + assert_eq!(unused_context(None), Current::Keep, "nothing open"); + assert_eq!(unused_context(Some((main, true))), Current::Close, "the pen window's context closes"); + assert_eq!(unused_context(Some((main, false))), Current::Drop, "a gone window's is dropped"); + } + + #[test] + fn another_app_becoming_active_closes_the_context() { + assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); + assert_eq!(message(WM_ACTIVATEAPP, 1, 0), Message::Other, "this app becoming active"); + let ours = 0x5000; + let mut n = Notices::default(); + n.note(Message::Deactivated); + assert_eq!(n.take(Some(ours)), Notice { deactivated: true, ..Notice::default() }); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.note(Message::Deactivated); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, deactivated: true, ..Notice::default() }, "beside the driver's close"); + } + + #[test] + fn a_packet_that_cannot_be_read_starts_the_readings_afresh() { + let mut r = Readings::default(); + r.read(Some((packet(1, 750), AXIS)), 100); + assert_eq!(r.wheel_at(100, false), Some(0.75)); + r.read(None, 110); + assert_eq!(r.wheel_at(110, false), None, "the last reading is not kept after a failed read"); + r.read(Some((packet(1, 500), AXIS)), 120); + assert_eq!(r.wheel_at(120, false), Some(0.5), "the next packet reads again"); + } + + #[test] + fn the_drivers_notices_drop_or_reopen_the_context() { + let (ours, other) = (0x5000, 0x6000); + let keep = Notice::default(); + let closed = Notice { closed: true, ..Notice::default() }; + let reopen = Notice { info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + assert_eq!(n.take(Some(ours)), keep, "no notice"); + n.note(Message::Closed { ctx: other }); + assert_eq!(n.take(Some(ours)), keep, "another context closed"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), keep, "taken once"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(None), keep, "nothing open"); + assert_eq!(n, Notices::default(), "and the notice is gone"); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), reopen); + n.note(Message::InfoChange); + assert_eq!(n.take(None), reopen, "cursor ranges are read again even with nothing open"); + // The reader closes its context, and the driver's notice of that arrives during the call; + // a context opened next under the same handle value stays open. + n.note(Message::Closed { ctx: ours }); + n.closed_by_reader(ours); + assert_eq!(n.take(Some(ours)), keep); + for ctx in 0..20 { + n.note(Message::Closed { ctx }); + n.note(Message::Closed { ctx }); + } + assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); + assert_eq!(n.take(Some(19)), closed, "the latest kept"); + n.note(Message::Packet { serial: 1, ctx: ours }); + n.note(Message::Forget { ctx: ours }); + n.note(Message::Other); + assert_eq!(n, Notices::default(), "other messages are not notices"); + } + + #[test] + fn a_close_and_an_information_change_in_one_batch_both_count() { + let ours = 0x5000; + let both = Notice { closed: true, info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + n.note(Message::Closed { ctx: ours }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), both, "the closed handle is dropped, not closed again"); + n.note(Message::InfoChange); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), both, "in either order"); + n.note(Message::Closed { ctx: 0x6000 }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice { info_changed: true, ..Notice::default() }, "another context's close"); + } + + #[test] + fn a_leave_while_the_readings_are_in_use_starts_them_afresh_next() { + let ours = 0x5000; + let mut n = Notices::default(); + n.forget_later(); + assert_eq!(n.take(Some(ours)), Notice { forget: true, ..Notice::default() }, "the next look starts the readings afresh"); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.forget_later(); + assert_eq!(n.take(None), Notice { forget: true, ..Notice::default() }, "with nothing open too"); + n.forget_later(); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, forget: true, ..Notice::default() }, "beside a close"); + } + + #[test] + fn a_context_opens_only_behind_the_window_procedure() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || true, open), Some(7)); + assert_eq!(opens.get(), 1); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| false, || true, open), None, "no context without the procedure"); + assert_eq!(opens.get(), 1, "and the driver is not asked for one"); + assert_eq!(hooked_open(|| true, || true, || None::), None, "an open that fails"); + } + + #[test] + fn no_context_opens_when_another_app_became_active_before_the_open() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || false, open), None); + assert_eq!(opens.get(), 0, "the driver is not asked for one"); + } + + #[test] + fn another_pens_end_does_not_start_the_readings_afresh() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, true), None, "an eraser end before any packet"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(120, false), Some(0.3), "another pen's tip still reads the packet"); + assert_eq!(r.wheel_at(130, true), None, "the same pen turned over starts them afresh"); + // Pen 1's tip, then pen 2's, then pen 1's eraser, before either reads a wheel. + r.forget(); + assert_eq!(r.wheel_at(200, false), None, "no packet yet"); + assert_eq!(r.wheel_for(210, other, false), None); + r.packet(packet(1, 300), AXIS, 220); + assert_eq!(r.wheel_at(230, true), None, "pen 1's turn is seen past pen 2's message"); + for pen in 10..40 { + r.wheel_for(5000, pen, false); + } + assert_eq!(r.ends.len(), MAX_PENS, "bounded"); + } + + #[test] + fn a_failed_cursor_lookup_is_asked_again_later() { + let asks = std::cell::Cell::new(0); + let failing = || { + asks.set(asks.get() + 1); + Err(()) + }; + let mut c = Cursors::default(); + assert_eq!(c.axis(1, 1000, failing), None); + assert_eq!(c.axis(1, 1000 + RETRY_MS - 1, || Ok(AXIS)), None, "not asked again before the interval"); + assert_eq!(asks.get(), 1); + assert_eq!(c.axis(1, 1000 + RETRY_MS, || Ok(AXIS)), AXIS, "asked again after it"); + assert_eq!(c.axis(1, 9000, || Ok(None)), AXIS, "a range the driver gave is kept"); + assert_eq!(c.axis(2, 9000, || Ok(None)), None, "a cursor without a wheel"); + assert_eq!(c.axis(2, 9000 + RETRY_MS, || Ok(AXIS)), None, "is not asked again"); + c.clear(); + assert_eq!(c.axis(2, 9000, || Ok(AXIS)), AXIS, "until the driver's information changes"); + for cursor in 10..40 { + c.axis(cursor, 9000, || Ok(None)); + } + assert_eq!(c.0.len(), MAX_READINGS * 4, "bounded"); + } + + #[test] + fn the_readings_belong_to_the_pen_that_took_them_first() { + let other = 2; + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_for(5000, other, false), None, "a pen message long after the packet does not take them"); + assert_eq!(r.wheel_for(150, other, false), Some(0.3), "one near the packet does"); + assert_eq!(r.wheel_at(5010, false), None, "another pen with no packets of its own"); + assert_eq!(r.wheel_for(5020, other, false), Some(0.3), "and the pen that took them still reads them"); + r.forget(); + assert_eq!(r.wheel_at(5030, false), None, "no packet since the readings started afresh"); + r.packet(packet(1, 400), AXIS, 5040); + assert_eq!(r.wheel_at(5040, false), Some(0.4), "then another pen takes them"); + } + + #[test] + fn a_pen_takes_the_readings_only_when_it_reads_a_wheel() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, false), None, "no packet yet"); + assert_eq!(r.owner_or(PEN), PEN, "and no pen took the readings"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, false), Some(0.3), "the pen with the reading"); + assert_eq!(r.owner_or(other), PEN, "the pen whose leaving starts the readings afresh"); + r.forget(); + assert_eq!(r.owner_or(other), other); + } + + #[test] + fn a_queue_overflow_starts_every_reading_afresh() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + r.packet(packet(2, 500), None, 110); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(2, 500) }, None, 120); + assert!(r.list.is_empty(), "the queue is the context's, not the cursor's"); + assert_eq!(r.wheel_at(5000, false), None, "the airbrush's old wheel is not taken"); + r.packet(packet(1, 400), AXIS, 5000); + assert_eq!(r.wheel_at(5000, false), Some(0.4), "the next packet reads again"); + r.packet(packet(2, 500), None, 5010); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(2, 500) }, None, 5020); + assert_eq!(r.list.len(), 1, "a cursor that leaves drops only its own reading"); + } + + #[test] + fn wintab_messages_name_their_context() { + assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); + assert_eq!(message(WT_CSRCHANGE, 42, 0x5000), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_PROXIMITY, 0x5000, 1), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_CTXCLOSE, 0x5000, 0), Message::Closed { ctx: 0x5000 }); + assert_eq!(message(WT_INFOCHANGE, 0, 0), Message::InfoChange); + // WM_POINTERUPDATE and the context-open message. + assert_eq!(message(0x0245, 0, 0), Message::Other); + assert_eq!(message(WT_DEFBASE + 1, 0, 0), Message::Other); + } +} diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..cadfb6b7a6 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -131,6 +131,13 @@ impl Node { matches!(self.kind, NodeKind::Layer { template: true, .. }) } + /// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this + /// object out: a template layer while templates are hidden, or a path made into a guide while + /// guides are hidden. The canvas draws ruler guides apart from the art. + pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool { + (templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. })) + } + /// The art objects of this container: its children, looking through sublayers, which are not /// objects (bottom first). With `editable`, only the visible, unlocked objects in visible, /// unlocked, non-template sublayers. @@ -360,17 +367,32 @@ impl Node { self.geometric(Some(symbols)) } - /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. + /// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for + /// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline + /// [`Node::drawn_children`]. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); - let trace_source = self.extras().trace.is_some() - && !self.trace_view().shows_source() - && children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_))); + let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible); let skip = usize::from(self.extras().shaper.is_some() || trace_source); children.get(skip..).unwrap_or_default() } + /// The children a selection highlight outlines: [`Node::editing_children`] without the hidden + /// members, which the canvas does not draw. An Image Trace object's hidden source image stays + /// when the object's view shows it, and every path of a compound path stays, since the compound + /// path draws all of them. + pub fn drawn_children(&self) -> impl Iterator> { + let members = !matches!(self.kind, NodeKind::Compound { .. }); + let source = self.trace_source().filter(|_| self.trace_view().shows_source()); + self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) + } + + /// The first child of an Image Trace object when it is an image: the bitmap the trace keeps. + fn trace_source(&self) -> Option<&Arc> { + self.extras().trace.as_ref()?; + self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_))) + } + /// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols` /// is given. pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option { diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..071d3c3b64 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec { "stylize.dropShadow", "Drop Shadow…", STYLIZE, - "{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", + "{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}), ), r( "stylize.innerGlow", "Inner Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}), ), r( "stylize.outerGlow", "Outer Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), ), r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 1b8067e91c..555610f206 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -82,11 +82,12 @@ pub use group::{ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; +pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use placement::pinned_gradient_item; pub use raster::{ - RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects, - without_geometry, + RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, + staged_effects, without_geometry, }; pub use reshape::{ SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index fed9df7811..d97c16b554 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -1,6 +1,28 @@ +use vectorcraft_doc::color::BlendMode; + use super::catalog::{catalog_index, plugin_info}; use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util}; +/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in. +pub fn takes_blend_mode(effect: &str, key: &str) -> bool { + key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow") +} + +/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode. +pub fn parse_blend_mode(s: &str) -> Option { + let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect(); + BlendMode::parse(&name) +} + +/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`. +pub fn blend_mode_id(mode: BlendMode) -> String { + let mut name = format!("{mode:?}"); + if let Some(first) = name.get_mut(..1) { + first.make_ascii_lowercase(); + } + name +} + /// Dialog defaults for `id` (`None` for unknown effects). pub fn default_params(id: &str) -> Option { match catalog_index().get(id) { diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index c474cfae85..12754ce6b6 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -1172,6 +1172,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() { assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn"); } +/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where +/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it +/// back. +#[test] +fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + let n = steps(&s); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + assert_eq!(steps(&s), n + 1, "one undo step"); + let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(); + let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6) + }; + assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a)); + assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b)); + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap(); + assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2)); + assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too"); +} + +/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the +/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected. +#[test] +fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() { + let mut s = session(); + line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false); + select(&mut s, &[other]); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index)); + let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") }; + assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}"); +} + fn ids(v: &Value) -> Vec { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index f29e2e3745..25d7d38321 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption } } +/// The effect an apply request names, including the older `id` parameter. +pub(crate) fn requested_effect(p: &Value) -> Option<&str> { + str_param(p, "effect").or_else(|| str_param(p, "id")) +} + /// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the -/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one; -/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. +/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one. +/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.apply"; - let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?; + let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?; // An effect given as `id` names no objects: the targets are read with that `id` as null. let effect_as_id; let p = if str_param(p, "effect").is_none() { diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 64ce29e337..e88f348085 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -34,7 +34,8 @@ //! plays. A key a schema doesn't name passes there too, and the values of the parameters it names //! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` -//! themselves ([`check_effect_color`], [`check_effect_channel`]). +//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown +//! shadow or glow blend mode, which the effect draws as Normal. use std::collections::HashMap; use std::sync::OnceLock; @@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> { /// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the /// effect takes (those of its dialog defaults and of its params description), each of the type /// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`]) -/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range +/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or +/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range /// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its /// manifest, and an unknown effect is the command's to report. pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { @@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) { return Err(unknown(id, key, &keys)); } + check_effect_blend(id, effect, params)?; check_effect_types(id, effect, params)?; // An SVG filter's XML is one drawable element. if effect == vectorcraft_render::effects::SVG_FILTER @@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", ")))) } +/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was +/// given it: a parameter error naming the blend modes unless the effect reads it as one +/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal. +fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects; + let key = "mode"; + let Some(v) = params.get(key) else { return Ok(()) }; + if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() { + return Ok(()); + } + let modes: Vec = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect(); + Err(bad(id, format!("`{key}` must be one of {}", modes.join(", ")))) +} + /// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id` /// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's /// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they @@ -1067,7 +1084,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = - (id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params")) + (id, super::effectcmd::requested_effect(params), params.get("params")) { check_effect_params(id, effect, given)?; } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 965abf399c..be4615bb43 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1069,6 +1069,12 @@ impl Session { self.tool.wants_samples() } + /// Does a stroke the active tool draws now vary with an airbrush pen's finger wheel + /// ([`vectorcraft_tools::Tool::reads_wheel`])? False with no document open. + pub fn tool_reads_wheel(&mut self, view: ViewInfo) -> bool { + self.with_tool_cx(view, |t, cx| t.reads_wheel(cx)) + } + /// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input /// held until an edit it computes is applied, or are requests for the UI left from making it? pub fn tool_waiting(&self) -> bool { diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index cb364167a2..fb30bf3c5c 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -263,6 +263,56 @@ fn a_tone_curve_channel_it_does_not_have_is_refused() { assert_eq!(back.layers[0].children().unwrap()[0].appearance.effects[0].params["channel"], json!("alpha")); } +/// A Drop Shadow's or glow's `mode` that names no blend mode (which it drew as Normal) is refused +/// in new calls to `effect.apply`, `appearance.addEffect` and `effect.setParams`, with the modes it +/// takes, and the document and its undo history stay as they were. Blend-mode names in any +/// spelling pass, an omitted `mode` keeps the default, and an older saved step still plays. +#[test] +fn a_shadow_or_glow_mode_that_is_no_blend_mode_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"opacity": 50}})).unwrap(); + let state = |s: &Session| { + let st = s.active().unwrap(); + (st.doc.clone(), st.history.undo.len()) + }; + let before = state(&s); + let why = "`mode` must be one of normal, darken, multiply, colorBurn"; + for bad in [json!("multipy"), json!(""), json!("passThrough"), json!(null), json!(["multiply"]), json!(1), json!(false)] { + for (cmd, params) in [ + ("effect.setParams", json!({"index": 0, "params": {"mode": bad}})), + ("effect.apply", json!({"effect": "stylize.innerGlow", "params": {"mode": bad}})), + ("effect.apply", json!({"effect": null, "id": "stylize.dropShadow", "ids": [id], "params": {"mode": bad}})), + ("appearance.addEffect", json!({"effect": "stylize.outerGlow", "params": {"mode": bad}})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{cmd} {params}: {e}"); + let checked = s.check_params(cmd, ¶ms).unwrap_err().to_string(); + assert!(checked.contains(why), "{cmd} {params}: {checked}"); + assert!(state(&s) == before, "{cmd} {params} changed the document or its undo history"); + } + } + let effect = |s: &Session| s.active().unwrap().doc.layers[0].children().unwrap()[0].appearance.effects[0].clone(); + let shadow = effect(&s); + let drawn = vectorcraft_render::effects::merged_params(&shadow.id, &shadow.params); + assert_eq!(drawn["mode"], json!("multiply"), "an omitted mode keeps the default"); + for good in ["screen", "Color Burn", "color-burn", "COlor!!Burn#", "softLight", "LUMINOSITY"] { + let params = json!({"index": 0, "params": {"mode": good}}); + s.check_params("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + s.execute("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + assert_eq!(effect(&s).params["mode"], json!(good)); + } + s.replay("effect.setParams", &json!({"index": 0, "params": {"mode": "multipy"}})).unwrap(); + assert_eq!(effect(&s).params["mode"], json!("multipy")); + assert_eq!(vectorcraft_render::effects::blend_mode("multipy"), vectorcraft_color::BlendMode::Normal); + for mode in vectorcraft_color::BlendMode::ALL { + let id = vectorcraft_render::effects::blend_mode_id(mode); + assert_eq!(vectorcraft_render::effects::parse_blend_mode(&id), Some(mode)); + assert_eq!(vectorcraft_render::effects::blend_mode(&id), mode); + } +} + /// What a command adds to its own journal entry passes the check, so a recorded journal can be /// sent back through the control channel or MCP. #[test] diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..ab2c480c4b 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -140,7 +140,7 @@ enum Job { /// What happens when the running job's call ends. enum Then { /// The result resolves this promise, and an exception rejects it. - Settle(ObjId), + Settle(ObjId, Option), /// An exception rejects through this resolving record. Reject(ObjId), /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or @@ -214,7 +214,11 @@ impl Promises { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); roots.values.extend(self.completion.iter()); match &self.running { - Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Settle(o, site)) => { + roots.objects.push(*o); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Some(Then::Reject(o)) => roots.objects.push(*o), Some(Then::Finally { derived, value, .. }) => { roots.objects.push(*derived); roots.values.push(value); @@ -662,7 +666,7 @@ impl Interp { interp.temp_roots.extend([handler, argument.clone()]); (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws }) } - None => (handler, Value::Undefined, vec![argument], Then::Settle(derived)), + None => (handler, Value::Undefined, vec![argument], Then::Settle(derived, site)), } } Job::Thenable { promise, thenable, then } => { @@ -689,8 +693,8 @@ impl Interp { let site = if r.is_err() { caught(self) } else { None }; let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) }; match (then, r) { - (Then::Settle(d), Ok(v)) => resolve_promise(self, d, v), - (Then::Settle(d), Err(e)) => reject_promise(self, d, e, site), + (Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v), + (Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site), (Then::Reject(_), Ok(_)) => Ok(()), (Then::Reject(rec), Err(e)) => scoped(self, |interp| { root(interp, &Value::Object(rec)); @@ -731,6 +735,7 @@ impl Interp { pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { let rejected = std::mem::take(&mut self.promises.rejected); let mut out = Vec::new(); + let mut attribution = Vec::new(); let mut count = 0; for p in rejected { let (reason, site) = match self.heap.object(p).map(|o| &o.class) { @@ -748,7 +753,17 @@ impl Interp { message.truncate(cut); message.push('…'); } - let authored = self.thrown_by_script(&reason); + let authored = if let Some(object) = reason.as_object() { + if let Some((_, authored)) = attribution.iter().find(|(seen, _)| *seen == object) { + *authored + } else { + let authored = self.thrown_by_script(&reason); + attribution.push((object, authored)); + authored + } + } else { + self.thrown_by_script(&reason) + }; let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc))); out.push(crate::Rejection { message, line, column, tag, authored }); } @@ -796,7 +811,10 @@ fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// A promise's reject function (section 25.6.1.3.1). fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?; - let site = here(interp); + let site = here(interp).or_else(|| match &interp.promises.running { + Some(Then::Settle(_, site)) => site.clone(), + _ => None, + }); reject_through(interp, rec, arg(args, 1), site)?; Ok(Value::Undefined) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index c2b707e3c6..6a57041cfe 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2830,9 +2830,12 @@ impl Interp { return Err(self.type_error("apply was called on a value that is not a function")); } let list = args.get(1).cloned().unwrap_or(Value::Undefined); + let mut roots = vec![f.clone(), this.clone()]; + roots.extend(args.iter().cloned()); + let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?; f = this; this = args.first().cloned().unwrap_or(Value::Undefined); - args = self.list_from_array_like(&list)?; + args = expanded; } Func::Bound { target, this: bound_this, args: bound_args } => { self.use_fuel()?; diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 586ae77e24..a300d22451 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -613,6 +613,26 @@ fn apply_keeps_its_arguments_alive_while_a_native_function_runs() { assert_eq!(realm.run(src), Ok(JsValue::Number(42.0))); } +#[test] +fn successive_apply_expansions_keep_getter_receivers_alive() { + for queued in [false, true] { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 1 << 20, ..Limits::default() }); + let src = "var result; function callback(a) { result = this.kept + a; } \ + var inner = {length: 1, get 0() { for (var i = 0; i < 20000; i++) ({i: i}); return 2; }}; \ + var outer = {length: 2, get 0() { return {kept: 40}; }, get 1() { return inner; }};"; + realm.run(src).unwrap(); + let collections = realm.interp().heap.collections; + let call = if queued { + "Promise.resolve(outer).then(Function.prototype.apply.bind(Function.prototype.apply, callback));" + } else { + "Function.prototype.apply.apply(callback, outer);" + }; + realm.run(call).unwrap(); + assert!(realm.interp().heap.collections > collections); + assert_eq!(realm.run("result"), Ok(JsValue::Number(42.0)), "queued: {queued}"); + } +} + #[test] fn to_number_skips_the_white_space_the_lexer_skips() { let mut realm = small(Limits::default()); diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 915427de89..ef0ed1d0d1 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -226,6 +226,30 @@ fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { assert_eq!(got, want); } +#[test] +fn combinator_rejection_relays_keep_the_input_location() { + for method in ["all", "race"] { + let mut r = realm(); + r.run(&format!("var input =\n Promise.reject('lost');\nPromise.{method}([input]);")).unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 1, "{method}: {reported:?}"); + assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]); + assert!(reported[0].column > 0); + assert_eq!(reported[0].tag, r.script_tag()); + } + let mut r = realm(); + r.run("var reject; new Promise(function (_, no) { reject = no; });\nPromise.reject('handled').catch(function () {\n reject('lost');\n});") + .unwrap(); + assert_eq!(r.unhandled_rejections().len(), 1); + assert_eq!(r.unhandled_rejections()[0].line, 3); + assert!(r.unhandled_rejections()[0].column > 0); + let mut r = realm(); + r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 2); + assert!(reported.iter().all(|r| r.tag == UNKNOWN_SOURCE), "{reported:?}"); +} + #[test] fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() { let mut r = realm(); diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index a4d9fda7af..ecba138052 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -112,9 +112,7 @@ pub(crate) fn holds_instance(n: &Node) -> bool { /// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its /// symbol is being edited from? pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool { - let view_item = a.is_ruler_guide() - || (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) - || (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); + let view_item = a.is_ruler_guide() || a.hidden_by_view(opts.skip_templates || opts.hide_templates, opts.skip_templates || opts.hide_guides); !a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id) } diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index c04ce6b22c..845379311d 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -15,19 +15,23 @@ //! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either -//! segment's shape differs from the one they were found on. +//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at +//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the +//! segments the circle touches get an anchor point at each touch, which splits them without changing +//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. //! //! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`; -//! `center` and `radii` show or hide the circle's center cross and the lines from its center to the +//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the //! two points it touches; `color` is the color of the circle, the cross, those lines and the note //! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment //! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger, //! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked //! within the selection tolerance, as a click on a path picks it, and that is also the least reach -//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default the -//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on. +//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default +//! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and +//! `snapWithoutGuides` is on. -use kurbo::{CubicBez, Shape}; +use kurbo::{CubicBez, ParamCurveNearest, Shape}; use serde_json::{Value, json}; use vectorcraft_doc::NodeId; use vectorcraft_geom::{BezPath, ParamCurve, Point}; @@ -52,6 +56,12 @@ pub const NO_CIRCLE: &str = "No tangent circle here"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +/// The label of the `addPoints` option in the tool's options. +pub const ADD_POINTS: &str = "Add Points to Existing Paths"; +/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in +/// effect, and its size. +const DOT_PX: f64 = 10.0; +const DOT_SIZE: f32 = 4.0; /// The colors the `color` option takes, by option value, with the color the circle, its center /// cross, its radii and the note are drawn in. Red is the first. pub const COLORS: &[(&str, [u8; 3])] = &[ @@ -67,7 +77,7 @@ pub const SNAP_PX: f64 = 3.0; /// The snapping tolerance the `snapTolerance` option takes (screen pixels). pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0); /// The option keys that are true or false. -const SWITCHES: &[&str] = &["center", "radii", "snapWithoutGuides"]; +const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"]; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -101,6 +111,11 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether drawing a circle adds anchor points where it touches the segments. + add_points: bool, + /// The keys held at the last pointer event, and whether the pointer is over the canvas. + mods: Mods, + over: bool, /// Whether the preview shows the center cross and the radii. center: bool, radii: bool, @@ -130,6 +145,9 @@ impl Default for TangentCircleTool { fn default() -> Self { Self { radius: RADIUS, + add_points: false, + mods: Mods::default(), + over: false, center: true, radii: true, color: 0, @@ -189,6 +207,11 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { + second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect() +} + +/// [`second_set`] with each segment's index on the second pick's subpath. +fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> { if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { return vec![]; } @@ -205,7 +228,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { indices.sort_unstable(); indices.dedup(); let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; - indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() + indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect() +} + +/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either +/// end, where the segment already has an anchor point. +fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option { + if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol { + return None; + } + let t = curve.nearest(p, 1e-12).t; + (t > 0.0 && t < 1.0).then_some(t) +} + +/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment +/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath +/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the +/// anchor added before it does not move it along. +fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec { + let mut at: Vec<(NodeId, usize, usize, f64)> = vec![]; + if let Some(t) = split_at(&first.curve, c.first, tol) { + at.push((first.id, first.subpath, first.segment, t)); + } + let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq)); + if let Some((k, curve)) = nearest + && let Some(t) = split_at(curve, c.second, tol) + { + at.push((pick.id, pick.subpath, *k, t)); + } + at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2))); + at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect() } /// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot @@ -242,6 +294,14 @@ fn round_step(least: f64) -> f64 { /// distance from the origin, or too large, in floating point), or when the circle would reach past /// the canvas ([`crate::circle::circle_of`]), which the command refuses. fn draw(c: &SegmentCircle, tol: f64) -> Option { + circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p)) +} + +/// The command [`draw`] runs. +const CIRCLE: &str = "shape.circleThroughPoints"; + +/// The params of the [`CIRCLE`] command that [`draw`] runs. +fn circle_params(c: &SegmentCircle, tol: f64) -> Option { let (at, r) = (c.circle.center, c.circle.radius); let points: Vec = [90.0f64, 210.0, 330.0] .iter() @@ -255,7 +315,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option { return None; } let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect(); - Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points }))) + Some(json!({ "points": points })) } fn segment_path(c: &CubicBez) -> BezPath { @@ -391,6 +451,8 @@ impl Tool for TangentCircleTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.pointer = ev.pos; + self.mods = ev.mods; + self.over = true; match ev.kind { PointerKind::Move => { self.hover = pick_at(cx, ev.pos, self.reach(cx)); @@ -424,15 +486,34 @@ impl Tool for TangentCircleTool { // The release's own position and keys set the radius of a drag. self.drag_to(cx, ev); self.picking = false; - if self.press.take().is_none() { - return vec![]; - } + let Some(press) = self.press.take() else { return vec![] }; // No circle, or one the three points cannot draw: the first segment stays picked, // for another try. It also stays when the command fails: only a drawn circle tells // the tool (`notify`) to forget it. - let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + let Some(c) = self.found.take() else { return vec![] }; + let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] }; self.looked = false; - vec![action, Action::Notify(DRAWN.into())] + // Alt at the release turns `addPoints` the other way. + let steps = match &self.first { + Some(first) if self.add_points != ev.mods.alt => { + let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] }; + anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX)) + } + _ => vec![], + }; + if steps.is_empty() { + return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())]; + } + let mut commands = steps; + // A path that was not selected becomes the selection when it gets an anchor; the + // selection is put back before the circle, which Draw Behind places behind it. + if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) { + let ids: Vec = cx.selection.objects.iter().map(|id| id.0).collect(); + commands.push(json!({ "command": "select.set", "params": { "ids": ids } })); + } + commands.push(json!({ "command": CIRCLE, "params": params })); + // One undo step for the anchors and the circle, and none of them when a step fails. + vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())] } // The canvas sends a double-click after the second click's `Up`, which drew the circle. PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -483,6 +564,7 @@ impl Tool for TangentCircleTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.over = false; if self.press.is_none() { self.found = None; self.looked = false; @@ -525,6 +607,11 @@ impl Tool for TangentCircleTool { // A label, which the canvas shows in the interface language. out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color }); } + // `addPoints` in effect, with Alt as it is now. + if (self.over || self.press.is_some()) && self.add_points != self.mods.alt { + let off = cx.tol(DOT_PX); + out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE }); + } out } @@ -535,6 +622,7 @@ impl Tool for TangentCircleTool { fn options(&self) -> Value { json!({ "radius": self.radius, + "addPoints": self.add_points, "center": self.center, "radii": self.radii, "color": COLORS.get(self.color).map_or("red", |(name, _)| *name), @@ -550,6 +638,7 @@ impl Tool for TangentCircleTool { } match key { "radius" => self.radius = v.as_f64().unwrap_or(self.radius), + "addPoints" => self.add_points = v.as_bool().unwrap_or(self.add_points), "center" => self.center = v.as_bool().unwrap_or(self.center), "radii" => self.radii = v.as_bool().unwrap_or(self.radii), "color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color), @@ -1059,6 +1148,144 @@ mod tests { assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); } + /// The steps of the `command.batch` an action list runs: (command, params) each. + fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> { + let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") }; + assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN)); + p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect() + } + + /// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment. + fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) { + let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap()); + let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize]; + (id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap())) + } + + fn alt(mut e: PointerEvent) -> PointerEvent { + e.mods.alt = true; + e + } + + #[test] + fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y), cx.pick_tol()).map(|p| p.id.0).unwrap(); + let (top, below) = (line_at(100.0), line_at(140.0)); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + assert_eq!(t.options()["addPoints"], json!(true)); + // The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter + // along each line, then the circle, in one batch. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}"); + let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + anchors.sort_by_key(|a| a.0); + let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))]; + want.sort_by_key(|a| a.0); + assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}"); + // The lines were not selected, so the selection (none) is put back before the circle. + assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}"); + let (cmd, params) = &steps[3]; + let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]); + assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}"); + assert!(t.first.is_none(), "ready for the next circle"); + // With both lines selected, the anchors leave the selection as it is: no step puts it back. + let mut both = Selection::default(); + both.add(NodeId(top)); + both.add(NodeId(below)); + let selected = self::cx(&d, &both, &p); + t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0))); + assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}"); + // Alt at the release turns it off for that circle, and with the option off turns it on. + for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] { + t.set_option("addPoints", &json!(on)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0))); + let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) }; + let released = up(&mut t, &cx, &release); + if adds { + assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}"); + } else { + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}"); + } + } + } + + #[test] + fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + t.set_option("radius", &json!(10)); + // The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310) + // on its second: the second segment's anchor comes first, so the first one's index holds. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + let l = pick_at(&cx, Point::new(300.0, 350.0), cx.pick_tol()).map(|p| p.id.0); + let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))]; + assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}"); + assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE)); + // A circle touching both lines at their right ends: no anchor is added on top of an anchor, + // so only the circle is drawn, as without the option. + t.set_option("radius", &json!(36)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0)); + assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!(t.options()["addPoints"], json!(false), "off to start"); + let dot = + |t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(!dot(&t)); + // Alt turns it on while held, and back off with the option on. + t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0))); + assert!(dot(&t)); + t.set_option("addPoints", &json!(true)); + assert!(!dot(&t)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(dot(&t)); + let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else { + panic!("no dot") + }; + assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}"); + // The pointer off the canvas: no dot left behind. + t.hover_ended(&cx); + assert!(!dot(&t)); + for bad in [json!(1), json!("true"), Value::Null] { + assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}"); + t.set_option("addPoints", &bad); + assert_eq!(t.options()["addPoints"], json!(true), "{bad}"); + } + assert_eq!(t.check_option("addPoints", &json!(false)), Ok(())); + } + #[test] fn a_circle_that_would_reach_past_the_canvas_is_not_offered() { // Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 6bbdc737d2..ede52c46c7 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1882,6 +1882,11 @@ impl Tool for GestureTool { fn wants_samples(&self) -> bool { matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser") } + /// The Blob Brush's and the Eraser's tip varies with the wheel when a value is on Stylus Wheel + /// with a Variation above 0. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + self.tip_modes().contains(&Variation::StylusWheel) + } /// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again /// after a zoom change, reach the whole drag over several frames. fn overlays_pending(&self) -> bool { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index db755ccae5..c8aa002add 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -4129,3 +4129,26 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil")); assert_eq!(last[1], Action::Commit); } + +#[test] +fn a_tip_reads_the_wheel_only_with_a_value_on_stylus_wheel() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + for id in ["pencil", "paintbrush", "blobBrush", "eraser"] { + assert!(!GestureTool::new(id).reads_wheel(&cx), "{id} at its defaults"); + } + for value in ["angle", "roundness", "size"] { + let mut t = GestureTool::new("eraser"); + t.set_option(&format!("{value}Mode"), &json!("stylusWheel")); + assert!(!t.reads_wheel(&cx), "{value} on Stylus Wheel with no Variation"); + t.set_option(&format!("{value}Variation"), &json!(4)); + assert!(t.reads_wheel(&cx), "{value} on Stylus Wheel"); + t.set_option(&format!("{value}Mode"), &json!("pressure")); + assert!(!t.reads_wheel(&cx), "{value} on Pressure"); + } + let mut t = GestureTool::new("blobBrush"); + t.set_option("sizeMode", &json!("stylusWheel")); + t.set_option("sizeVariation", &json!(4)); + assert!(t.reads_wheel(&cx), "the Blob Brush's size on Stylus Wheel"); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index acc5ff594e..ec2b83f1a6 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -319,6 +319,12 @@ pub trait Tool: Send { fn wants_samples(&self) -> bool { false } + /// Does a stroke the tool draws now vary with an airbrush pen's finger wheel (a brush or tip + /// with Stylus Wheel variation)? A host that has to open a tablet interface of its own to read + /// the wheel opens it only while this is so. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + false + } /// Is the tool waiting for work it runs on another thread (the planar map of a large selection /// for the Shape Builder and the Live Paint Bucket, a Shape Builder merge of one)? It /// highlights nothing under the pointer until a map is done. While this holds, the desktop app diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97b3c75cd2..185450a1ca 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -108,7 +108,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 165ced795e..9d6fe2e887 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -438,6 +438,20 @@ impl Tool for BrushPaintTool { fn wants_samples(&self) -> bool { self.inner.wants_samples() } + /// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus + /// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values + /// differ, or an Art brush whose width is on it with two different widths. + fn reads_wheel(&self, cx: &ToolContext) -> bool { + use vectorcraft_brush::{BrushKind, Variation}; + let wheel = |mode: Variation| mode == Variation::StylusWheel; + let Some(brush) = self.brush_name(cx).and_then(|n| vectorcraft_brush::find(cx.doc, &n)) else { return false }; + match brush.kind { + BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0), + BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b), + BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1, + BrushKind::Pattern(_) | BrushKind::Bristle(_) => false, + } + } fn busy(&self) -> bool { self.inner.busy() } @@ -758,4 +772,52 @@ mod tests { let a = drag(&d, &mut BrushPaintTool::default()); assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}"); } + + #[test] + fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation}; + let wheel = Variation::StylusWheel; + let calligraphic = + |modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() }); + let scatter = |size| { + BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() }) + }; + let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() }); + let library = [ + Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) }, + Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) }, + Brush { name: "Still nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 0.0) }, + Brush { name: "Dots".into(), kind: scatter((50.0, 150.0)) }, + Brush { name: "Even dots".into(), kind: scatter((100.0, 100.0)) }, + Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) }, + Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) }, + Brush { name: "Flat".into(), kind: art(None, 200.0) }, + ]; + let (mut d, _) = doc_with_rect(); + d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap()); + let (s, p) = (Selection::default(), paint()); + let reads = |d: &vectorcraft_doc::Document, t: &BrushPaintTool| t.reads_wheel(&cx(d, &s, &p)); + let mut t = BrushPaintTool::default(); + assert!(!reads(&d, &t), "no brush"); + let brushes = [ + ("Plain", false), + ("Nib", true), + ("Still nib", false), + ("Dots", true), + ("Even dots", false), + ("Taper", true), + ("Even taper", false), + ("Flat", false), + ("Deleted", false), + ]; + for (name, varies) in brushes { + d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!(name)); + assert_eq!(reads(&d, &t), varies, "the current brush {name}"); + } + t.set_option("brush", &json!("Plain")); + assert!(!reads(&d, &t), "the tool's own brush comes first"); + t.set_option("brush", &json!("Nib")); + d.unknown.remove(vectorcraft_brush::CURRENT_KEY); + assert!(reads(&d, &t), "and reads the wheel"); + } } diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 8765b57c00..1914b37a36 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -307,6 +307,7 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec { let snap = ParamKind::number(Some(snap_lo), Some(snap_hi), tangent_circle_tool::SNAP_PX, 1.0, 2); return vec![ Param::new("radius", tl!("Radius"), kind).length(lengths), + Param::new("addPoints", tl!(tangent_circle_tool::ADD_POINTS), ParamKind::bool(false)), Param::new("center", tl!("Circle Center"), ParamKind::bool(true)), Param::new("radii", tl!("Circle Radii Lines"), ParamKind::bool(true)), Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))), diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 3c7af267e9..df2571a136 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -84,11 +84,18 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("straight")); ok(&mut app, &[("mode", FieldValue::Text("arc".into()))]); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); - // The Tangent Circle tool's radius for Shift. + // The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start). app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); - assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("radius")), Some(36.0)); - ok(&mut app, &[("radius", FieldValue::Number(12.5))]); + let shown = held(&app, |d| { + let f = d.expect("the held dialog").fields(); + (f.number("radius"), f.bool("addPoints")) + }); + assert_eq!(shown, (Some(36.0), Some(false))); + let rows = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app)); + assert!(rows.iter().any(|p| p.key == "addPoints" && p.label.as_str() == "Add Points to Existing Paths"), "the option has a row"); + ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true))]); assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); + assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true)); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); assert_eq!(KIND, "pathToolOptions"); } @@ -150,6 +157,7 @@ fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() { rows, [ ("radius", "Radius"), + ("addPoints", "Add Points to Existing Paths"), ("center", "Circle Center"), ("radii", "Circle Radii Lines"), ("color", "Color"), diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 89d64872e8..00a8b9cd61 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -232,6 +232,7 @@ impl VectorcraftApp { shortcuts_dialog: None, shortcut_overrides: Default::default(), told: Default::default(), + missing_font_edit_token: None, held: Default::default(), edit_scopes: Default::default(), command_dialog: Default::default(), @@ -445,6 +446,11 @@ impl VectorcraftApp { let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // With no document open too, so closing the last one stops the host reading the wheel. A + // held press, whose previews change the document each frame, keeps what it was told. + if self.canvas.grab.is_none() { + crate::stylus::sync_wheel_use(self); + } // A document that moved between the main window and a floating OS window, or opened, takes // the density of the display that shows it. self.settle_screen_ppi_if_changed(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a4f97d7f6e..d13d79e4b9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -9,6 +9,7 @@ use craft::ui::canvas::{ canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::primitives::PaintSlot; use craft::ui::runtime::env::Env; use craft::ui::runtime::focus::NudgeMods; use craft::ui::style::StyleCx; @@ -277,7 +278,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } -/// The body of the canvas in order: controls that take presses first, the tool host, the picture last. +/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the +/// picture last. fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; @@ -297,7 +299,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); - selection::show(app, ui, space, win, kind); + // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this + // frame's pointer event, from the document as the event leaves it. + let marks = PaintSlot::reserve(ui.painter()); widgets::show(app, ui, space, win, kind); if !presenting && !revolve_editing(app) { crate::panels::three_d::handles::show(app, ui, space); @@ -334,6 +338,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::type_editing::show(app, ui); } } + let after = PaintSlot::reserve(ui.painter()); + selection::show(app, ui, space, win, kind); + marks.extend(ui.ctx(), after.take_after(ui.ctx())); drops::show(app, ui, win, kind); raster::picture(app, ui, space, win, kind); out diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 50ab4ed40a..03b8e4da67 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,12 +8,36 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } +/// What the view hides among a selected object's members, which the selection marks leave out as +/// the canvas does ([`Node::hidden_by_view`]): template layers while View › Hide Template is on, +/// and paths made into guides while the guides are hidden. The default hides nothing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ViewHides { + pub(super) templates: bool, + pub(super) guides: bool, +} + +impl ViewHides { + /// What `app`'s view hides. + pub(super) fn of(app: &VectorcraftApp) -> Self { + Self { templates: !app.ui.view.templates, guides: !app.ui.view.guides_shown() } + } + + /// [`Node::drawn_children`] of `n` without the members the view leaves out. Every path of a + /// compound path stays, since the compound path draws all of them, guides or not. + fn children(self, n: &Node) -> impl Iterator> { + let hide_guides = self.guides && !matches!(n.kind, NodeKind::Compound { .. }); + n.drawn_children().filter(move |c| !c.hidden_by_view(self.templates, hide_guides)) + } +} + /// Outline of a node for highlighting (paths, compound children, area type frames, image bounds, /// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures -/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it). -pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { +/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it, +/// without the members `hides` leaves out). +pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Path { path, .. } => bp.extend(path.to_bezpath()), // Area type shows its frame: the type area Direct Selection reshapes; type on a path its // path, which the selection tools' brackets sit on; point type shows its baseline(s). @@ -31,9 +55,10 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { corners(&mut bp, q); } } + // An image shows its frame, turned or distorted with it. NodeKind::Image(_) => { - if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + if let Some(frame) = c.image_frame() { + bp.extend(frame); } } // A symbol instance shows its art's box, turned, skewed or in perspective with it. @@ -62,6 +87,38 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Whether `n` is a linked image or a placed document, which the selection marks cross. +fn is_linked(n: &Node) -> bool { + match &n.kind { + NodeKind::Image(im) => im.link.is_some(), + NodeKind::PlacedDocument(_) => true, + _ => false, + } +} + +/// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, +/// from corner to corner of its frame or box (#9080), without the members `hides` leaves out. The +/// selection marks draw them; the hover highlight does not. +pub(super) fn linked_crosses(n: &Node, hides: ViewHides) -> BezPath { + let mut bp = BezPath::new(); + walk_drawn(n, hides, &mut |c| match &c.kind { + NodeKind::Image(_) if is_linked(c) => { + if let Some(cross) = c.image_cross() { + bp.extend(cross); + } + } + NodeKind::PlacedDocument(p) => { + let [tl, tr, br, bl] = p.corners(); + bp.move_to(tl); + bp.line_to(br); + bp.move_to(tr); + bp.line_to(bl); + } + _ => {} + }); + bp +} + /// Adds the closed outline through the four corners `q` to `bp`. fn corners(bp: &mut BezPath, q: [Point; 4]) { let [a, b, c, d] = q; @@ -77,22 +134,36 @@ fn corners(bp: &mut BezPath, q: [Point; 4]) { /// #2460). pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; -/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; -/// counting stops there). -pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - fn over(n: &Node, left: &mut usize) -> bool { - match left.checked_sub(overlay_points(n)) { +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`], +/// without the members `hides` leaves out; counting stops there). +pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, false, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them +/// without the members `hides` leaves out. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, true, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the +/// ends of the crossing lines when `crosses`) in what [`walk_drawn`] visits; counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool, hides: ViewHides) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool, hides: ViewHides) -> bool { + let ends = if crosses && is_linked(n) { 4 } else { 0 }; + match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, None => return true, } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses, hides)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left)) + !matches!(n.kind, NodeKind::Envelope { .. }) && hides.children(n).any(|c| over(c, left, crosses, hides)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left)) + nodes.into_iter().any(|n| over(n, &mut left, crosses, hides)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a @@ -120,21 +191,22 @@ fn overlay_points(n: &Node) -> usize { } /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the -/// envelope shows its mesh instead), and a clip group or clipping layer shows only its clipping -/// path, its first child, not the art the path clips (#2422). -pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { +/// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, +/// its first child, not the art the path clips (#2422), and hidden members +/// ([`Node::drawn_children`]) and the members `hides` leaves out are left out. +pub(super) fn walk_drawn<'a>(n: &'a Node, hides: ViewHides, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { return; } if n.clips() { if let Some(clip) = n.children().and_then(|children| children.first()) { - walk_drawn(clip, f); + walk_drawn(clip, hides, f); } return; } - for c in n.editing_children().iter() { - walk_drawn(c, f); + for c in hides.children(n) { + walk_drawn(c, hides, f); } } diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 0ed7de10cd..4ea015bac6 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -798,6 +798,69 @@ fn other_panes_draw_their_guides_and_selected_objects() { assert!(!crate::canvas::selection::outlines(&app, st).is_empty(), "the selected rectangle is outlined in its pane"); } +/// Another pane crosses a selected linked image from corner to corner, as the current pane does, and outlines a +/// selected embedded image alone (#9080). +#[test] +fn other_panes_cross_a_selected_linked_image() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir("panes-linked-image").join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut place = |link: bool, at: [f64; 2]| { + app.session.execute("file.place", &json!({"path": png, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (linked, embedded) = (place(true, [100.0, 100.0]), place(false, [250.0, 100.0])); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // How many paths the first document's pane outlines with `id` selected there. + let mut paths = |id: u64| { + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(&app, st).iter().map(|o| o.paths.len()).sum::() + }; + let (linked, embedded) = (paths(linked), paths(embedded)); + assert_eq!((linked, embedded), (2, 1), "the outline of a linked image and its crossing lines; an embedded image's outline alone"); +} + +/// Another pane outlines a selected group's visible members only: hiding a member draws the same outlines as deleting +/// it. +#[test] +fn other_panes_leave_out_a_selected_groups_hidden_members() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let id = |made: serde_json::Value| made["id"].as_u64().unwrap(); + let shown = id(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80})).unwrap()); + let hidden = id(app.run("shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60})).unwrap()); + app.run("select.set", json!({"ids": [shown, hidden]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // The paths the first document's pane outlines with the group selected there, after the commands `edit` there. + let outlines = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + app.run("document.activate", json!({"index": 0})).unwrap(); + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(app, &ctx, vec![]); + frame(app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect::>() + }; + let both = outlines(&mut app, &[]); + let without = outlines(&mut app, &[("select.set", json!({"ids": [hidden]})), ("edit.clear", json!({}))]); + let with_hidden = outlines(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the outlines show both members"); + assert_eq!(with_hidden, without, "a hidden member is not outlined"); +} + #[test] fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let mut app = app_with(2); diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 96be3fcc89..c8e0dd5212 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -24,7 +24,7 @@ use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; -use super::outline::{c32, node_outline, selection_hit_at, too_many_anchors, walk_drawn}; +use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). @@ -147,9 +147,9 @@ fn hidden(app: &VectorcraftApp) -> bool { crate::dialogs::halftone::previewing(app) } -/// Whether the selection has too many points to outline: its bounds stand for it. -fn too_big(st: &DocState) -> bool { - too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id))) +/// Whether the selection has too many points to outline and cross in `app`'s view: its bounds stand for it. +fn too_big(app: &VectorcraftApp, st: &DocState) -> bool { + too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)), ViewHides::of(app)) } /// The rectangle of `bounds` as a path. @@ -166,17 +166,17 @@ fn group(out: &mut Vec, color: Color32) -> &mut Outlined { &mut out[at] } -/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline (the bounds of -/// all of them when they have too many points), the spine of each selected blend, and the key object's outline (its +/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline and the lines +/// across its linked images and placed documents (the bounds of all of them when they have too many points), the spine of each selected blend, and the key object's outline (its /// bounds when it has too many points). Nothing during Halftone Preview. pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { let mut out: Vec = vec![]; if hidden(app) { return out; } - let (sel, symbols) = (&st.selection, st.doc.symbol_boxes()); + let (sel, symbols, hides) = (&st.selection, st.doc.symbol_boxes(), ViewHides::of(app)); let color_of = |id: NodeId| c32(st.doc.layer_color(id)); - if too_big(st) { + if too_big(app, st) { // The cache is warmed by `show`; a test or a miss measures again. let bounds = match app.canvas.selection_bounds { Some((key, bounds)) if key == (st.uid, st.revision) => bounds, @@ -188,9 +188,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } else { for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; - let path = node_outline(node, &symbols); - if !path.elements().is_empty() { - group(&mut out, color_of(*id)).paths.push(path); + // Linked images and placed documents are also crossed from corner to corner. + for path in [node_outline(node, &symbols, hides), linked_crosses(node, hides)] { + if !path.elements().is_empty() { + group(&mut out, color_of(*id)).paths.push(path); + } } } for (blend, spine) in blend_spines(st) { @@ -198,7 +200,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } } if let Some((key, node)) = sel.key.and_then(|key| Some((key, st.doc.node(key)?))) { - let path = if too_many_anchors([node]) { node.geometric_bounds_with(&symbols).map(bounds_path) } else { Some(node_outline(node, &symbols)) }; + let path = if too_many_anchors([node], hides) { + node.geometric_bounds_with(&symbols).map(bounds_path) + } else { + Some(node_outline(node, &symbols, hides)) + }; if let Some(path) = path { group(&mut out, color_of(key)).key = Some(path); } @@ -266,10 +272,10 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin segment_mark: SegmentMark::Line, options: path_options(prefs), }; - if hidden(app) || too_big(st) || (curvature && tool_points) { + if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; } - let sel = &st.selection; + let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; @@ -277,7 +283,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let Some(node) = st.doc.node(*id) else { continue }; let partial = sel.partial(*id); let color = c32(st.doc.layer_color(*id)); - walk_drawn(node, &mut |c| { + walk_drawn(node, hides, &mut |c| { let envelope = vectorcraft_doc::live::envelope_overlay(c).and_then(|(_, grid)| grid); let grid = match &c.kind { NodeKind::Mesh(m) => Some(m), @@ -369,13 +375,14 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, if kept { return None; } - outline_of(st, id) + outline_of(st, id, ViewHides::of(app)) } -/// The hover outline of `id` in its layer colour, unless it has too many points. -fn outline_of(st: &DocState, id: NodeId) -> Option { - let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?; - Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) }) +/// The hover outline of `id` in its layer colour, without the members `hides` leaves out, unless it has too many +/// points. +fn outline_of(st: &DocState, id: NodeId, hides: ViewHides) -> Option { + let node = st.doc.node(id).filter(|n| !too_many_anchors([*n], hides))?; + Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes(), hides), color: c32(st.doc.layer_color(id)) }) } /// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view @@ -405,7 +412,7 @@ pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, } let info = app.view_info(); let id = eyedropper_hover_object(app, at, mods, info)?; - outline_of(app.session.active()?, id) + outline_of(app.session.active()?, id, ViewHides::of(app)) } /// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and @@ -495,7 +502,7 @@ fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view /// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor. pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots { let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() }; - if hidden(app) || too_big(st) { + if hidden(app) || too_big(app, st) { return out; } let symbols = st.doc.symbol_boxes(); diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 4f5e469a63..a2c32f5d53 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -243,7 +243,7 @@ fn the_key_object_has_its_own_outline() { let ids = app.session.active().unwrap().selection.objects.clone(); app.run("select.key", json!({"id": curve.0})).unwrap(); let st = app.session.active().unwrap(); - let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes()); + let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes(), ViewHides::default()); let color = c32(st.doc.layer_color(curve)); let out = outlines(&app, st); let key = out.iter().find(|o| o.color == color).and_then(|o| o.key.as_ref()).unwrap(); @@ -252,6 +252,298 @@ fn the_key_object_has_its_own_outline() { assert_eq!(out.iter().map(|o| o.paths.len()).sum::(), ids.len(), "the selection's own outlines stay"); } +/// A file with a 40 × 40 px red PNG in a new temporary folder named `name`. +fn red_png(name: &str) -> std::path::PathBuf { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir(name).join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + png +} + +/// The two lines from corner to corner of `[tl, tr, br, bl]`. +fn cross_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(br), PathEl::MoveTo(tr), PathEl::LineTo(bl)] +} + +/// The outline of `[tl, tr, br, bl]`: its corners joined by straight lines. +fn frame_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(tr), PathEl::LineTo(br), PathEl::LineTo(bl), PathEl::ClosePath] +} + +/// A selected linked image and a selected placed document are crossed from corner to corner, on a turned or +/// distorted image along its frame; a selected embedded image shows its outline alone, along its frame when turned or +/// distorted. The key object's outline and the hover outline are not crossed (#9080). +#[test] +fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { + let png = red_png("selection-linked"); + let placed = png.with_file_name("art.vectorcraft"); + std::fs::write(&placed, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(60.0, 40.0))).unwrap(); + let mut app = blank(); + let place = |app: &mut VectorcraftApp, path: &std::path::Path, link: bool, at: [f64; 2]| { + NodeId(app.run("file.place", json!({"path": path, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap()) + }; + let linked = place(&mut app, &png, true, [100.0, 120.0]); + let embedded = place(&mut app, &png, false, [300.0, 120.0]); + let document = place(&mut app, &placed, true, [200.0, 230.0]); + let corners = |app: &VectorcraftApp, id: NodeId| { + let n = app.session.active().unwrap().doc.node(id).unwrap(); + match &n.kind { + NodeKind::PlacedDocument(p) => p.corners(), + _ => n.image_corners().unwrap(), + } + }; + // Whether the selection's outlines hold a path made of `els`. + let drawn = |app: &VectorcraftApp, els: &[PathEl]| { + outlines(app, app.session.active().unwrap()).iter().any(|o| o.paths.iter().any(|p| p.elements() == els)) + }; + // Whether `id` is crossed, and whether it is outlined along its frame. + let marked = |app: &VectorcraftApp, id: NodeId| (drawn(app, &cross_of(corners(app, id))), drawn(app, &frame_of(corners(app, id)))); + app.run("select.all", json!({})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a linked image"); + assert!(drawn(&app, &cross_of(corners(&app, document))), "a placed document"); + assert_eq!(marked(&app, embedded), (false, true), "an embedded image"); + assert_eq!(outlines(&app, app.session.active().unwrap()).iter().map(|o| o.paths.len()).sum::(), 5, "three outlines and two crosses"); + app.run("select.set", json!({"ids": [linked.0, embedded.0]})).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a turned linked image, along its frame"); + assert_eq!(marked(&app, embedded), (false, true), "a turned embedded image, outlined along its frame"); + // Move each image's bottom right corner up its right side, so its corners no longer make a parallelogram. + app.session + .edit("Distort", |doc, _| { + for id in [linked, embedded] { + if let Some(n) = doc.node_mut(id) + && let Some([tl, tr, br, bl]) = n.image_corners() + { + n.set_image_corners([tl, tr, br.lerp(tr, 0.4), bl]).map_err(|e| vectorcraft_engine::EngineError::Other(format!("{e:?}")))?; + } + } + Ok(()) + }) + .unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!([linked, embedded].iter().all(|id| doc.node(*id).unwrap().is_distorted_image()), "both images are distorted"); + assert_eq!(marked(&app, linked), (true, true), "a distorted linked image, corner to corner"); + assert_eq!(marked(&app, embedded), (false, true), "a distorted embedded image, outlined along its frame"); + // The key object's outline is its frame alone, and so is the hover outline. + for id in [linked, embedded] { + app.run("select.key", json!({"id": id.0})).unwrap(); + let st = app.session.active().unwrap(); + let key = outlines(&app, st).into_iter().find_map(|o| o.key).unwrap(); + assert_eq!(key.elements(), frame_of(corners(&app, id)).as_slice(), "the key object's outline of {id:?}"); + assert_eq!( + outline_of(st, id, ViewHides::default()).unwrap().path.elements(), + frame_of(corners(&app, id)).as_slice(), + "the hover outline of {id:?}" + ); + } +} + +/// The selection's outlines count the ends of the lines that cross linked images toward the overlay's limit; the +/// hover outline and the key object's outline, which draw no such lines, do not (#9080). +#[test] +fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { + use super::super::outline::{too_many_anchors, too_many_marks}; + let image = |link: Option| { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + vectorcraft_doc::Node::new(NodeId(1), NodeKind::Image(Box::new(im))) + }; + // Four corners each fit; with the four ends of the crossing lines they do not. + let count = OVERLAY_MAX_ANCHORS / 6; + let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; + let embedded = vec![image(None); count]; + let all = ViewHides::default(); + assert!(!too_many_anchors(&linked, all) && too_many_marks(&linked, all), "linked images"); + assert!(!too_many_anchors(&embedded, all) && !too_many_marks(&embedded, all), "embedded images"); +} + +/// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member and a linked image +/// in a hidden group inside it leave no outline, anchors or crossing lines, in the selection's marks and in the hover +/// outline. Hiding them shows the same as deleting them. +#[test] +fn a_selected_group_leaves_its_hidden_members_unmarked() { + let png = red_png("selection-hidden"); + let mut app = blank(); + let left = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let right = id_of(&app.run("shape.rectangle", json!({"x": 330, "y": 230, "width": 20, "height": 20})).unwrap()); + let hidden = id_of(&app.run("shape.rectangle", json!({"x": 120, "y": 100, "width": 40, "height": 40})).unwrap()); + let linked = app.run("file.place", json!({"path": png, "link": true, "at": [240.0, 150.0]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + let inner = id_of(&app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [left.0, right.0, hidden.0, inner.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + // With the group selected after the commands `edit`: its outline paths, the paths that show anchors with their + // anchor count, and its hover outline. + let shown = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app, &[]); + let without = shown(&mut app, &[("select.set", json!({"ids": [hidden.0, inner.0]})), ("edit.clear", json!({}))]); + let with_hidden = shown(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden.0, inner.0]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the marks show every member"); + assert_eq!(without.1, vec![4, 4], "the anchors of the two visible members"); + assert_eq!(with_hidden, without, "hidden members are not marked"); +} + +/// A selected group leaves out a member made into a guide while the guides are hidden, as the canvas does: its +/// outlines, anchors and hover outline are the same as with that member deleted. With the guides shown, the guide is +/// marked too. +#[test] +fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { + let mut app = blank(); + let path = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let guide = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [path.0, guide.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + assert!( + matches!(app.session.active().unwrap().doc.node(guide).map(|n| &n.kind), Some(NodeKind::Path { guide: true, .. })), + "the group holds a guide" + ); + // With the group selected: the boxes of its outline paths, the paths that show anchors, and its hover outline's box. + let shown = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides_shown(), "the guides are hidden"); + let guides_hidden = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let without = shown(&mut app); + assert_eq!(both.1.len(), 2, "with the guides shown, the guide shows its anchors too: {both:?}"); + assert_ne!(both, without, "with the guides shown, the guide is marked"); + assert_eq!(guides_hidden, without, "with the guides hidden, only the path is marked"); +} + +/// A selected layer leaves out the art of a template sublayer while View › Hide Template is on, and a group a guide +/// while the guides are hidden: their outlines and the overlay's point limit count only what the canvas draws. +#[test] +fn the_marks_leave_out_template_layers_and_guides_the_view_hides() { + use super::super::outline::{node_outline, too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let rect = |id: u64, r: vectorcraft_geom::Rect| Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + let path = Arc::new(rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0))); + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut many = Node::path(NodeId(3), PathData::single(SubPath::polyline(&points, false)), Appearance::default()); + let mut template = Node::layer(NodeId(4), "Template", LayerColor::Preset(1)); + if let NodeKind::Layer { template: on, children, .. } = &mut template.kind { + *on = true; + children.push(Arc::new(many.clone())); + } + let mut layer = Node::layer(NodeId(5), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(template), path.clone()]); + } + if let NodeKind::Path { guide, .. } = &mut many.kind { + *guide = true; + } + let group = Node::group(NodeId(6), vec![Arc::new(many), path.clone()]); + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let alone = node_outline(&path, &symbols, ViewHides::default()).bounding_box(); + let mut wrong = vec![]; + for (n, what, hides) in [ + (&layer, "a layer with a template sublayer", ViewHides { templates: true, guides: false }), + (&group, "a group with a guide", ViewHides { templates: false, guides: true }), + ] { + for (hides, hidden) in [(ViewHides::default(), false), (hides, true)] { + let outline = node_outline(n, &symbols, hides).bounding_box(); + if (outline == alone) != hidden || too_many_anchors([n], hides) == hidden || too_many_marks([n], hides) == hidden { + wrong.push(format!("{what}, hidden by the view: {hidden}")); + } + } + } + assert!(wrong.is_empty(), "the marks count only what the view draws: {wrong:?}"); + // A compound path made into a guide draws every path, so each stays outlined while the guides are hidden. + let guide_rect = |id: u64, r: vectorcraft_geom::Rect| { + let mut n = rect(id, r); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + Arc::new(n) + }; + let compound = Node::new( + NodeId(7), + NodeKind::Compound { + children: vec![ + guide_rect(8, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0)), + guide_rect(9, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)), + ], + rule: vectorcraft_geom::FillRule::EvenOdd, + }, + ); + let contours = |hides| node_outline(&compound, &symbols, hides).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(ViewHides { templates: false, guides: true }), contours(ViewHides::default()), "a compound path keeps its guide paths"); +} + +/// The overlay's limit counts the points of the members the highlight outlines: a hidden member of a group, a blend, a +/// repeat or an intertwine, and the art of a hidden sublayer, do not count toward it. +#[test] +fn the_overlay_limit_leaves_out_hidden_members() { + use super::super::outline::{too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let many = Arc::new(Node::path(NodeId(2), PathData::single(SubPath::polyline(&points, false)), Appearance::default())); + let few = Arc::new(Node::path( + NodeId(3), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::default(), + )); + let mut wrong = vec![]; + for visible in [true, false] { + let mut member = (*many).clone(); + member.visible = visible; + let members = || vec![Arc::new(member.clone()), few.clone()]; + let group = Node::group(NodeId(1), members()); + let blend = Node::new(NodeId(6), NodeKind::Blend { children: members(), spec: Default::default() }); + let repeat = Node::new(NodeId(7), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(members(), 0.0, 0.0))); + let intertwine = Node::new(NodeId(8), NodeKind::Intertwine { children: members() }); + let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = visible; + if let Some(children) = sublayer.children_mut() { + children.push(many.clone()); + } + let mut layer = Node::layer(NodeId(4), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(sublayer), few.clone()]); + } + for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { + if too_many_anchors([n], ViewHides::default()) != visible || too_many_marks([n], ViewHides::default()) != visible { + wrong.push(format!("{what}, member visible: {visible}")); + } + } + } + assert!(wrong.is_empty(), "the limit is crossed only by visible points: {wrong:?}"); +} + #[test] fn the_anchors_of_a_container_selected_whole_draw_selected() { let (mut app, _) = scene(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7c4cb6aebf..50bcfc23d0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11,7 +11,7 @@ use super::artboards::names_an_artboard; use super::cursor::still_wait; use super::fill::{fill_view, polygon_area}; use super::marks::{HiddenMarks, thread_overlays}; -use super::outline::{node_outline, walk_drawn}; +use super::outline::{ViewHides, node_outline, walk_drawn}; use super::raster::{frame_view, pixel_region, placed_changes, placed_key_at, placed_since, poll_worker}; use super::*; use crate::CacheKey; @@ -31,9 +31,13 @@ fn shaper_selection_highlights_only_the_visible_result() { let g = st.doc.node(st.selection.objects[0]).unwrap(); assert!(g.extras().shaper.is_some()); let symbols = st.doc.symbol_boxes(); - let bounds = node_outline(g, &symbols).bounding_box(); + let bounds = node_outline(g, &symbols, ViewHides::default()).bounding_box(); assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}"); - assert_eq!(node_outline(st.doc.node(line).unwrap(), &symbols).bounding_box().x0, 50.0, "an isolated original still shows its full outline"); + assert_eq!( + node_outline(st.doc.node(line).unwrap(), &symbols, ViewHides::default()).bounding_box().x0, + 50.0, + "an isolated original still shows its full outline" + ); } #[test] @@ -50,7 +54,7 @@ fn a_symbol_instance_is_outlined_around_its_art() { inst = Some(n); } }); - assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); + assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes(), ViewHides::default()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); } /// The points of `bp`'s move and line elements, in order. @@ -111,7 +115,7 @@ fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() { ("skewed", Affine::skew(0.5, 0.0)), ] { let (n, frame) = placed(a); - let got = outline_points(&node_outline(&n, &symbols)); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}"); } // In perspective, the frame's corners go through the projection. @@ -120,7 +124,7 @@ fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() { in_perspective(&mut n, h); let (_, flat) = placed(Affine::IDENTITY); let drawn = flat.map(|p| h.apply(p).unwrap()); - let got = outline_points(&node_outline(&n, &symbols)); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}"); } @@ -137,7 +141,7 @@ fn type_in_perspective_is_outlined_by_its_projected_box() { let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]); in_perspective(&mut n, h); let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap()); - let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes())); + let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes(), ViewHides::default())); assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}"); } @@ -254,6 +258,99 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); } +/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the +/// points of lines and paths. +fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut points = vec![]; + for shape in flat_shapes(out.shapes) { + match shape { + Shape::Circle(c) => points.push(c.center), + Shape::Rect(r) => points.push(r.rect.center()), + Shape::LineSegment { points: ends, .. } => points.extend_from_slice(&ends), + Shape::Path(p) => points.extend_from_slice(&p.points), + _ => {} + } + } + points +} + +/// A document with smart guides and the task bar off, every frame drawn on this thread. +fn drag_app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.task_bar = false; + app.canvas.worker_started = true; + app +} + +fn press(at: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A drag with the Selection tool draws the moved object's marks in the frame the pointer moves: at the corner the +/// object has after that frame's event, and none at the corner it had before it. +#[test] +fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let corner = |app: &VectorcraftApp| { + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + xf.to_screen(Point::new(b.x0, b.y0)) + }; + let start = xf.to_screen(Point::new(180.0, 120.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut moved = 0; + for i in 1..=6 { + let before = corner(&app); + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(12.0, 7.0) * i as f32)]); + let after = corner(&app); + if after.distance(before) < 4.0 { + continue; + } + moved += 1; + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(after), "move {i}: a mark at the corner after the move, {after:?}"); + assert!(!near(before), "move {i}: no mark at the corner before it, {before:?}"); + } + assert!(moved >= 4, "the drag moves the object: {moved} frames"); +} + +/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and +/// none at the pointer of the frame before. +#[test] +fn a_pen_drag_draws_its_handle_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pen"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let start = xf.to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut before = start; + for i in 1..=6 { + let at = start + vec2(9.0, 5.0) * i as f32; + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(at), "move {i}: the handle's end at this frame's pointer, {at:?}"); + if i > 1 { + assert!(!near(before), "move {i}: no handle end at the pointer of the frame before, {before:?}"); + } + before = at; + } +} + /// A click with the Selection tool inside an artboard makes it the active one, and Paste in /// Place then pastes onto it, where the objects were on their own artboard (#693). #[test] @@ -3599,7 +3696,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // Cancel: nothing is edited, and the document, its undo history and the selection stay. let (before, undo, selected) = (node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone()); + let cancelled_token = app.missing_font_edit_token.expect("the question's edit token"); answer(&mut app, false); + // A delayed approval for the cancelled question can no longer start an edit. + app.session.set_tool_option("missingFontEdit", &json!({"token": cancelled_token, "ok": true})); timed(&mut app, 1.5, vec![]); assert_eq!(app.session.tool_options()["editing"], json!(null)); assert!(!app.session.tool_wants_text()); @@ -3609,6 +3709,16 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // A new double-click asks again; OK edits with the caret where the type was clicked. double_click(&mut app, 3.0); assert!(asking(&app), "asked again"); + let replaced_token = app.missing_font_edit_token; + // A Type press sent through automation can replace the prompt before the user answers. + let view = app.view_info(); + let point = Point::new(b.x0 + b.width() * 0.25, b.center().y); + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, point.x, point.y), view); + } + assert_ne!(app.missing_font_edit_token, replaced_token); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(asking(&app), "the replacement question is open"); answer(&mut app, true); timed(&mut app, 3.5, vec![]); assert!(!asking(&app)); @@ -4832,17 +4942,83 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); let mut visited = vec![]; - walk_drawn(&group, &mut |n| visited.push(n.id)); + walk_drawn(&group, ViewHides::default(), &mut |n| visited.push(n.id)); assert_eq!(visited.contains(&NodeId(2)), view.shows_source()); let want = if view.shows_source() { vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0) } else { vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0) }; - assert_eq!(node_outline(&group, &symbols).bounding_box(), want); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), want); } + // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + // A hidden path sent to the back of a trace is not its source image, in any view. + let mut path = + Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); + path.visible = false; + let art = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)), Appearance::default()); + let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); + for view in TraceView::ALL { + group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); + assert_eq!( + node_outline(&group, &symbols, ViewHides::default()).bounding_box(), + vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), + "{view:?}" + ); + } +} + +/// A compound path draws every path it holds, hidden ones included, so its highlight outlines them +/// all; a group, a blend, a repeat, an intertwine and a layer leave out a hidden member, and a +/// layer the art of a hidden sublayer. A clip group shows its clipping path whether or not it is +/// hidden, and a hidden object on its own keeps its outline. +#[test] +fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::{FillRule, PathEl}; + let rect = |id: u64, r: vectorcraft_geom::Rect, visible: bool| { + let mut n = Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + n.visible = visible; + Arc::new(n) + }; + let children = || { + vec![rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), true), rect(3, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0), false)] + }; + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let contours = |n: &Node| node_outline(n, &symbols, ViewHides::default()).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); + assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(children(), 0.0, 0.0)))), 1, "a repeat"); + // A clip group shows its clipping path, hidden or not, and none of the art it clips. + let clip = |visible: bool| { + let mut members = children(); + members.insert(0, rect(6, vectorcraft_geom::Rect::new(10.0, 10.0, 90.0, 90.0), visible)); + let mut n = Node::group(NodeId(1), members); + if let NodeKind::Group { clip, .. } = &mut n.kind { + *clip = true; + } + contours(&n) + }; + assert_eq!((clip(true), clip(false)), (1, 1), "a clip group"); + // A hidden object that is itself selected keeps its outline. + assert_eq!(contours(&rect(7, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0), false)), 1, "a hidden object"); + let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); + let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = false; + if let Some(c) = sublayer.children_mut() { + c.push(rect(5, vectorcraft_geom::Rect::new(150.0, 150.0, 200.0, 200.0), true)); + } + if let Some(c) = layer.children_mut() { + c.extend(children()); + c.push(Arc::new(sublayer)); + } + assert_eq!(contours(&layer), 1, "a layer"); } /// #2572: Show Text Threads links a thread's frames from the out port of one to the in port of diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 3a8f20f69c..5bda6d918e 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -577,8 +577,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too } // Once a frame, before its press, which then uses the new tool; a held press (its grab) waits for the frame after // the release, and a pointer over another window for the pointer to come in. - if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() && ui.input(|i| i.pointer.has_pointer()) { - crate::stylus::sync_eraser_tool(app); + if ui.ctx().current_pass_index() == 0 + && app.canvas.grab.is_none() + && ui.input(|i| i.pointer.has_pointer()) + && crate::stylus::sync_eraser_tool(app) + { + // Before the press, which holds what the host was told about the wheel until its release. + crate::stylus::sync_wheel_use(app); } // A press on the canvas that a view tool takes (a middle-button pan, a held Space's Hand) counts as a press // elsewhere for the clicks the tool's double-click or triple-click compares. diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 0fbfa24fd4..4ba5c01293 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -224,11 +224,30 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { crumbs.push((None, false, pn.clone())); } // Up one level: the isolated object's parent group, or `object.exitIsolation`, which goes from an - // isolated sublayer to its parent layer and otherwise leaves isolation mode. - let up = match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { + // isolated sublayer to its parent layer, from a group in a symbol's art to the symbol's layer, and + // otherwise leaves isolation mode. While a pattern is edited the back arrow is Done. Screen readers + // call it by what it does. + let parent_group = ancestry.iter().rev().nth(1).copied().filter(|p| st.doc.node(*p).is_some_and(|n| !n.is_layer())); + let up = match parent_group { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), }; + let symbol_layer = st.doc.symbol_edit.as_ref().map(|e| e.layer); + let up_one = parent_group.is_some() + || symbol_layer.is_some_and(|l| l != iso && ancestry.contains(&l)) + || (st.doc.mask_edit.is_none() + && symbol_layer.is_none() + && st.doc.node(iso).is_some_and(|n| n.is_layer()) + && st.doc.parent_of(iso).is_some_and(|p| st.doc.is_editable(p))); + let back_name = if pattern_edit.is_some() { + tl!("Done") + } else if up_one { + tl!("Back One Level") + } else if symbol_layer == Some(iso) { + tl!("Exit Symbol Editing Mode") + } else { + tl!("Exit Isolation Mode") + }; let entries: Vec> = crumbs.iter().enumerate().map(|(i, (_, _, name))| Entry::new(i, name.clone())).collect(); let mut nav: Option<(&str, serde_json::Value)> = None; let mut pattern_cmd: Option<&str> = None; @@ -237,7 +256,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(area)); Bar::new(tl!("Isolation mode"), BarKind::Options).show(&mut bar_ui, |ui, _| { Row::new().fill().senses_surface().show(ui, |ui, cx| { - if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(tl!("Back")).show(ui).clicked() { + if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(back_name).show(ui).clicked() { if pattern_edit.is_some() { pattern_cmd = Some("object.pattern.done"); } else { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 0d8ef2d500..6484290054 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1277,9 +1277,28 @@ fn isolation_shown(app: crate::VectorcraftApp) -> Shown { /// A point on the isolation bar's own surface: right of its crumbs, at the end of the path, which fills the bar up /// to the pattern editing buttons at its right. fn isolation_bar_surface(bar: &mut Shown) -> egui::Pos2 { - let back = bar.named("Back"); let path = bar.named("Isolation path"); - egui::pos2(path.rect.right() - 8.0, back.center().y) + egui::pos2(path.rect.right() - 8.0, path.center().y) +} + +/// The names of the isolation bar's controls in the latest frame that screen readers read with `role`, sorted. +fn isolation_names(bar: &Shown, role: Role) -> Vec { + let tree = bar.tree(); + let mut names: Vec = + tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(role)).filter_map(|key| tree.name_of(key)).map(str::to_owned).collect(); + names.sort(); + names +} + +/// The isolation bar's back arrow: the leftmost button named `name`. +fn isolation_back(bar: &mut Shown, name: &str) -> Target { + bar.frame(Vec::new()); + let tree = bar.tree(); + let keys: Vec<_> = tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(Role::BUTTON) && tree.name_of(*key) == Some(name)).collect(); + keys.into_iter() + .filter_map(|key| bar.fixture.target(key)) + .min_by(|a, b| a.rect.left().total_cmp(&b.rect.left())) + .unwrap_or_else(|| panic!("no {name:?} button in {:?}", bar.names())) } /// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy, @@ -1308,15 +1327,15 @@ fn isolation_bar_navigation_and_back_button_steps_up() { let isolation = |bar: &Shown| bar.app().session.active().unwrap().isolation; // Clicking back from `a` steps up to parent group `g1` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g1))); // Clicking back from `g1` steps up to grandparent group `g2` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g2))); // Clicking back from `g2` (parent is layer) exits isolation mode completely - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None); // Deep isolate again to test clicking ancestor breadcrumb directly @@ -1355,11 +1374,11 @@ fn isolation_bar_back_button_steps_up_through_sublayers() { let steps = |bar: &Shown| bar.app().session.doc().unwrap().history.undo.len(); let before = steps(&bar); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(mid), "back from the deepest sublayer"); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(top), "back from the middle sublayer"); - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None, "back from the top-level layer"); assert_eq!(steps(&bar), before, "no undo step"); @@ -1422,7 +1441,8 @@ fn isolation_bar_background_click_leaves_pattern_edit_open() { let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_some() && st.isolation.is_some(), "pattern editing stays open"); } - bar.click("Back"); + let back = isolation_back(&mut bar, "Done"); + bar.click_on(&back); let app = bar.app(); let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_none() && st.isolation.is_none(), "the back arrow ends pattern editing"); @@ -1506,6 +1526,72 @@ fn isolation_bar_click_on_the_current_name_exits() { assert_eq!(bar.app().session.active().unwrap().isolation, None); } +/// Screen readers call the isolation bar's back arrow by what it does: Back One Level, Exit Isolation Mode, Exit +/// Symbol Editing Mode, or Done while a pattern is edited, in the UI's language. Each crumb of the levels above is +/// a link with the name it shows, and the current object's name is not a control. +#[test] +fn the_isolation_bars_controls_have_screen_reader_names() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let name = |app: &crate::VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().display_name(); + let st = app.session.active().unwrap(); + let (layer, group) = (st.doc.layer_of(NodeId(a)).unwrap(), st.doc.parent_of(NodeId(a)).unwrap()); + let (layer_name, group_name) = (name(&app, layer), name(&app, group)); + let mut bar = isolation_shown(app); + let shown = |bar: &mut Shown, role: Role| { + bar.frame(Vec::new()); + isolation_names(bar, role) + }; + + // A path in a group: back goes to the group. + bar.app().run("object.isolate", json!({"id": a})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + let mut crumbs = vec![layer_name.clone(), group_name.clone()]; + crumbs.sort(); + assert_eq!(shown(&mut bar, Role::LINK), crumbs, "the current object's name is not a link"); + + // The group itself: back leaves isolation mode. + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + assert_eq!(shown(&mut bar, Role::LINK), std::slice::from_ref(&layer_name)); + + // An isolated sublayer: back goes to its parent layer, and from the top-level layer it leaves. + let sub = bar.app().run("layer.newSublayer", json!({"parent": layer.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap(); + bar.app().run("object.isolate", json!({"id": sub})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + bar.app().run("object.isolate", json!({"id": layer.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + + // In German. + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = shown(&mut bar, Role::BUTTON); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(german, ["Isolationsmodus beenden"]); + bar.app().run("object.exitIsolation", json!({"all": true})).unwrap(); + + // Pattern editing: back is Done, beside Save a Copy, Done and Cancel. + let c = rect(&mut bar.app(), 200.0); + bar.app().run("select.set", json!({"ids": [c]})).unwrap(); + bar.app().run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Cancel", "Done", "Done", "Save a Copy"]); + bar.app().run("object.pattern.cancel", json!({})).unwrap(); + + // Symbol editing mode: back leaves it. + let d = rect(&mut bar.app(), 300.0); + bar.app().run("select.set", json!({"ids": [d]})).unwrap(); + bar.app().run("symbol.new", json!({"name": "Box"})).unwrap(); + bar.app().run("symbol.edit", json!({"name": "Box"})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Symbol Editing Mode"]); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 813ed31d97..9d729c31d4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1465,6 +1465,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { params["dialog"] = json!(top.id.value().to_string()); } + if method == "ui.dialog.set" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::effect::normalize_set_mode(app, id, &mut params); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 12e13a36b3..72fb9a40a6 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -100,8 +100,7 @@ wrapped_dialog!(Question, StandardPrompt, KIND); pub(crate) struct Message(HostedAlert); wrapped_dialog!(Message, HostedAlert, MESSAGE); -/// The Type tool's question whether to edit type set in fonts that aren't available; its tag is the -/// tool's edit token. +/// The Type tool's question whether to edit type set in fonts that aren't available. pub(crate) struct MissingFontQuestion(StandardPrompt); wrapped_dialog!(MissingFontQuestion, StandardPrompt, MISSING_FONT_EDIT); @@ -215,13 +214,15 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str /// While another dialog is open (a press sent with `ui.pointer` reaches the tool then), that dialog /// stays and the Type tool forgets the edit, as Cancel would. pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { - let token = p.get("token").cloned().unwrap_or(Value::Null); + let Some(token) = p.get("token").and_then(Value::as_u64) else { + return; + }; let Some(dialogs) = app.dialogs() else { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; }; if app.any_dialog_open() && !dialogs.with(|host| host.is_open::()) { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; } let names = |k: &str| p.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::>(); @@ -234,14 +235,18 @@ pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { let prompt = StandardPrompt::custom(tl!("Edit type set in fonts that aren't available?")) .paragraph(detail) .button(PromptChoice::Proceed, tl!("OK")) - .button(PromptChoice::Cancel, tl!("Cancel")) - .tag(token); - dialogs.with(|host| host.open(MissingFontQuestion(prompt))); + .button(PromptChoice::Cancel, tl!("Cancel")); + dialogs.with(|host| { + host.open(MissingFontQuestion(prompt)); + // Replacing a prompt leaves its Cancel in the host. The tool is already waiting on the new token. + let _ = host.take::(); + }); + app.missing_font_edit_token = Some(token); } /// Give the Type tool the answer to [`ask_missing_font_edit`]'s question about the edit `token` /// names: with `ok` the edit starts at once; without, the tool forgets it. -pub(crate) fn answer_missing_font_edit(app: &mut VectorcraftApp, token: &Value, ok: bool) { +fn answer_missing_font_edit(app: &mut VectorcraftApp, token: u64, ok: bool) { app.session.set_tool_option("missingFontEdit", &json!({"token": token, "ok": ok})); if ok { let r = app.session.tool_poll(app.view_info(), false); @@ -277,13 +282,12 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { let Some(dialogs) = app.dialogs() else { return; }; - let (ok, token) = match dialogs.with(|host| host.take::()) { - None => return, - Some(DialogResult::Ok(mut answer)) => (answer.choice == PromptChoice::Proceed, answer.take_tag::()), - // PLAN: a question the host cancelled carries no tag, so the tool's token is unknown here. - Some(_) => (false, None), - }; - answer_missing_font_edit(app, &token.unwrap_or(Value::Null), ok); + if let Some(result) = dialogs.with(|host| host.take::()) + && let Some(token) = app.missing_font_edit_token.take() + { + let ok = matches!(result, DialogResult::Ok(answer) if answer.choice == PromptChoice::Proceed); + answer_missing_font_edit(app, token, ok); + } } /// The confirmation open now, if one is: its message and detail as shown, and the command OK runs. diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 0d28e683a2..195d2759f9 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -389,7 +389,14 @@ fn grid_colors_row(setup: DocSetup) -> Param { picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + let number = (i + 1).to_string(); + let template = tl!("Grid Colors: {number}"); + let name = if template == "Grid Colors: {number}" { + // Keep the translated prefix for catalogs that have yet to add the complete label. + format!("{} {number}", tl!("Grid Colors:")) + } else { + crate::i18n::fmt(template, &[("number", &number)]) + }; let [r, g, b, _] = color.to_rgba8(1.0); let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index ebb78e8c90..97dc95426d 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -69,6 +69,26 @@ pub(crate) struct Open { asking: bool, } +/// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog. +pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) { + let Some(open) = app.effect_dialogs.effect.as_ref() else { return }; + if id != open.id || open.asking || !vectorcraft_effects::takes_blend_mode(&open.cx.id, "mode") { + return; + } + let normalize = |field: &mut Value| { + if field["field"] == "mode" + && let Some(mode) = field["value"].as_str().and_then(vectorcraft_effects::parse_blend_mode) + { + field["value"] = json!(vectorcraft_effects::blend_mode_id(mode)); + } + }; + if let Some(fields) = params.get_mut("fields").and_then(Value::as_array_mut) { + fields.iter_mut().for_each(normalize); + } else { + normalize(params); + } +} + /// `effect.dialog {effect, index?, item?}`: edit applied effect `index` of `item` (null: the /// object's effects; omitted: the active item's, else the object's) prefilled with its values, /// or add `effect`, first asking when that list already has it. diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 06bf617898..ef5b2a5ea4 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -150,6 +150,11 @@ fn generic_row(cx: &EffectCx, key: &str, default: &Value, relative: bool) -> Opt Param::number(key, label, n, 1.0, 2) } } + // The blend mode the effect draws in: the mode it draws a name in, Normal for one it doesn't know. + Value::String(text) if vectorcraft_effects::takes_blend_mode(id, key) => { + let mode = vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(text)); + Param::new(key, label, ParamKind::blend(crate::fields::effect_blend_modes(), Some(mode))) + } Value::String(text) => match options() { Some(list) => Param::new(key, label, ParamKind::choice(list, Some(text.clone()))), None if text.starts_with('#') => Param::new(key, label, ParamKind::color(None)), diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 8a31fafae0..be7cf18a3b 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -171,6 +171,13 @@ fn field_value(row: Option<&Param>, value: &Value) -> Option { }, // A pair of radio buttons over a flag (Relative / Absolute): the ids are "true" and "false". Some(ParamKind::Radio { .. }) if value.is_boolean() => value.as_bool().map(|b| FieldValue::Text(b.to_string())), + // Use the renderer's mode for each spelling, including Normal for unknown names and the effect's default for + // a legacy value that is not text. + Some(ParamKind::Blend { default, .. }) => value + .as_str() + .map(|s| vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(s))) + .or_else(|| default.clone()) + .map(FieldValue::Text), // A custom row's list, and one a key no row has carries through (an export's `artboards: [0, 1]`), stay JSON: a // list of whole numbers would read back as a grid, and one of two or three as a point or colour. Some(ParamKind::Custom(_)) | None if value.is_array() => Some(FieldValue::Json(value.clone())), diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index 1aac4c28b8..6eb690989d 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -361,10 +361,11 @@ impl KinsokuDialog { let rows: Vec> = list.iter().map(|s| PresetRow::item(name_of(s).to_owned(), name_of(s), 0)).collect(); let mut value = list.get(self.index(list.len())).map(|s| name_of(s).to_owned()); let suggestion = new_name(&list, &self.opened); - // PLAN: PresetPicker has no placeholder: an empty list shows an empty name field, not "None". let source = PresetSource::listed(&rows); let refuses = |typed: &str| name_problem(&list, typed); - let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)).field(PickerField::Name); + let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)) + .field(PickerField::Name) + .placeholder(tl!("None")); let out = NamedPresetRow::new(tl!("Kinsoku Set"), picker).suggest_name(suggestion).check_name(NameCheck::of_host(&refuses)).show(ui); self.apply(out.events); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index f39cf6d596..887dbbc202 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -47,6 +47,21 @@ fn cancel(app: &VectorcraftApp) { app.dialogs().unwrap().with(|h| h.cancel::(&ctx)); } +#[test] +fn empty_kinsoku_list_shows_none_in_the_preset_picker() { + let mut fixture = craft::ui::testing::Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui))); + fixture.room(egui::vec2(800.0, 600.0)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(fixture.ctx().clone()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + open(&mut app).unwrap(); + fixture.settle(); + + let picker = fixture.by_label("Kinsoku Set").expect("Kinsoku Set picker"); + assert_eq!(fixture.tree().value_of(picker.node), Some("None")); + assert!(picked(&app).is_empty(), "the caption does not select a set"); +} + /// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its /// categories edited in their fields and Add putting in a character by its code point; nothing /// changes until OK, which sets them as one undo step; Cancel leaves them. diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index c65dc15f45..60bf25a04a 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -54,17 +54,22 @@ impl LivePreview { if !app.session.in_interaction() { return app.run(cmd, params); } - let v = app.session.preview(cmd, ¶ms).map_err(|e| e.to_string())?; - let r = app.session.commit_interaction().map(|_| Value::Null).map_err(|e| e.to_string()); - if r.is_ok() - && let Some(w) = v.get("warning").and_then(Value::as_str) - { - app.status(w.to_string()); + let result = app.session.preview(cmd, ¶ms).and_then(|answer| { + app.session.commit_interaction()?; + Ok(answer) + }); + let answer = match result { + Ok(answer) => answer, + Err(error) => { + self.cancel(app); + return Err(error.to_string()); + } + }; + if let Some(warning) = answer.get("warning").and_then(Value::as_str) { + app.status(warning.to_string()); } - if r.is_ok() { - crate::plugin_runs::show_notice(app, cmd, &v); - } - r + crate::plugin_runs::show_notice(app, cmd, &answer); + Ok(Value::Null) } /// Cancel: rolls a shown preview back. @@ -106,6 +111,31 @@ mod tests { } } + #[test] + fn refused_confirmation_restores_the_art_and_ends_the_preview() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + let original = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + let mut preview = LivePreview::default(); + let fill = json!({"color": "#00a000"}); + assert!(matches!(preview.run(&mut app, true, "Fill Color", "paint.setFill", &fill), Some(Ok(_)))); + assert_ne!(app.session.doc().unwrap().doc, original); + assert!(preview.commit(&mut app, "paint.setFill", json!({"color": true})).is_err()); + assert!(!app.session.in_interaction(), "the refused edit left no open interaction"); + assert_eq!(app.session.doc().unwrap().doc, original); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + let mut next = LivePreview::default(); + assert!(matches!(next.run(&mut app, true, "Next Fill", "paint.setFill", &fill), Some(Ok(_)))); + next.commit(&mut app, "paint.setFill", fill).unwrap(); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Next Fill"); + } + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts /// from it; the status bar shows the warning of the typing's preview that keeping it applied. #[test] diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 5713d3d27e..6576e17c73 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -422,7 +422,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } // PLAN: assumed TileGrid::show_items(ui, &source, &mut |key, _| tile) as the framework's stories call it; // the checks arrive as `CollectionEvent::Item(key, TilePartEvent::Check { .. })` in `response.events`. - let grid = TileGrid::new("Artboards").checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { + let grid = TileGrid::new(tl!("Artboards")).checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { let on = boards.get(*i).copied().unwrap_or(false); let mut tile = Tile::new(menus.names.get(*i).cloned().unwrap_or_default()).check(if on { ToggleState::On } else { ToggleState::Off }); if let Some(file) = files.get(*i).cloned().flatten() { diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 8227766b4a..200b91f458 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -247,27 +247,31 @@ fn legacy_ai_saves_the_artboards_checked_in_its_picker() { assert_eq!(boards_in(&dialog(&mut app)), Some(vec![true, false, true, false])); } -/// The legacy picker's note and its count of checked artboards are in the window's accessibility tree, and the count -/// follows the checks. +/// The legacy picker's note, grid name and count are announced. The count follows the checks and +/// the grid name follows the interface language. #[test] -fn legacy_ai_names_its_note_and_artboard_count_in_the_accessibility_tree() { +fn legacy_ai_announces_its_note_grid_name_and_artboard_count() { let (mut app, _, _) = desktop("art.ai"); app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80})).unwrap(); save_as(&mut app, "file.saveAs"); set(&mut app, "aiVersion", json!("7")); - let labels = |app: &mut VectorcraftApp| -> Vec { + let labels = |app: &mut VectorcraftApp, role: Option| -> Vec { frame(app); let ctx = app.ui_ctx.clone().unwrap(); - let out = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.ui(ui)); + let out = crate::testing::app_frame(app, &ctx, egui::RawInput::default()); let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); - nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_owned).collect() + nodes.iter().filter(|(_, node)| role.is_none_or(|role| node.role() == role)).filter_map(|(_, node)| node.label()).map(str::to_owned).collect() }; - let shown = labels(&mut app); + let shown = labels(&mut app, None); assert!(shown.iter().any(|l| l.starts_with("A legacy .ai file holds one artboard")), "{shown:?}"); assert!(shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); set(&mut app, "boards", json!([true, false])); - let shown = labels(&mut app); + let shown = labels(&mut app, None); assert!(shown.iter().any(|l| l == "1 of 2 artboards") && !shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); + + app.session.prefs.interface_language = "fr".into(); + let shown = labels(&mut app, Some(egui::accesskit::Role::ListBox)); + assert!(shown.iter().any(|label| label == "Plans de travail"), "{shown:?}"); } #[test] diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1eeec2d52d..c45284ba5a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -213,6 +213,85 @@ fn effect_dialog_refuses_a_color_it_cannot_draw() { } } +/// Drop Shadow's, Inner Glow's and Outer Glow's Mode is a blend-mode menu of every mode the effect draws, opening on the +/// effect's default, in the dialog and in the Appearance panel's editor (the same rows over the stored values, where a +/// mode in another spelling shows as its menu entry). Picking Multiply in a glow's dialog stores `multiply`, and a mode +/// the menu lacks is refused as it is set. +#[test] +fn shadow_and_glow_dialogs_pick_mode_from_a_blend_mode_menu() { + use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, ParamKind}; + let modes: Vec = vectorcraft_doc::color::BlendMode::ALL.into_iter().map(vectorcraft_effects::blend_mode_id).collect(); + for (effect, default) in [("stylize.dropShadow", "multiply"), ("stylize.innerGlow", "screen"), ("stylize.outerGlow", "screen")] { + let mut app = app(); + for editing in [false, true] { + let cx = super::effect_params::EffectCx::new(&app, effect, editing); + let rows = super::effect_params::effect_params(&cx, &DialogFields::new()); + let row = rows.iter().find(|p| p.key == "mode").unwrap_or_else(|| panic!("{effect}: a Mode row")); + let ParamKind::Blend { modes: listed, default: shown, .. } = &row.kind else { panic!("{effect}: Mode is {:?}", row.kind) }; + let listed: Vec = listed.iter().map(|(entry, _)| entry.key.clone()).collect(); + assert_eq!(listed, modes, "{effect}"); + assert_eq!(shown.as_deref(), Some(default), "{effect}"); + let stored = serde_json::Map::from_iter([("mode".to_string(), json!("Color Burn"))]); + let fields = super::form::fields_of(&rows, &stored); + assert_eq!(fields.get("mode"), Some(&FieldValue::from("colorBurn")), "{effect}"); + } + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": effect})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(default), "{effect}"); + let (dialog, ctx) = (top(&app).0, app.ui_ctx.clone().expect("a window app")); + let refused = app.dialogs().expect("a window app").with(|h| h.set_json_field(&ctx, dialog, "mode", json!("multipy"))); + assert!(refused.is_err(), "{effect}: a mode the menu lacks"); + let want = if default == "multiply" { "colorBurn" } else { "multiply" }; + let mode = if default == "multiply" { "Color Burn" } else { "Multiply" }; + let params = match effect { + "stylize.dropShadow" => json!({"field": "mode", "value": mode}), + "stylize.innerGlow" => json!({"dialog": dialog.value(), "fields": [{"field": "mode", "value": mode}]}), + _ => json!({"dialog": dialog.value().to_string(), "fields": [{"field": "mode", "value": mode}]}), + }; + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", params); + assert_eq!(fields(&app)["mode"], json!(want)); + frame(&mut app, vec![]); + assert!(confirm(&mut app), "{effect}"); + let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert_eq!(n.appearance.effects[0].params["mode"], json!(want), "{effect}"); + } +} + +/// Confirming an untouched legacy mode keeps the file's value and does not add an undo step. +/// Choosing a different mode updates the stored value. +#[test] +fn unchanged_effect_dialog_preserves_legacy_blend_modes() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let effect = "stylize.dropShadow"; + app.run("effect.apply", json!({"ids": [id], "effect": effect, "item": null})).unwrap(); + for (old_mode, shown_mode) in [(Value::Null, "multiply"), (json!("multipy"), "normal")] { + app.session.replay("effect.setParams", &json!({"ids": [id], "index": 0, "item": null, "params": {"mode": old_mode}})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(shown_mode)); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params.get("mode"), Some(&old_mode)); + assert_eq!(state.history.undo.len(), before); + + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + let ctx = app.ui_ctx.clone().expect("a window app"); + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"field": "mode", "value": "Screen"})); + frame(&mut app, vec![]); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params["mode"], json!("screen")); + assert_eq!(state.history.undo.len(), before + 1); + } +} + /// After File › Document Color Mode, a Drop Shadow's, an Outer Glow's and a Shift to Color's dialog open on the /// converted color, and OK without editing it keeps the color. #[test] diff --git a/crates/ui-egui/src/fields.rs b/crates/ui-egui/src/fields.rs index f5eb2e33f2..a2f0e728d9 100644 --- a/crates/ui-egui/src/fields.rs +++ b/crates/ui-egui/src/fields.rs @@ -44,6 +44,15 @@ pub fn blend_entries() -> Vec> { framework_blend_entries(&entries, |entry| mode_label(entry.key)) } +/// The modes of an effect's blend-mode row. The entries use the stored IDs and translated names. +/// The framework uses each mode's key metadata to separate the existing groups. +pub fn effect_blend_modes() -> Vec<(BlendKeyEntry, Label)> { + blend_table() + .into_iter() + .map(|(mode, shortcut)| (BlendKeyEntry::new(vectorcraft_effects::blend_mode_id(mode), shortcut), mode_label(mode))) + .collect() +} + /// `mode`'s name in the interface language. fn mode_label(mode: BlendMode) -> Label { Label::from(crate::i18n::t(mode.label())) diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index e0e4c32a32..cd0362187a 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -37,6 +37,9 @@ fn the_document_filter_lists_the_families_the_documents_type_uses() { app.run("object.lock", serde_json::json!({})).unwrap(); app.run("text.create", serde_json::json!({"x": 20, "y": 150, "text": "Missing", "font": "Missing Family 7059"})).unwrap(); let db = vectorcraft_text::FontDb::global(); + // Tests running alongside register composite fonts and load fonts in the process-wide database; + // their changes wait until this test ends, so both listings of every family are the same. + let _steady = vectorcraft_text::test_fonts::steady_fonts(db); let used_by_doc = super::document_families(db, &app.session.active().unwrap().doc); let mut names: Vec<_> = used_by_doc.iter().cloned().collect(); names.sort(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 99d88741c1..6078ca0c07 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -266,6 +266,8 @@ pub struct VectorcraftApp { pub(crate) shortcut_overrides: Arc, /// Messages waiting for the dialog that shows them. pub(crate) told: dialogs::host::Told, + /// The Type tool's pending edit, kept even when the dialog closes without a prompt answer. + pub(crate) missing_font_edit_token: Option, /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 1467de23c8..3957d294b6 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -100,6 +100,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())), None => label.into(), }, + // Repeat Pathfinder is named after the Shape Mode or Pathfinder operation that ran last. + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => format!("Repeat {name}"), + None => label.into(), + }, // Apply Last Filter and Last Filter… are named after the filter that ran last. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => format!("Apply {name}"), @@ -130,6 +135,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some(text) } +/// The Pathfinder panel's name for the Shape Mode or Pathfinder operation that ran last. +fn last_pathfinder_label(app: &VectorcraftApp) -> Option<&'static str> { + app.last_pathfinder.as_deref().and_then(crate::panels::pathfinder::operation_label) +} + /// Does the menu item `id` show a name that is user, file or system data rather than an interface /// label: a recent file, a saved view, a font, a user library or preset, a custom workspace, a /// plug-in, an SVG filter, a script of the Scripts folder? Such names are shown as they are, never @@ -202,6 +212,10 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } None => crate::i18n::tr_id(lang, id, label).to_string(), }, + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => fmt(tl!("Repeat {name}"), &[("name", tl!(name))]), + None => crate::i18n::tr_id(lang, id, label).to_string(), + }, // The filter's name is the plug-in's own text, never translated. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => fmt(tl!("Apply {filter}"), &[("filter", &name)]), diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 2d4fcad4d5..a1f3dabb97 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -485,9 +485,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .popup(PopupKind::Menu) .pressed(library_panel::any_open::(&app.ui)), FooterAction::new(svg("link-2-off"), tl!("Break Link to Graphic Style")).enabled(linked), - FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style")).enabled(!sel.is_empty()).takes_drops_disabled(true).accepts_drops(ours), + FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style (Alt-click: without asking)")) + .enabled(!sel.is_empty()) + .takes_drops_disabled(true) + .accepts_drops(ours), // A style dropped here is duplicated with or without art selected. - FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style")) + FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style (Alt-click to name it)")) .enabled(selection_len(app) > 0) .takes_drops_disabled(true) .accepts_drops(ours), @@ -1430,4 +1433,22 @@ mod tests { app.session.documents().iter().map(|st| st.doc.graphic_styles.iter().map(|g| g.name.clone()).collect()).collect(); assert!(names.iter().all(|n| n.iter().any(|g| g == "Mine")), "no style is renamed: {names:?}"); } + + /// The New and Delete buttons name what an Alt-click does, and an Alt-click does it: New asks for a name, Delete + /// deletes without asking. + #[test] + fn the_new_and_delete_buttons_name_their_alt_click() { + use crate::tests::panel_harness::Panel; + use egui::Modifiers; + let mut panel = Panel::new(app(), show); + panel.click_with("New Graphic Style (Alt-click to name it)", Modifiers::ALT); + assert!(open_dialog(&panel.app(), graphic_style_options::KIND).is_some(), "Alt-click on New asks for a name"); + let mut app = app(); + app.session.execute("graphicStyle.new", &json!({"name": "Mine"})).unwrap(); + let mut panel = Panel::new(app, show); + panel.click("Mine"); + panel.click_with("Delete Graphic Style (Alt-click: without asking)", Modifiers::ALT); + let app = panel.app(); + assert!(!names(&app).iter().any(|s| s == "Mine") && confirm::open_question(&app).is_none(), "Alt-click on Delete deletes at once"); + } } diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 8280c4c3d1..d1ee58262d 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -520,6 +520,28 @@ mod tests { assert!(p.app().run("pathfinder.repeat", json!({})).is_err()); } + /// The state the window's menus give the Repeat row, which the panel menu's row reads. + fn repeat_row(p: &Panel) -> Option { + crate::menus::model::refresh(&mut p.app(), p.ctx()); + p.app().menus.states.get(&CommandRef::new("pathfinder.repeat")).cloned() + } + + /// Before an operation has run, the Repeat row reads Repeat Pathfinder and is dimmed; after Unite + /// or Minus Front from the panel it names that operation. + #[test] + fn the_repeat_row_names_the_last_operation() { + let mut p = Panel::new(two_squares(), show); + let command = CommandRef::new("pathfinder.repeat"); + let off = crate::menus::model::off_reason(&p.app(), &command, "Repeat Pathfinder"); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(false).hint(off)), "the plain label, dimmed"); + p.click("Unite"); + select_two_squares(&mut p.app(), 110.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Unite"))); + p.click("Minus Front"); + select_two_squares(&mut p.app(), 210.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Minus Front"))); + } + /// One selected path cannot supply the operands for Unite; the command reports the failure. #[test] fn repeat_with_one_path_keeps_art_and_history() { diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index d7c8926ef9..0a9ba94b33 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -62,6 +62,9 @@ pub struct Services { /// The pen the host reads itself (tablet APIs the window system doesn't route): the same /// handle the host installs for the framework's pointer feed. pub pen: Option, + /// Told whether the active tool reads an airbrush pen's finger wheel (Windows: the host opens + /// the tablet driver's Wintab context only while it does). Without it nothing is told. + pub stylus_wheel: Option>, pub read: Option, /// Read at most a number of bytes from a file (desktop). A file with a size limit is read one /// byte past the limit, so a larger file is refused without reading all of it. Without it, the diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index f92fc2f347..dc3a9f5195 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -22,6 +22,10 @@ use crate::VectorcraftApp; /// The tool the pen's eraser end selects. const ERASER: &str = "eraser"; +/// What decides whether the active tool reads an airbrush pen's finger wheel ([`sync_wheel_use`]): +/// the active document's uid and revision, its current brush, and the tool with its options. +type WheelKey = (Option<(u64, u64)>, Option, &'static str, serde_json::Value); + /// The end of the pen the canvas saw last, and the tool the eraser end stands in for /// ([`sync_eraser_tool`]). #[derive(Clone, Debug, Default)] @@ -30,6 +34,8 @@ pub(crate) struct PenEnd { end: Option, /// The tool that was active when the eraser end selected the Eraser. before: Option<&'static str>, + /// What the host was last told about the finger wheel, and for which state ([`sync_wheel_use`]). + wheel: Option<(WheelKey, bool)>, } impl PenEnd { @@ -79,6 +85,33 @@ pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool { } } +/// Tells the host whether the active tool reads an airbrush pen's finger wheel +/// ([`crate::Services::stylus_wheel`]): the Paintbrush with a brush on Stylus Wheel, or +/// the Blob Brush or the Eraser with a value on it. The host is told at the first call and then each time the answer +/// changes; the tool is asked again only when the document, its current brush, the tool or its +/// options change. +/// +/// [`VectorcraftApp::tick`] calls this once a frame, with no document open too, and the canvas +/// calls it again when the pen's end changes the tool ([`sync_eraser_tool`]). +pub(crate) fn sync_wheel_use(app: &mut VectorcraftApp) { + if app.services.stylus_wheel.is_none() { + return; + } + let st = app.session.active(); + let key = + (st.map(|s| (s.uid, s.revision)), st.and_then(|s| vectorcraft_brush::current(&s.doc)), app.session.tool_id(), app.session.tool_options()); + if app.pen_end.wheel.as_ref().is_some_and(|(k, _)| *k == key) { + return; + } + let used = app.session.tool_reads_wheel(app.view_info()); + let told = app.pen_end.wheel.replace((key, used)).map(|(_, u)| u); + if told != Some(used) + && let Some(tell) = app.services.stylus_wheel.as_mut() + { + tell(used); + } +} + #[cfg(test)] mod tests { use super::*; @@ -126,4 +159,33 @@ mod tests { assert!(!sync_eraser_tool(&mut app)); assert_eq!(app.session.tool_id(), "rectangle"); } + + #[test] + fn the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel() { + use serde_json::json; + let told = std::rc::Rc::new(std::cell::RefCell::new(vec![])); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let tell = told.clone(); + app.services.stylus_wheel = Some(Box::new(move |used| tell.borrow_mut().push(used))); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.select_tool("paintbrush"); + let frame = |app: &mut VectorcraftApp| { + sync_wheel_use(app); + told.borrow().clone() + }; + assert_eq!(frame(&mut app), [false], "told at the first frame"); + assert_eq!(frame(&mut app), [false], "and not again while nothing changes"); + app.session.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap(); + assert_eq!(frame(&mut app), [false], "a brush without Stylus Wheel"); + let params = json!({"variation": [0, 0, 2], "modes": ["fixed", "fixed", "stylusWheel"]}); + app.session.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap(); + assert_eq!(frame(&mut app), [false, true], "its size on Stylus Wheel"); + app.select_tool("rectangle"); + assert_eq!(frame(&mut app), [false, true, false], "another tool"); + app.select_tool(ERASER); + assert_eq!(frame(&mut app), [false, true, false], "the Eraser at its defaults"); + app.session.set_tool_option("sizeMode", &json!("stylusWheel")); + app.session.set_tool_option("sizeVariation", &json!(4)); + assert_eq!(frame(&mut app), [false, true, false, true], "its size on Stylus Wheel"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 35827ca59c..4993e92808 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2161,6 +2161,20 @@ one opens as before and draws it as `rgb`: → invalid parameters for `effect.setParams`: `channel` must be one of rgb, red, green, blue ``` +The `mode` of Drop Shadow, Inner Glow and Outer Glow must name one of the 16 blend modes: `normal`, `darken`, +`multiply`, `colorBurn`, `lighten`, `screen`, `colorDodge`, `overlay`, `softLight`, `hardLight`, `difference`, +`exclusion`, `hue`, `saturation`, `color` or `luminosity`. The name is read in any letter case and with any spaces, +hyphens or underscores (`Color Burn` and `color-burn` are `colorBurn`). An omitted `mode` keeps the effect's default +(`multiply` for Drop Shadow, `screen` for the glows). New `effect.apply` and `effect.setParams` calls refuse any other +value. An older document, action or journal with an unknown name still draws it as `normal`. A non-string value uses +the effect's default. The effect dialogs and the Appearance panel show `mode` as a blend-mode menu. +`ui.dialog.set` accepts the same blend-mode spellings. + +```json +{"id": "effect.setParams", "params": {"index": 0, "params": {"mode": "multipy"}}} +→ invalid parameters for `effect.setParams`: `mode` must be one of normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color, luminosity +``` + Radial Blur's Blur Center, `centerX` and `centerY`, must each be a number from 0 to 1: the share of the object's bounds across from its left edge and down from its top edge (0.5 each, the object's center, by default). The effect turns or zooms about that point, which moves and scales with the object. `effect.apply` and `effect.setParams` refuse any other @@ -2899,6 +2913,9 @@ own rules: rejected (the `throw`, or the call of its reject function or of `Promise.reject`), `unhandledRejectionCount` counts all of them, and the Script Console shows an error line for each, as in `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. + `all` and `race` preserve an input rejection's known location. Calling a saved reject function from script uses + that call's location. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits + `file` and sets `line` and `column` to 0. The first run in an engine decides whether the engine has `Symbol` and the iterators of arrays, strings and `arguments` objects, and each run's script decides which syntax that run reads. The built-in functions' names follow @@ -4510,9 +4527,12 @@ already walks Image Trace. Short agent entry points: value goes from the value less the variation (a Scatter brush's first value, an Art brush's `width`) at 0 to the value plus the variation (the second value, `width_max`) at 1, and a stroke without a wheel draws the value half way. Brush Options offers Stylus Wheel for a Calligraphic or Scatter brush's Size and an Art brush's Width. The - desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11 and from AppKit (`tangentialPressure`) on macOS; - it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation - code 3. + desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and + on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` + is installed; without it a Windows pen reads no wheel. Windows opens the Wintab context only while the active tool + uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Blob Brush or + the Eraser with a value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps + no wheel. The web build does not read it. `.ai` brush definitions read and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it @@ -15359,8 +15379,16 @@ Tools: change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a canceled preview does not leave a circle worked out on the previewed paths. + With `addPoints` on, the circle also adds an anchor point to the first segment and to the second segment (or the + one beside it) where it touches them, with `path.insertAnchor` at that point, so the segments are split without + changing their shape; the anchors and the circle are one `command.batch` undo step, and one Undo removes all of them. + When a touched path was not selected, a `select.set` step puts the selection back before the circle is drawn, so + Draw Behind places the circle behind the objects that were selected. + A touch within 0.05 screen pixels of an existing anchor adds no anchor there; when neither touch adds one, only the + circle is drawn. Alt (Option on macOS) held at the release turns `addPoints` the other way for that circle, and a + dot right of and below the pointer shows while it is in effect, following Alt as it is pressed and let go. Options (`tool.setOption`, or a double-click on the tool; kept with the preferences): `radius` (pt, 0.01 to - 1000000, 36); `center` and `radii` (true or false, both true) show the center cross and the radii; `color` (`red`, + 1000000, 36); `addPoints` (Add Points to Existing Paths, true or false, false); `center` and `radii` (true or false, both true) show the center cross and the radii; `color` (`red`, `blue`, `magenta`, `green`, `black` or `gray`; `red`) is the color of the circle, the cross, the radii and the note; `snapTolerance` (screen pixels, 0 to 25, 3; VectorCraft's own range and default) is how near the pointer picks a segment while Smart Guides are on (their Snapping Tolerance counts instead when it is larger) or while they are off diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d4a1268661..969a00aea6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -680,6 +680,8 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline and the hover highlight; `the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn` in the same file covers the limit; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group or layer draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover outline and other panes. A selected blend, repeat or intertwine draws no outline for its hidden members. The points of hidden members do not count toward the 100,000-point limit. The rectangle drawn above that limit still uses the selection's bounds, which include a group's hidden members. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` (with the hover outline) and `the_overlay_limit_leaves_out_hidden_members` in `crates/ui-egui/src/canvas/selection/tests.rs`; `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. @@ -1116,7 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. @@ -1371,6 +1373,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`). + - Screen readers read the isolation bar's back arrow as a button named for what it does (Back One Level, Exit Isolation Mode, Exit Symbol Editing Mode, or Done while a pattern is edited), in the UI's language (`the_isolation_bars_controls_have_screen_reader_names`). - In isolation mode the Layers panel lists only the art of the isolated layer, sublayer or group, and lists the other layers and groups again when isolation mode ends ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=212)). As VectorCraft's own rules, the isolated layer, sublayer, group or object is the top row and opens on entering, the panel scrolls back to its row on leaving, search and filter look only inside it, nothing is dropped beside its row or into the empty space under the rows, Rename and Locate Object open no rows outside it, and rows highlighted outside it are no longer highlighted. With no row highlighted, Delete Selection and the trash do not delete a current layer outside it. New Layer, New Sublayer and Duplicate (in the panel menu and a row's context menu) are off, and OK in New Layer Options is an error, while the layer or copy they make would be outside it (`isolation_lists_only_the_isolated_art_and_exit_lists_every_layer_again`, `isolation_opens_the_isolated_row_and_keeps_drops_inside_it`, `isolation_drops_highlights_outside_the_isolated_art`, `isolation_keeps_rename_and_locate_to_the_rows_listed`, `isolation_keeps_delete_to_the_rows_listed`, `isolation_keeps_new_layers_to_the_rows_listed`, `new_layer_options_ok_checks_isolation_again`). - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). @@ -2130,7 +2133,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2138,7 +2141,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still, no packet has come for longer, or another tablet's cursor has been read since, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. @@ -3097,6 +3100,8 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +Add Points to Existing Paths (2026-11-20): the tool's `addPoints` option (in its options, off to start) also adds an anchor point where the circle touches each of the two segments, splitting them without changing their shape, in the circle's undo step; a touch at an existing anchor adds none. Alt held at the release turns the option the other way for that circle, and a dot beside the pointer shows while it is in effect. Tests: `addons::tangent_circle::tests::add_points_*` in `vectorcraft-tools`, `the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step` in `vectorcraft-engine`, and the options dialog test in `vectorcraft-ui-egui`. + The tool's options dialog also sets the preview and how a segment is picked, the options the help page lists (https://docs.astutegraphics.com/subscribe/tangent-circle-tool): Circle Center and Circle Radii Lines (`center`, `radii`) show or hide the center cross and the radii, Color (`color`: red, blue, magenta, green, black or gray) colors the circle, the cross, the radii and the note, Snap Tolerance (`snapTolerance`, screen pixels) is how near the pointer picks a segment with Smart Guides on, the Smart Guides Snapping Tolerance counting when it is larger, and Snap When Smart Guides Are Off (`snapWithoutGuides`) keeps that reach with Smart Guides off; without it the Selection Tolerance applies. Of the segments within reach the nearest is picked. The defaults (both shown, red, 3 px, snapping on) and the 0 to 25 px range are VectorCraft's own; they are kept with the preferences, and `tool.setOption` gives an error for a value an option does not take. Tests: `addons::tangent_circle::tests` in `vectorcraft-tools` (the preview options, the snapping reach, the options' values) and `the_tangent_circle_options_set_the_preview_and_snapping` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 372d4fe912..142666cec2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -561,7 +561,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored |