mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 23:50:13 +00:00
Merge main into fix/flare-lone-x2-y2-error
This commit is contained in:
@@ -644,13 +644,19 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
// (style source, shape) per stack entry; keys index `sources`.
|
||||
let mut sources: Vec<Node> = vec![];
|
||||
let mut shapes: Vec<po::Shape> = vec![];
|
||||
// Keys of the group operands whose art has no area left at the precision.
|
||||
let mut collapsed: Vec<u64> = vec![];
|
||||
for mut lv in all {
|
||||
if shape_mode && lv.len() > 1 {
|
||||
let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(geometry).collect();
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
let key = sources.len() as u64;
|
||||
if let Some(top) = lv.pop() {
|
||||
shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key));
|
||||
let united = po::unite_all_with(&refs, options.precision);
|
||||
if united.is_empty() && !parts.is_empty() {
|
||||
collapsed.push(key);
|
||||
}
|
||||
shapes.push(po::Shape::new(united, FillRule::NonZero, key));
|
||||
sources.push(top);
|
||||
}
|
||||
} else {
|
||||
@@ -662,6 +668,18 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
}
|
||||
}
|
||||
}
|
||||
// An operand with no area still takes part: Intersect, and Minus Front or Minus Back when
|
||||
// it is the shape the others are cut from, then leave nothing.
|
||||
let is_collapsed = |s: &po::Shape| collapsed.contains(&s.key);
|
||||
let nothing_left = match op {
|
||||
PathfinderOp::Intersect => shapes.iter().any(is_collapsed),
|
||||
PathfinderOp::MinusFront => shapes.first().is_some_and(is_collapsed),
|
||||
PathfinderOp::MinusBack => shapes.last().is_some_and(is_collapsed),
|
||||
_ => false,
|
||||
};
|
||||
if nothing_left {
|
||||
return Some(vec![]);
|
||||
}
|
||||
shapes.retain(|s| !s.path.is_empty() && s.path.subpaths.iter().all(|sp| sp.anchors.iter().all(|a| a.p.x.is_finite() && a.p.y.is_finite())));
|
||||
if shapes.is_empty() {
|
||||
return Some(vec![]);
|
||||
|
||||
@@ -196,6 +196,49 @@ fn shape_modes_follow_the_pathfinder_panel() {
|
||||
assert_eq!(div.len(), 3);
|
||||
}
|
||||
|
||||
/// An Intersect effect draws nothing when a group member's art has no area left at the effect's
|
||||
/// precision, and so do Minus Back when that group is in front and Subtract when it is at the
|
||||
/// back. Add, and Subtract with the group in front, leave such a member out.
|
||||
#[test]
|
||||
fn intersect_with_a_group_that_collapses_at_its_precision_draws_nothing() {
|
||||
let thin_pair = |width: f64| {
|
||||
let bar = |id: u64, x: f64| {
|
||||
let fill = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 10.0, x + width, 30.0)), fill))
|
||||
};
|
||||
Node::group(NodeId(5), vec![bar(3, 10.0), bar(4, 50.0)])
|
||||
};
|
||||
let with_precision = |front: Node, effect: &str| {
|
||||
let mut g = square_and(Some(front), effect);
|
||||
g.appearance.effects[0].params = serde_json::json!({"precision": 1.0});
|
||||
g
|
||||
};
|
||||
let int = results(&with_precision(thin_pair(0.5), "pathfinder.intersect"));
|
||||
assert!(int.is_empty(), "{int:#?}");
|
||||
// Bars wider than the precision keep their area.
|
||||
let int = results(&with_precision(thin_pair(2.0), "pathfinder.intersect"));
|
||||
let total: f64 = int.iter().map(|n| area(n)).sum();
|
||||
assert!((total - 80.0).abs() < 1.0, "{total}: {int:#?}");
|
||||
// Add keeps the square alone.
|
||||
let add = results(&with_precision(thin_pair(0.5), "pathfinder.add"));
|
||||
assert_eq!(add.len(), 1);
|
||||
assert!((area(&add[0]) - 10_000.0).abs() < 1.0, "{add:#?}");
|
||||
// Minus Back cuts the square from the empty group in front, and Subtract cuts nothing from
|
||||
// the square.
|
||||
let minus_back = results(&with_precision(thin_pair(0.5), "pathfinder.minusBack"));
|
||||
assert!(minus_back.is_empty(), "{minus_back:#?}");
|
||||
let subtract = results(&with_precision(thin_pair(0.5), "pathfinder.subtract"));
|
||||
assert_eq!(subtract.len(), 1);
|
||||
assert!((area(&subtract[0]) - 10_000.0).abs() < 1.0, "{subtract:#?}");
|
||||
// With the group at the back, Subtract cuts the square from it and leaves nothing.
|
||||
let mut back = with_precision(thin_pair(0.5), "pathfinder.subtract");
|
||||
if let NodeKind::Group { children, .. } = &mut back.kind {
|
||||
children.reverse();
|
||||
}
|
||||
let subtract = results(&back);
|
||||
assert!(subtract.is_empty(), "{subtract:#?}");
|
||||
}
|
||||
|
||||
/// Divide and Outline draw no piece of a member without fill or stroke, the same as when such
|
||||
/// pieces are left out.
|
||||
#[test]
|
||||
|
||||
@@ -91,6 +91,8 @@ impl FontDb {
|
||||
/// guard's thread uses the fonts it lends and not this one.
|
||||
pub fn set_composite_font(&self, font: &CompositeFont) -> bool {
|
||||
let key = font.name.to_lowercase();
|
||||
#[cfg(any(test, feature = "test-fonts"))]
|
||||
let _change = crate::test_fonts::font_change();
|
||||
{
|
||||
let mut map = self.composites.write().unwrap_or_else(|e| e.into_inner());
|
||||
if map.get(&key).is_some_and(|f| **f == *font) {
|
||||
@@ -104,6 +106,8 @@ impl FontDb {
|
||||
|
||||
/// Forget the composite font named `name` (any case). Whether there was one.
|
||||
pub fn remove_composite_font(&self, name: &str) -> bool {
|
||||
#[cfg(any(test, feature = "test-fonts"))]
|
||||
let _change = crate::test_fonts::font_change();
|
||||
let removed = self.composites.write().unwrap_or_else(|e| e.into_inner()).remove(&name.to_lowercase()).is_some();
|
||||
if removed {
|
||||
self.changed();
|
||||
|
||||
@@ -305,6 +305,8 @@ impl FontDb {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(any(test, feature = "test-fonts"))]
|
||||
let _change = (!made.is_empty()).then(crate::test_fonts::font_change);
|
||||
let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let before = faces.len();
|
||||
for f in made {
|
||||
@@ -325,7 +327,7 @@ impl FontDb {
|
||||
|
||||
/// Catalog the installed fonts unless that has been done: the first caller scans the font
|
||||
/// folders, any other waits for that scan to finish. A no-op on wasm.
|
||||
pub(super) fn ensure_catalog(&self) {
|
||||
pub(crate) fn ensure_catalog(&self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.cataloged.get_or_init(|| {
|
||||
self.scan_font_dirs();
|
||||
@@ -448,6 +450,9 @@ impl FontDb {
|
||||
}
|
||||
log::debug!("cataloged {n} system font faces");
|
||||
let installed: std::collections::HashSet<PathBuf> = catalog.values().flat_map(|c| c.faces.iter().map(|cf| cf.path.clone())).collect();
|
||||
// The first scan waits for nothing: a guard is made only for a database already cataloged.
|
||||
#[cfg(any(test, feature = "test-fonts"))]
|
||||
let _change = self.cataloged.get().is_some().then(crate::test_fonts::font_change);
|
||||
*self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at });
|
||||
*self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog;
|
||||
*self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases;
|
||||
|
||||
@@ -45,6 +45,136 @@ pub fn drop_kept_layouts() {
|
||||
crate::kept::drop_kept_layouts();
|
||||
}
|
||||
|
||||
/// Who holds [`SteadyFonts`] and who changes fonts ([`font_change`]), guarded by [`steadiness`] and
|
||||
/// signaled through [`STEADINESS_CHANGED`].
|
||||
struct Steadiness {
|
||||
/// Threads that hold a [`SteadyFonts`].
|
||||
holders: usize,
|
||||
/// Font changes waiting to start.
|
||||
waiting: usize,
|
||||
/// Of `waiting`, those made on a thread that holds a [`SteadyFonts`].
|
||||
holders_waiting: usize,
|
||||
/// Whether a font change is under way.
|
||||
changing: bool,
|
||||
}
|
||||
|
||||
static STEADINESS: std::sync::Mutex<Steadiness> = std::sync::Mutex::new(Steadiness { holders: 0, waiting: 0, holders_waiting: 0, changing: false });
|
||||
static STEADINESS_CHANGED: std::sync::Condvar = std::sync::Condvar::new();
|
||||
|
||||
fn steadiness() -> std::sync::MutexGuard<'static, Steadiness> {
|
||||
STEADINESS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Wait for [`STEADINESS_CHANGED`].
|
||||
fn await_steadiness(s: std::sync::MutexGuard<'static, Steadiness>) -> std::sync::MutexGuard<'static, Steadiness> {
|
||||
STEADINESS_CHANGED.wait(s).unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// How many [`SteadyFonts`] this thread holds.
|
||||
static STEADY: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Whether this thread holds the [`FontChange`] under way.
|
||||
static CHANGING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While held, a cataloged font database's fonts and its
|
||||
/// [`FontDb::generation`](crate::FontDb::generation) change only on this thread: a change on another
|
||||
/// thread (a system font loaded for a character no loaded font covers, fonts added, a rescan, a
|
||||
/// composite font set or removed) waits until it is dropped, before it publishes anything. A change
|
||||
/// on this thread waits until no other thread holds one, unless every other thread that holds one is
|
||||
/// itself waiting to change fonts. Tests hold it to count the layouts that a cache keyed on the
|
||||
/// generation keeps. The guards one thread holds count as one, until the last of them is dropped, in
|
||||
/// whatever order they are.
|
||||
pub struct SteadyFonts {
|
||||
/// Dropped on the thread that made it.
|
||||
_thread: std::marker::PhantomData<*const ()>,
|
||||
}
|
||||
|
||||
impl Drop for SteadyFonts {
|
||||
fn drop(&mut self) {
|
||||
let last = STEADY.with(|n| {
|
||||
n.set(n.get() - 1);
|
||||
n.get() == 0
|
||||
});
|
||||
if last {
|
||||
steadiness().holders -= 1;
|
||||
STEADINESS_CHANGED.notify_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`SteadyFonts`] for `db`. Catalogs `db`'s installed fonts first: a first scan does not wait for
|
||||
/// any guard, so this thread can wait for one running on another thread while it holds a guard. A
|
||||
/// thread's first guard waits for the font changes under way or waiting.
|
||||
pub fn steady_fonts(db: &crate::FontDb) -> SteadyFonts {
|
||||
db.ensure_catalog();
|
||||
if STEADY.with(std::cell::Cell::get) == 0 {
|
||||
let mut s = steadiness();
|
||||
while !CHANGING.with(std::cell::Cell::get) && (s.changing || s.waiting > 0) {
|
||||
s = await_steadiness(s);
|
||||
}
|
||||
s.holders += 1;
|
||||
}
|
||||
STEADY.with(|n| n.set(n.get() + 1));
|
||||
SteadyFonts { _thread: std::marker::PhantomData }
|
||||
}
|
||||
|
||||
/// Held while a font database's fonts change, from before the change is published until its
|
||||
/// generation has changed ([`font_change`]).
|
||||
pub(crate) struct FontChange {
|
||||
/// Made while this thread already held one (a change made inside another, as a test hook run
|
||||
/// when faces are published can).
|
||||
nested: bool,
|
||||
}
|
||||
|
||||
impl Drop for FontChange {
|
||||
fn drop(&mut self) {
|
||||
if !self.nested {
|
||||
CHANGING.with(|c| c.set(false));
|
||||
steadiness().changing = false;
|
||||
STEADINESS_CHANGED.notify_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`FontChange`]: waits until no other change is under way and no other thread holds a
|
||||
/// [`SteadyFonts`] (on a thread that holds one: none that is not itself waiting to change fonts).
|
||||
/// Inside a change this thread is making, it does not wait.
|
||||
pub(crate) fn font_change() -> FontChange {
|
||||
if CHANGING.with(std::cell::Cell::get) {
|
||||
return FontChange { nested: true };
|
||||
}
|
||||
let holder = STEADY.with(std::cell::Cell::get) > 0;
|
||||
let mut s = steadiness();
|
||||
#[cfg(test)]
|
||||
font_changers().push(std::thread::current().id());
|
||||
s.waiting += 1;
|
||||
s.holders_waiting += usize::from(holder);
|
||||
while s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 } {
|
||||
s = await_steadiness(s);
|
||||
}
|
||||
s.waiting -= 1;
|
||||
s.holders_waiting -= usize::from(holder);
|
||||
s.changing = true;
|
||||
CHANGING.with(|c| c.set(true));
|
||||
FontChange { nested: false }
|
||||
}
|
||||
|
||||
/// Whether a font change on another thread would wait now (a [`SteadyFonts`] is held, or another
|
||||
/// change is under way).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn font_changes_held_back() -> bool {
|
||||
let s = steadiness();
|
||||
s.holders > 0 || s.changing
|
||||
}
|
||||
|
||||
/// The threads that have asked to change a font database's generation ([`font_change`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn font_changers() -> std::sync::MutexGuard<'static, Vec<std::thread::ThreadId>> {
|
||||
static CHANGERS: std::sync::Mutex<Vec<std::thread::ThreadId>> = std::sync::Mutex::new(Vec::new());
|
||||
CHANGERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The family of [`variable_font`].
|
||||
pub const VARIABLE_FAMILY: &str = "Varitest Sans";
|
||||
|
||||
|
||||
@@ -421,26 +421,27 @@ fn composer_x_mixed_sizes_around_text_wrap() {
|
||||
let l = layout(db(), &t);
|
||||
(line_texts(&t, &l), l, t)
|
||||
};
|
||||
let (every, l, t) = set(Composer::EveryLine);
|
||||
assert_eq!(
|
||||
every,
|
||||
["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."]
|
||||
);
|
||||
assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{:?}", l.lines);
|
||||
// Two spans share each baseline beside the object.
|
||||
assert_eq!(l.lines[1].baseline, l.lines[2].baseline);
|
||||
assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{:?}", l.lines);
|
||||
// The single-line composer measures each line across its height too, and breaks this
|
||||
// paragraph the same way.
|
||||
let (greedy, _, _) = set(Composer::SingleLine);
|
||||
assert_eq!(every, greedy);
|
||||
// paragraph the same way, with its lines set clear of the object as well.
|
||||
for composer in [Composer::EveryLine, Composer::SingleLine] {
|
||||
let (texts, l, t) = set(composer);
|
||||
assert_eq!(
|
||||
texts,
|
||||
["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."],
|
||||
"{composer:?}"
|
||||
);
|
||||
assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{composer:?}: {:?}", l.lines);
|
||||
// Two spans share each baseline beside the object.
|
||||
assert_eq!(l.lines[1].baseline, l.lines[2].baseline, "{composer:?}");
|
||||
assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{composer:?}: {:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -581,23 +582,23 @@ fn composer_x_mixed_sizes_overflow_around_text_wrap() {
|
||||
let l = layout(db(), &t);
|
||||
(line_texts(&t, &l), l, t)
|
||||
};
|
||||
let (every, l, t) = set(Composer::EveryLine);
|
||||
assert!(l.overflow && l.lines.len() >= 3, "{:?}", l.lines);
|
||||
assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{:?}", l.lines);
|
||||
assert!(past_their_room(&t, &l).is_empty(), "{:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{:?}", l.lines);
|
||||
// The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame.
|
||||
assert_eq!(every, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"]);
|
||||
// The single-line composer measures each line across its height too, and breaks the lines
|
||||
// that fit the same way.
|
||||
let (greedy, ..) = set(Composer::SingleLine);
|
||||
assert_eq!(every, greedy);
|
||||
// The single-line composer measures each line across its height too, and breaks and sets the
|
||||
// lines that fit the same way.
|
||||
for composer in [Composer::EveryLine, Composer::SingleLine] {
|
||||
let (texts, l, t) = set(composer);
|
||||
assert!(l.overflow && l.lines.len() >= 3, "{composer:?}: {:?}", l.lines);
|
||||
assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{composer:?}: {:?}", l.lines);
|
||||
assert!(past_their_room(&t, &l).is_empty(), "{composer:?}: {:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines);
|
||||
// The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame.
|
||||
assert_eq!(texts, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"], "{composer:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -50,6 +50,121 @@ fn concurrent_fallback_lookups_all_find_the_installed_face() {
|
||||
std::fs::remove_dir(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Two [`test_fonts::steady_fonts`] guards on one thread hold font changes back until the last of
|
||||
/// them is dropped, whichever was made first.
|
||||
#[test]
|
||||
fn steady_fonts_hold_back_font_changes_until_the_last_guard_is_dropped() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let outer = crate::test_fonts::steady_fonts(&db);
|
||||
let inner = crate::test_fonts::steady_fonts(&db);
|
||||
drop(outer);
|
||||
assert!(crate::test_fonts::font_changes_held_back(), "the inner guard is still held");
|
||||
drop(inner);
|
||||
let first = crate::test_fonts::steady_fonts(&db);
|
||||
let second = crate::test_fonts::steady_fonts(&db);
|
||||
drop(second);
|
||||
assert!(crate::test_fonts::font_changes_held_back(), "the first guard is still held");
|
||||
drop(first);
|
||||
}
|
||||
|
||||
/// While a thread holds [`test_fonts::steady_fonts`], a font added on another thread, which may
|
||||
/// hold one too, changes the database's generation only once the guard is dropped. A thread that
|
||||
/// holds the only guard adds a font itself while another thread's change waits, which then still
|
||||
/// waits for the guard.
|
||||
#[test]
|
||||
fn steady_fonts_hold_back_other_threads_font_changes() {
|
||||
for guarded in [false, true] {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let font = crate::test_fonts::variable_font().unwrap();
|
||||
let steady = crate::test_fonts::steady_fonts(&db);
|
||||
let before = db.generation();
|
||||
std::thread::scope(|scope| {
|
||||
let adding = scope.spawn(|| {
|
||||
let _steady = guarded.then(|| crate::test_fonts::steady_fonts(&db));
|
||||
db.add_font(font)
|
||||
});
|
||||
let id = adding.thread().id();
|
||||
while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(db.generation(), before, "guarded {guarded}: the other thread's change waits for the guard");
|
||||
let listed = db.families().iter().any(|f| f == crate::test_fonts::VARIABLE_FAMILY);
|
||||
assert!(!listed, "guarded {guarded}: the other thread publishes the font only once the guard is dropped");
|
||||
drop(steady);
|
||||
assert!(adding.join().unwrap() > 0, "guarded {guarded}: the font is new to this database");
|
||||
});
|
||||
assert_ne!(db.generation(), before, "guarded {guarded}: the change is made once the guard is dropped");
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let steady = crate::test_fonts::steady_fonts(&db);
|
||||
std::thread::scope(|scope| {
|
||||
let adding = scope.spawn(|| db.add_font(crate::test_fonts::two_axis_font().unwrap()));
|
||||
let id = adding.thread().id();
|
||||
while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
let before = db.generation();
|
||||
assert!(db.add_font(crate::test_fonts::variable_font().unwrap()) > 0);
|
||||
let after = db.generation();
|
||||
assert_ne!(after, before, "the guard's own thread changes the fonts");
|
||||
assert!(!adding.is_finished(), "the waiting change still waits for the guard");
|
||||
assert_eq!(db.generation(), after, "the waiting change still waits for the guard");
|
||||
drop(steady);
|
||||
assert!(adding.join().unwrap() > 0);
|
||||
});
|
||||
}
|
||||
|
||||
/// The first scan of a database's installed fonts does not wait for [`test_fonts::steady_fonts`]
|
||||
/// held for another database, so a thread holding one can catalog a database that another thread
|
||||
/// is scanning.
|
||||
#[test]
|
||||
fn a_first_scan_does_not_wait_for_steady_fonts() {
|
||||
let (held, scanned) = (FontDb::with_font_dirs(vec![]), FontDb::with_font_dirs(vec![]));
|
||||
let steady = crate::test_fonts::steady_fonts(&held);
|
||||
std::thread::scope(|scope| {
|
||||
let scanning = scope.spawn(|| scanned.load_system_fonts());
|
||||
let id = scanning.thread().id();
|
||||
while !scanning.is_finished() && !crate::test_fonts::font_changers().contains(&id) {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
let finished = scanning.is_finished();
|
||||
drop(steady);
|
||||
assert!(finished, "the first scan waited for the guard");
|
||||
scanning.join().unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
/// A font that a hook adds while another add publishes its faces, on the same thread, is added
|
||||
/// without that thread waiting for its own change.
|
||||
#[test]
|
||||
fn a_font_added_while_faces_are_published_is_added() {
|
||||
let db = Arc::new(FontDb::with_font_dirs(vec![]));
|
||||
let adder = db.clone();
|
||||
// Not scoped: a thread that waits for its own change never finishes, and the test still reports.
|
||||
let adding = std::thread::spawn(move || {
|
||||
let (hook_db, mut extra) = (adder.clone(), crate::test_fonts::two_axis_font());
|
||||
crate::fontdb::on_faces_published(Some(Box::new(move || {
|
||||
if let Some(font) = extra.take() {
|
||||
hook_db.add_font(font);
|
||||
}
|
||||
})));
|
||||
let added = adder.add_font(crate::test_fonts::variable_font().unwrap());
|
||||
crate::fontdb::on_faces_published(None);
|
||||
added
|
||||
});
|
||||
let id = adding.thread().id();
|
||||
let changes = || crate::test_fonts::font_changers().iter().filter(|t| **t == id).count();
|
||||
while !adding.is_finished() && changes() < 2 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(adding.is_finished(), "the hook's add waited for the change around it");
|
||||
assert!(adding.join().unwrap() > 0);
|
||||
let families = db.families();
|
||||
for family in [crate::test_fonts::VARIABLE_FAMILY, crate::test_fonts::TWO_AXIS_FAMILY] {
|
||||
assert!(families.iter().any(|f| f == family), "{family} is added");
|
||||
}
|
||||
}
|
||||
|
||||
/// A bundled Source Sans 3 file renamed [`FAMILY`] (as long as the original name).
|
||||
fn renamed(file: &str) -> Vec<u8> {
|
||||
renamed_to(file, FAMILY)
|
||||
|
||||
@@ -12,8 +12,10 @@
|
||||
//! three points can draw, a note says so. The circle is a new ellipse with the current paint, drawn
|
||||
//! with `shape.circleThroughPoints` in one undo step, so Align New Objects to Pixel Grid leaves it
|
||||
//! in place; the first segment stays picked until the circle is drawn, also when drawing fails or the
|
||||
//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, or another
|
||||
//! document forgets the first segment.
|
||||
//! 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.
|
||||
|
||||
use kurbo::{CubicBez, Shape};
|
||||
use serde_json::{Value, json};
|
||||
@@ -55,7 +57,8 @@ struct Pick {
|
||||
/// A press on the second segment, kept while the button is down.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Press {
|
||||
/// The segments a circle may touch.
|
||||
/// The segment pressed on, and the segments a circle may touch.
|
||||
pick: Pick,
|
||||
second: Vec<CubicBez>,
|
||||
/// Where the press was.
|
||||
at: Point,
|
||||
@@ -78,12 +81,13 @@ pub struct TangentCircleTool {
|
||||
found: Option<SegmentCircle>,
|
||||
looked: bool,
|
||||
pointer: Point,
|
||||
/// The circles the last second segment gave (its path, subpath and segment, and the radius
|
||||
/// asked for), so that moving along it only picks among them.
|
||||
/// The circles the last second segment gave (its path, subpath and segment, the radius asked
|
||||
/// for, and the shapes of the first segment and of the segments a circle may touch), so that
|
||||
/// moving along it only picks among them.
|
||||
cache: Option<(CacheKey, Vec<SegmentCircle>)>,
|
||||
}
|
||||
|
||||
type CacheKey = (NodeId, usize, usize, Option<u64>);
|
||||
type CacheKey = (NodeId, usize, usize, Option<u64>, CubicBez, Vec<CubicBez>);
|
||||
|
||||
impl Default for TangentCircleTool {
|
||||
fn default() -> Self {
|
||||
@@ -102,6 +106,17 @@ fn pick_at(cx: &ToolContext, p: Point) -> Option<Pick> {
|
||||
Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve })
|
||||
}
|
||||
|
||||
/// The document's segment at `pick` as it is now: none when its path, subpath or segment is gone.
|
||||
fn segment_now(cx: &ToolContext, pick: &Pick) -> Option<CubicBez> {
|
||||
let sp = cx.doc.node(pick.id)?.path_data()?.subpaths.get(pick.subpath)?;
|
||||
(pick.segment < sp.segment_count()).then(|| sp.segment(pick.segment))
|
||||
}
|
||||
|
||||
/// Whether the document's segment at `pick` still has the shape it had when it was picked.
|
||||
fn unchanged(cx: &ToolContext, pick: &Pick) -> bool {
|
||||
segment_now(cx, pick) == Some(pick.curve)
|
||||
}
|
||||
|
||||
/// 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<CubicBez> {
|
||||
@@ -192,24 +207,35 @@ impl TangentCircleTool {
|
||||
}
|
||||
|
||||
/// The circles `pick` gives as the second segment, with Shift's `radius`: worked out again only
|
||||
/// when the segment or the radius changes.
|
||||
/// when the segment, the radius or the shape of either segment changes.
|
||||
fn circles_on(&mut self, cx: &ToolContext, pick: &Pick, radius: Option<f64>) -> Vec<SegmentCircle> {
|
||||
let key = (pick.id, pick.subpath, pick.segment, radius.map(f64::to_bits));
|
||||
let Some(first) = &self.first else { return vec![] };
|
||||
let second = second_set(cx, first, pick);
|
||||
let key = (pick.id, pick.subpath, pick.segment, radius.map(f64::to_bits), first.curve, second);
|
||||
if let Some((k, found)) = &self.cache
|
||||
&& *k == key
|
||||
{
|
||||
return found.clone();
|
||||
}
|
||||
let Some(first) = &self.first else { return vec![] };
|
||||
let found = circles(first, &second_set(cx, first, pick), radius);
|
||||
let found = circles(first, &key.5, radius);
|
||||
self.cache = Some((key, found.clone()));
|
||||
found
|
||||
}
|
||||
|
||||
/// Forget the first segment when the document's no longer has the shape it was picked with: a
|
||||
/// live preview, or one that was canceled, changes it without an undo step, so the tool is not
|
||||
/// told ([`Tool::history_moved`]).
|
||||
fn forget_if_changed(&mut self, cx: &ToolContext) {
|
||||
if self.first.as_ref().is_some_and(|f| !unchanged(cx, f)) {
|
||||
self.forget();
|
||||
}
|
||||
}
|
||||
|
||||
/// Look for the circle the pointer at `p` would give over `hover`, before any press.
|
||||
fn look(&mut self, cx: &ToolContext, p: Point, mods: Mods) {
|
||||
self.found = None;
|
||||
self.looked = false;
|
||||
self.forget_if_changed(cx);
|
||||
let Some(hover) = self.hover.clone().filter(|_| self.first.is_some()) else { return };
|
||||
let found = self.circles_on(cx, &hover, mods.shift.then_some(self.radius));
|
||||
self.found = nearest_to(found, p, cx.tol(DRAW_PX));
|
||||
@@ -219,15 +245,25 @@ impl TangentCircleTool {
|
||||
/// The pointer at `ev` during a press on the second segment: once it is far enough from the
|
||||
/// press, the radius follows it (Cmd/Ctrl: a tenth of its movement; Shift: round steps).
|
||||
fn drag_to(&mut self, cx: &ToolContext, ev: &PointerEvent) {
|
||||
if self.press.is_none() {
|
||||
return;
|
||||
}
|
||||
// A change without an undo step since the press: a changed first segment is forgotten (the
|
||||
// press then draws nothing), and the circle follows the segments it may touch as they are now.
|
||||
self.forget_if_changed(cx);
|
||||
let radius = self.radius;
|
||||
let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return };
|
||||
// A pressed segment that is gone leaves nothing to touch.
|
||||
let second = if segment_now(cx, &press.pick).is_some() { second_set(cx, first, &press.pick) } else { vec![] };
|
||||
let moved = second != press.second;
|
||||
press.second = second;
|
||||
let reach = ev.pos.distance(press.at);
|
||||
let gear = if ev.mods.cmd { SLOW } else { 1.0 };
|
||||
let r = match press.radius {
|
||||
None if reach <= cx.tol(DRAG_PX) => {
|
||||
// Shift pressed or let go before the drag starts: the click's circle, with or
|
||||
// without the tool's radius.
|
||||
if ev.mods.shift != press.shift {
|
||||
// Shift pressed or let go before the drag starts, or the segments changed: the
|
||||
// click's circle, with or without the tool's radius.
|
||||
if moved || ev.mods.shift != press.shift {
|
||||
press.shift = ev.mods.shift;
|
||||
let found = circles(first, &press.second, press.shift.then_some(radius));
|
||||
self.found = nearest_to(found, press.at, cx.tol(DRAW_PX));
|
||||
@@ -273,6 +309,7 @@ impl Tool for TangentCircleTool {
|
||||
}
|
||||
PointerKind::Down => {
|
||||
let Some(pick) = pick_at(cx, ev.pos) else { return vec![] };
|
||||
self.forget_if_changed(cx);
|
||||
let Some(first) = self.first.clone() else {
|
||||
self.first = Some(pick);
|
||||
self.picking = true;
|
||||
@@ -286,7 +323,7 @@ impl Tool for TangentCircleTool {
|
||||
self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX));
|
||||
self.looked = true;
|
||||
self.hover = None;
|
||||
self.press = Some(Press { second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None });
|
||||
self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None });
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Drag => {
|
||||
@@ -431,10 +468,14 @@ mod tests {
|
||||
/// Two open lines, (100, 100)–(300, 100) and (100, 140)–(300, 140), and an L from (100, 300)
|
||||
/// over to (300, 300) and down to (300, 400).
|
||||
fn doc() -> Document {
|
||||
doc_at(100.0, 140.0)
|
||||
}
|
||||
|
||||
/// [`doc`] with the two open lines at heights `a` and `b`, with the same ids.
|
||||
fn doc_at(a: f64, b: f64) -> Document {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let lines: [&[(f64, f64)]; 3] =
|
||||
[&[(100.0, 100.0), (300.0, 100.0)], &[(100.0, 140.0), (300.0, 140.0)], &[(100.0, 300.0), (300.0, 300.0), (300.0, 400.0)]];
|
||||
let lines: [&[(f64, f64)]; 3] = [&[(100.0, a), (300.0, a)], &[(100.0, b), (300.0, b)], &[(100.0, 300.0), (300.0, 300.0), (300.0, 400.0)]];
|
||||
for pts in lines {
|
||||
let id = d.alloc_id();
|
||||
let pts: Vec<Point> = pts.iter().map(|(x, y)| Point::new(*x, *y)).collect();
|
||||
@@ -676,6 +717,58 @@ mod tests {
|
||||
assert!(t.first.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_without_an_undo_step_is_not_drawn_from_the_old_shapes() {
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let (d, previewed, first_previewed) = (doc(), doc_at(100.0, 180.0), doc_at(80.0, 140.0));
|
||||
let (cx, during, first_during) = (cx(&d, &sel, &p), cx(&previewed, &sel, &p), cx(&first_previewed, &sel, &p));
|
||||
let mut t = TangentCircleTool::default();
|
||||
// A live preview moves the second line down to 180, and the pointer over it shows a 40 pt
|
||||
// circle. The preview is canceled, which leaves no undo step: the click draws the 20 pt circle
|
||||
// touching the line where it is again, not the one found during the preview.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
|
||||
t.pointer(&during, &ev(PointerKind::Move, 200.0, 179.0));
|
||||
assert!(t.overlays(&during).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 40.00"))));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
|
||||
let released = up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0));
|
||||
assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}");
|
||||
// The same for a press made during the preview and released after it was canceled.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
|
||||
t.pointer(&during, &ev(PointerKind::Down, 200.0, 179.0));
|
||||
let released = up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 179.0));
|
||||
assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}");
|
||||
// A first segment picked during a preview that moved it, canceled since: forgotten, with no
|
||||
// circle shown from where it was.
|
||||
t.pointer(&first_during, &ev(PointerKind::Down, 150.0, 81.0));
|
||||
t.pointer(&first_during, &ev(PointerKind::Up, 150.0, 81.0));
|
||||
assert!(t.first.is_some());
|
||||
t.pointer(&cx, &ev(PointerKind::Move, 200.0, 139.0));
|
||||
assert!(t.first.is_none() && t.found.is_none() && !t.looked);
|
||||
// A press on a first segment that the preview changed since the press draws nothing.
|
||||
t.pointer(&first_during, &ev(PointerKind::Down, 150.0, 81.0));
|
||||
t.pointer(&first_during, &ev(PointerKind::Up, 150.0, 81.0));
|
||||
t.pointer(&first_during, &ev(PointerKind::Down, 200.0, 139.0));
|
||||
assert!(t.busy());
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)).is_empty());
|
||||
assert!(t.first.is_none() && !t.busy());
|
||||
// A press on the L's second segment, which a preview then removes: nothing to touch, so the
|
||||
// release draws no circle against the segment left beside it.
|
||||
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, 300.0, 350.0));
|
||||
let l = t.press.as_ref().map(|p| (p.pick.id, p.pick.segment));
|
||||
assert!(matches!(l, Some((_, 1))), "{l:?}");
|
||||
let mut cut = doc();
|
||||
if let Some(path) = l.and_then(|(id, _)| cut.node_mut(id)).and_then(|n| n.path_data_mut()) {
|
||||
path.subpaths[0] = SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(300.0, 300.0)], false);
|
||||
}
|
||||
let cut_cx = crate::testutil::cx(&cut, &sel, &p);
|
||||
assert!(t.pointer(&cut_cx, &ev(PointerKind::Up, 300.0, 350.0)).is_empty(), "nothing drawn");
|
||||
assert!(t.first.is_some(), "the first segment stays for another try");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_the_three_points_cannot_draw_keeps_the_first_segment() {
|
||||
// A circle the geometry found, moved to (x, 0) and given radius `r`.
|
||||
|
||||
+167
-12
@@ -77,6 +77,13 @@ pub struct DimensionTool {
|
||||
/// The path that holds the first Linear point, when it was picked on a corner of that path's
|
||||
/// preview bounds.
|
||||
first_corner: Option<NodeId>,
|
||||
/// The link the first Linear point took at its click when it was not on an anchor: held
|
||||
/// against the path whose preview-bounds corner it was picked on, or on the segment under it.
|
||||
/// When the art moves before the second click, the first point moves with it.
|
||||
first_link: Option<FreePoint>,
|
||||
/// Where the first Linear point was picked. The point goes back there when its anchor or
|
||||
/// [`Self::first_link`] no longer resolves.
|
||||
first_pick: Option<Point>,
|
||||
/// Whether the press under way began on an anchor a Linear click picks.
|
||||
press_on_anchor: bool,
|
||||
/// The second point clicked for the Linear dimension being placed, and where the pointer was
|
||||
@@ -564,28 +571,34 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
|
||||
/// point, so that it moves with that path. None when neither point has a path to link to.
|
||||
/// `held_a` and `held_b` name the path holding a point picked on a corner of that path's
|
||||
/// preview bounds: such a point is held against that path, however far its strokes or effects
|
||||
/// put the corner from the path and whatever other segment lies there.
|
||||
/// put the corner from the path and whatever other segment lies there. `link_a` is the link the
|
||||
/// first point took at its own click ([`own_link`]): while it still resolves, the point keeps it,
|
||||
/// whatever other art lies there now.
|
||||
fn points_source(
|
||||
cx: &ToolContext,
|
||||
(a, ra, held_a): (Point, &Option<PointRef>, Option<NodeId>),
|
||||
(b, rb, held_b): (Point, &Option<PointRef>, Option<NodeId>),
|
||||
link_a: Option<FreePoint>,
|
||||
) -> Option<DimensionSource> {
|
||||
// A path deleted since the pick holds nothing.
|
||||
let holder = |held: Option<NodeId>| held.filter(|node| cx.doc.node(*node).is_some());
|
||||
let (corner_a, corner_b) = (holder(held_a), holder(held_b));
|
||||
let link_a = link_a.filter(|link| ra.is_none() && link.position(cx.doc).is_some());
|
||||
let edge = |p: Point, corner: Option<NodeId>| if corner.is_some() { None } else { pick(cx, p) };
|
||||
let (edge_a, edge_b) = (edge(a, corner_a), edge(b, corner_b));
|
||||
let (edge_a, edge_b) = (if link_a.is_some() { None } else { edge(a, corner_a) }, edge(b, corner_b));
|
||||
let node = |r: &Option<PointRef>, corner: Option<NodeId>, e: &Option<SegmentRef>| {
|
||||
r.as_ref().map(|r| r.node).or(corner).or_else(|| e.as_ref().map(|e| e.node))
|
||||
};
|
||||
let (path_a, path_b) = (node(ra, corner_a, &edge_a), node(rb, corner_b, &edge_b));
|
||||
let path_a = link_a.as_ref().map(FreePoint::node).or_else(|| node(ra, corner_a, &edge_a));
|
||||
let path_b = node(rb, corner_b, &edge_b);
|
||||
let free = |p: Point, r: &Option<PointRef>, edge: &Option<SegmentRef>, own: Option<NodeId>, other: Option<NodeId>| {
|
||||
if r.is_some() {
|
||||
return None;
|
||||
}
|
||||
edge.as_ref().and_then(|e| FreePoint::on_segment(cx.doc, e, p)).or_else(|| own.or(other).and_then(|node| FreePoint::on(cx.doc, node, p)))
|
||||
};
|
||||
let (free_a, free_b) = (free(a, ra, &edge_a, path_a, path_b), free(b, rb, &edge_b, path_b, path_a));
|
||||
let free_a = link_a.or_else(|| free(a, ra, &edge_a, path_a, path_b));
|
||||
let free_b = free(b, rb, &edge_b, path_b, path_a);
|
||||
(ra.is_some() || rb.is_some() || free_a.is_some() || free_b.is_some()).then(|| DimensionSource::Points {
|
||||
a: ra.clone(),
|
||||
b: rb.clone(),
|
||||
@@ -595,6 +608,17 @@ fn points_source(
|
||||
})
|
||||
}
|
||||
|
||||
/// The link a point picked at `p` off any anchor takes from its own pick, as [`points_source`]
|
||||
/// links it: held against `corner`'s path when it was picked on a corner of that path's preview
|
||||
/// bounds, else on the segment under it, or held against that segment's path. None when nothing
|
||||
/// under it holds it.
|
||||
fn own_link(cx: &ToolContext, p: Point, corner: Option<NodeId>) -> Option<FreePoint> {
|
||||
match corner.filter(|node| cx.doc.node(*node).is_some()) {
|
||||
Some(node) => FreePoint::on(cx.doc, node, p),
|
||||
None => pick(cx, p).and_then(|e| FreePoint::on_segment(cx.doc, &e, p).or_else(|| FreePoint::on(cx.doc, e.node, p))),
|
||||
}
|
||||
}
|
||||
|
||||
impl DimensionTool {
|
||||
/// Where a Linear pick at `p` lands: with Use Preview Bounds on, on the nearest corner of a
|
||||
/// path's preview bounds within reach, where they differ from its anchors, unless another
|
||||
@@ -610,6 +634,7 @@ impl DimensionTool {
|
||||
/// A point the guides leave where the pointer is (right on a guide line) stays there, and with
|
||||
/// Snap to Pixel or Snap to Grid on a point stays where they place it.
|
||||
fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option<PointRef>) {
|
||||
self.follow_first(cx);
|
||||
let leave = self.points.last().map(|(first, anchor)| match anchor {
|
||||
Some(_) => crate::guides::Leave::segment(cx, *first, false),
|
||||
None => crate::guides::Leave::contact(*first),
|
||||
@@ -652,6 +677,30 @@ impl DimensionTool {
|
||||
None => (p, None),
|
||||
}
|
||||
}
|
||||
/// Moves the first Linear point to where its link puts it in the document as it is now: on
|
||||
/// its anchor, or where [`Self::first_link`] holds it. A point whose link no longer resolves,
|
||||
/// or that has none, stays where it was picked, and an anchor that no longer resolves is
|
||||
/// dropped from it.
|
||||
fn follow_first(&mut self, cx: &ToolContext) {
|
||||
if let Some(now) = self.first_now(cx)
|
||||
&& let [(at, reference)] = self.points.as_mut_slice()
|
||||
{
|
||||
*at = now;
|
||||
if reference.as_ref().is_some_and(|r| r.position(cx.doc).is_none()) {
|
||||
*reference = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Where the first Linear point is in the document as it is now ([`Self::follow_first`]),
|
||||
/// while it is the only point picked.
|
||||
fn first_now(&self, cx: &ToolContext) -> Option<Point> {
|
||||
let [(at, reference)] = self.points.as_slice() else { return None };
|
||||
let now = match reference {
|
||||
Some(r) => r.position(cx.doc),
|
||||
None => self.first_link.as_ref().and_then(|link| link.position(cx.doc)),
|
||||
};
|
||||
Some(now.or(self.first_pick).unwrap_or(*at))
|
||||
}
|
||||
fn target(&self, cx: &ToolContext, p: Point) -> Option<Target> {
|
||||
let edge = pick(cx, p)?;
|
||||
match self.kind {
|
||||
@@ -800,6 +849,8 @@ impl DimensionTool {
|
||||
self.on_end = false;
|
||||
self.corner = None;
|
||||
self.first_corner = None;
|
||||
self.first_link = None;
|
||||
self.first_pick = None;
|
||||
self.points.clear();
|
||||
self.lines.clear();
|
||||
self.dragging = false;
|
||||
@@ -824,13 +875,16 @@ impl DimensionTool {
|
||||
reference = reference.filter(|r| r.position(cx.doc) == Some(at));
|
||||
corner = corner.filter(|_| at.distance(snapped) <= 1e-9);
|
||||
}
|
||||
self.points.push((at, reference));
|
||||
if self.points.len() == 1 {
|
||||
if self.points.is_empty() {
|
||||
self.first_corner = corner;
|
||||
self.first_link = reference.is_none().then(|| own_link(cx, at, corner)).flatten();
|
||||
self.first_pick = Some(at);
|
||||
}
|
||||
self.points.push((at, reference));
|
||||
if let [(a, ra), (b, rb)] = self.points.as_slice() {
|
||||
let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner));
|
||||
let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner), self.first_link.take());
|
||||
self.first_corner = None;
|
||||
self.first_pick = None;
|
||||
let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source);
|
||||
if d.resolve(cx.doc).is_ok() {
|
||||
self.second = Some((*b, p));
|
||||
@@ -1041,8 +1095,10 @@ impl Tool for DimensionTool {
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
// The first point where the art puts it now, also when the art moved without a pointer move.
|
||||
let first = self.first_now(cx);
|
||||
for (p, _) in &self.points {
|
||||
out.push(Overlay::Anchor { p: *p, color, filled: true, size: 6.0 });
|
||||
out.push(Overlay::Anchor { p: first.unwrap_or(*p), color, filled: true, size: 6.0 });
|
||||
}
|
||||
for edge in &self.lines {
|
||||
segment(edge, &mut out);
|
||||
@@ -1057,10 +1113,10 @@ impl Tool for DimensionTool {
|
||||
let on_anchor = reference.is_some() || self.on_end;
|
||||
out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } });
|
||||
}
|
||||
if let Some((p, _)) = self.points.last() {
|
||||
if let Some(p) = first.or_else(|| self.points.last().map(|(p, _)| *p)) {
|
||||
let target = snapped.map_or(self.at, |(q, _)| q);
|
||||
let b = if self.shift { constrained(cx, *p, target) } else { target };
|
||||
out.push(Overlay::Line { a: *p, b, color, dashed: true });
|
||||
let b = if self.shift { constrained(cx, p, target) } else { target };
|
||||
out.push(Overlay::Line { a: p, b, color, dashed: true });
|
||||
}
|
||||
// The Smart Guides of the point the next click picks (after the rubber band).
|
||||
if linear_pick {
|
||||
@@ -1814,7 +1870,7 @@ mod tests {
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let (corner, b) = (Point::new(99.5, 99.5), Point::new(250.0, 99.5));
|
||||
for (held, node) in [(Some(id), id), (None, line)] {
|
||||
let source = points_source(&c, (corner, &None, held), (b, &None, None));
|
||||
let source = points_source(&c, (corner, &None, held), (b, &None, None), None);
|
||||
let Some(DimensionSource::Points { free_a: Some(free), .. }) = &source else { panic!("{source:?}") };
|
||||
let linked = match free {
|
||||
FreePoint::Anchors { node, .. } => *node,
|
||||
@@ -1824,6 +1880,105 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A first point keeps its link when the art moves before the second click: a point picked on
|
||||
/// a corner of the preview bounds, on a segment or on an anchor is measured, shown and
|
||||
/// constrained by Shift from where the art puts it now.
|
||||
#[test]
|
||||
fn a_first_point_follows_art_moved_before_the_second_click() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
let moved = |by: (f64, f64)| {
|
||||
let mut m = d.clone();
|
||||
m.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::translate(by), false);
|
||||
m
|
||||
};
|
||||
let click = |t: &mut DimensionTool, c: &ToolContext, (x, y): (f64, f64), shift: bool| {
|
||||
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
|
||||
let mut ev = PointerEvent::new(kind, x, y);
|
||||
ev.mods.shift = shift;
|
||||
t.pointer(c, &ev);
|
||||
}
|
||||
};
|
||||
let base = |doc| ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(doc, &s, &p) };
|
||||
// A corner of the preview bounds, then the rectangle moved 20 points right.
|
||||
let right = moved((20.0, 0.0));
|
||||
let mut t = DimensionTool::default();
|
||||
click(&mut t, &base(&d), (101.0, 101.0), false);
|
||||
let c = ToolContext { revision: (0, 1), ..base(&right) };
|
||||
let shown = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Anchor { p, filled: true, .. } if near(p, Point::new(119.5, 99.5))));
|
||||
assert!(shown, "the first point shows at the moved corner before the pointer moves");
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, 219.0, 101.0));
|
||||
let band = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Line { a, dashed: true, .. } if near(a, Point::new(119.5, 99.5))));
|
||||
assert!(band, "the rubber band starts at the moved corner");
|
||||
click(&mut t, &c, (219.0, 101.0), false);
|
||||
let pending = t.pending.take().expect("both points were picked");
|
||||
assert!(near(pending.a, Point::new(119.5, 99.5)) && near(pending.b, Point::new(220.5, 99.5)), "{:?} {:?}", pending.a, pending.b);
|
||||
assert!((pending.length - 101.0).abs() < 1e-9, "{}", pending.length);
|
||||
let Some(DimensionSource::Points { free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert!(free.position(&right).is_some_and(|q| near(q, Point::new(119.5, 99.5))), "{free:?}");
|
||||
// The same corner, the rectangle moved 20 points right with the pointer moving, then
|
||||
// deleted: the first point goes back to where it was picked.
|
||||
let mut gone = right.clone();
|
||||
gone.remove(id).expect("the rectangle");
|
||||
let (l, line) = (gone.layers[0].id, gone.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 300.0), Point::new(400.0, 300.0)], false));
|
||||
gone.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line");
|
||||
let mut t = DimensionTool::default();
|
||||
click(&mut t, &base(&d), (101.0, 101.0), false);
|
||||
let c = ToolContext { revision: (0, 1), ..base(&right) };
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, 219.0, 101.0));
|
||||
let c = ToolContext { revision: (0, 2), ..base(&gone) };
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, 300.0, 300.0));
|
||||
let shown = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Anchor { p, filled: true, .. } if near(p, Point::new(99.5, 99.5))));
|
||||
assert!(shown, "the first point shows where it was picked once its rectangle is deleted");
|
||||
click(&mut t, &c, (300.0, 300.0), false);
|
||||
let pending = t.pending.take().expect("both points were picked");
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)), "{:?}", pending.a);
|
||||
// An anchor, then its rectangle deleted: the dimension starts where the anchor was picked.
|
||||
let mut t = DimensionTool::default();
|
||||
let unbounded = |doc| ToolContext { preview_bounds: false, ..base(doc) };
|
||||
click(&mut t, &unbounded(&d), (100.0, 100.0), false);
|
||||
click(&mut t, &ToolContext { revision: (0, 2), ..unbounded(&gone) }, (300.0, 300.0), false);
|
||||
let pending = t.pending.take().expect("both points were picked");
|
||||
assert!(near(pending.a, Point::new(100.0, 100.0)), "{:?}", pending.a);
|
||||
let Some(DimensionSource::Points { a: None, .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
// A point on the top segment, then the rectangle moved 20 points down.
|
||||
let down = moved((0.0, 20.0));
|
||||
let mut t = DimensionTool::default();
|
||||
click(&mut t, &unbounded(&d), (150.0, 100.0), false);
|
||||
click(&mut t, &ToolContext { revision: (0, 1), ..unbounded(&down) }, (300.0, 300.0), false);
|
||||
let pending = t.pending.take().expect("both points were picked");
|
||||
assert!(near(pending.a, Point::new(150.0, 120.0)), "{:?}", pending.a);
|
||||
let Some(DimensionSource::Points { free_a: Some(FreePoint::OnSegment { edge, .. }), .. }) = &pending.source else {
|
||||
panic!("{:?}", pending.source)
|
||||
};
|
||||
assert_eq!(edge.node, id);
|
||||
// The same, with a line drawn on top along the moved segment before the second click: the
|
||||
// point keeps the segment it was picked on, where a pick there now finds the line.
|
||||
let mut covered = down.clone();
|
||||
let (l, line) = (covered.layers[0].id, covered.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 120.0), Point::new(300.0, 120.0)], false));
|
||||
covered.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = unbounded(&covered);
|
||||
let at = Point::new(150.0, 120.0);
|
||||
assert_eq!(pick(&c, at).map(|e| e.node), Some(line));
|
||||
let link = own_link(&unbounded(&d), Point::new(150.0, 100.0), None);
|
||||
assert!(matches!(&link, Some(FreePoint::OnSegment { edge, .. }) if edge.node == id), "{link:?}");
|
||||
let source = points_source(&c, (at, &None, None), (Point::new(300.0, 300.0), &None, None), link);
|
||||
let Some(DimensionSource::Points { free_a: Some(FreePoint::OnSegment { edge, .. }), .. }) = &source else { panic!("{source:?}") };
|
||||
assert_eq!(edge.node, id, "the line on top does not take the point");
|
||||
// An anchor, then the rectangle moved 20 points down: Shift constrains from the anchor's
|
||||
// new place.
|
||||
let mut t = DimensionTool::default();
|
||||
click(&mut t, &unbounded(&d), (100.0, 100.0), false);
|
||||
click(&mut t, &ToolContext { revision: (0, 1), ..unbounded(&down) }, (300.0, 124.0), true);
|
||||
let pending = t.pending.take().expect("both points were picked");
|
||||
assert!(near(pending.a, Point::new(100.0, 120.0)) && (pending.b.y - 120.0).abs() < 1e-9, "{:?} {:?}", pending.a, pending.b);
|
||||
}
|
||||
|
||||
/// Hovering right on the end of a dimension's line shows the anchor ring there.
|
||||
#[test]
|
||||
fn hovering_right_on_a_dimension_lines_end_shows_the_anchor_ring() {
|
||||
|
||||
@@ -705,8 +705,12 @@ pub(crate) mod testutil {
|
||||
/// and a count must not include a refresh another test caused.
|
||||
static LAYOUT_INPUTS: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
pub fn steady_layout_inputs() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner())
|
||||
/// Catalogs the installed fonts, then also holds back the font changes other tests make without
|
||||
/// [`changing_layout_inputs`] (a system font loaded for a character no loaded font covers, a
|
||||
/// rescan) until it is dropped.
|
||||
pub fn steady_layout_inputs() -> (std::sync::RwLockReadGuard<'static, ()>, vectorcraft_text::test_fonts::SteadyFonts) {
|
||||
let inputs = LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner());
|
||||
(inputs, vectorcraft_text::test_fonts::steady_fonts(vectorcraft_text::FontDb::global()))
|
||||
}
|
||||
|
||||
pub fn changing_layout_inputs() -> std::sync::RwLockWriteGuard<'static, ()> {
|
||||
|
||||
+5
-1
@@ -31,7 +31,11 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers
|
||||
anchor, guide, grid or pixel snapping places lands on the closest point of a segment, or of a
|
||||
line of a dimension already drawn, within 8 pixels. With Smart Guides and Anchor/Path Labels
|
||||
on, a point on an anchor or a line end shows the "anchor" label, and a point on a segment or
|
||||
line shows the "path" label. These rules apply to the Linear points.
|
||||
line shows the "path" label. These rules apply to the Linear points. A first point picked on
|
||||
an anchor, on a segment or on a corner of preview bounds moves with that art when the art moves
|
||||
before the second click: the rubber band, Shift and the dimension start from where the art puts
|
||||
the point then. When that art is deleted before the second click, the point goes back to where
|
||||
it was picked.
|
||||
With Use Preview Bounds on (Preferences › General), a Linear point can land on a corner of the
|
||||
preview bounds of a path or compound path whose strokes or effects reach past its anchors. The
|
||||
[linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html)
|
||||
|
||||
+4
-2
@@ -14503,8 +14503,10 @@ Tools:
|
||||
undo step. A circle too small or too large for its three points to give it back in floating point counts as no
|
||||
circle. Shift pressed or let go during a click counts at the release. With no circle the note shows, a click draws
|
||||
nothing and the first segment stays picked; it also stays when drawing the circle fails or the press on the second
|
||||
segment is canceled (a canceled touch). Escape, an edit, Undo or Redo outside the tool, or another document forgets
|
||||
the first segment.
|
||||
segment is canceled (a canceled touch). Escape, an edit, Undo or Redo outside the tool, another document, or a
|
||||
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.
|
||||
Option (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36). `tool.setOption`
|
||||
gives an error for a value outside that range or one that is not a number, and for any other option.
|
||||
- **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed,
|
||||
|
||||
@@ -2992,7 +2992,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
|
||||
|
||||
## Path Precision Tools add-on: Tangent Circle Tool (2026-11-17)
|
||||
|
||||
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, and circles too small or too large for three of their points to give them back in floating point; 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. 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 circle its three points cannot draw), 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.
|
||||
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, and circles too small or too large for three of their points to give them back in floating point; 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), 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.
|
||||
|
||||
## Path Precision Tools add-on: Trim at Crossings (2026-11-13)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user