Merge main into fix/pathfinder-disabled-shape-modes-dim

This commit is contained in:
dotCooCoo
2026-11-28 22:31:02 -08:00
13 changed files with 252 additions and 29 deletions
+98
View File
@@ -0,0 +1,98 @@
//! The hand-off from the browser's input hook to the visible UI pass.
use std::cell::Cell;
use egui::{DroppedFileHandle, Pos2, RawInput};
/// CSS pixels from the canvas origin, and whether Shift was held.
pub(crate) type DragPosition = (f32, f32, bool);
pub(crate) struct DropBatch {
pub(crate) files: Vec<DroppedFileHandle>,
pub(crate) pos: Option<Pos2>,
pub(crate) shift: bool,
}
#[derive(Default)]
pub(crate) struct FileDrops(Vec<DroppedFileHandle>);
impl FileDrops {
pub(crate) fn capture(&mut self, raw: &mut RawInput) {
// The shared router reads dropped files at the start of the pass, before the web UI runs.
self.0.append(&mut raw.dropped_files);
}
pub(crate) fn take(&mut self, ctx: &egui::Context, position: &Cell<Option<DragPosition>>) -> Option<DropBatch> {
let files = std::mem::take(&mut self.0);
if files.is_empty() {
return None;
}
let at = position.take();
let z = ctx.zoom_factor();
let pos = at.map(|(x, y, _)| egui::pos2(x / z, y / z));
let shift = at.is_some_and(|(_, _, shift)| shift);
Some(DropBatch { files, pos, shift })
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
#[derive(Debug)]
struct Svg;
impl egui::DroppedFile for Svg {
fn path(&self) -> &Path {
Path::new("drawing.svg")
}
fn bytes(&self) -> Result<Vec<u8>, String> {
Err("test file has no contents".into())
}
}
fn check_handoff(at: Option<DragPosition>, expected_pos: Option<Pos2>, expected_shift: bool) {
let ctx = egui::Context::default();
let shared_files = Arc::new(AtomicUsize::new(0));
ctx.on_begin_pass("observe dropped files before the app UI", {
let shared_files = shared_files.clone();
Arc::new(move |ui| {
shared_files.fetch_add(ui.ctx().input(|input| input.raw.dropped_files.len()), Ordering::Relaxed);
})
});
let mut drops = FileDrops::default();
let position = Cell::new(at);
let svg = Arc::new(Svg) as DroppedFileHandle;
let mut raw = RawInput { dropped_files: vec![svg.clone()], ..Default::default() };
drops.capture(&mut raw);
let mut delivered = Vec::new();
ctx.run_ui(raw, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
let mut next = RawInput::default();
drops.capture(&mut next);
ctx.run_ui(next, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
assert_eq!(shared_files.load(Ordering::Relaxed), 0, "the shared router must not see browser-owned drops");
assert_eq!(delivered.len(), 1, "the browser UI must receive exactly one batch");
let batch = &delivered[0];
assert_eq!(batch.files.len(), 1, "the browser UI must receive exactly one file");
assert!(Arc::ptr_eq(&batch.files[0], &svg));
assert_eq!((batch.pos, batch.shift), (expected_pos, expected_shift));
assert!(position.get().is_none());
}
#[test]
fn a_positioned_browser_drop_reaches_the_web_ui_once() {
check_handoff(Some((53.0, 27.0, true)), Some(egui::pos2(53.0, 27.0)), true);
}
#[test]
fn a_browser_drop_without_a_position_reaches_the_web_ui_once() {
check_handoff(None, None, false);
}
}
+2
View File
@@ -22,6 +22,8 @@
#[cfg(target_arch = "wasm32")]
mod api;
#[cfg(any(target_arch = "wasm32", test))]
mod file_drops;
#[cfg(target_arch = "wasm32")]
mod fonts;
#[cfg(any(target_arch = "wasm32", test))]
+9 -12
View File
@@ -22,6 +22,7 @@ use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
use vectorcraft_ui_egui::{Services, VectorcraftApp};
use wasm_bindgen::JsCast as _;
use crate::file_drops::{DragPosition, DropBatch, FileDrops};
use crate::locks::WebLocks;
use crate::pencil::SharedPointers;
@@ -39,7 +40,7 @@ struct OpenInboxes {
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
/// whether Shift was held: where dropped files land.
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
type DragPos = Rc<Cell<Option<DragPosition>>>;
/// A picture or file pasted into the page, read and waiting for the next frame with the modifiers
/// held at the paste, and the context to wake for it (the current runner's).
@@ -176,7 +177,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
}
};
app.adopt_context(ctx);
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss }))
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss, dropped: FileDrops::default() }))
}),
)
.await;
@@ -376,6 +377,7 @@ struct WebShell {
host: Host,
canvas: web_sys::HtmlCanvasElement,
loss: GraphicsLoss,
dropped: FileDrops,
}
impl WebShell {
@@ -410,9 +412,9 @@ impl eframe::App for WebShell {
embed::logic(ctx, || app.close_decision());
}
/// Forward host-gathered pointer events into this frame's raw input, then let the app apply its
/// shared input hook before egui runs.
/// Gather browser drops and forward host pointer events before egui runs.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.dropped.capture(raw);
raw.events.extend(self.host.pointers.borrow_mut().take());
if let Some(app) = &mut self.app {
app.raw_input(ctx, raw);
@@ -425,18 +427,13 @@ impl eframe::App for WebShell {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
if let Some(app) = &mut self.app {
// DOM paste and drop are host input: read them in the UI phase, once per pass, not in
// `logic` where a hidden tab replays the last shown frame's input.
// Deliver host input in a visible UI pass. Hidden tabs only run `logic`.
let pasted = self.host.pasted.borrow_mut().flavour.take();
if let Some((f, held)) = pasted {
app.paste_from_host(&ctx, f, held);
}
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
if !dropped.is_empty() {
let at = self.host.drag.take();
let z = ctx.zoom_factor();
let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2));
for f in dropped {
if let Some(DropBatch { files, pos, shift }) = self.dropped.take(&ctx, &self.host.drag) {
for f in files {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
let target = app.drop_target(&name, app.drop_spot(pos), shift);
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
+13 -1
View File
@@ -97,6 +97,16 @@ pub(super) fn walk_but<'a>(nodes: &'a [Arc<Node>], skip: &HashSet<NodeId>, f: &m
}
}
/// [`walk_but`] in reverse paint order: the topmost node first.
fn walk_but_topmost_first<'a>(nodes: &'a [Arc<Node>], skip: &HashSet<NodeId>, f: &mut impl FnMut(&'a Node)) {
for n in nodes.iter().rev().filter(|n| n.visible && !skip.contains(&n.id)) {
if let Some(ch) = n.children() {
walk_but_topmost_first(ch.get(usize::from(n.extras().shaper.is_some())..).unwrap_or_default(), skip, f);
}
f(n);
}
}
/// The lines of `lines` (sorted by where they run) within `tol` of `v`.
pub(super) fn lines_near(lines: &[(f64, Point, Kind)], v: f64, tol: f64) -> &[(f64, Point, Kind)] {
within(lines, |l| l.0, v, tol)
@@ -629,7 +639,9 @@ impl Targets {
}
}
let (mut budget, mut segment_budget) = (BUDGET, BUDGET);
walk_but(&doc.layers, &exclude.iter().copied().collect(), &mut |n| {
// Topmost first, so when the budgets run out the objects in front, the newest, keep
// their anchors, edges and centre (#8531).
walk_but_topmost_first(&doc.layers, &exclude.iter().copied().collect(), &mut |n| {
if budget == 0 || n.is_container() || !n.visible {
return;
}
+34
View File
@@ -11,6 +11,40 @@ fn artboard_bleed_is_a_target() {
assert_eq!(t.snap_point(Point::new(512.0, 300.0), 4.0).0.x, 510.0);
}
/// #8531: when a document has more anchors than the targets gather, the object drawn last, in
/// front, still gives its anchors, edges and centre, for a ruler guide, a moved selection and a
/// drawn point, while the anchors stay capped.
#[test]
fn the_topmost_object_keeps_its_targets_past_the_anchor_budget() {
let (d, rect) = doc_with_rect_over_many_anchors();
let t = Targets::collect(&d, &[], None);
let anchors: Vec<Point> = t.points.iter().filter(|(_, k)| *k == Kind::Anchor).map(|(p, _)| *p).collect();
let in_doc: usize = d.layers[0]
.children()
.into_iter()
.flatten()
.map(|n| match &n.kind {
NodeKind::Path { path, .. } => path.anchors().count(),
_ => 0,
})
.sum();
assert!(anchors.len() < in_doc, "the anchors stay capped");
assert!(anchors.contains(&Point::new(400.0, 300.0)), "the rectangle's corner");
assert_eq!(t.snap_guide(false, 301.0, 4.0).0, 300.0, "the bottom edge");
assert_eq!(t.snap_guide(true, 398.0, 4.0).0, 400.0, "the right edge");
let (p, ov) = t.snap_point(Point::new(302.0, 201.0), 4.0);
assert_eq!(p, Point::new(300.0, 200.0));
assert!(matches!(&ov[0], Overlay::Label { text, .. } if text == "center"), "{ov:?}");
// A box moved next to it lines up with its top edge.
let other = Targets::collect(&d, &[rect], None);
let (s, pt) = (Selection::default(), paint());
let moving = Targets::for_move(&cx(&d, &s, &pt), &[]);
assert_eq!(moving.snap_rect(Rect::new(420.0, 102.0, 450.0, 130.0), 4.0).0.y, -2.0);
assert_eq!(other.snap_rect(Rect::new(420.0, 102.0, 450.0, 130.0), 4.0).0.y, 0.0, "without the rectangle, nothing near");
let drawn = Targets::for_drawing(&d, &[], None, None);
assert_eq!(drawn.snap_point(Point::new(450.0, 298.0), 4.0).0.y, 300.0);
}
#[test]
fn snaps_to_anchor_and_alignment() {
let (d, _) = doc_with_rect();
+15
View File
@@ -442,6 +442,21 @@ pub(crate) mod testutil {
(d, id)
}
/// #8531: 21 polygons of 1000 sides at (40, 30)–(80, 70), 21,000 anchors (more than the
/// snap targets gather), drawn first, and over them a rectangle (200, 100)–(400, 300): the
/// document and the rectangle.
pub fn doc_with_rect_over_many_anchors() -> (Document, NodeId) {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
for i in 0..21 {
let id = d.alloc_id();
d.insert(Some(l), i, Node::path(id, shapes::polygon(Point::new(60.0, 50.0), 20.0, 1000, 0.0), Appearance::default_art())).unwrap();
}
let id = d.alloc_id();
d.insert(Some(l), 21, Node::path(id, shapes::rectangle(Rect::new(200.0, 100.0, 400.0, 300.0)), Appearance::default_art())).unwrap();
(d, id)
}
/// A live 100 × 100 rectangle at (100, 100)–(200, 200) with no paint: its centre point
/// (Attributes › Show Center) is at (150, 150), and a press in the middle of it hits no art.
pub fn doc_with_live_rect() -> (Document, NodeId) {
+15
View File
@@ -108,6 +108,21 @@ fn a_new_guide_snaps_to_the_art_and_the_artboard() {
assert_eq!(drag(true, 320.0), (320.0, None), "nothing within reach");
}
/// #8531: in a document with more anchors than the snap targets gather, a guide dragged out of
/// the top ruler still lands on the edge of the rectangle drawn last, over all of them.
#[test]
fn a_new_guide_snaps_to_the_newest_object_over_many_anchors() {
let (d, _) = doc_with_rect_over_many_anchors();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let m = Mods::default();
let mut g = NewGuide::new(&c, false, None);
assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 300.0, -5.0, m), false), vec![], "still over the ruler");
let a = g.pointer(&c, &ev(PointerKind::Drag, 300.0, 301.0, m), true);
assert_eq!(a.last(), Some(&Action::Preview("guide.add".into(), json!({"vertical": false, "pos": 300.0}))), "onto the bottom edge: {a:?}");
assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 300.0, 301.0, m), true), vec![Action::Commit]);
}
/// Preferences › Smart Guides (#394) reach a guide dragged out of a ruler: Snapping
/// Tolerance sets how far a target pulls it, Anchor/Path Labels and Measurement Labels what
/// shows by it.
+29 -7
View File
@@ -37,6 +37,12 @@ const TODO_TOOLTIP: &str = "Coming soon — tracked in the parity plan";
pub(crate) struct Menus {
key: Option<u64>,
target: Option<Target>,
/// The pass number of the last frame with a pointer button or a key press ([`pressed_pass`]), `None` before the
/// first: the `input` of [`state_key`].
pressed: Option<u64>,
/// How many times [`refresh`] built the model.
#[cfg(test)]
pub(crate) rebuilds: u64,
/// The menus as built, before a layout.
pub(crate) bar: MenuBar,
/// `bar` laid out for the shell's target: what the in-window bar shows.
@@ -79,8 +85,9 @@ pub(crate) fn translate_label(english: &'static str) -> String {
/// What the menus' rows depend on, cheaply (no allocation): commands run, the active document,
/// its revision (edits, selection and view changes), history and clipboard, the filter plug-in that ran last, the language,
/// shortcuts, plug-ins, the Scripts folder's listing, an open file dialog and the fonts (Type › Font lists the loaded fonts
/// until the installed ones are scanned, then all of them, #5483). `input` forces a change on frames with a click or
/// a key press, which covers what the hash doesn't list (panels shown, a tool picked). While an
/// until the installed ones are scanned, then all of them, #5483). `input`, the pass of the last frame with a pointer
/// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash
/// doesn't list (panels shown, a tool picked). While an
/// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's
/// preview, or a typing session), the revision, which each of its previews changes, is left out:
/// the hash changes as the interaction begins and as it ends.
@@ -122,19 +129,34 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
/// when the rows' state ([`state_key`]) or the shell's target changed.
pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) {
let target = Target::of_shell(&WindowHost::of(ctx).shell());
let key = state_key(app, pressed_pass(ctx));
let press = last_press(app, ctx);
let key = state_key(app, press);
if app.menus.key == Some(key) && app.menus.target == Some(target) {
return;
}
rebuild(app, target);
#[cfg(test)]
{
app.menus.rebuilds += 1;
}
app.menus.key = Some(key);
app.menus.target = Some(target);
}
/// The frame's pass number when it has a click or a key press: the `input` of [`state_key`].
pub(crate) fn pressed_pass(ctx: &egui::Context) -> Option<u64> {
let pressed = ctx
.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::Key { pressed: true, .. })));
/// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read
/// last included: the `input` of [`state_key`]. It stays the same over the frames after that one, so each of them
/// changes the key once.
pub(crate) fn last_press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option<u64> {
if let Some(pass) = pressed_pass(ctx) {
app.menus.pressed = Some(pass);
}
app.menus.pressed
}
/// The frame's pass number when it has a pointer button pressed or released (a click ends at the release) or a key
/// pressed.
fn pressed_pass(ctx: &egui::Context) -> Option<u64> {
let pressed = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { .. } | egui::Event::Key { pressed: true, .. })));
pressed.then(|| ctx.cumulative_pass_nr())
}
+5 -4
View File
@@ -6,7 +6,7 @@ use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac,
use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder};
use crate::VectorcraftApp;
use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label};
use crate::menus::model::{APP_NAME, item_title, last_press, recording_shortcut, refresh, state_key, translate_label};
use crate::menus::{command_shortcuts, item_shortcut_in, unbound};
/// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its
@@ -40,13 +40,14 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
}
/// Once per frame, after the UI: bring the native menu up to date. Frames with input read the
/// menus again, as input may change state the key doesn't list.
/// Once per frame, after the UI: bring the native menu up to date. A frame with a click or a key
/// press reads the menus again, as input may change state the key doesn't list.
pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) {
if app.services.native_menu.is_none() {
return;
}
let state = state_key(app, pressed_pass(ctx));
let press = last_press(app, ctx);
let state = state_key(app, press);
let keys = |chord: &_| holder(ctx, chord);
let options = options().keys(&keys);
// Out of the app while the layout reads it.
+23
View File
@@ -164,6 +164,29 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() {
assert_eq!(menu.toggled("Pixel Snapping Options…"), None);
}
/// A key press builds the menus' states again once: the frames after it, with no press, keep them.
#[test]
fn a_key_press_rebuilds_the_menus_once() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
let ctx = crate::testing::ui_context();
for _ in 0..3 {
app_frame(&mut app, &ctx, vec![]);
}
let before = app.menus.rebuilds;
for _ in 0..3 {
app_frame(&mut app, &ctx, vec![]);
}
assert_eq!(app.menus.rebuilds, before, "idle frames keep the menus");
// F20 runs no command and changes nothing the menus show.
let press = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
app_frame(&mut app, &ctx, vec![press(true), press(false)]);
for _ in 0..4 {
app_frame(&mut app, &ctx, vec![]);
}
assert_eq!(app.menus.rebuilds, before + 1);
}
#[test]
fn help_f1_opens_discover_without_a_document() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
+3 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -2
View File
File diff suppressed because one or more lines are too long