Merge main into fix/include-bleed-native-files

This commit is contained in:
dotCooCoo committed 2026-12-01 14:38:42 -08:00
commit bb9a4463ee
32 files changed
+1406 -116

No files matched your search

+1 -2
View File
@@ -654,8 +654,7 @@ mod tests {
let held = rss_mb();
drop(buffer);
let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else {
eprintln!("no memory reading (Linux without `ps`): nothing to check");
return;
panic!("rss_mb gave no memory reading");
};
assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}");
}
+16 -4
View File
@@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() {
use vectorcraft_doc::text::{CharStyle, TextObject};
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths");
let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
let b = baked(g);
assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b));
@@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec<Effect>) -> Node {
n
}
/// Whether the face of the default character style is installed, so that type lays out glyphs.
/// When it is, `type_node`'s type must outline to paths.
fn fonts() -> bool {
let style = vectorcraft_doc::text::CharStyle::default();
if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() {
return false;
}
assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family);
true
}
/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square
/// centered on its origin.
fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
@@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
/// image and the instance are checked.
#[test]
fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() {
let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0);
let fonts = fonts();
if !fonts {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
}
@@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef
/// listed before that effect, as the canvas draws it, rather than staying type under one shadow.
#[test]
fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() {
if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
@@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() {
n
};
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
+4 -2
View File
@@ -445,11 +445,13 @@ fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() {
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}}));
let before = render(&s);
if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) {
let style = vectorcraft_doc::text::CharStyle::default();
if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() {
eprintln!("skipped: built without a font that draws the type");
return;
}
let before = render(&s);
assert!((0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])), "the type draws in red");
// The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow.
let red =
(100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0);
+5 -9
View File
@@ -68,20 +68,16 @@ problem;
#[test]
fn json2_polyfill_round_trips_with_the_built_in_json() {
let mut realm = Realm::new();
match realm.run(NEEDS) {
Ok(JsValue::Bool(true)) => {}
other => panic!("json2: the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses: {other:?}"),
}
let Some(path) = json2_file() else {
println!("json2: SKIPPED (no json2.js; run cargo xtask test262)");
return;
};
let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let mut realm = Realm::new();
match realm.run(NEEDS) {
Ok(JsValue::Bool(true)) => {}
Ok(JsValue::Bool(false)) => {
println!("json2: SKIPPED (the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses)");
return;
}
other => panic!("json2: the built-in check failed: {other:?}"),
}
match realm.run(&format!("{BEFORE}\n{source}\n{ROUND_TRIP}")) {
Ok(JsValue::String(s)) if s == "ok" => println!("json2: the polyfill and the built-in JSON agree on every sample"),
other => panic!("json2: {other:?}"),
+3 -3
View File
@@ -503,13 +503,13 @@ fn arabic_ligatures_keep_their_letters_in_order() {
let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style);
vectorcraft_text::layout(db, &t).glyphs.len() == 1
};
// An installed Arabic font with a lam-alef ligature whose glyphs come back as live type.
// An installed Arabic font with a lam-alef ligature. The test checks that its type comes
// back, so the choice of font does not depend on the import.
let Some(face) = preferred
.iter()
.chain(&db.families())
.filter_map(|f| db.face(f, "Regular"))
.filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f))
.find(|f| !imported_texts(f, "بب").is_empty())
.find(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f))
else {
return; // No such font on this host.
};
+7 -11
View File
@@ -202,8 +202,7 @@ fn line_break_hyphens_of_right_to_left_lines_are_written_as_text_where_the_canva
/// The kashidas of justified Arabic type (Insert Kashidas), which stand for no character either,
/// are drawn as paths: reopened, the type holds its letters and no hyphen or tatweel. Skipped
/// without an OpenType font that covers Arabic and the tatweel, when the layout adds no kashida,
/// or when PDF text import returns no strings on this platform.
/// without an OpenType font that covers Arabic and the tatweel.
#[test]
fn kashidas_are_not_written_as_hyphens() {
let db = FontDb::global();
@@ -221,20 +220,17 @@ fn kashidas_are_not_written_as_hyphens() {
t.para.justify = vectorcraft_doc::Justify::JustifyAll;
t.para.kashida = vectorcraft_doc::text::Kashida::Medium;
let tatweel = face.glyph_for('\u{0640}');
if !vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel) {
return;
}
assert!(
vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel),
"{}: justified layout inserts a kashida",
face.family
);
let back = texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text));
if back.is_empty() {
return;
}
assert!(!back.is_empty(), "{}: the PDF's type comes back", face.family);
assert!(!back.concat().contains(['-', '\u{2010}', '\u{0640}']), "{back:?}");
// Every letter comes back, at least as often as the text holds it (the justified words may
// come back as type objects of their own).
let all = back.concat();
if all.is_empty() {
return;
}
let count = |s: &str, c: char| s.chars().filter(|&x| x == c).count();
for c in text.chars().filter(|c| c.is_alphabetic()) {
assert!(count(&all, c) >= count(text, c), "{c}: {back:?}");
+4 -4
View File
@@ -228,11 +228,10 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() {
let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels);
let mut shaped = Vec::new();
shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &[], &OtFeatures::default(), levels, &mut shaped);
let Some(first) = shaped.first() else { return };
let first = shaped.first().expect("the text shapes to glyphs");
let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count();
if first.byte != 0 || first_end < 2 || first_end >= shaped.len() {
return;
}
assert_eq!(first.byte, 0, "{}: the first cluster starts the text: {shaped:?}", face.family);
assert!(first_end >= 2 && first_end < shaped.len(), "{}: the base and its mark are one cluster of two glyphs: {shaped:?}", face.family);
// Pick a narrow width that fits glyphs before one positive-advance glyph but not that next
// glyph. This ensures the old per-glyph loop would have returned inside the first cluster.
let mut prefix = shaped.first().map_or(0.0, |g| g.adv);
@@ -245,6 +244,7 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() {
None
}
});
// A face whose mark has no advance gives no width that splits the cluster.
let Some(width) = width else { return };
let mut object = TextObject::point(Point::ZERO, text, style);
+1 -12
View File
@@ -183,12 +183,7 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() {
let split_width: f64 = hindi_glyphs.iter().filter(|g| g.byte == split).map(|g| g.advance).sum();
assert!(prefix_width.is_finite() && prefix_width > 0.0, "setup: prefix has positive finite advance");
assert!(split_width.is_finite(), "setup: the internal raw-group advance is finite");
if split_width <= 0.0 {
eprintln!(
"SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the selected face has no positive-advance raw group at internal byte {split}"
);
return;
}
assert!(split_width > 0.0, "setup: {} lays out a positive-advance raw group at internal byte {split}", face.family);
let width = prefix_width + split_width * 0.5;
assert!(width.is_finite() && width > prefix_width && width < prefix_width + split_width, "setup: one measured width separates the raw groups");
@@ -205,12 +200,6 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() {
assert_eq!(edit::prev_cluster(text, hindi.len()), second, "setup: logical cluster start is 6");
assert_eq!(edit::prev_cluster(text, split), second, "setup: raw line endpoint 12 is inside the grapheme");
assert_eq!(edit::next_cluster(text, split), hindi.len(), "setup: raw line endpoint 12 is not its end");
if lay.lines.len() < 2 || (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start) != (0, split, split) {
eprintln!(
"SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the measured frame does not expose adjacent wrapped endpoints at internal byte {split}"
);
return;
}
assert!(lay.lines.len() >= 2, "setup: actual wrapping occurred");
assert_eq!(
(lay.lines[0].start, lay.lines[0].end, lay.lines[1].start),
+1 -2
View File
@@ -248,6 +248,5 @@ fn properties_and_the_control_bar_remove_the_background_at_once() {
assert!(closed(&app), "it runs at once");
assert_eq!(steps(&app), n + 1, "one undo step");
// The defaults (tolerance and softness 10): the white goes, the near-white ring fades.
let [corner, ring, block] = alphas(&app);
assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app));
assert_eq!(alphas(&app), [0, 95, 255]);
}
@@ -84,13 +84,14 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() {
let name = "10 pt. Oval";
app.run("brush.apply", json!({"name": name})).unwrap();
let before = app.session.active().unwrap().history.undo.len();
let width = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap().width;
ask(&mut app, json!({"name": name}), true);
answer::<BrushDeleteQuestion>(&mut app, choice, pump);
assert_eq!(open_question(&app), None);
assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice.is_some()));
let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap();
assert_eq!(stroke.brush.as_deref(), choice.is_none().then_some(name));
assert!(stroke.width > 0.0);
assert_eq!(stroke.width, width, "the stroke keeps its width");
}
}
+2 -2
View File
@@ -437,8 +437,8 @@ mod tests {
confirm(&mut app, &ctx);
assert!(!app.session.in_interaction());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
let lighter = vectorcraft_color::Color::from_hex(&fill_hex(&app, id)).unwrap().to_rgb()[0];
assert!(lighter > 0.6, "{lighter}");
// #808080 holds less than 50% black, so taking 50% away leaves none.
assert_eq!(fill_hex(&app, id), "#ffffff");
}
#[test]
+1
View File
@@ -22,6 +22,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
| "blend"
| "character"
| "color"
| "docInfo"
| "magicWand"
| "openType"
| "paragraph"
+3
View File
@@ -884,6 +884,9 @@ impl LibraryKind for BrushLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.brush_libraries.path(id).map(str::to_string)
}
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
Rc::ptr_eq(a, b)
}
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibBrush>> {
lib.iter().map(|b| Row { name: b.name(), item: Some(b) }).collect()
}
+1 -1
View File
@@ -950,7 +950,7 @@ mod tests {
app.canvas.doc_info.clone().unwrap().1
};
let all = shown(&mut app, "");
assert!(all["pathArea"].as_f64().is_some_and(|a| a > 0.0), "{}", all["pathArea"]);
assert!(all["pathArea"].as_f64().is_some_and(|a| (a - 200.0).abs() < 1e-6), "{}", all["pathArea"]);
assert!(Arc::ptr_eq(&all, &shown(&mut app, "objects")), "Objects reuses All Categories' result");
for category in ["document", "fonts"] {
let other = shown(&mut app, category);
@@ -1004,6 +1004,9 @@ impl LibraryKind for GraphicStyleLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.style_libraries.path(id).map(str::to_string)
}
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
Arc::ptr_eq(a, b)
}
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibStyle>> {
lib.iter().map(|s| Row { name: &s.style().name, item: Some(s) }).collect()
}
+71 -17
View File
@@ -15,9 +15,11 @@
//! Library… (`ui.libraryPanel.locate`). The find text is the browser's; the selection is panel state
//! (`UiState::library_selection`).
use std::any::Any;
use std::borrow::Cow;
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use craft::behavior::{IconId, Selection, SelectionModel};
use craft::host::PickRequest;
@@ -25,9 +27,7 @@ use craft::theme::variant::Tone;
use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger};
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::notices::{Notice, NoticeAction, NoticeLayout};
use craft::ui::patterns::presets::{
PresetBrowser, PresetEvent, PresetFns, PresetKind, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView,
};
use craft::ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView};
use craft::ui::primitives::{ContentPainterCx, IconSpec};
use craft::ui::runtime::access::PopupKind;
use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates};
@@ -122,7 +122,7 @@ pub(crate) trait LibraryKind {
/// The view a panel shows until another is picked.
const VIEW: View = View::MediumThumb;
/// A library's contents, cheap to clone.
type Lib;
type Lib: Clone + 'static;
type Item: Sync;
/// What the thumbnails paint with besides each item (a panel setting, the documents a library's patterns come
/// from); `()` for nothing.
@@ -135,6 +135,9 @@ pub(crate) trait LibraryKind {
fn find(app: &VectorcraftApp, key: &str) -> Found;
/// The file library `id` was read from, if any.
fn path(app: &VectorcraftApp, id: &str) -> Option<String>;
/// Whether `a` and `b` are the same contents, not only equal ones: the panel reuses the browser rows it built for
/// `a` while [`get`](Self::get) returns `b`.
fn same(a: &Self::Lib, b: &Self::Lib) -> bool;
/// The rows of library `id`; the browser's search filters what it shows (by the shown name and
/// [`PresetRow::search_name`]).
fn rows<'a>(lib: &'a Self::Lib, id: &str) -> Vec<Row<'a, Self::Item>>;
@@ -608,6 +611,7 @@ fn saved_view(view: PresetView, zoom: f64) -> View {
/// The browser rows of library `id`'s `rows`, flat: a folder is a row of its own before its items, which a click
/// selects as it selects an item (production's folder tiles neither opened nor closed).
fn browser_rows<K: LibraryKind>(panel: &str, id: &str, rows: &[Row<K::Item>]) -> Vec<PresetRow<LibraryKey>> {
BUILDS.with(|n| n.set(n.get() + 1));
rows.iter()
.map(|r| {
let label = K::label(id, r.name);
@@ -624,22 +628,73 @@ fn browser_rows<K: LibraryKind>(panel: &str, id: &str, rows: &[Row<K::Item>]) ->
.collect()
}
/// A library panel's browser rows, built for one library's contents in one UI language.
struct BuiltRows<L> {
/// The contents the rows were built from, held so that [`LibraryKind::same`] does not match other contents
/// later stored at the same address.
lib: L,
lang: crate::i18n::Lang,
/// Different for every build, so the browser's memo key changes with the rows.
build: u64,
rows: Rc<Vec<PresetRow<LibraryKey>>>,
/// Each item row's position in [`LibraryKind::rows`], by stored name.
items: Rc<HashMap<String, usize>>,
}
thread_local! {
/// Each library panel's [`BuiltRows`], by panel id.
static BUILT_ROWS: RefCell<HashMap<String, Box<dyn Any>>> = RefCell::new(HashMap::new());
/// How many times [`browser_rows`] has run, for tests.
static BUILDS: Cell<u64> = const { Cell::new(0) };
}
/// How many times the panels have built browser rows on this thread.
#[cfg(test)]
pub(crate) fn row_builds() -> u64 {
BUILDS.with(Cell::get)
}
/// [`BuiltRows::build`], [`BuiltRows::rows`] and [`BuiltRows::items`].
type Built = (u64, Rc<Vec<PresetRow<LibraryKey>>>, Rc<HashMap<String, usize>>);
/// Panel `panel`'s browser rows of `lib`: the ones built before while the panel shows the same contents in the same
/// language, otherwise built now. Building drops the rows of the panels that are no longer open in `ui`.
fn built_rows<K: LibraryKind>(ui: &UiState, panel: &str, id: &str, lib: &K::Lib) -> Built {
let lang = crate::i18n::current();
BUILT_ROWS.with(|cache| {
let mut cache = cache.borrow_mut();
if let Some(b) = cache.get(panel).and_then(|b| b.downcast_ref::<BuiltRows<K::Lib>>())
&& b.lang == lang
&& K::same(&b.lib, lib)
{
return (b.build, b.rows.clone(), b.items.clone());
}
let flat = K::rows(lib, id);
let rows = Rc::new(browser_rows::<K>(panel, id, &flat));
let items = Rc::new(flat.iter().enumerate().filter(|(_, r)| r.item.is_some()).map(|(i, r)| (r.name.to_string(), i)).collect());
let build = BUILDS.with(Cell::get);
let built = BuiltRows { lib: lib.clone(), lang, build, rows: rows.clone(), items: Rc::clone(&items) };
cache.retain(|p, _| is_open(ui, p));
cache.insert(panel.to_string(), Box::new(built));
(build, rows, items)
})
}
/// What a library's browser shows: its rows, the items their thumbnails paint and what those paint with.
struct Shown<'a, K: LibraryKind> {
/// [`BuiltRows::build`] of `rows`.
build: u64,
rows: &'a [PresetRow<LibraryKey>],
items: HashMap<&'a str, &'a K::Item>,
flat: &'a [Row<'a, K::Item>],
items: &'a HashMap<String, usize>,
thumbs: K::Thumbs,
}
/// By the rows (each names its library and item, whose look a library keeps) and what the thumbnails paint with.
/// By the build of the rows (each names its library and item, whose look a library keeps) and what the thumbnails
/// paint with.
impl<K: LibraryKind> MemoProps for Shown<'_, K> {
fn key(&self, key: &mut MemoKey) {
for row in self.rows {
row.key.key(key);
row.label.key(key);
row.depth.key(key);
(row.kind == PresetKind::Item).key(key);
}
self.build.key(key);
self.rows.len().key(key);
self.thumbs.key(key);
}
@@ -658,15 +713,14 @@ fn body<K: LibraryKind>(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
};
let panel = panel_id(K::KIND, id);
let (view, hide_find) = settings(&app.ui, K::KIND, id).map_or((K::VIEW, false), |s| (s.view.unwrap_or(K::VIEW), s.hide_find));
let (build, rows, items) = built_rows::<K>(&app.ui, &panel, id, &lib);
let flat = K::rows(&lib, id);
let rows = browser_rows::<K>(&panel, id, &flat);
let items = flat.iter().filter_map(|r| r.item.map(|i| (r.name, i))).collect();
let fns = PresetFns::new(|shown: &Shown<'_, K>, _| shown.rows.to_vec()).thumb(|shown, cx, rect, info| {
if let Some(item) = shown.items.get(info.key.name.as_str()) {
if let Some(item) = shown.items.get(info.key.name.as_str()).and_then(|&i| shown.flat.get(i)).and_then(|r| r.item) {
K::thumb(&shown.thumbs, cx, rect, item);
}
});
let source = PresetSource::new(Shown::<K> { rows: &rows, items, thumbs: K::thumbs(app, &lib) }, fns);
let source = PresetSource::new(Shown::<K> { build, rows: &rows, flat: &flat, items: &items, thumbs: K::thumbs(app, &lib) }, fns);
let selection = selected(app, &panel);
// The search text and the open groups are the browser's; the view is the panel's setting.
let state_id = egui::Id::unique(("library-panel-state", &panel));
@@ -786,3 +786,27 @@ fn built_in_library_swatches_are_listed_in_the_ui_language() {
assert!(app.session.doc().unwrap().doc.swatch("Clay 1").is_some(), "added under its own name");
crate::i18n::set_current(crate::i18n::Lang::EN);
}
/// A library panel builds its browser rows once for the library it shows, not on every frame, and builds them again
/// when the UI language changes the names it lists.
#[test]
fn library_panel_builds_its_rows_once_per_library_and_language() {
let mut app = app();
let ctx = context();
app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap();
let panel = shown(&app);
app.run("ui.libraryPanel", json!({"panel": panel, "view": "smallList"})).unwrap();
let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel);
let before = row_builds();
for _ in 0..4 {
draw_frame(&mut app, &ctx, &draw, vec![]);
}
assert_eq!(row_builds() - before, 1, "four frames of an unchanged library build its rows once");
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered"));
draw_frame(&mut app, &ctx, &draw, vec![]);
let out = draw_frame(&mut app, &ctx, &draw, vec![]);
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(row_builds() - before, 2, "a new UI language builds the rows again, once");
let painted = crate::tests_labels::shapes_text(&out);
assert!(painted.lines().any(|l| l == "Argile 1"), "the rebuilt rows are in the new language: {painted}");
}
+32 -1
View File
@@ -855,7 +855,38 @@ mod tests {
let mut app = selected_text();
let Some((st, _)) = text_style(&app) else { panic!("no text style") };
let sets = set_entries(&app, &st);
// Builds without the bundled fonts have no face that offers sets.
// With the bundled fonts, the text's face offers sets. Without them, an installed face may.
assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets");
// The submenu lists the `ss01` to `ss20` sets that the text's face offers, read here from
// the face itself, so the test returns early only when the face offers none.
let db = FontDb::global();
let available = db.has_family(&db.canonical(&st.font_family, &st.font_style).0);
let face_sets = if available { db.style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default() } else { Vec::new() };
let expected: Vec<String> = face_sets.iter().filter(|set| (1..=20).contains(&set.number)).map(|set| format!("ss{:02}", set.number)).collect();
let listed: Vec<String> = sets.iter().map(|(_, flag, _)| flag.tag().unwrap_or_default().to_string()).collect();
assert_eq!(listed, expected, "the submenu lists the stylistic sets of the text's face");
let rows = menu_rows(&app);
if expected.is_empty() {
assert!(!rows.iter().any(|row| matches!(row, PanelRow::Submenu(..))), "the submenu is left out when the face offers no sets");
} else {
let submenu = rows.iter().find_map(|row| match row {
PanelRow::Submenu(_, sub) if (1..=20).any(|number| has_row(sub, &toggle_ref(&format!("ss{number:02}")))) => Some(sub),
_ => None,
});
let actual: Vec<&str> = submenu
.expect("the menu has a Stylistic Sets submenu")
.iter()
.filter_map(|row| match row {
PanelRow::Command(c) if c.id == TOGGLE => Some(c.params["tag"].as_str().expect("a toggle has a tag")),
_ => None,
})
.collect();
assert_eq!(actual, expected, "the submenu toggle tags match the face's sets in order");
}
for tag in &expected {
let r = toggle_ref(tag);
assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}");
}
let Some((first, flag, _)) = sets.first() else { return };
let (label, tag) = (set_label(first), flag.tag().unwrap());
set(&mut app, OtFeatures { small_caps: true, ..Default::default() });
@@ -106,6 +106,9 @@ impl LibraryKind for SwatchLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.swatch_libraries.path(id).map(str::to_string)
}
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
Arc::ptr_eq(a, b)
}
/// Ungrouped swatches, then each colour group's folder and swatches, as in the Swatches panel; the browser's Find
/// narrows them.
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, Swatch>> {
@@ -135,7 +138,7 @@ impl LibraryKind for SwatchLibraries {
row
}
fn thumbs(app: &VectorcraftApp, lib: &Self::Lib) -> PatternSources {
PatternSources(lib.iter().filter_map(|w| Some((w.name.clone(), swatchlib::pattern_source(&app.session, w)?))).collect())
PatternSources(lib.iter().filter_map(|w| swatchlib::pattern_source(&app.session, w).map(|d| (w.name.clone(), d))).collect())
}
/// A pattern library's pattern, or a loaded library's, drawn from the library.
fn thumb(sources: &PatternSources, cx: &ContentPainterCx<'_>, rect: Rect, w: &Swatch) {
+4
View File
@@ -981,6 +981,10 @@ impl LibraryKind for SymbolLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.symbol_libraries.path(id).map(str::to_string)
}
/// [`get`](LibraryKind::get) wraps the library anew each time: by the library the symbols are in.
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
a.len() == b.len() && a.first().zip(b.first()).is_none_or(|(a, b)| Arc::ptr_eq(&a.lib, &b.lib))
}
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibSymbol>> {
lib.iter().map(|s| Row { name: s.name(), item: Some(s) }).collect()
}
+3 -3
View File
@@ -217,10 +217,10 @@ fn ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options() {
assert_eq!(undo_depth(&p.app()), depth + 1, "one undo step for both blends");
// The value typed goes to both; each keeps its own spacing, type and the other value.
if name == "Ramp:" {
assert!(after_a.ease.ramp > 0.0 && after_a.ease.ramp == after_b.ease.ramp, "{after_a:?} {after_b:?}");
assert!((after_a.ease.ramp - 0.75).abs() < 1e-9 && (after_b.ease.ramp - 0.75).abs() < 1e-9, "{after_a:?} {after_b:?}");
assert_eq!((after_a.color_shift, after_b.color_shift), (before_a.color_shift, before_b.color_shift));
} else {
assert!(after_a.color_shift > 0.0 && after_a.color_shift == after_b.color_shift, "{after_a:?} {after_b:?}");
assert_eq!((after_a.color_shift, after_b.color_shift), (75.0, 75.0), "{after_a:?} {after_b:?}");
assert_eq!((after_a.ease.ramp, after_b.ease.ramp), (before_a.ease.ramp, before_b.ease.ramp));
}
assert_eq!((after_a.spacing, after_b.spacing), (BlendSpacing::Steps(3), BlendSpacing::Distance(12.0)));
@@ -238,7 +238,7 @@ fn ramp_is_dimmed_while_a_selected_blend_has_no_spine() {
assert!(!p.enabled("Ramp:") && p.enabled("Shift:"));
p.type_into("Shift:", "75");
let app = p.app();
assert!(spec(&app, a).color_shift > 0.0 && spec(&app, b).color_shift == spec(&app, a).color_shift);
assert_eq!((spec(&app, a).color_shift, spec(&app, b).color_shift), (75.0, 75.0));
}
#[test]
@@ -452,7 +452,7 @@ fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() {
quick_click(&mut p, rail.rect.center());
let (hex, opacity) = first_stop(&p);
assert_eq!(hex, "#336699", "the text applies");
assert!(opacity > 0.2 && opacity < 0.8, "the press sets the opacity: {opacity}");
assert!((opacity - 0.5).abs() < 0.005, "the press sets the opacity: {opacity}");
}
/// A press on the opacity slider that takes the focus from an edited field applies the text and
@@ -94,7 +94,7 @@ fn the_row_shows_under_the_box_view() {
let at = along(&slider(&p), 0.5);
p.fx.click_at(at).idle(2);
let o = fill_opacity(&p.app());
assert!((o - 0.5).abs() < 0.05, "{o}");
assert!((o - 0.5).abs() < 0.005, "{o}");
}
/// A value this build does not read keeps the rest of the preferences and reads as the default.
@@ -122,7 +122,7 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() {
let at = along(&slider(&p), 0.5);
p.fx.click_at(at).idle(2);
let o = fill_opacity(&p.app());
assert!((o - 0.5).abs() < 0.05, "{o}");
assert!((o - 0.5).abs() < 0.005, "{o}");
let labels = undo_labels(&p.app());
assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity")));
assert_eq!(crate::panels::current_paints(&p.app()).0.color().unwrap().to_hex(), "#ff0000");
+3
View File
@@ -1838,6 +1838,9 @@ fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() {
// the key is still running when Cancel stops it, however long the frames take.
let jobs = std::sync::Arc::new(craft::host::ManualJobs::new());
app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build());
// The clock stands still: the run's progress window, which opens once the run is old enough
// and takes the keys, stays closed however slowly the frames run.
app.now_override = Some(0.0);
app.session.allow_plugin_grants_from_requests();
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks");
+1
View File
@@ -23,6 +23,7 @@ mod numfields;
mod overprint;
mod paintchips;
pub(crate) mod panel_harness;
mod panel_scroll;
mod pastechords;
mod pathtype;
mod pdfoutput;
+14
View File
@@ -383,6 +383,20 @@ impl Panel {
seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0)
}
/// The named control the latest frame lays out lowest, where its name finds that control: the control a reader
/// reaches last.
pub(crate) fn lowest(&self) -> Option<String> {
let mut names = self.names();
names.sort();
names.dedup();
names
.into_iter()
.filter_map(|name| self.fixture.by_label(&name).map(|t| (name, t.rect.bottom())))
.filter(|(_, bottom)| bottom.is_finite())
.max_by(|a, b| a.1.total_cmp(&b.1))
.map(|(name, _)| name)
}
/// Whether the control named `name` takes input.
pub(crate) fn enabled(&self, name: &str) -> bool {
!self.fixture.tree().is_disabled_key(self.look(name).node)
+61
View File
@@ -0,0 +1,61 @@
//! Every panel in a dock group shorter than its contents scrolls to its last control (#10262).
use std::cell::RefCell;
use egui::{Ui, pos2, vec2};
use serde_json::json;
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
use crate::tests::panel_harness::Panel;
thread_local! {
/// The panel the harness draws.
static SHOWN: RefCell<String> = const { RefCell::new(String::new()) };
}
fn draw(app: &mut VectorcraftApp, ui: &mut Ui) {
let id = SHOWN.with(|s| s.borrow().clone());
crate::dock::panel_body(app, ui, &id);
}
/// The panels whose last control a short dock group hides and the wheel does not bring into view.
fn unreachable_panels(room_height: f32) -> Vec<String> {
let mut stuck = Vec::new();
for (id, _) in crate::state::all_panels() {
SHOWN.with(|s| *s.borrow_mut() = id.to_owned());
let mut app = VectorcraftApp::new(Session::new(), Default::default());
if let Err(e) = app.run("file.new", json!({"width": 200, "height": 200})) {
panic!("file.new: {e}");
}
// A selected path, so the panels that edit a selection show their controls.
if let Err(e) = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})) {
panic!("shape.rectangle: {e}");
}
let mut panel = Panel::new(app, draw);
let Some(last) = panel.lowest() else { continue };
panel.room(vec2(300.0, room_height));
panel.frame();
panel.frame();
if !panel.shows(&last) || panel.in_view(&last) {
continue;
}
for _ in 0..60 {
panel.scroll_at(pos2(150.0, room_height / 2.0), -120.0);
if panel.in_view(&last) {
break;
}
}
if !panel.in_view(&last) {
stuck.push(format!("{id}: {last:?}"));
}
}
stuck
}
#[test]
fn every_panel_in_a_short_dock_group_scrolls_to_its_last_control() {
let mut stuck = unreachable_panels(120.0);
stuck.extend(unreachable_panels(60.0));
assert!(stuck.is_empty(), "panels whose last control the wheel cannot reach: {stuck:?}");
}
+4 -2
View File
@@ -215,8 +215,10 @@ fn filter_dialog_previews_and_commits_one_undo_step() {
set_field(&mut h, "amount", json!(50)).unwrap();
step(&mut h);
assert!(h.state().session.in_interaction(), "previewing");
let [r, g, _] = fill_rgb(h.state(), id);
assert!(r < 1.0 && g > 0.0, "half desaturated on the canvas: {r} {g}");
let [r, g, b] = fill_rgb(h.state(), id);
for (got, want) in [(r, 0.6063), (g, 0.1063), (b, 0.1063)] {
assert!((got - want).abs() < 1e-4, "half desaturated on the canvas: {r} {g} {b}");
}
step(&mut h);
let (shown, _) = h.state().canvas.shown.as_ref().expect("a rendered canvas frame");
let shown_fill = shown.node(id).unwrap().appearance.fill_paint().color().unwrap().to_rgb_uncalibrated();
+2 -2
View File
@@ -214,7 +214,7 @@ mod tests {
#[test]
fn jobs_come_back_newest_last_per_slot() {
let Some(w) = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test") else { return };
let w = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test").expect("the worker thread starts");
let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) };
for k in 1..=3 {
assert!(w.submit(0, k, job(k)));
@@ -238,7 +238,7 @@ mod tests {
#[test]
fn discarded_jobs_do_not_run_and_the_running_one_finishes() {
let Some(w) = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test") else { return };
let w = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test").expect("the worker thread starts");
let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) };
// A job that holds the thread until it is let go, so the others queue behind it.
let (started, running) = channel::<()>();
+1 -1
View File
@@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For
## Test lint
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
## Tests
+3 -2
View File
@@ -35,8 +35,9 @@ commands:
cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails)
test-lint [--base <rev>] [--all]
weak tests in the lines changed since the base: fail on self-compares, reasonless
#[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion,
early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit
#[ignore], sleeps, reads of Rust source and tests no CI target runs; list only
is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env
gates, constant echoes, exact pixels... (xtask/src/test_lint.rs); --all lists every hit
by crate and never fails
i18n-report list the strings each language's catalog lacks, shown in English (fails only on a
broken scan; ci runs it too)
+1122 -31
View File
File diff suppressed because it is too large. Load diff