From e67211f07036a29014aeec2e27179b7488d416ab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:17:06 -0800 Subject: [PATCH 01/50] Fix #8583: document tab titles draw in a condensed face, so more tabs fit Desktop builds with a craft-fonts checkout that has Noto Sans Condensed SemiBold in its opt-in Latin catalog (fonts/latin-manifest.txt) embed that one face as vectorcraft_text::CONDENSED_UI_FONT. Tab titles draw in a new theme::FONT_TAB family headed by it, scaled to the x-height of the interface's semibold face, with the semibold faces after it on its baseline. In a 1280 pt window, 9 tabs named "Poster draft N" fit whole instead of 8. Without CRAFT_FONTS_DIR, on the web, or with a checkout that lacks the row (a build warning), FONT_TAB is the semibold family and tabs look as before. The tab tests that count tabs measure in the semibold face. --- crates/text/build.rs | 71 +++++++++++++++++++----- crates/text/src/craft_fonts.rs | 3 + crates/text/src/lib.rs | 11 +++- crates/ui-egui/src/chrome/tabs.rs | 9 +-- crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/tests/tab_overflow.rs | 41 +++++++++++++- crates/ui-egui/src/theme.rs | 53 +++++++++++++++++- crates/ui-egui/src/ui_fonts.rs | 2 +- docs/development.md | 6 ++ docs/ui-parity.md | 1 + 10 files changed, 171 insertions(+), 27 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index 5402ddbe07..5979c6557c 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -12,6 +12,10 @@ //! `fonts//` beside the wasm instead of embedding (`cargo xtask web-fonts` copies them //! there; `apps/vectorcraft-web/src/fonts.rs` fetches them). A list line the manifest lacks is left //! out with a warning, never an error, and never costs the desktop its fonts. +//! +//! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in +//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A +//! checkout without that row leaves it `None` with a warning, never an error. use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -25,7 +29,7 @@ fn main() { println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); - let (mut fonts, mut web) = (String::new(), String::new()); + let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { let dir = from_workspace(dir); match craft_fonts(&dir) { @@ -48,8 +52,16 @@ fn main() { Err(e) if required => println!("cargo::error=web-fonts.txt: {e}"), Err(e) => println!("cargo::warning=web build fetches no craft fonts: web-fonts.txt: {e}"), } + if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { + match condensed_ui_font(&dir) { + Ok(entry) => condensed = format!("Some({entry})"), + Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + } + } } - let src = format!("pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\n"); + let src = format!( + "pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\npub static CONDENSED_UI_FONT: Option = {condensed};\n" + ); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); // Unchanged output keeps its mtime. Rewritten just before this crate compiles, it can read as // newer than that compile where cargo's recorded times lose their sub-second part (ecryptfs @@ -91,23 +103,52 @@ fn craft_fonts(dir: &Path) -> Result { if wasm && !(*family == WEB_FONT.0 && *style == WEB_FONT.1) { continue; } - let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; - // The manifest is supplier data: embed only regular files inside the checkout. - if !path.starts_with(&root) || !path.is_file() { - return Err(format!("{file}: not a file inside the font checkout")); - } - println!("cargo::rerun-if-changed={}", path.display()); - let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); - let _ = writeln!( - out, - " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", - scripts.join(", "), - path.display().to_string(), - ); + let _ = writeln!(out, " {},", craft_font(dir, &root, family, style, file, scripts)?); } Ok(out) } +/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { + let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; + // The manifest is supplier data: embed only regular files inside the checkout. + if !path.starts_with(root) || !path.is_file() { + return Err(format!("{file}: not a file inside the font checkout")); + } + println!("cargo::rerun-if-changed={}", path.display()); + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); + Ok(format!( + "CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }}", + scripts.join(", "), + path.display().to_string(), + )) +} + +/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in +/// Latin catalog. +const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. +fn condensed_ui_font(dir: &Path) -> Result { + let manifest = dir.join("fonts/latin-manifest.txt"); + // A checkout without the catalog is watched through its folder, so the build runs again once + // the catalog appears. + let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; + println!("cargo::rerun-if-changed={}", watched.display()); + let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; + let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; + let row = text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(|l| l.split(" | ").map(str::trim).collect::>()) + .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); + let Some([family, style, file, scripts, ..]) = row.as_deref() else { + return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + }; + craft_font(dir, &root, family, style, file, scripts) +} + /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and /// the listed faces the manifest lacks (an older craft-fonts checkout), which are left out. fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 24eef3de40..68ddc548b9 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -3,6 +3,9 @@ //! Built with `CRAFT_FONTS_DIR=`, [`CRAFT_FONTS`] holds every font in its //! manifest (Japanese UI and document fonts, Arabic fonts and Noto Sans Thai); built without it, //! it is empty and that text falls back to the installed system fonts. Release builds always set it. See `build.rs`. +//! [`CONDENSED_UI_FONT`] is the condensed face document tab titles draw in, from the checkout's +//! opt-in Latin catalog: `None` on wasm32, without `CRAFT_FONTS_DIR`, or with a checkout that +//! lacks it. /// A font from the optional craft-fonts build input (empty unless built with `CRAFT_FONTS_DIR`). pub struct CraftFont { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7b70b9c5a2..2028639af4 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -37,7 +37,7 @@ pub mod thread; pub use bitmap::GlyphImage; pub use context_alternates::{ContextAlternate, ContextAlternates, alternate_changes, alternates_in_context, is_alternate_feature}; -pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; +pub use craft_fonts::{CONDENSED_UI_FONT, CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; @@ -1059,6 +1059,15 @@ pub fn line_metrics(data: &[u8], index: u32) -> Option<(f32, f32, f32, f32)> { Some((f32::from(m.units_per_em.max(1)), m.ascent, m.descent, m.leading)) } +/// The x-height of the font at `index` of `data`, at its default axis settings, in ems. `None` if +/// the font can't be read or gives no x-height. +pub fn x_height(data: &[u8], index: u32) -> Option { + use skrifa::MetadataProvider; + let f = skrifa::FontRef::from_index(data, index).ok()?; + let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) +} + #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index b92d1e5d04..1aff4fe1a9 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -190,7 +190,8 @@ fn tab_close_box(ui: &Ui, t: &Tokens, xr: egui::Rect, w: f32, id: egui::Id) -> O /// (#746). The first tab that doesn't fit whole fills the room left before the » button with its /// title shortened, when that room holds some of the title (#8584). When the active tab is among /// the last ones and the tabs from it to the end leave room, the tab before them fills that room -/// instead. An active tab wider than the whole strip is shortened to it. +/// instead. An active tab wider than the whole strip is shortened to it. Titles draw in +/// [`theme::FONT_TAB`], a condensed face in builds with craft-fonts (#8583). /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] @@ -224,7 +225,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::semibold(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); (w, text, title, galley) }) .collect(); @@ -258,7 +259,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::semibold(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..7954785e30 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1498,6 +1498,7 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_UI.into()), egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), + egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index 59af211e17..c9f9edec0a 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -44,6 +44,12 @@ fn frame_sized(app: &mut VectorcraftApp, ctx: &egui::Context, size: egui::Vec2, texts } +/// The interface fonts with tab titles in the semibold face, as in a build without craft-fonts' +/// condensed face: the tab counts below are measured in it. +fn install_semibold_tab_fonts(ctx: &egui::Context) { + ctx.set_fonts(crate::theme::interface_fonts_with(None)); +} + fn click(at: Pos2, pressed: bool) -> Event { Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } } @@ -61,7 +67,7 @@ fn the_tab_that_does_not_fit_whole_fills_the_rest_of_the_strip() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -100,7 +106,7 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -118,6 +124,35 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { assert!(texts.iter().any(|(t, _)| t == "Tab test 2 @ 100 % (RGB/Preview)"), "the tooltip shows the whole title: {texts:?}"); } +/// With craft-fonts' condensed face, tab titles draw in it at the semibold face's x-height, and +/// more tabs fit whole in the strip of a 1280 pt window than with the semibold face (#8583). +#[test] +fn tab_titles_in_the_condensed_face_fit_more_tabs() { + let Some(condensed) = vectorcraft_text::CONDENSED_UI_FONT.as_ref() else { + eprintln!("skipped: built without craft-fonts' condensed face (set CRAFT_FONTS_DIR to a craft-fonts checkout that has it)"); + return; + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..24 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Poster draft {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + let mut whole_tabs = |face: Option<&vectorcraft_text::CraftFont>| { + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(face)); + let texts = frame_sized(&mut app, &ctx, egui::vec2(1280.0, 700.0), 0.0, vec![]); + let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); + // The height of an x, in the tab font and in semibold text. + let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; + (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + }; + let (semibold, _, _) = whole_tabs(None); + let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); + assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); + assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + /// With the last document active, the tabs from it to the end leave room before the » button, and /// the tab before them fills that room with its title shortened instead of the strip ending short /// of the » button (#8584). @@ -132,7 +167,7 @@ fn with_the_last_document_active_the_tab_before_the_shown_ones_fills_the_room() app.session.set_active(7); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index f539ddbe71..11e8af8e22 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -494,16 +494,29 @@ pub fn strong_selected_text(ui: &mut egui::Ui) { pub const FONT_UI: &str = "ui"; pub const FONT_UI_SEMIBOLD: &str = "ui-semibold"; pub const FONT_MONO: &str = "mono"; +/// The family document tab titles draw in. In a build with craft-fonts' condensed face +/// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the +/// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so +/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } +/// A document tab's title font ([`FONT_TAB`]). +pub fn tab_font(size: f32) -> FontId { + FontId::new(size, FontFamily::Name(FONT_TAB.into())) +} +/// Whether `family` draws semibold text and takes the bold fallback faces. +pub(crate) fn is_semibold(family: &FontFamily) -> bool { + matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) +} pub fn mono(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_MONO.into())) } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -520,6 +533,11 @@ pub fn install_fonts(ctx: &egui::Context) { /// whether egui applied them at once or deferred them to the next pass (it must not take input /// or draw with fallback metrics while they are pending). pub fn interface_fonts() -> FontDefinitions { + interface_fonts_with(vectorcraft_text::CONDENSED_UI_FONT.as_ref()) +} + +/// [`interface_fonts`] with `condensed` as the face that heads [`FONT_TAB`]. +pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFont>) -> FontDefinitions { let mut fonts = FontDefinitions::default(); let (ui, semi, mono) = interface_faces(&mut fonts); let stack = |fonts: &FontDefinitions, family: FontFamily| fonts.families.get(&family).cloned().unwrap_or_default(); @@ -529,13 +547,42 @@ pub fn interface_fonts() -> FontDefinitions { let family = |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); - fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), family(semi, &fallback)); + let semi = family(semi, &fallback); + let tab = tab_faces(&mut fonts, &semi, condensed); + fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); fonts } +/// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first +/// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its +/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { + let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); + let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; + let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let name = craft_font_name(f); + let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); + // `baseline_copies` reads the head of each family it is given: here only this one. + let mut row = FontDefinitions::empty(); + row.font_data.insert(name.clone(), Arc::new(head.clone())); + row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + let mut faces = vec![name.clone()]; + for face in semi { + let Some(data) = fonts.font_data.get(face).cloned() else { continue }; + for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + fonts.font_data.insert(copy.clone(), Arc::new(data)); + faces.push(copy); + } + } + fonts.font_data.insert(name, Arc::new(head)); + faces +} + /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace /// faces that head their families, in order. #[cfg(feature = "interface-fonts")] @@ -587,7 +634,7 @@ fn add_craft_fonts(fonts: &mut FontDefinitions) { } } for (family, stack) in fonts.families.iter_mut() { - let bold = *family == FontFamily::Name(FONT_UI_SEMIBOLD.into()); + let bold = is_semibold(family); let copy = |f: &vectorcraft_text::CraftFont| { let name = craft_font_name(f); copies.get(&(family.clone(), name.clone())).cloned().unwrap_or(name) diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 73c1a30891..cb419067e1 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -454,7 +454,7 @@ mod tests { let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, egui::Color32::WHITE)).rows[0].glyphs.clone(); for family in families { - let semibold = family == FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()); + let semibold = crate::theme::is_semibold(&family); for &(regular, bold, c) in &probes { let face = if semibold { bold } else { regular }; for size in [13.0_f32, 24.0, 40.0] { diff --git a/docs/development.md b/docs/development.md index fb30fad2bb..66f925324e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -174,6 +174,12 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- Noto Sans Georgian for the Georgian interface), after the UI fonts and before the installed fonts `ui_fonts.rs` discovers for other scripts. On the web, Noto Sans Georgian is fetched at startup and reaches the UI through `ui_fonts.rs`. +- Document tab titles: on desktop builds, `crates/text/build.rs` also reads one row of the + checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as + `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the + x-height of the interface's semibold face, so more tabs fit in the strip. Without + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab + titles draw in the semibold face. - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..8b5a9f315a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,6 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From 2400aa7712cd7be374ef957fdd4b6caa470293ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:51:26 -0800 Subject: [PATCH 02/50] Scripts: reflect describes an object's properties and methods Every object now has a read-only reflect property. Each read gives a new frozen reflection with the class name, the properties and methods as entries (name, type, dataType, defaultValue, min, max, isCollection, arguments), and find(name). - app, its documents, page items, layers, DocumentPreset and each class constructor are described from the host class registry: the installed members give the names and access, and the new HostClass.info gives the types, bounds, defaults and method arguments dom.rs declares beside each member. Members that are not available yet are left out. A class that names a member twice or describes a member it does not have is refused. - Any other object is described by its own properties without running a getter; a JavaScript function's parameters are its arguments. - An object with more than 10,000 members and arguments throws a RangeError. - script.check counts reflection as a language feature, not host-only. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 312 +++++++++++++---- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/builtins/extensions.rs | 7 +- crates/js/src/host_classes.rs | 139 +++++++- crates/js/src/host_tests.rs | 2 +- crates/js/src/lib.rs | 6 +- crates/js/src/realm.rs | 4 +- crates/js/src/reflect.rs | 331 ++++++++++++++++++ crates/js/src/reflect_tests.rs | 242 +++++++++++++ crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/tests.rs | 7 + docs/mcp.md | 20 +- docs/target-app-parity.md | 1 + 13 files changed, 995 insertions(+), 80 deletions(-) create mode 100644 crates/js/src/reflect.rs create mode 100644 crates/js/src/reflect_tests.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bce4edad74..6fda66efe1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -25,7 +25,12 @@ //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. -//! - Members the help pages list that are not here yet throw an error that says so. +//! - Members the help pages list that are not here yet throw an error that says so, and `reflect` +//! leaves them out. +//! - `reflect` on an object or a class gives each member's type from the declaration that installs +//! the member ([`classes`]): a class name, `boolean`, `number`, `string`, `Array` for a list of +//! numbers, the enumeration's name for an enumerated value, and `*` where the value can be of +//! more than one type. use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -33,7 +38,9 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_geom::{Point, Rect}; -use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; +use vectorcraft_js::{ + ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts, +}; use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; @@ -151,9 +158,23 @@ fn method(link: &Link, f: Member) -> HostMember { HostMember::Method(function(link, f)) } +/// A member of a class with what `reflect` tells of it. +type Described = (String, HostMember, MemberInfo); + +/// A property's or a method's result's type for `reflect`. +fn typed(data_type: &str) -> MemberInfo { + MemberInfo { data_type: data_type.into(), ..MemberInfo::default() } +} + +/// A method's result's type and its arguments' names and types, for `reflect`. +fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { + let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect(); + MemberInfo { arguments, ..typed(data_type) } +} + /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document or page item `this` is still there. -fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { +fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -170,7 +191,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM } Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }) + (name.to_string(), HostMember::Property { get: f.clone(), set: f }, MemberInfo { unavailable: true, ..MemberInfo::default() }) } fn text(s: impl Into) -> Data { @@ -1765,12 +1786,30 @@ fn typename_of(name: &'static str) -> HostMember { HostMember::Get(Rc::new(move |_| Ok(text(name)))) } -fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { - HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +fn class(name: &str, parent: Option<&str>, members: Vec, index: Option) -> HostClass { + let info = members.iter().map(|(n, _, i)| (n.clone(), i.clone())).collect(); + let members = members.into_iter().map(|(n, m, _)| (n, m)).collect(); + HostClass { name: name.into(), parent: parent.map(Into::into), members, info, index, construct: None } } -fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { - items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +fn named(items: Vec<(&str, HostMember, MemberInfo)>) -> Vec { + items.into_iter().map(|(n, m, i)| (n.to_string(), m, i)).collect() +} + +/// The type of a `DocumentPreset` field's value. +fn preset_type(field: &str) -> &'static str { + match field { + "artboardLayout" => "DocumentArtboardLayout", + "colorMode" => "DocumentColorSpace", + "documentBleedLink" => "boolean", + "documentBleedOffsetRect" => "Array", + "previewMode" => "DocumentPreviewMode", + "rasterResolution" => "DocumentRasterResolution", + "title" => "string", + "transparencyGrid" => "DocumentTransparencyGrid", + "units" => "RulerUnits", + _ => "number", + } } /// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. @@ -1807,14 +1846,20 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))]) +} + +/// The classes of the object model, each member with the type `reflect` gives for it. +fn classes(link: &Link) -> Vec { let l = link; + let placement = [("relativeObject", "*"), ("insertionLocation", "ElementPlacement")]; let mut application = named(vec![ - ("typename", typename_of("Application")), - ("documents", get(l, app_documents)), - ("activeDocument", property(l, app_active, app_set_active)), - ("selection", get(l, app_selection)), - ("coordinateSystem", property(l, app_coords, app_set_coords)), - ("getIsFileOpen", method(l, app_is_open)), + ("typename", typename_of("Application"), typed("string")), + ("documents", get(l, app_documents), MemberInfo { collection: true, ..typed("Documents") }), + ("activeDocument", property(l, app_active, app_set_active), typed("Document")), + ("selection", get(l, app_selection), typed("*")), + ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), + ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), ]); application.push(later(l, "Application", "beep")); let preset = { @@ -1824,9 +1869,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), h.charge_call(64)?; new_preset(&h) }); - let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; - members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); - HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"), typed("string"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k))))); + HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) } }; let mut classes = vec![ class("Application", None, application, None), @@ -1835,29 +1880,52 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "Documents", None, named(vec![ - ("typename", typename_of("Documents")), - ("length", get(l, docs_length)), - ("parent", get(l, app_ref)), - ("index", method(l, docs_index)), - ("getByName", method(l, docs_by_name)), - ("add", method(l, docs_add)), - ("addDocument", method(l, docs_add_document)), + ("typename", typename_of("Documents"), typed("string")), + ("length", get(l, docs_length), typed("number")), + ("parent", get(l, app_ref), typed("Application")), + ("index", method(l, docs_index), returns("Document", &[("itemKey", "*")])), + ("getByName", method(l, docs_by_name), returns("Document", &[("name", "string")])), + ( + "add", + method(l, docs_add), + returns( + "Document", + &[ + ("colorSpace", "DocumentColorSpace"), + ("width", "number"), + ("height", "number"), + ("numArtBoards", "number"), + ("artboardLayout", "DocumentArtboardLayout"), + ("artboardSpacing", "number"), + ("artboardRowsOrCols", "number"), + ], + ), + ), + ( + "addDocument", + method(l, docs_add_document), + returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]), + ), ]), Some(function(l, docs_at)), ), ]; let mut document = named(vec![ - ("typename", get(l, doc_typename)), - ("parent", get(l, doc_parent)), - ("name", get(l, doc_name)), - ("width", get(l, doc_width)), - ("height", get(l, doc_height)), - ("rulerUnits", get(l, doc_units)), - ("documentColorSpace", get(l, doc_color_space)), - ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), - ("convertCoordinate", method(l, doc_convert)), - ("pageItems", get(l, doc_page_items)), - ("selection", property(l, doc_selection, doc_set_selection)), + ("typename", get(l, doc_typename), typed("string")), + ("parent", get(l, doc_parent), typed("Application")), + ("name", get(l, doc_name), typed("string")), + ("width", get(l, doc_width), typed("number")), + ("height", get(l, doc_height), typed("number")), + ("rulerUnits", get(l, doc_units), typed("RulerUnits")), + ("documentColorSpace", get(l, doc_color_space), typed("DocumentColorSpace")), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin), typed("Array")), + ( + "convertCoordinate", + method(l, doc_convert), + returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), + ), + ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("selection", property(l, doc_selection, doc_set_selection), typed("*")), ]); document.extend( ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] @@ -1869,38 +1937,44 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "PageItems", None, named(vec![ - ("typename", get(l, items_typename)), - ("length", get(l, items_length)), - ("parent", get(l, items_parent)), - ("index", method(l, items_index)), - ("getByName", method(l, items_by_name)), - ("removeAll", method(l, items_remove_all)), + ("typename", get(l, items_typename), typed("string")), + ("length", get(l, items_length), typed("number")), + ("parent", get(l, items_parent), typed("Document")), + ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), + ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), + ("removeAll", method(l, items_remove_all), returns("undefined", &[])), ]), Some(function(l, items_at)), )); let mut page_item = named(vec![ - ("typename", get(l, item_typename)), - ("parent", get(l, item_parent)), - ("name", property(l, item_name, item_set_name)), - ("note", property(l, item_note, item_set_note)), - ("hidden", property(l, item_hidden, item_set_hidden)), - ("locked", property(l, item_locked, item_set_locked)), - ("selected", property(l, item_selected, item_set_selected)), - ("opacity", property(l, item_opacity, item_set_opacity)), - ("position", property(l, item_position, item_set_position)), - ("left", property(l, item_left, item_set_left)), - ("top", property(l, item_top, item_set_top)), - ("width", property(l, item_width, item_set_width)), - ("height", property(l, item_height, item_set_height)), - ("geometricBounds", get(l, item_geometric)), - ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), - ("editable", get(l, item_editable)), - ("zOrderPosition", get(l, item_z_order_position)), - ("duplicate", method(l, item_duplicate)), - ("move", method(l, item_move)), - ("remove", method(l, item_remove)), - ("zOrder", method(l, item_z_order)), + ("typename", get(l, item_typename), typed("string")), + ("parent", get(l, item_parent), typed("*")), + ("name", property(l, item_name, item_set_name), typed("string")), + ("note", property(l, item_note, item_set_note), typed("string")), + ("hidden", property(l, item_hidden, item_set_hidden), typed("boolean")), + ("locked", property(l, item_locked, item_set_locked), typed("boolean")), + ("selected", property(l, item_selected, item_set_selected), typed("boolean")), + ("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }), + ("position", property(l, item_position, item_set_position), typed("Array")), + ("left", property(l, item_left, item_set_left), typed("number")), + ("top", property(l, item_top, item_set_top), typed("number")), + ("width", property(l, item_width, item_set_width), typed("number")), + ("height", property(l, item_height, item_set_height), typed("number")), + ("geometricBounds", get(l, item_geometric), typed("Array")), + ("visibleBounds", get(l, item_visible), typed("Array")), + ("controlBounds", get(l, item_visible), typed("Array")), + ("editable", get(l, item_editable), typed("boolean")), + ("zOrderPosition", get(l, item_z_order_position), typed("number")), + ("duplicate", method(l, item_duplicate), returns("PageItem", &placement)), + ("move", method(l, item_move), { + let mut info = returns("PageItem", &placement); + if let Some(at) = info.arguments.get_mut(1) { + at.default = Some(text("ElementPlacement.PLACEATBEGINNING")); + } + info + }), + ("remove", method(l, item_remove), returns("undefined", &[])), + ("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ]); page_item.extend( [ @@ -1928,8 +2002,13 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ); classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); - classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); - realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) + classes.push(class( + "Layer", + None, + named(vec![("typename", get(l, layer_typename), typed("string")), ("name", get(l, layer_name), typed("string"))]), + None, + )); + classes } #[cfg(test)] @@ -1944,4 +2023,107 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + + /// A script function that writes a reflection as one line, in the form [`expected_line`] gives. + const LINE: &str = "function line(r) {\ + function args(a) { var s = []; for (var i = 0; i < a.length; i++) s.push([a[i].name, a[i].type, a[i].dataType, a[i].defaultValue].join('=')); return s.join(','); }\ + function list(a) { var s = []; for (var i = 0; i < a.length; i++) { var e = a[i];\ + s.push([e.name, e.type, e.dataType, e.isCollection, e.min, e.max, e.defaultValue, args(e.arguments)].join(':')); } return s.join(' '); }\ + return r.name + '|' + list(r.properties) + '|' + list(r.methods); }"; + + fn shown(d: Option<&Data>) -> String { + match d { + None | Some(Data::Undefined) => String::new(), + Some(Data::String(s)) => s.clone(), + Some(Data::Number(n)) => n.to_string(), + Some(other) => panic!("no form for {other:?}"), + } + } + + /// The line [`LINE`] should write for `class`: its parents' members, then its own, a member it + /// declares again in its parent's place, without the members that are not available. + fn expected_line(classes: &[HostClass], class: &HostClass) -> String { + let mut chain = vec![class]; + while let Some(p) = chain.last().and_then(|c| c.parent.as_ref()) { + chain.push(classes.iter().find(|c| &c.name == p).unwrap_or_else(|| panic!("no class {p}"))); + } + let mut members: Vec<(String, &'static str, MemberInfo)> = Vec::new(); + for c in chain.iter().rev() { + for (name, member) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i.clone()).unwrap_or_default(); + let kind = match member { + HostMember::Get(_) => "readonly", + HostMember::Property { .. } => "readwrite", + HostMember::Method(_) => "method", + }; + match members.iter_mut().find(|(n, ..)| n == name) { + Some(slot) => *slot = (name.clone(), kind, info), + None => members.push((name.clone(), kind, info)), + } + } + } + members.retain(|(.., i)| !i.unavailable); + let one = |(name, kind, i): &(String, &str, MemberInfo)| { + let args: Vec = + i.arguments.iter().map(|a| format!("{}=parameter={}={}", a.name, a.data_type, shown(a.default.as_ref()))).collect(); + let number = |n: Option| n.map(|n| n.to_string()).unwrap_or_default(); + format!( + "{name}:{kind}:{}:{}:{}:{}:{}:{}", + i.data_type, + i.collection, + number(i.min), + number(i.max), + shown(i.default.as_ref()), + args.join(",") + ) + }; + let properties: Vec = members.iter().filter(|m| m.1 != "method").map(one).collect(); + let methods: Vec = members.iter().filter(|m| m.1 == "method").map(one).collect(); + format!("{}|{}|{}", class.name, properties.join(" "), methods.join(" ")) + } + + fn logged(s: &mut Session, source: &str) -> Vec { + let r = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().unwrap_or_else(|| panic!("{r}")).iter().map(|v| v.as_str().unwrap_or_default().to_string()).collect() + } + + #[test] + fn reflect_of_every_class_equals_its_declaration() { + let link = Link::default(); + let classes = classes(&link); + // Every member that is available declares its type, so `reflect` never answers `unknown`. + for c in &classes { + for (name, _) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i); + assert!(info.is_some_and(|i| i.unavailable || !i.data_type.is_empty()), "{}.{name} declares no type", c.name); + } + } + let mut s = Session::new(); + let logs: Vec = classes.iter().map(|c| format!("vc.log(line({}.reflect));", c.name)).collect(); + let script = format!("{LINE} {}", logs.join(" ")); + let got = logged(&mut s, &script); + let want: Vec = classes.iter().map(|c| expected_line(&classes, c)).collect(); + assert_eq!(got, want); + assert!(want.iter().any(|w| w.contains("insertionLocation=parameter=ElementPlacement=ElementPlacement.PLACEATBEGINNING"))); + } + + #[test] + fn reflect_of_an_object_equals_its_class_and_calls_no_member() { + let link = Link::default(); + let classes = classes(&link); + let want = |name: &str| expected_line(&classes, classes.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name}"))); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap_or_else(|e| panic!("{e}")); + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap_or_else(|e| panic!("{e}")); + let script = format!( + "{LINE} var d = app.activeDocument, p = d.pageItems[0]; vc.log(line(app.reflect)); vc.log(line(app.documents.reflect));\ + vc.log(line(d.reflect)); vc.log(line(d.pageItems.reflect)); vc.log(line(p.reflect)); vc.log(line(new DocumentPreset().reflect));\ + p.remove(); vc.log(line(p.reflect)); vc.log(String(p.reflect.find('opacity').max));" + ); + let got = logged(&mut s, &script); + let path = want("PathItem"); + let expected = + [want("Application"), want("Documents"), want("Document"), want("PageItems"), path.clone(), want("DocumentPreset"), path, "100".into()]; + assert_eq!(got, expected); + } } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..4b3b95e517 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -45,7 +45,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), - ("Object.prototype.", "toSource"), + ("Object.prototype.", "reflect toSource"), ("localize.", "length"), ("toSource.", "length"), ( diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..68eca8d657 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -1,6 +1,6 @@ //! The script extensions a host adds with [`crate::Realm::add_script_extensions`]: the global -//! `localize`, the global `toSource` and `Object.prototype.toSource`, and the getters behind -//! [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of +//! `localize`, the global `toSource` and `Object.prototype.toSource`, `Object.prototype.reflect` +//! ([`crate::reflect`]), and the getters behind [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of //! [`Localization`]. //! //! `toSource` writes primitives, arrays and plain objects as the text of a JavaScript expression @@ -96,7 +96,8 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { method(interp, global, "localize", localize, 1)?; method(interp, global, "toSource", to_source, 1)?; let object_proto = interp.intrinsics.object_proto; - method(interp, object_proto, "toSource", to_source_method, 0) + method(interp, object_proto, "toSource", to_source_method, 0)?; + crate::reflect::install(interp) } /// The text of the localization object `id` for the current locale: the string value of the first diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..2af2fc130f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -17,6 +17,11 @@ //! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each //! array index `i` with it, called with `this` and the index, and `i in object` is true when it //! gives a value other than `undefined`; other names are looked up as usual. +//! +//! A script's `reflect` ([`crate::reflect`]) describes an object of a host class, and the class's +//! constructor, from the members installed here and their [`HostClass::info`], so what a script is +//! told always matches what the class has. A class that names a member twice, or describes a member +//! it does not have, is refused. use std::rc::Rc; @@ -40,6 +45,39 @@ pub enum HostMember { Method(HostFunction), } +/// What a script's `reflect` tells of a member of a host class ([`HostClass::info`]). The member's +/// name and whether it is read-only, read-write or a method come from the [`HostMember`] itself. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MemberInfo { + /// The type of the member's value, or of a method's result: `boolean`, `number`, `string`, a + /// class name, `*` for any type, `null` or `undefined`. Empty reads as `unknown`. + pub data_type: String, + pub description: Option, + pub help: Option, + /// The value an omitted value means. + pub default: Option, + pub min: Option, + pub max: Option, + /// The value, or a method's result, is a collection. + pub collection: bool, + /// A method's arguments, in order. + pub arguments: Vec, + /// The member is installed but throws when used: `reflect` leaves it out. + pub unavailable: bool, +} + +/// What a script's `reflect` tells of an argument of a host class's method ([`MemberInfo::arguments`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ArgInfo { + pub name: String, + /// As [`MemberInfo::data_type`]. + pub data_type: String, + pub description: Option, + pub default: Option, + pub min: Option, + pub max: Option, +} + /// A class [`crate::Realm::define_host_classes`] adds. #[derive(Clone)] pub struct HostClass { @@ -48,6 +86,9 @@ pub struct HostClass { /// class's prototype inherits from. pub parent: Option, pub members: Vec<(String, HostMember)>, + /// What `reflect` tells of the members, each under the name of one of `members`. A member + /// without an entry has the type `unknown` and nothing else. + pub info: Vec<(String, MemberInfo)>, /// What `object[i]` gives for an array index `i`. pub index: Option, /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. @@ -72,6 +113,26 @@ pub(crate) struct Entry { /// The class without a parent this class descends from (itself for such a class), as an index /// into the realm's classes. family: u32, + /// The parent class, as an index into the realm's classes. + parent: Option, + /// The class's own members as `reflect` lists them. + members: Rc<[Reflected]>, +} + +/// How a script may use a member of a host class. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Access { + ReadOnly, + ReadWrite, + Method, +} + +/// A member of a host class as `reflect` lists it. +#[derive(Clone, Debug)] +pub(crate) struct Reflected { + pub(crate) name: Rc, + pub(crate) access: Access, + pub(crate) info: MemberInfo, } impl Entry { @@ -168,6 +229,41 @@ impl Interp { self.host_classes.iter().any(|e| e.ctor == id) } + /// The name of the host class of `id`, when it is an object of a host class. + pub(crate) fn host_class_name(&self, id: ObjId) -> JsResult>> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + Ok(self.host_classes.get(h.class as usize).map(|e| e.name.clone())) + } + + /// The name and members of the host class of `id`, an object of the class or its constructor: + /// the members of its parents first, then its own, a member a class declares again in the place + /// of its parent's. Members marked [`MemberInfo::unavailable`] are left out. `None` when `id` is + /// neither. + pub(crate) fn host_class_members(&self, id: ObjId) -> JsResult, Vec)>> { + let class = match &self.object(id)?.class { + Class::Host(h) => Some(h.class as usize), + _ => self.host_classes.iter().position(|e| e.ctor == id), + }; + let Some(class) = class else { return Ok(None) }; + let Some(entry) = self.host_classes.get(class) else { return Err(Abrupt::Internal("host class out of range".into())) }; + let mut chain = vec![entry]; + while let Some(p) = chain.last().and_then(|e| e.parent) { + let Some(parent) = self.host_classes.get(p as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; + chain.push(parent); + } + let mut out: Vec = Vec::new(); + for e in chain.iter().rev() { + for m in e.members.iter() { + match out.iter_mut().find(|r| r.name == m.name) { + Some(slot) => *slot = m.clone(), + None => out.push(m.clone()), + } + } + } + out.retain(|m| !m.info.unavailable); + Ok(Some((entry.name.clone(), out))) + } + /// The indexer of the host class of `id`, when it is an object of a host class that has one. pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; @@ -223,24 +319,57 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); - let (parent, family) = match &class.parent { - None => (i.intrinsics.object_proto, own), - Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => (e.proto, e.family), + let (parent, family, parent_index) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((n, e)) => (e.proto, e.family, Some(u32::try_from(n).unwrap_or(u32::MAX))), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; + let members = match reflected_members(&class) { + Ok(m) => m, + Err(message) => return Err(i.throw(ErrorType::Type, &message)), + }; let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); let mark = i.temp_roots.len(); i.temp_roots.push(Value::Object(proto)); let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family, parent: parent_index, members }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } +/// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the +/// error's message when a member is named twice, or an entry names no member or is given twice. +fn reflected_members(class: &HostClass) -> Result, String> { + let mut out: Vec = Vec::with_capacity(class.members.len()); + for (name, member) in &class.members { + if out.iter().any(|r| *r.name == **name) { + return Err(format!("the host class {} names the member {name} twice", class.name)); + } + let access = match member { + HostMember::Get(_) => Access::ReadOnly, + HostMember::Property { .. } => Access::ReadWrite, + HostMember::Method(_) => Access::Method, + }; + out.push(Reflected { name: name.as_str().into(), access, info: MemberInfo::default() }); + } + let mut seen: Vec<&str> = Vec::with_capacity(class.info.len()); + for (name, info) in &class.info { + if seen.contains(&name.as_str()) { + return Err(format!("the host class {} describes the member {name} twice", class.name)); + } + seen.push(name); + let Some(slot) = out.iter_mut().find(|r| *r.name == **name) else { + return Err(format!("the host class {} describes {name}, which is not one of its members", class.name)); + }; + slot.info = info.clone(); + } + Ok(out.into()) +} + /// Puts the members of `class` on `proto` and makes its constructor. → the constructor. fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { let path = &class.name; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..040361d460 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -644,7 +644,7 @@ fn with_thing(r: &mut Realm, make: Option) { let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; - let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: make }; r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..8d61712e36 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -65,6 +65,7 @@ mod number; mod number_builtins; mod parser; mod realm; +mod reflect; mod regexp; mod regexp_builtins; mod regexp_vm; @@ -82,10 +83,11 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{ArgInfo, HOST_REF_KEY, HostClass, HostMember, MemberInfo, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; +pub use reflect::MAX_REFLECTED_MEMBERS; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -211,6 +213,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod reflect_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index f1ca6b570d..745c2b9364 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -539,7 +539,9 @@ impl Realm { /// Adds the script extensions: the global `localize(object, ...values)`, which gives a /// localization object's text for the locale of [`Realm::localization`], the global /// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text, - /// and the localized `Object.prototype.toString` while [`crate::Localization::enabled`]. + /// `Object.prototype.reflect`, which describes an object's properties and methods (a host + /// class's from its [`crate::HostClass`]), and the localized `Object.prototype.toString` while + /// [`crate::Localization::enabled`]. pub fn add_script_extensions(&mut self) -> Result<(), RunError> { match crate::builtins::extensions::install(&mut self.interp) { Ok(()) => Ok(()), diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs new file mode 100644 index 0000000000..a84c221d3a --- /dev/null +++ b/crates/js/src/reflect.rs @@ -0,0 +1,331 @@ +//! The script extension `reflect` ([`crate::Realm::add_script_extensions`]): a read-only property +//! of `Object.prototype` that gives, on each read, a new reflection object describing the object it +//! is read on. +//! +//! A reflection object has `name` (the object's class), `description` and `help` (`undefined`), +//! `properties` and `methods` (arrays of ReflectionInfo objects), and `find(name)`, which gives the +//! ReflectionInfo of the property or method with that name, or `null`. A ReflectionInfo has `name` +//! (a string, or a number for an array index), `description`, `help`, `type` (`readonly`, +//! `readwrite`, `method`, or `parameter` for a method's argument), `dataType`, `defaultValue`, +//! `min`, `max`, `isCollection` and `arguments` (an array of ReflectionInfo objects, empty for a +//! property). Each entry of `properties`, `methods` and `arguments` is also under its name when +//! that name is not an array index or `length`. +//! +//! An object of a host class and the class's constructor are described by the class's members +//! ([`crate::HostClass::members`] and [`crate::HostClass::info`]), its parents' included. Any other +//! object is described by its own properties: a property whose value is a function is a method, +//! with the parameter names of a function written in JavaScript as its arguments; a data property +//! is read-write when it is writable and gives the type of its value; an accessor is read-write +//! when it has a setter and its type is `unknown`. A string, number or boolean is described by its +//! prototype's own properties. No getter or other script code runs. +//! +//! Every object made is frozen, so a script cannot change one; `reflect` itself has no setter. +//! Each member described takes fuel, and an object with more than [`MAX_REFLECTED_MEMBERS`] +//! members and arguments throws a `RangeError`. + +use crate::builtins::native; +use crate::heap::{Class, ENUMERABLE, Func, Key, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, WRITABLE, key}; +use crate::host::Data; +use crate::host_classes::{Access, Reflected}; +use crate::interp::{ErrorType, Interp, JsResult}; +use crate::value::{Str, Value, array_index, index_key, number_to_str}; + +/// The most members and arguments `reflect` describes for one object. +pub const MAX_REFLECTED_MEMBERS: usize = 10_000; + +/// The properties of a ReflectionInfo object. +const INFO_PROPS: usize = 10; + +/// A member or argument as a ReflectionInfo object describes it. +struct Info { + name: Value, + kind: &'static str, + data_type: String, + description: Option, + help: Option, + default: Option, + min: Option, + max: Option, + collection: bool, + arguments: Vec, +} + +impl Info { + fn new(name: Value, kind: &'static str, data_type: &str) -> Self { + Self { + name, + kind, + data_type: data_type.to_string(), + description: None, + help: None, + default: None, + min: None, + max: None, + collection: false, + arguments: Vec::new(), + } + } +} + +/// The type a [`crate::MemberInfo`] gives, `unknown` when it gives none. +fn declared(data_type: &str) -> &str { + if data_type.is_empty() { "unknown" } else { data_type } +} + +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let get = native(interp, "reflect", reflect, 0, NativeKind::Plain, false)?; + let object_proto = interp.intrinsics.object_proto; + interp.define(object_proto, key("reflect"), Prop::Accessor { get: Some(get), set: None, flags: 0 }) +} + +/// Counts one more member or argument against [`MAX_REFLECTED_MEMBERS`], with a unit of fuel. +fn count(interp: &mut Interp, total: &mut usize) -> JsResult<()> { + interp.use_fuel()?; + *total += 1; + if *total > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + Ok(()) +} + +/// The getter of `Object.prototype.reflect`. +fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (id, primitive) = match &this { + Value::Undefined | Value::Null => return Err(interp.type_error("reflect needs an object")), + Value::String(_) => (interp.intrinsics.string_proto, Some("String")), + Value::Number(_) => (interp.intrinsics.number_proto, Some("Number")), + Value::Bool(_) => (interp.intrinsics.boolean_proto, Some("Boolean")), + Value::Object(o) => (*o, None), + }; + let (name, properties, methods) = match interp.host_class_members(id)? { + Some((name, members)) if primitive.is_none() => { + let (properties, methods) = host_infos(interp, &members)?; + (name.to_string(), properties, methods) + } + _ => { + let name = primitive.unwrap_or(interp.object(id)?.class.name()).to_string(); + let (properties, methods) = own_infos(interp, id)?; + (name, properties, methods) + } + }; + interp.rooted(&[this], |i| { + let mark = i.temp_roots.len(); + let r = reflection(i, &name, &properties, &methods); + i.temp_roots.truncate(mark); + r + }) +} + +/// The properties and methods of a host class's `members`. +fn host_infos(interp: &mut Interp, members: &[Reflected]) -> JsResult<(Vec, Vec)> { + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for m in members { + count(interp, &mut total)?; + let kind = match m.access { + Access::ReadOnly => "readonly", + Access::ReadWrite => "readwrite", + Access::Method => "method", + }; + let mut info = Info::new(Value::str(&m.name), kind, declared(&m.info.data_type)); + info.description = m.info.description.clone(); + info.help = m.info.help.clone(); + info.default = m.info.default.clone(); + info.min = m.info.min; + info.max = m.info.max; + info.collection = m.info.collection; + for a in &m.info.arguments { + count(interp, &mut total)?; + let mut arg = Info::new(Value::str(&a.name), "parameter", declared(&a.data_type)); + arg.description = a.description.clone(); + arg.default = a.default.clone(); + arg.min = a.min; + arg.max = a.max; + info.arguments.push(arg); + } + if m.access == Access::Method { methods.push(info) } else { properties.push(info) } + } + Ok((properties, methods)) +} + +/// The properties and methods of the own properties of `id`. No getter runs. +fn own_infos(interp: &mut Interp, id: ObjId) -> JsResult<(Vec, Vec)> { + let o = interp.object(id)?; + let extra = match &o.class { + Class::String(s) => s.len().saturating_add(1), + Class::Array { .. } => 1, + _ => 0, + }; + // Checked before the names are listed, so a huge object costs no more than a small one. + if o.props.len().saturating_add(extra) > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + let keys = interp.own_keys(id)?; + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for k in keys { + count(interp, &mut total)?; + let Some(prop) = interp.get_own_property(id, &k)? else { continue }; + let name = member_name(&k); + match prop { + Prop::Data { value, .. } if interp.is_callable(&value) => { + let mut info = Info::new(name, "method", "unknown"); + if let Some(params) = parameters(interp, &value)? { + for p in params { + count(interp, &mut total)?; + info.arguments.push(Info::new(Value::String(Str::from_rc(p)), "parameter", "*")); + } + } + methods.push(info); + } + Prop::Data { value, flags } => { + let kind = if flags & WRITABLE != 0 { "readwrite" } else { "readonly" }; + let data_type = value_type(interp, &value)?; + properties.push(Info::new(name, kind, &data_type)); + } + Prop::Accessor { set, .. } => properties.push(Info::new(name, if set.is_some() { "readwrite" } else { "readonly" }, "unknown")), + } + } + Ok((properties, methods)) +} + +/// A property name as a ReflectionInfo's `name`: a number for an array index. +fn member_name(k: &Key) -> Value { + match array_index(k) { + Some(i) => Value::Number(f64::from(i)), + None => Value::String(Str::from_rc(k.clone())), + } +} + +/// The parameter names of the function `f` when it is written in JavaScript. +fn parameters(interp: &Interp, f: &Value) -> JsResult>> { + let Some(id) = f.as_object() else { return Ok(None) }; + Ok(match &interp.object(id)?.class { + Class::Function(Func::Closure { code, .. }) => Some(code.params.clone()), + _ => None, + }) +} + +/// The `dataType` of a data property holding `v`. +fn value_type(interp: &Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => "undefined".into(), + Value::Null => "null".into(), + Value::Bool(_) => "boolean".into(), + Value::Number(_) => "number".into(), + Value::String(_) => "string".into(), + Value::Object(o) => match interp.host_class_name(*o)? { + Some(name) => name.to_string(), + None => interp.object(*o)?.class.name().into(), + }, + }) +} + +/// The reflection object. Every object it makes is kept in `interp.temp_roots`. +fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[Info]) -> JsResult { + let properties = info_array(interp, properties)?; + let methods = info_array(interp, methods)?; + interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?; + let find = native(interp, "find", find, 1, NativeKind::Plain, false)?; + interp.temp_roots.push(Value::Object(find)); + let r = interp.new_object(); + interp.temp_roots.push(Value::Object(r)); + for (k, v) in [ + ("name", Value::str(name)), + ("description", Value::Undefined), + ("help", Value::Undefined), + ("properties", Value::Object(properties)), + ("methods", Value::Object(methods)), + ] { + interp.define(r, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.define(r, key("find"), Prop::Data { value: Value::Object(find), flags: 0 })?; + interp.object_mut(r)?.extensible = false; + Ok(Value::Object(r)) +} + +/// A frozen array of ReflectionInfo objects for `infos`, each also under its name when that name +/// is not an array index or `length`. +fn info_array(interp: &mut Interp, infos: &[Info]) -> JsResult { + interp.reserve_heap(OBJECT_BYTES.saturating_add(infos.len().saturating_mul(2 * PROP_BYTES)))?; + let proto = interp.intrinsics.array_proto; + let a = interp.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: false }, Some(proto))); + interp.temp_roots.push(Value::Object(a)); + for (n, info) in infos.iter().enumerate() { + let o = info_object(interp, info)?; + interp.define(a, index_key(u32::try_from(n).unwrap_or(u32::MAX)), Prop::Data { value: Value::Object(o), flags: ENUMERABLE })?; + } + for (n, info) in infos.iter().enumerate() { + let Value::String(s) = &info.name else { continue }; + let k = s.flat(); + if array_index(&k).is_some() || *k == *key("length") || interp.object(a)?.props.contains(&k) { + continue; + } + let Some(Prop::Data { value, .. }) = interp.get_own_property(a, &index_key(u32::try_from(n).unwrap_or(u32::MAX)))? else { continue }; + interp.define(a, k, Prop::Data { value, flags: 0 })?; + } + interp.object_mut(a)?.extensible = false; + Ok(a) +} + +/// A frozen ReflectionInfo object for `info`. +fn info_object(interp: &mut Interp, info: &Info) -> JsResult { + let arguments = info_array(interp, &info.arguments)?; + interp.reserve_heap(OBJECT_BYTES + INFO_PROPS * PROP_BYTES)?; + let o = interp.new_object(); + interp.temp_roots.push(Value::Object(o)); + let text = |s: &Option| s.as_deref().map_or(Value::Undefined, Value::str); + let number = |n: Option| n.map_or(Value::Undefined, Value::Number); + let default = match &info.default { + Some(d) => interp.write_data(d.clone(), 0, true)?, + None => Value::Undefined, + }; + let fields = [ + ("name", info.name.clone()), + ("description", text(&info.description)), + ("help", text(&info.help)), + ("type", Value::str(info.kind)), + ("dataType", Value::str(&info.data_type)), + ("defaultValue", default), + ("min", number(info.min)), + ("max", number(info.max)), + ("isCollection", Value::Bool(info.collection)), + ("arguments", Value::Object(arguments)), + ]; + for (k, v) in fields { + interp.define(o, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.object_mut(o)?.extensible = false; + Ok(o) +} + +/// `reflect.find(name)`: the ReflectionInfo of the property, or else the method, named `name` (a +/// string, or a number for an array index), or `null`. +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let wanted = match args.first() { + Some(Value::String(s)) => s.flat(), + Some(Value::Number(n)) => number_to_str(*n).flat(), + _ => return Err(interp.type_error("reflect.find: give the member's name, as a string or a number")), + }; + let not_reflection = "reflect.find must be called on a reflection object"; + let Value::Object(r) = this else { return Err(interp.type_error(not_reflection)) }; + for list in ["properties", "methods"] { + let Some(Prop::Data { value: Value::Object(a), .. }) = interp.get_own_property(r, &key(list))? else { + return Err(interp.type_error(not_reflection)); + }; + let Class::Array { length, .. } = interp.object(a)?.class else { return Err(interp.type_error(not_reflection)) }; + for i in 0..length { + interp.use_fuel()?; + let Some(Prop::Data { value: Value::Object(e), .. }) = interp.get_own_property(a, &index_key(i))? else { continue }; + let name = match interp.get_own_property(e, &key("name"))? { + Some(Prop::Data { value: Value::String(s), .. }) => s.flat(), + Some(Prop::Data { value: Value::Number(n), .. }) => number_to_str(n).flat(), + _ => continue, + }; + if *name == *wanted { + return Ok(Value::Object(e)); + } + } + } + Ok(Value::Null) +} diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs new file mode 100644 index 0000000000..3e8827cf4f --- /dev/null +++ b/crates/js/src/reflect_tests.rs @@ -0,0 +1,242 @@ +//! `reflect`: the description of an object's properties and methods, from a host class's members +//! or from an object's own properties. + +use std::rc::Rc; + +use super::*; + +fn realm() -> Realm { + let mut r = Realm::new(); + r.add_script_extensions().unwrap(); + r +} + +fn text(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Ok(JsValue::String(s)) => s, + other => panic!("{source}: {other:?}"), + } +} + +fn thrown(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Err(e) if e.kind == RunErrorKind::Thrown => e.message, + other => panic!("{source}: {other:?}"), + } +} + +/// `name:type:dataType` of each entry of a list, joined with spaces. +const LIST: &str = "function list(a) { var s = []; for (var i = 0; i < a.length; i++) s.push(a[i].name + ':' + a[i].type + ':' + a[i].dataType); \ + return s.join(' '); }"; + +#[test] +fn a_script_object_lists_its_own_properties_and_methods_without_running_getters() { + let mut r = realm(); + let setup = "var o = {a: 1, b: 'x', c: null, d: [1], f: function (p, q) {}, get g() { throw new Error('ran'); }, set h(v) {}};\ + Object.defineProperty(o, 'k', {value: true, writable: false});"; + r.run(setup).unwrap(); + r.run(LIST).unwrap(); + assert_eq!(text(&mut r, "o.reflect.name"), "Object"); + assert_eq!( + text(&mut r, "list(o.reflect.properties)"), + "a:readwrite:number b:readwrite:string c:readwrite:null d:readwrite:Array g:readonly:unknown h:readwrite:unknown k:readonly:boolean" + ); + assert_eq!(text(&mut r, "list(o.reflect.methods)"), "f:method:unknown"); + assert_eq!(text(&mut r, "list(o.reflect.methods[0].arguments)"), "p:parameter:* q:parameter:*"); + assert_eq!(text(&mut r, "list(o.reflect.properties[0].arguments) + '|' + o.reflect.description + '|' + o.reflect.help"), "|undefined|undefined"); + // A value replaced by a function becomes a method on the next read; each read is a new snapshot. + assert_eq!( + text(&mut r, "var before = o.reflect; o.a = function () {}; delete o.b; list(before.methods) + '|' + list(o.reflect.methods)"), + "f:method:unknown|a:method:unknown f:method:unknown" + ); + assert_eq!(text(&mut r, "String(o.reflect.find('b'))"), "null"); +} + +#[test] +fn find_and_names_look_up_properties_then_methods() { + let mut r = realm(); + r.run("var o = {width: 2, draw: function () {}};").unwrap(); + assert_eq!(text(&mut r, "o.reflect.find('width').dataType + ' ' + o.reflect.find('draw').type"), "number method"); + assert_eq!(text(&mut r, "String(o.reflect.find('nothing'))"), "null"); + assert_eq!(text(&mut r, "o.reflect.properties.width.name + ' ' + o.reflect.methods.draw.name"), "width draw"); + // Array indexes are numbers, found by number or by their text. + assert_eq!( + text( + &mut r, + "var a = [5, 'x']; a[3] = true; var f = a.reflect.find(1); typeof f.name + ' ' + f.dataType + ' ' + a.reflect.find('3').dataType" + ), + "number string boolean" + ); + assert_eq!(text(&mut r, "[5].reflect.properties.length + ' ' + [5].reflect.find('length').type"), "2 readwrite"); + // A name that is missing or of another type is refused. + assert!(thrown(&mut r, "o.reflect.find();").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find({});").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find.call({}, 'width');").starts_with("TypeError")); +} + +#[test] +fn a_reflection_info_has_every_field() { + let mut r = realm(); + let fields = "var i = ({a: 1}).reflect.properties[0]; var k = []; for (var n in i) k.push(n); k.join(' ')"; + assert_eq!(text(&mut r, fields), "name description help type dataType defaultValue min max isCollection arguments"); + let values = + "var i = ({a: 1}).reflect.properties[0]; [i.description, i.help, i.defaultValue, i.min, i.max, i.isCollection, i.arguments.length].join()"; + assert_eq!(text(&mut r, values), ",,,,,false,0"); + assert_eq!(text(&mut r, "var k = []; for (var n in ({}).reflect) k.push(n); k.join(' ')"), "name description help properties methods"); +} + +#[test] +fn functions_primitives_and_built_ins_are_described() { + let mut r = realm(); + r.run(LIST).unwrap(); + assert_eq!( + text(&mut r, "function f(a, b) {} f.reflect.name + ' ' + list(f.reflect.properties)"), + "Function length:readonly:number prototype:readwrite:Object" + ); + assert_eq!(text(&mut r, "Math.reflect.name + ' ' + Math.reflect.find('PI').type + ' ' + Math.reflect.find('max').type"), "Math readonly method"); + assert_eq!(text(&mut r, "'abc'.reflect.name + ' ' + 'abc'.reflect.find('charAt').type"), "String method"); + assert_eq!(text(&mut r, "(5).reflect.name + ' ' + true.reflect.name"), "Number Boolean"); + assert!(thrown(&mut r, "var n = null; n.reflect;").starts_with("TypeError")); + let getter = "Object.getOwnPropertyDescriptor(Object.prototype, 'reflect').get"; + assert!(thrown(&mut r, &format!("{getter}.call(undefined);")).starts_with("TypeError")); + // Neither a getter nor `toString` runs, so a cyclic object is described as it is. + assert_eq!(text(&mut r, "var c = {}; c.self = c; c.toString = function () { throw 1; }; c.reflect.find('self').dataType"), "Object"); +} + +#[test] +fn a_reflection_cannot_be_changed() { + let mut r = realm(); + r.run("var o = {a: 1}; var x = o.reflect;").unwrap(); + // Outside strict mode the writes are ignored. + let tries = "o.reflect = 5; x.name = 'y'; x.properties[0].dataType = 'y'; x.properties[1] = 2; x.extra = 1; delete x.methods;\ + [typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()"; + assert_eq!(text(&mut r, tries), "object,Object,number,1,,object"); + // In strict mode each one throws a TypeError. + for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] { + assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}"); + } + assert_eq!( + text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"), + "true true true" + ); +} + +#[test] +fn a_very_wide_object_is_refused() { + let mut r = realm(); + let wide = |n: usize| format!("var w = {{}}; for (var i = 0; i < {n}; i++) w['p' + i] = i;"); + r.run(&wide(MAX_REFLECTED_MEMBERS)).unwrap(); + assert_eq!(text(&mut r, "String(w.reflect.properties.length)"), MAX_REFLECTED_MEMBERS.to_string()); + r.run(&wide(MAX_REFLECTED_MEMBERS + 1)).unwrap(); + assert!(thrown(&mut r, "w.reflect;").starts_with("RangeError")); + // A function with too many parameters is counted with the members. + let params = (0..MAX_REFLECTED_MEMBERS).map(|i| format!("a{i}")).collect::>().join(","); + assert!(thrown(&mut r, &format!("({{f: function ({params}) {{}}}}).reflect;")).starts_with("RangeError")); +} + +fn constant(value: f64) -> HostFunction { + Rc::new(move |_| Ok(Data::Number(value))) +} + +/// `Item` with `size` (read-write, 1 to 10, default 5), `kind` and the method `fit(target, +/// margin?)`; and `Box`, a child that declares `kind` again as a method and adds `cut`, which is +/// not available. +fn classes() -> Vec { + let item = HostClass { + name: "Item".into(), + parent: None, + members: vec![ + ("size".into(), HostMember::Property { get: constant(5.0), set: constant(0.0) }), + ("kind".into(), HostMember::Get(constant(1.0))), + ("fit".into(), HostMember::Method(constant(2.0))), + ], + info: vec![ + ( + "size".into(), + MemberInfo { + data_type: "number".into(), + description: Some("The size.".into()), + help: Some("How large the item is.".into()), + default: Some(Data::Number(5.0)), + min: Some(1.0), + max: Some(10.0), + ..MemberInfo::default() + }, + ), + ( + "fit".into(), + MemberInfo { + data_type: "boolean".into(), + collection: true, + arguments: vec![ + ArgInfo { name: "target".into(), data_type: "Item".into(), ..ArgInfo::default() }, + ArgInfo { + name: "margin".into(), + data_type: "number".into(), + default: Some(Data::Number(0.0)), + min: Some(0.0), + ..ArgInfo::default() + }, + ], + ..MemberInfo::default() + }, + ), + ], + index: None, + construct: None, + }; + let child = HostClass { + name: "Box".into(), + parent: Some("Item".into()), + members: vec![("kind".into(), HostMember::Method(constant(3.0))), ("cut".into(), HostMember::Method(constant(4.0)))], + info: vec![("cut".into(), MemberInfo { unavailable: true, ..MemberInfo::default() })], + index: None, + construct: None, + }; + vec![item, child] +} + +#[test] +fn a_host_class_is_described_by_its_members_and_their_info() { + let mut r = realm(); + r.define_host_classes(classes(), vec![("item".into(), host_ref("Item", &[1.0])), ("box".into(), host_ref("Box", &[2.0]))]).unwrap(); + r.run(LIST).unwrap(); + for target in ["item", "Item"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Item"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number kind:readonly:unknown"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "fit:method:boolean"); + } + let size = "var s = item.reflect.find('size'); [s.description, s.help, s.defaultValue, s.min, s.max, s.isCollection].join('|')"; + assert_eq!(text(&mut r, size), "The size.|How large the item is.|5|1|10|false"); + let fit = "var f = item.reflect.find('fit'); f.isCollection + ' ' + list(f.arguments) + ' ' + f.arguments.margin.defaultValue + ' ' + f.arguments[1].min"; + assert_eq!(text(&mut r, fit), "true target:parameter:Item margin:parameter:number 0 0"); + // The child lists its parent's members first, its own declaration of one in its place, and + // leaves out the member that is not available. + for target in ["box", "Box"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Box"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "kind:method:unknown fit:method:boolean"); + assert_eq!(text(&mut r, &format!("String({target}.reflect.find('cut'))")), "null"); + } + // No member's function ran: a data property of the class's type names it. + assert_eq!(text(&mut r, "({b: box}).reflect.find('b').dataType"), "Box"); +} + +#[test] +fn info_for_a_member_a_class_does_not_have_is_refused() { + for (info, message) in [ + (vec![("nothing".to_string(), MemberInfo::default())], "not one of its members"), + (vec![("size".to_string(), MemberInfo::default()), ("size".to_string(), MemberInfo::default())], "twice"), + ] { + let mut r = realm(); + let mut class = classes().remove(0); + class.info = info; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains(message), "{}", e.message); + } + let mut r = realm(); + let mut class = classes().remove(0); + class.members.push(("size".into(), HostMember::Get(constant(1.0)))); + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains("names the member size twice"), "{}", e.message); +} diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..1e61b47bf5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -174,7 +174,7 @@ features! { Notify "notify" Language, OperatorOverloading "operatorOverloading" HostOnly, Preferences "preferences" Language, - Reflection "reflection" HostOnly, + Reflection "reflection" Language, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, ScriptuiPalette "scriptui.palette" HostOnly, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..ac75fb0256 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -212,6 +212,13 @@ fn directives_are_read_at_the_start_of_a_line_in_both_forms() { assert_eq!(r.needs, [Need::Language], "VectorCraft runs #targetengine"); } +#[test] +fn reflection_needs_only_the_language() { + let r = report("var p = obj.reflect.properties;\nvar m = $.reflect.find('write');\n"); + assert_eq!(feature(&r, "reflection").map(|f| f.lines.clone()), Some(vec![1, 2])); + assert_eq!(r.needs, [Need::Language], "VectorCraft runs reflect"); +} + #[test] fn a_byte_order_mark_and_every_line_break_are_read() { // U+2028 ends line 2. diff --git a/docs/mcp.md b/docs/mcp.md index 51cd09fdbb..eff8b953f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2540,9 +2540,9 @@ top-level `import` or `export`, such as a React `.jsx` file), `notText` (a NUL b control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, the reply holds these lists: - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects - and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's + and directives, such as `$`, `alert`, `UnitValue`, `reflect`, `#target` and `#targetengine`), `dom` (the reference app's document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions + palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, actions and `selectTool`). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and @@ -2794,6 +2794,22 @@ itself throws a `TypeError`. So does a property that is not writable or not conf would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 characters throws a `RangeError`. +`value.reflect` describes an object, as the reflection interface page lays out +(https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/). Each read +gives a new frozen object with `name` (the class), `description` and `help` (`undefined`), `properties` and +`methods` (arrays of entries), and `find(name)`, which gives the entry of the property, or else the method, with that +name, or `null`; a name that is not a string or a number throws a `TypeError`. Each entry has `name` (a number for an +array index), `description`, `help`, `type` (`readonly`, `readwrite`, `method`, or `parameter` for an argument), +`dataType`, `defaultValue`, `min`, `max`, `isCollection` and `arguments`; an entry is also under its name in its array +when that name is not an array index or `length`. `app`, its documents, page items and layers, `DocumentPreset` and +each class's constructor list the members of their class and its parents, with the types, bounds, defaults and method +arguments the object model declares for them (VectorCraft's own values); members that are not available yet are left +out. Any other object lists its own properties: a function value is a method, with a JavaScript function's parameter +names as its arguments, a data property gives the type of its value, and an accessor gives `unknown`. A string, number +or boolean lists its prototype's own properties. No getter runs. `reflect` has no setter, and nothing in a reflection +can be changed: a write is ignored, or throws a `TypeError` in strict mode. An object with more than 10,000 members +and arguments throws a `RangeError`. + The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A run that changes no document adds no undo step. The journal records each command the run finished, as it records commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..762fde881d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,6 +1029,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. + - Scripts: every object has a read-only `reflect` property (https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/) that gives its class name, its properties and methods with their types, access, bounds, defaults and method arguments, and `find(name)`. `app`, its documents and page items and their classes are described from the declarations that install their members, and any other object from its own properties, without running a getter. `script.check` no longer counts it as host-only. `crates/js/src/reflect_tests.rs`, `crates/engine/src/script/dom.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. From 9e6c315689cbb59d9ae67a6cba04385fb3e34e1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:36:43 -0800 Subject: [PATCH 03/50] Scripts: selection, controlBounds, Revert and preset limits in the object model - Document.selection = undefined throws a TypeError and keeps the selection; null and [] still clear it. The assignment finds the locked artboards once and drops repeated objects with a set. - PageItem.controlBounds is the visible bounds widened to take in the direction points of every path in the object. - A page item or layer handle carries the document's revert count, so an object read before file.revert throws Stale page item. - Restoring a selection gives a path with only segments selected no anchors of its own before its segments are added back. - A failed object-model call and a vc.run result that cannot reach the script put back the growth they were charged. - DocumentPreset values count against the run's heap by what they hold now; an assignment past it throws a RangeError. - A host class member named constructor is refused, and reflect's find function is frozen. - file.new keeps the stored columns while rows are set, so a change of spacing alone no longer changes the grid a later layout uses. - command_value passes the id and params through without copying them. - Tests: the getIsFileOpen test passes its paths as JSON strings, and the locked removeAll test checks both objects from inside the script. --- crates/engine/src/cmd/newdoc.rs | 5 +- crates/engine/src/script/dom.rs | 139 ++++++++++++++++++------- crates/engine/src/script/mod.rs | 29 ++++-- crates/engine/src/tests/script_dom.rs | 143 ++++++++++++++++++++++++-- crates/js/src/host_classes.rs | 4 + crates/js/src/reflect.rs | 1 + crates/js/src/reflect_tests.rs | 20 +++- docs/mcp.md | 14 +-- 8 files changed, 295 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index fb26b13c68..0a5ed93ba3 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -394,9 +394,8 @@ impl DocSettings { if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn { self.rows = 0; } - if self.grid_rows().is_some() { - self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); - } + // While rows are set, `grid_columns` gives the columns they make; the stored columns stay as + // they were given, and are the ones a later layout without rows uses. Ok(()) } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6fda66efe1..0753cc5263 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -6,9 +6,10 @@ //! describe them. //! //! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the -//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the -//! document and the object up again. An object that was deleted, a document that was closed and an -//! object from an earlier run of a named engine throw an error on every member. Every change runs +//! document's [`crate::DocState::uid`] and, for art and layers, the document's +//! [`crate::DocState::reverts`] and the object's id, and every read looks the document and the +//! object up again. An object that was deleted, a document that was closed, an object from before +//! File › Revert and an object from an earlier run of a named engine throw an error on every member. Every change runs //! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each //! changed document; a change that changes nothing runs no command. A change to a document that is //! not the active one makes it active for the command and makes the other one active again after. @@ -24,7 +25,9 @@ //! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object -//! must be one of that document's that can be selected, or nothing changes. +//! must be one of that document's that can be selected, or nothing changes. `undefined` throws. +//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path +//! in the object. //! - Members the help pages list that are not here yet throw an error that says so, and `reflect` //! leaves them out. //! - `reflect` on an object or a class gives each member's type from the declaration that installs @@ -33,6 +36,7 @@ //! more than one type. use std::cell::{Cell, RefCell}; +use std::collections::HashSet; use std::rc::Rc; use std::sync::Arc; @@ -93,16 +97,24 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's /// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made, with the size +/// of the values they hold now and the most they may hold: the run's heap. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, presets: RefCell>>, + preset_bytes: Cell, + preset_limit: u64, } impl State { + /// The state of a run whose heap is `heap_bytes`. + pub(super) fn new(heap_bytes: usize) -> Self { + Self { preset_limit: heap_bytes as u64, ..Self::default() } + } + /// Whether a call's own savepoint is open: its commands take none of their own. pub(super) fn saving(&self) -> bool { self.saving.get() @@ -111,20 +123,25 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step -/// and no change to the document's saved state. +/// and no change to the document's saved state, and the growth its commands were charged is not +/// counted. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); + let mark = h.growth_mark(); h.dom.saving.set(true); let r = f(h); h.dom.saving.set(false); let mut s = h.session.borrow_mut(); if r.is_ok() { save.keep(&mut s); - } else if !save.restore(&mut s) { - return Err(HostError::Abort(HISTORY_LOST.to_string())); + } else { + h.put_growth_back(mark); + if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } } r } @@ -304,11 +321,17 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result bool { + whole(reverts) != Some(with_doc(h, doc, |_, st| st.reverts)) +} + /// The page item `d` names, which must still be in its document. fn item_of(h: &Host, d: &Data) -> std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc(h, *run, *uid).filter(|doc| !reverted_since(h, *doc, *reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; @@ -346,8 +369,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), }, None => Data::Null, } @@ -509,6 +532,8 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - .map(|i| { let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + // A path with only segments selected gets them back below, with no anchors. + None if before.segments.contains_key(i) => Vec::new(), None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), }; json!({"id": i.0, "anchors": anchors}) @@ -963,17 +988,30 @@ fn new_preset(h: &Host) -> Answer { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ + let fields = vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ]); + ]; + hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| data_size(v)).sum())?; + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } +/// Counts that the run's presets now hold `added` bytes of values in place of `replaced`, and +/// refuses when they would hold more than the run's heap. +fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result<(), HostError> { + let total = h.dom.preset_bytes.get().saturating_sub(replaced).saturating_add(added); + if total > h.dom.preset_limit { + return Err(HostError::Range(format!("the DocumentPreset settings would hold more than {} bytes", h.dom.preset_limit))); + } + h.dom.preset_bytes.set(total); + Ok(()) +} + /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; @@ -1026,8 +1064,12 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; - match fields.iter_mut().find(|(k, _)| k == key) { - Some((_, v)) => *v = value, + // The values the presets hold now count against the run's heap: a value assigned again + // replaces the one before it. + let at = fields.iter().position(|(k, _)| k == key); + hold_preset_bytes(&h, at.map_or(0, |n| data_size(&fields[n].1)), data_size(&value))?; + match at { + Some(n) => fields[n].1 = value, None => fields.push((key.to_string(), value)), } Ok(Data::Undefined) @@ -1157,28 +1199,33 @@ fn selection_of(h: &Host, uid: u64) -> Answer { } /// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or -/// `[]`. Every one must be an object of that document that can be selected. +/// `[]`. Every one must be an object of that document that can be selected. `undefined`, such as +/// an index past the end of `pageItems`, is refused and clears nothing. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), + Data::Undefined => return Err(HostError::Type("a selection is a page item, a list of them, null or []".into())), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], }; - let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; - let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); - if !ok { - let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); - return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + // The locked artboards are found once for the whole list, and repeated objects are kept once. + with_doc(h, doc, |_, st| { + let locks = st.doc.locked_artboards(); + let mut seen: HashSet = HashSet::with_capacity(list.len()); + let mut ids: Vec = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, item.id) { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if seen.insert(item.id) { + ids.push(item.id); + } } - if !ids.contains(&item.id) { - ids.push(item.id); - } - } - Ok(ids) + Ok(ids) + }) } fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { @@ -1440,6 +1487,25 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in +/// the object. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let r = with_doc(h, item.doc, |_, st| { + let mut r = r; + if let Some(n) = st.doc.node(item.id) { + n.walk(&mut |c| { + if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) { + r = r.union(handles); + } + }); + } + r + }); + Ok(f.bounds(h.dom.coords.get(), r)) +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1611,13 +1677,13 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(&[run, uid, reverts, high, low]) = handle.as_deref() else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let doc = find_doc(h, run, uid).filter(|doc| !reverted_since(h, *doc, reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } @@ -1771,8 +1837,11 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + if reverted_since(h, doc, *reverts) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } @@ -1962,7 +2031,7 @@ fn classes(link: &Link) -> Vec { ("height", property(l, item_height, item_set_height), typed("number")), ("geometricBounds", get(l, item_geometric), typed("Array")), ("visibleBounds", get(l, item_visible), typed("Array")), - ("controlBounds", get(l, item_visible), typed("Array")), + ("controlBounds", get(l, item_control), typed("Array")), ("editable", get(l, item_editable), typed("boolean")), ("zOrderPosition", get(l, item_z_order_position), typed("number")), ("duplicate", method(l, item_duplicate), returns("PageItem", &placement)), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..8e79b7bdda 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1076,6 +1076,20 @@ impl Host { self.pause.set(true); Ok(()) } + + /// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about + /// it, for [`Host::put_growth_back`]. + fn growth_mark(&self) -> (u64, u64, bool) { + (self.objects.get(), self.bytes_kept.get(), self.waiting.get()) + } + + /// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added + /// it were put back. + fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) { + self.objects.set(objects); + self.bytes_kept.set(bytes); + self.waiting.set(waiting); + } } /// A run in progress. @@ -1309,16 +1323,14 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { - let id = id.to_string(); - let params = params.clone(); let session = host.session.clone(); let started = clock(); let r = { let mut s = session.borrow_mut(); - step(&mut s, host, &id, ¶ms) + step(&mut s, host, id, params) }; // Only commands that exist are timed, so the table holds at most one row per command. - if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { + if let (Some(started), Some(spec)) = (started, crate::find_command(id)) { let nanos = started.elapsed().as_nanos(); let mut times = host.commands.borrow_mut(); let row = times.entry(spec.id).or_insert((0, 0, 0)); @@ -1331,13 +1343,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())), Err(e) => return Err(HostError::Error(e.to_string())), }; + let mark = host.growth_mark(); let crossed = host.charge_growth(objects, added).and_then(|()| { let data = to_data(&value, &result_limits(), 0, &mut (0, 0)) .map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?; host.charge_call(data_size(&data))?; Ok(data) }); - // A command whose result does not reach the script is put back, like one that failed. + // A command whose result does not reach the script is put back, like one that failed, and so is + // the growth it was charged. + if crossed.is_err() { + host.put_growth_back(mark); + } if let Some(save) = save { let mut s = session.borrow_mut(); if crossed.is_ok() { @@ -2064,7 +2081,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::default(), + dom: dom::State::new(heap_bytes), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..d0cb4e7ecd 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -229,6 +229,41 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +/// An index past the end of `pageItems` gives `undefined`, which does not clear the selection; +/// `null` and `[]` do. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let caught = "var d = app.activeDocument, m = '';\ + try { d.selection = d.pageItems[99]; } catch (e) { m = e.name; }\ + vc.log(m); vc.log(d.selection.length);"; + assert_eq!(log(&mut s, caught), vec![json!("TypeError"), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + for clear in ["null", "[]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, &format!("app.activeDocument.selection = {clear};")); + assert!(s.active().unwrap().selection.objects.is_empty(), "{clear}"); + } +} + +/// `controlBounds` takes in a direction point that lies past the curve; `visibleBounds` does not. +#[test] +fn control_bounds_take_in_direction_points_past_the_curve() { + let (mut s, _, _) = doc(); + s.execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})).unwrap(); + let out = log( + &mut s, + "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.pageItems;\ + vc.log(p[2].controlBounds); vc.log(p[2].visibleBounds); vc.log(p[0].controlBounds); vc.log(p[0].visibleBounds);", + ); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!((top(&out[0]) + 100.0).abs() < 1e-9, "{out:?}"); + assert!(top(&out[1]) > -90.0, "{out:?}"); + // A rectangle's direction points lie on its edges. + assert_eq!(out[2], out[3]); +} + #[test] fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); @@ -364,6 +399,17 @@ fn a_copy_that_cannot_be_placed_is_deleted() { assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); // The refused copy leaves no undo step and does not change the document's step. assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step)); + // Nor does it count toward the run's growth allowance: many refused copies stay within one + // that a few kept copies would pass. + crate::script::TEST_GROWTH.with(|g| g.set(Some(5))); + let r = run( + &mut s, + "var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], refused = 0;\ + for (var k = 0; k < 20; k++) { try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { refused++; } }\ + vc.log(refused);", + ); + crate::script::TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(r.unwrap()["log"], json!([20])); } #[test] @@ -482,6 +528,14 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); } + // A change of spacing alone leaves the stored columns as they are, so leaving the rows later + // gives the same grid with or without it. + let to_row = json!({"artboardLayout": {"layout": "gridByRow"}}); + let plain = stored.clone().with_params(&json!({"artboards": 9}), "file.new").unwrap(); + let spaced = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": {"spacing": 20}}), "file.new").unwrap(); + assert_eq!((plain.grid_columns(), spaced.grid_columns()), (3, 3)); + let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap()); + assert_eq!(plain.grid_columns(), spaced.grid_columns()); let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); assert!(e.contains("rows must be 1 or more"), "{e}"); for layout in ["gridByRow", "row", "column"] { @@ -549,6 +603,26 @@ fn an_edit_keeps_the_order_of_a_mixed_selection() { assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors)); } +/// A path with segments selected and no anchors gets the segments back, not every anchor. +#[test] +fn an_edit_keeps_a_path_with_only_a_segment_selected() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + s.doc_mut().unwrap().selection.anchors.remove(&b); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[2].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((&sel.objects, &sel.segments, sel.anchors.get(&a)), (&before.objects, &before.segments, before.anchors.get(&a))); + // The segment brings back its own two end points, as `select.segments` selects them, and none + // of the path's other anchors: the journaled restore selects none of them first. + assert_eq!(sel.anchors.get(&b).map(|k| k.len()), Some(2), "{sel:?}"); + let restore = s.journal.iter().rev().find(|(id, _)| id == "select.anchorsMany").map(|(_, p)| p.clone()).unwrap(); + let path = restore["items"].as_array().unwrap().iter().find(|i| i["id"] == json!(b.0)).cloned().unwrap(); + assert_eq!(path["anchors"], json!([]), "{restore}"); +} + #[test] fn assigning_the_selection_clears_a_layers_panel_target() { let (mut s, a, _) = doc(); @@ -733,6 +807,28 @@ fn a_document_preset_is_an_instance_of_its_class() { assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); } +/// The values the presets hold count against the run's heap, a value assigned again in place of +/// the one before it. +#[test] +fn document_preset_values_are_bounded_by_the_runs_heap() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let big = "var s = 'a'; while (s.length < (1 << 19)) s += s;"; + let again = + format!("#targetengine presets\n{big} var p = new DocumentPreset(); for (var k = 0; k < 40; k++) p.title = s + k; vc.log(p.title.length);"); + assert_eq!(log(&mut s, &again), vec![json!(524_290)]); + let many = format!( + "#targetengine presets\n{big} var m = '';\ + try {{ for (var k = 0; k < 40; k++) {{ var p = new DocumentPreset(); p.title = s; }} }} catch (e) {{ m = e.name + ': ' + e.message; }}\ + vc.log(k < 40); vc.log(m);" + ); + let out = log(&mut s, &many); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!(out[0], json!(true), "{out:?}"); + assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); +} + #[test] fn the_same_document_or_item_is_the_same_object() { let (mut s, a, _) = doc(); @@ -928,20 +1024,52 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +/// File › Revert loads objects with the ids they were saved with: an object or a layer read before +/// the revert does not name the loaded one. +#[test] +fn wrappers_go_stale_after_revert() { + let (mut s, a, _) = doc(); + let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] { + let source = format!("var i = app.activeDocument.pageItems[0], l = i.parent; i.name = 'before'; vc.run('file.revert'); {read};"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{read}: {e}"); + } + // Objects read after the revert are the loaded ones. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; p[0].name = 'before'; vc.run('file.revert');\ + app.activeDocument.pageItems[0].name = 'loaded'; vc.log(app.activeDocument.pageItems.length);", + ); + assert_eq!(out, vec![json!(2)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("loaded")); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); - let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); - assert!(e.contains(&b.0.to_string()), "{e}"); - assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + // The script catches the error and finds both objects still there before the run ends, so the + // run's own rollback cannot hide a deletion. + let caught = "var p = app.activeDocument.pageItems, m = '';\ + try { p.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length);"; + let out = log(&mut s, caught); + assert!(out[0].as_str().unwrap().contains(&b.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); // A locked object inside an unlocked group stops it too. s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); - let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); - assert!(e.contains(&g.to_string()), "{e}"); + let out = log(&mut s, caught); + assert!(out[0].as_str().unwrap().contains(&g.to_string()), "{out:?}"); + assert_eq!(out[1], json!(3)); assert!(s.active().unwrap().doc.node(b).is_some()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);"); @@ -1002,8 +1130,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy().to_string(); + let (p, other) = (serde_json::to_string(&p).unwrap(), serde_json::to_string(&format!("{p}.other")).unwrap()); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 2af2fc130f..7380cc574c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -349,6 +349,10 @@ fn reflected_members(class: &HostClass) -> Result, String> { if out.iter().any(|r| *r.name == **name) { return Err(format!("the host class {} names the member {name} twice", class.name)); } + // The prototype's `constructor` is the class's own constructor. + if name == "constructor" { + return Err(format!("the host class {} names a member constructor, which is the name of its constructor", class.name)); + } let access = match member { HostMember::Get(_) => Access::ReadOnly, HostMember::Property { .. } => Access::ReadWrite, diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index a84c221d3a..0b6b7fffff 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -227,6 +227,7 @@ fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[I let methods = info_array(interp, methods)?; interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?; let find = native(interp, "find", find, 1, NativeKind::Plain, false)?; + interp.object_mut(find)?.extensible = false; interp.temp_roots.push(Value::Object(find)); let r = interp.new_object(); interp.temp_roots.push(Value::Object(r)); diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs index 3e8827cf4f..e28247e162 100644 --- a/crates/js/src/reflect_tests.rs +++ b/crates/js/src/reflect_tests.rs @@ -112,13 +112,20 @@ fn a_reflection_cannot_be_changed() { [typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()"; assert_eq!(text(&mut r, tries), "object,Object,number,1,,object"); // In strict mode each one throws a TypeError. - for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] { + for write in + ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find", "x.find.extra = 1"] + { assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}"); } assert_eq!( - text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"), - "true true true" + text( + &mut r, + "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments) + ' ' + Object.isFrozen(x.find)" + ), + "true true true true" ); + // The frozen `find` still finds. + assert_eq!(text(&mut r, "x.find('a').name"), "a"); } #[test] @@ -239,4 +246,11 @@ fn info_for_a_member_a_class_does_not_have_is_refused() { class.members.push(("size".into(), HostMember::Get(constant(1.0)))); let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); assert!(e.message.contains("names the member size twice"), "{}", e.message); + // `constructor` is the class's own constructor, so no member may take its name. + let mut r = realm(); + let mut class = classes().remove(0); + class.members.push(("constructor".into(), HostMember::Get(constant(1.0)))); + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains("names a member constructor"), "{}", e.message); + assert_eq!(text(&mut r, "typeof Item"), "undefined"); } diff --git a/docs/mcp.md b/docs/mcp.md index eff8b953f8..8219fb3d83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2631,7 +2631,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and + starts with the defaults that page gives. The values a run's `DocumentPreset` objects hold together may not take + more than the run's heap; an assignment past that throws a `RangeError`, and a value assigned again replaces the + one before it in that count. A preset's `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a @@ -2648,7 +2650,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds, widened to take in the direction points of every path in the object), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same @@ -2670,16 +2672,16 @@ app through the global object `vc`, and writes to the Script Console and runs ot is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active - tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a + tab as it was. A bad value throws an error and changes nothing. An object that was deleted, that was read before + `file.revert` reloaded its document, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, - a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + a list of at most 10,000, `null` or `[]`; `undefined`, such as an index past the end of `pageItems`, throws a + `TypeError`, and an object that cannot be selected throws `Cannot select`, both with nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, From 99e07b0f6bd5129ffbc46c2b33a86d1e19542272 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:40:07 -0800 Subject: [PATCH 04/50] Scripts: DocumentPreset arrays count each element against the heap The heap limit on DocumentPreset values counted a boolean as 4 bytes, while the host keeps a whole value for each array element, so arrays kept by many presets could hold several times the run's heap. The limit now counts the host's copy: a value for the field and for each element or property, plus the text of its strings and property names. --- crates/engine/src/script/dom.rs | 16 ++++++++++++++-- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 0753cc5263..8054a1b174 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -996,7 +996,7 @@ fn new_preset(h: &Host) -> Answer { item("numArtboards", num(1.0)), item("width", num(612.0)), ]; - hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| data_size(v)).sum())?; + hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?; presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } @@ -1012,6 +1012,18 @@ fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result Ok(()) } +/// The bytes the host's copy of `d` takes: a `Data` for the value and each element or property +/// in it, plus the text of its strings and property names. +fn held_bytes(d: &Data) -> u64 { + let owned = match d { + Data::String(s) => s.len() as u64, + Data::Array(a) => a.iter().map(held_bytes).sum(), + Data::Object(o) => o.iter().map(|(k, v)| (size_of::() + k.len()) as u64 + held_bytes(v)).sum(), + Data::Undefined | Data::Null | Data::Bool(_) | Data::Number(_) => 0, + }; + size_of::() as u64 + owned +} + /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; @@ -1067,7 +1079,7 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { // The values the presets hold now count against the run's heap: a value assigned again // replaces the one before it. let at = fields.iter().position(|(k, _)| k == key); - hold_preset_bytes(&h, at.map_or(0, |n| data_size(&fields[n].1)), data_size(&value))?; + hold_preset_bytes(&h, at.map_or(0, |n| held_bytes(&fields[n].1)), held_bytes(&value))?; match at { Some(n) => fields[n].1 = value, None => fields.push((key.to_string(), value)), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index d0cb4e7ecd..039d5d17e8 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -829,6 +829,24 @@ fn document_preset_values_are_bounded_by_the_runs_heap() { assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); } +/// An array a preset holds counts a whole value for each element, so arrays of booleans kept by +/// many presets stop at the run's heap too. +#[test] +fn document_preset_arrays_count_each_element_they_hold() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + "#targetengine presets\nvar a = []; for (var i = 0; i < 20000; i++) a.push(true); var m = '';\ + try { for (var k = 0; k < 40; k++) { var p = new DocumentPreset(); p.title = a; } } catch (e) { m = e.name + ': ' + e.message; }\ + vc.log(k < 40); vc.log(m);", + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!(out[0], json!(true), "{out:?}"); + assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); +} + #[test] fn the_same_document_or_item_is_the_same_object() { let (mut s, a, _) = doc(); From 99c4a82b3088efaebb181d065f2c2b9d090e99b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:43:40 -0800 Subject: [PATCH 05/50] Tabs: fallback glyphs in tab titles sit on the condensed face's baseline The tab family's copies of the semibold faces took the copy made for egui's empty Proportional family, which has no baseline shift, instead of the one made for the tab family. They now take the tab family's copy. egui's own faces stay under their own names, as in the semibold family: egui skips some of their characters (the Ubuntu logo, two symbols in its emoji face) only under those names. ui_fonts::baseline_copies measured a fallback face without its own FontTweak scale, while egui draws the face and its y_offset_factor at that scale. The shift now uses it, so a scaled fallback (Inter SemiBold at 0.92) sits on the row's baseline. Faces added before this change are at scale 1 and keep their shift. Without the condensed face the tab family is no longer bound, and tabs draw in theme::tab_title_font: the tab family when the context's fonts bind it, otherwise the semibold family as it is. Fonts an embedder adds to the semibold family then reach tab titles too, and an embedder's own definitions that bind only the other families keep working. The condensed face and the lookup of its catalog row move to build/condensed_ui_face.rs, which the crate's tests include. With CRAFT_FONTS_REQUIRED=1, an unreadable catalog, a malformed row for the face or a row whose file can't be embedded is a build error; a checkout without the catalog or the row still gives a warning. A checkout whose catalog names the condensed face without its file is watched through the file's folder inside the checkout, so the build runs again once the file appears. docs/development.md lists FONT_TAB among the families an embedder adds fonts to. ASSETS.md and NOTICE name the face, and the docs/ui-parity.md row says official builds wait for the craft-fonts pin to move. Tests: with the monospace face standing in for the condensed face, and without craft-fonts, one test checks the tab family's x-height, the baseline of a character only the semibold face has, and that the characters egui skips draw in a tab title as in semibold text. Two tab-strip tests check that titles are laid out in the tab family with a stand-in face and in the semibold family without one. The condensed-face test checks the x-height at 200 pt, the shortened-title test also runs in the tab font, the install_fonts test checks the tab family, and ui_fonts' no-craft-fonts test allows the condensed face, which a checkout can give alone. A text-crate test finds the face's row as craft-fonts' catalog has it and rejects malformed rows for it. Two comments use American spelling. --- ASSETS.md | 2 +- NOTICE | 2 + crates/text/build.rs | 52 +++++++----- crates/text/build/condensed_ui_face.rs | 45 ++++++++++ crates/text/src/lib.rs | 3 + crates/ui-egui/src/chrome/tabs.rs | 7 +- crates/ui-egui/src/chrome/tests.rs | 22 ++--- crates/ui-egui/src/i18n/tests.rs | 3 + crates/ui-egui/src/tests/tab_overflow.rs | 79 +++++++++++++++++- crates/ui-egui/src/theme.rs | 101 +++++++++++++++++++---- crates/ui-egui/src/ui_fonts.rs | 26 +++--- crates/ui-egui/tests/install_fonts.rs | 14 +++- docs/development.md | 8 +- docs/ui-parity.md | 2 +- 14 files changed, 299 insertions(+), 67 deletions(-) create mode 100644 crates/text/build/condensed_ui_face.rs diff --git a/ASSETS.md b/ASSETS.md index 2812067e00..b949197d4c 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -24,7 +24,7 @@ Generated-in-code art is original and has no file to list. This covers the defau **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. -**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. +**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles. | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| diff --git a/NOTICE b/NOTICE index 434cd3e524..99470afd8e 100644 --- a/NOTICE +++ b/NOTICE @@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; web builds BIZ UDPGothic Regular only) under the SIL Open Font License 1.1. Their license texts ship with the release packages as OFL-.txt. +Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed +SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face. PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources), compiled into the app through the hayro-cmap crate under the BSD 3-Clause License: diff --git a/crates/text/build.rs b/crates/text/build.rs index 5979c6557c..2658094965 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -14,12 +14,16 @@ //! out with a warning, never an error, and never costs the desktop its fonts. //! //! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in -//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A -//! checkout without that row leaves it `None` with a warning, never an error. +//! (`build/condensed_ui_face.rs`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. +//! A checkout without the catalog or that row leaves it `None` with a warning, never an error; an +//! unreadable catalog, a malformed row or a file that can't be embedded is an error with +//! `CRAFT_FONTS_REQUIRED=1`. use std::fmt::Write as _; use std::path::{Path, PathBuf}; +#[path = "build/condensed_ui_face.rs"] +mod condensed_ui_face; #[path = "build/web_fonts.rs"] mod web_fonts; @@ -28,6 +32,7 @@ fn main() { println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); + println!("cargo::rerun-if-changed=build/condensed_ui_face.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { @@ -55,7 +60,8 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { match condensed_ui_font(&dir) { Ok(entry) => condensed = format!("Some({entry})"), - Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, true)) if required => println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, _)) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), } } } @@ -108,7 +114,7 @@ fn craft_fonts(dir: &Path) -> Result { Ok(out) } -/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +/// The `CraftFont { .. }` initializer of one manifest row of the checkout `dir` (canonical `root`). fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; // The manifest is supplier data: embed only regular files inside the checkout. @@ -124,29 +130,33 @@ fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, sc )) } -/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in -/// Latin catalog. -const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); - -/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. -fn condensed_ui_font(dir: &Path) -> Result { +/// The `CraftFont { .. }` initializer of the condensed face's row in `fonts/latin-manifest.txt` +/// (`build/condensed_ui_face.rs`). The error says whether the checkout is broken: one without the +/// catalog or the row is an older craft-fonts, and an unreadable catalog, a malformed row or a row +/// whose file can't be embedded is broken. +fn condensed_ui_font(dir: &Path) -> Result { + let (family, style) = condensed_ui_face::FACE; let manifest = dir.join("fonts/latin-manifest.txt"); // A checkout without the catalog is watched through its folder, so the build runs again once // the catalog appears. let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; println!("cargo::rerun-if-changed={}", watched.display()); - let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; - let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; - let row = text - .lines() - .map(str::trim) - .filter(|l| !l.is_empty() && !l.starts_with('#')) - .map(|l| l.split(" | ").map(str::trim).collect::>()) - .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); - let Some([family, style, file, scripts, ..]) = row.as_deref() else { - return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + let text = std::fs::read_to_string(&manifest).map_err(|e| { + let older = e.kind() == std::io::ErrorKind::NotFound; + (format!("{}: {e}{}", manifest.display(), if older { " (an older craft-fonts?)" } else { "" }), !older) + })?; + let row = condensed_ui_face::row(&text).map_err(|e| (format!("{}: {e}", manifest.display()), true))?; + let Some((file, scripts)) = row else { + return Err((format!("{family} {style} not in {} (an older craft-fonts?)", manifest.display()), false)); }; - craft_font(dir, &root, family, style, file, scripts) + let root = dir.canonicalize().map_err(|e| (format!("{}: {e}", dir.display()), true))?; + // A row whose file is missing is watched through the file's folder inside the checkout (or the + // checkout's `fonts/`), so the build runs again once the file appears. + craft_font(dir, &root, family, style, file, scripts).map_err(|e| { + let inside = dir.join(file).parent().and_then(|p| p.canonicalize().ok()).filter(|p| p.starts_with(&root) && p.is_dir()); + println!("cargo::rerun-if-changed={}", inside.unwrap_or_else(|| dir.join("fonts")).display()); + (e, true) + }) } /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and diff --git a/crates/text/build/condensed_ui_face.rs b/crates/text/build/condensed_ui_face.rs new file mode 100644 index 0000000000..c70e2cb2a4 --- /dev/null +++ b/crates/text/build/condensed_ui_face.rs @@ -0,0 +1,45 @@ +//! The condensed craft-fonts face document tab titles draw in, and its row in the checkout's opt-in +//! Latin catalog (`fonts/latin-manifest.txt`). Shared by `build.rs` and the crate's tests +//! (`#[path]`-included by both, so it has no dependencies). + +/// The condensed face's family and style. +pub const FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The file and scripts fields of [`FACE`]'s row in the catalog `text`: `None` when no row names +/// the face, and an error when the row that names it does not have the catalog's 8 fields or leaves +/// the file or scripts empty. +pub fn row(text: &str) -> Result, String> { + for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { + let fields: Vec<&str> = line.split(" | ").map(str::trim).collect(); + match fields.as_slice() { + [family, style, file, scripts, _, _, _, _] if (*family, *style) == FACE && !file.is_empty() && !scripts.is_empty() => { + return Ok(Some((*file, *scripts))); + } + [family, style, ..] if (*family, *style) == FACE => return Err(format!("malformed manifest line: {line}")), + _ => {} + } + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The face's row as storytold/craft-fonts#72 adds it to the catalog is found, rows for other + /// faces are not taken for it, and a row naming it without its file or scripts, or with one of + /// them empty, is an error. + #[test] + fn the_catalog_row_names_the_face() { + let catalog = "# Latin presentation fonts for the Crafting Apps (opt-in).\n\ + Inter | SemiBold | fonts/inter/Inter-SemiBold.ttf | Latn | OFL-1.1 | fonts/inter/OFL.txt | 78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3 | https://github.com/rsms/inter/releases/download/v4.1/Inter-4.1.zip#extras/ttf/Inter-SemiBold.ttf\n\ + Noto Sans | Condensed SemiBold | fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf | Latn | OFL-1.1 | fonts/noto-sans-condensed/OFL.txt | b41ecd0838ecd17b706432a01c0d63f8bf977d851cc2cf37242324233edb9294 | https://github.com/notofonts/latin-greek-cyrillic/releases/download/NotoSans-v2.015/NotoSans-v2.015.zip#NotoSans/unhinted/ttf/NotoSans-CondensedSemiBold.ttf\n"; + assert_eq!(row(catalog), Ok(Some(("fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf", "Latn")))); + let rest = "OFL-1.1 | fonts/a/OFL.txt | 00 | https://example.com/a.zip"; + assert_eq!(row(&format!("Noto Sans | SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "another style"); + assert_eq!(row(&format!("# Noto Sans | Condensed SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "a comment"); + assert_eq!(row("Inter | Bold\n"), Ok(None), "a short row for another face"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | {rest}\n")).is_err(), "a row without its scripts"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | | {rest}\n")).is_err(), "a row with empty scripts"); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2028639af4..d1e82be440 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -1068,6 +1068,9 @@ pub fn x_height(data: &[u8], index: u32) -> Option { m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) } +#[cfg(test)] +#[path = "../build/condensed_ui_face.rs"] +mod condensed_ui_face_build; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 1aff4fe1a9..782309a3f0 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_title_font(ui, title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -213,6 +213,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. let shown = crate::doc_windows::tab_window(app).filter(|_| app.ui.home.is_none()); + let title_font = theme::tab_title_font(ui, title_size); // The windows under the tabs, with the text each tab shows, its whole title and the text laid // out; `active` is the position of the highlighted one. An inactive tab shows the name alone, // without the zoom and the mode in parentheses (color mode and view, or the opacity mask being @@ -225,7 +226,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), title_font.clone(), color); (w, text, title, galley) }) .collect(); @@ -259,7 +260,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, title_font.clone(), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..b78968442e 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -29,27 +29,29 @@ fn the_tabs_after_the_leading_one_are_drawn_whole() { assert_eq!(super::tab_room(None, false, 120.0, 119.99), 119.99, "no leading tab"); } -/// A shortened title shows at every width that holds "…", fractional ones included (#8584). +/// A shortened title shows at every width that holds "…", fractional ones included (#8584), in the +/// semibold face and in the tab titles' face (the condensed one in a build with craft-fonts, #8583). #[test] fn a_shortened_title_fits_at_fractional_widths() { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - let font = crate::theme::semibold(13.0); let title = "Untitled-12 @ 66.67 % (RGB/Preview)"; let mut too_wide = vec![]; let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); - let mut width = ellipsis.size().x.ceil() + 1.0; - while width < 200.0 { - let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); - if !fits { - too_wide.push((width, galley.size().x)); + for font in [crate::theme::semibold(13.0), crate::theme::tab_title_font(ui, 13.0)] { + let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); + let mut width = ellipsis.size().x.ceil() + 1.0; + while width < 200.0 { + let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); + if !fits { + too_wide.push((font.family.clone(), width, galley.size().x)); + } + width += 0.25; } - width += 0.25; } }); output.textures_delta.clear(); - assert!(too_wide.is_empty(), "shortened titles wider than their room (room, width): {too_wide:?}"); + assert!(too_wide.is_empty(), "shortened titles wider than their room (family, room, width): {too_wide:?}"); } /// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7954785e30..6136913184 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1501,6 +1501,9 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; + // The tab family is bound only in builds with craft-fonts' condensed face. + let tab = egui::FontFamily::Name(crate::theme::FONT_TAB.into()); + let families: Vec = families.into_iter().filter(|f| *f != tab || fonts.definitions().families.contains_key(f)).collect(); for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { let (entries, _) = parse_entries(l.source); let cjk_checked = japanese_ui_font && l.code == "ja"; diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index c9f9edec0a..7b389001d5 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -145,12 +145,87 @@ fn tab_titles_in_the_condensed_face_fit_more_tabs() { let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); // The height of an x, in the tab font and in semibold text. let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; - (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + let tab = if face.is_some() { crate::theme::tab_font(200.0) } else { crate::theme::semibold(200.0) }; + (whole, x(tab), x(crate::theme::semibold(200.0))) }; let (semibold, _, _) = whole_tabs(None); let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); - assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ by + // about 8 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + +/// The tab strip lays its titles out in the tab family's own face when it has one: the monospace +/// face stands in for craft-fonts' condensed face, which CI's craft-fonts checkout does not have +/// (#8583). +#[test] +fn tab_titles_draw_in_the_tab_familys_face() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "name": "Tab test"})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(Some(&stand_in))); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 1, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_TAB.into()), "{title}"); + } +} + +/// The fonts the tab strip lays its "Tab test" titles out in. +fn title_fonts(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::FontId)> { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, SIZE)), ..Default::default() }, |ui| { + egui::CentralPanel::default().show(ui, |ui| chrome::doc_tabs(app, ui)); + }); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::FontId)>) { + match s { + egui::Shape::Text(t) if t.galley.text().starts_with("Tab test") => { + v.extend(t.galley.job.sections.first().map(|s| (t.galley.text().to_owned(), s.format.font_id.clone()))); + } + egui::Shape::Vec(list) => list.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut fonts = vec![]; + for c in &out.shapes { + walk(&c.shape, &mut fonts); + } + fonts +} + +/// Without the condensed face the tab family is not bound, and tab titles draw in the semibold +/// family as it is, with a face added to it later (#8583). +#[test] +fn tab_titles_draw_in_semibold_where_the_tab_family_is_not_bound() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..3 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Tab test {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + // A face put at the head of the semibold family after the interface's, as an embedder may. + let mut fonts = crate::theme::interface_fonts_with(None); + let added = "Added semibold".to_owned(); + fonts.font_data.insert( + added.clone(), + std::sync::Arc::new(egui::FontData::from_static(include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"))), + ); + fonts.families.entry(egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into())).or_default().insert(0, added); + let ctx = egui::Context::default(); + ctx.set_fonts(fonts); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 3, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), "{title}"); + } } /// With the last document active, the tabs from it to the end leave room before the » button, and diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 11e8af8e22..2743922495 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -497,16 +497,23 @@ pub const FONT_MONO: &str = "mono"; /// The family document tab titles draw in. In a build with craft-fonts' condensed face /// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the /// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so -/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +/// more tabs fit in the strip (#8583). Without it the family is not bound, and tab titles draw in +/// [`FONT_UI_SEMIBOLD`] ([`tab_title_font`]). pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } -/// A document tab's title font ([`FONT_TAB`]). -pub fn tab_font(size: f32) -> FontId { +/// A font in [`FONT_TAB`], which is bound only with the condensed face: see [`tab_title_font`]. +pub(crate) fn tab_font(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_TAB.into())) } +/// The font document tab titles draw in on `ui`: the [`FONT_TAB`] family when `ui`'s fonts bind +/// it (with the condensed face), otherwise [`semibold`]. +pub fn tab_title_font(ui: &egui::Ui, size: f32) -> FontId { + let font = tab_font(size); + if ui.ctx().fonts(|f| f.definitions().families.contains_key(&font.family)) { font } else { semibold(size) } +} /// Whether `family` draws semibold text and takes the bold fallback faces. pub(crate) fn is_semibold(family: &FontFamily) -> bool { matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) @@ -516,7 +523,7 @@ pub fn mono(size: f32) -> FontId { } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`], and [`FONT_TAB`] with the condensed face). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -548,9 +555,10 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); let semi = family(semi, &fallback); - let tab = tab_faces(&mut fonts, &semi, condensed); + if let Some(tab) = tab_faces(&mut fonts, &semi, condensed) { + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); + } fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); - fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); @@ -559,28 +567,38 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon /// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first /// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its -/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. -fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { +/// baseline. egui's own faces are listed under their own names, uncopied, as in the semibold +/// family: egui skips some of their characters (the Ubuntu logo, for one) only under those names. +/// `None` without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Option> { let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); - let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); - let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; - let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data))?; + let f = condensed?; + let own = vectorcraft_text::x_height(f.bytes, 0)?; let name = craft_font_name(f); let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); - // `baseline_copies` reads the head of each family it is given: here only this one. + // `baseline_copies` reads the head of each family it is given. `row` also has egui's empty + // Proportional and Monospace families, whose copies are not this family's. + let tab = FontFamily::Name(FONT_TAB.into()); let mut row = FontDefinitions::empty(); row.font_data.insert(name.clone(), Arc::new(head.clone())); - row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + row.families.insert(tab.clone(), vec![name.clone()]); let mut faces = vec![name.clone()]; for face in semi { + if FontDefinitions::builtin_font_names().contains(&face.as_str()) { + faces.push(face.clone()); + continue; + } let Some(data) = fonts.font_data.get(face).cloned() else { continue }; - for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + for (copy, data, _) in + crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data).into_iter().filter(|(_, _, f)| f.contains(&tab)) + { fonts.font_data.insert(copy.clone(), Arc::new(data)); faces.push(copy); } } fonts.font_data.insert(name, Arc::new(head)); - faces + Some(faces) } /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace @@ -831,4 +849,57 @@ mod tests { assert_eq!(ctx.global_style().interaction.tooltip_delay, f32::INFINITY); assert_eq!(ctx.global_style().visuals.window_fill, Tokens::for_brightness(Brightness::Light).panel); } + + /// The face heading the tab family draws an x as tall as the semibold face does, and a + /// character it lacks falls back to the semibold face (drawn at its own 0.92 scale) on its + /// baseline (#8583). The monospace face stands in for craft-fonts' condensed face, which CI's + /// craft-fonts checkout does not have. + #[cfg(feature = "interface-fonts")] + #[test] + fn the_tab_family_keeps_the_semibold_x_height_and_baseline() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut defs = interface_fonts_with(Some(&stand_in)); + assert_eq!(defs.families[&FontFamily::Name(FONT_TAB.into())][0], craft_font_name(&stand_in)); + // The semibold face alone, as it draws a character in its own family. + defs.families.insert(FontFamily::Name("probe".into()), vec!["Inter-SemiBold".to_owned()]); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + ctx.set_fonts(defs); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + output.textures_delta.clear(); + let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, Color32::WHITE)).rows[0].glyphs.clone(); + let x = |font: FontId| glyphs("x", font)[0].uv_rect.size.y; + let (x_tab, x_semibold) = (x(tab_font(200.0)), x(semibold(200.0))); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ + // by about 10 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // egui skips some characters of its own faces (the Ubuntu logo, two symbols in its emoji + // face); a tab title draws them as semibold text does. + for c in ['\u{534D}', '\u{5350}', '\u{E0FF}', '\u{EFFD}', '\u{F0FF}', '\u{F200}'] { + let has = |font: FontId| ctx.fonts_mut(|f| f.has_glyph(&font, c)); + let name = format!("U+{:04X}", u32::from(c)); + assert_eq!(has(tab_font(13.0)), has(semibold(13.0)), "{name} has a glyph in a tab title as in semibold text"); + if has(semibold(13.0)) { + // Both families take it from the same fallback face, which draws it at one size. + let size = |font: FontId| glyphs(&c.to_string(), font).first().map(|g| g.uv_rect.size); + assert_eq!(size(tab_font(13.0)), size(semibold(13.0)), "{name} draws at the same size in a tab title as in semibold text"); + } + } + let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; + // U+0182, which Inter has and the monospace face lacks. + let c = 'Ƃ'; + for size in [13.0_f32, 24.0, 40.0, 100.0] { + let own = glyphs(&c.to_string(), FontId::new(size, FontFamily::Name("probe".into()))); + let row = glyphs(&format!("H{c}"), tab_font(size)); + assert_eq!((own.len(), row.len()), (1, 2), "{c} lays out as one glyph"); + // Half a point: one device pixel at 2 pixels per point, for each glyph's rounding. + let drift = (bottom(&row[1]) - row[0].pos.y) - (bottom(&own[0]) - own[0].pos.y); + assert!(drift.abs() <= 0.5, "at {size} pt, {c} ends {drift:.2} pt below the tab family's baseline"); + } + } } diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index cb419067e1..8e2d07ff5c 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -239,7 +239,7 @@ pub(crate) fn baseline_copies(defs: &FontDefinitions, name: &str, data: &FontDat let mut copies: Vec<(String, FontData, Vec)> = vec![]; for (family, stack) in &defs.families { let head = stack.first().and_then(|head| Some((head.as_str(), defs.font_data.get(head)?))); - let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, (*data.font).as_ref(), data.index)); + let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, data)); if let Some((_, _, families)) = copies.iter_mut().find(|(_, copy, _)| copy.tweak.y_offset_factor.to_bits() == shift.to_bits()) { families.push(family.clone()); continue; @@ -266,15 +266,19 @@ fn em_metrics(data: &[u8], index: u32) -> Option<(f32, f32)> { Some((ascent / upem, (ascent - descent + gap) / upem)) } -/// The `y_offset_factor` that puts the glyphs of the face at `index` of `face` on the baseline of -/// the row's first face, whose ascent, row height and offset in ems are `row`. egui draws a -/// fallback glyph's baseline at its face's ascent plus half the difference between the two row -/// heights, so a face with a taller ascent or descent sits off the baseline by the shift computed -/// here, in ems of the font size, limited to half an em either way. -fn baseline_shift(row: (f32, f32, f32), face: &[u8], index: u32) -> f32 { +/// The `y_offset_factor` that puts the glyphs of the fallback face `data` on the baseline of the +/// row's first face, whose ascent, row height and offset in ems are `row`. egui draws a fallback +/// glyph's baseline at its face's ascent plus half the difference between the two row heights, so a +/// face with a taller ascent or descent sits off the baseline by the shift computed here, in ems of +/// the font size, limited to half an em either way. egui scales the face's metrics and its +/// `y_offset_factor` by the face's own `FontTweak` scale, so both are measured at that scale. +fn baseline_shift(row: (f32, f32, f32), data: &FontData) -> f32 { let (row_ascent, row_height, row_offset) = row; - let shift = em_metrics(face, index).map_or(0.0, |(ascent, height)| row_ascent + row_offset - (ascent + 0.5 * (row_height - height))); - if shift.is_finite() { shift.clamp(-0.5, 0.5) } else { 0.0 } + let scale = data.tweak.scale; + let shift = em_metrics((*data.font).as_ref(), data.index) + .map_or(0.0, |(ascent, height)| row_ascent + row_offset - scale * ascent - 0.5 * (row_height - scale * height)); + let factor = if shift.is_finite() { shift.clamp(-0.5, 0.5) / scale } else { 0.0 }; + if factor.is_finite() { factor } else { 0.0 } } /// Call `f` with the text of `shape` and the shapes it holds. @@ -375,8 +379,10 @@ mod tests { fonts.finish(&ctx); frame(&ctx, &mut fonts, "日本語の文字 Layer 1"); if vectorcraft_text::CRAFT_FONTS.is_empty() { + // The condensed tab face is read from its own catalog, so a checkout can give it alone. + let condensed = vectorcraft_text::CONDENSED_UI_FONT.as_ref().map(crate::theme::craft_font_name); let names: Vec = ctx.fonts(|f| f.definitions().font_data.keys().cloned().collect()); - assert!(names.iter().all(|n| !n.starts_with("craft-fonts")), "{names:?}"); + assert!(names.iter().all(|n| !n.starts_with("craft-fonts") || Some(n) == condensed.as_ref()), "{names:?}"); } assert!(has_glyph(&ctx, 'L')); } diff --git a/crates/ui-egui/tests/install_fonts.rs b/crates/ui-egui/tests/install_fonts.rs index d7ebcaab27..56d49bc3bc 100644 --- a/crates/ui-egui/tests/install_fonts.rs +++ b/crates/ui-egui/tests/install_fonts.rs @@ -33,7 +33,8 @@ fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) { fn every_family_the_panels_draw_in_is_bound() { let ctx = context(); frame(&ctx, |ui| { - for font in [theme::semibold(12.0), theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { + let tab = theme::tab_title_font(ui, 12.0); + for font in [theme::semibold(12.0), tab, theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { ui.label(egui::RichText::new("Gaussian Blur").font(font)); } }); @@ -45,6 +46,17 @@ fn every_family_the_panels_draw_in_is_bound() { let installed: Vec<&str> = INTERFACE_FACES.into_iter().filter(|face| definitions.font_data.contains_key(*face)).collect(); let family = |family: FontFamily| definitions.families[&family].clone(); let named = |name: &str| family(FontFamily::Name(name.into())); + // The tab family is bound, headed by craft-fonts' condensed face and followed by the semibold + // faces, when the build has that face and both faces give an x-height to match. + let x_height = |name: &String| definitions.font_data.get(name).and_then(|d| vectorcraft_text::x_height((*d.font).as_ref(), d.index)); + let semibold_head = named(theme::FONT_UI_SEMIBOLD).first().and_then(x_height); + match vectorcraft_text::CONDENSED_UI_FONT.as_ref().filter(|f| vectorcraft_text::x_height(f.bytes, 0).is_some() && semibold_head.is_some()) { + None => assert!(!definitions.families.contains_key(&FontFamily::Name(theme::FONT_TAB.into()))), + Some(f) => { + assert_eq!(named(theme::FONT_TAB)[0], format!("craft-fonts {} {}", f.family, f.style)); + assert!(named(theme::FONT_TAB).len() > named(theme::FONT_UI_SEMIBOLD).len(), "the semibold faces follow the condensed one"); + } + } if cfg!(feature = "interface-fonts") { assert_eq!(installed, INTERFACE_FACES); assert_eq!(named(theme::FONT_UI)[0], "Inter"); diff --git a/docs/development.md b/docs/development.md index 66f925324e..950b996ed9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -178,8 +178,9 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the x-height of the interface's semibold face, so more tabs fit in the strip. Without - `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab - titles draw in the semibold face. + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), + `theme::FONT_TAB` is not bound and tab titles draw in the semibold family + (`theme::tab_title_font`). - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. @@ -205,7 +206,8 @@ font that has them to each of the families below (`ctx.add_font` with an `Insert family). The panels and dialogs draw in their own egui families (`theme::FONT_UI`, `FONT_UI_SEMIBOLD`, -`FONT_MONO`), and egui panics drawing text in a family no font is bound to. `VectorcraftApp::logic` +`FONT_MONO`, and `FONT_TAB` for document tab titles in builds with the condensed face), and egui +panics drawing text in a family no font is bound to. `VectorcraftApp::logic` binds them on its first frame; an embedder that draws the panels or dialogs without it calls `theme::install_fonts` once on its context, with or without `interface-fonts`. It replaces the context's font definitions, so the embedder's own fonts are added after it. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8b5a9f315a..b6fa3393c1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,7 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | -| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done; release builds pending | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`, `theme::tests::the_tab_family_keeps_the_semibold_x_height_and_baseline`; the release and FreeBSD workflows pin a craft-fonts commit without the face, so official builds draw tab titles in the semibold face until that pin moves past storytold/craft-fonts#72; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From add7c0f48bf5f4202e58a12c3e1dfe928008202b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:42:05 -0800 Subject: [PATCH 06/50] Toolbars: a toolbar made with New Toolbar holds menu command buttons A toolbar made with Window > Toolbars > New Toolbar held tools only. Its Add Tool... menu now ends in an Add Command submenu that searches every Command Palette result other than a tool (menu commands, plug-in commands, effects and panels); a pick adds a button after the tools, and Remove Command in the same menu lists the buttons by their full names and takes one off. - A button shows its command's label without the ellipsis, on up to two lines, and its full name and shortcut on hover. A click runs what the command's menu item runs, so a command whose item ends in an ellipsis opens its dialog; while the item is dimmed, the button is dimmed and a click runs nothing and the status line says why. - Each command is asked whether it can run once per app state, at most 12 in a frame, and again on a click or a key press. - The button's context menu has Move Up, Move Down and Remove from Toolbar. - The buttons are saved with the toolbar (`commands`, left out when empty, so older layouts load unchanged), and Manage Toolbars' copy keeps them. A command that is gone, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it comes back or is removed. - `toolbar.addCommand {command, toolbar, at?}` adds or moves a button, `toolbar.removeCommand {command, toolbar}` takes one off, and `window.toolbar.list` reports `commands`. `toolbar.reset` with `toolbar` clears them along with the tools. A UI command that fails without params, such as `toolbar.addTool`, is not listed and cannot be added. Not done: dragging a menu item or a Command Palette result onto a toolbar, an Add to Toolbar item in the palette, dragging command buttons to reorder or remove them, and command icons. Command buttons are VectorCraft's own. Docs: docs/control-protocol.md, docs/mcp.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 14 +- crates/ui-egui/src/custom_toolbars.rs | 363 ++++++++++++++++++++++- crates/ui-egui/src/edit_toolbar.rs | 6 +- crates/ui-egui/src/edit_toolbar/tests.rs | 240 ++++++++++++++- crates/ui-egui/src/menus/ui_commands.rs | 14 +- crates/ui-egui/src/palette.rs | 72 ++++- crates/ui-egui/src/palette/search.rs | 11 +- crates/ui-egui/src/shortcut_editor.rs | 10 + crates/ui-egui/src/state.rs | 5 + docs/control-protocol.md | 13 +- docs/mcp.md | 20 ++ docs/target-app-parity.md | 1 + 12 files changed, 748 insertions(+), 21 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..d3fce19fda 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -613,6 +613,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", ), + ( + "toolbar.addCommand", + "Toolbar: Add Command", + "", + "{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:`, `effect:` or `panel:`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands", + ), + ( + "toolbar.removeCommand", + "Toolbar: Remove Command", + "", + "{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands", + ), ( "toolbar.reset", "Toolbar: Reset", @@ -671,7 +683,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 2b70748c9c..72edd613ae 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -3,9 +3,12 @@ //! All Tools drawer beside it, and tools dragged from the drawer fill it (`edit_toolbar`, with the //! `toolbar` param of its commands). The + button above it opens Add Tool…, a menu of every tool //! where a click adds the tool at the end, and whose Remove Tool items take tools out: VectorCraft's -//! own way to fill a toolbar without a drag. Its title bar moves it, its × hides it and its double -//! arrow shows its tools in one column or two. Each toolbar is listed under Window › Toolbars, where its -//! item shows or hides it, and is kept with the workspace it was made in (`Workspace::toolbars`). +//! own way to fill a toolbar without a drag. The same menu's Add Command submenu searches the Command +//! Palette's results and adds a command button after the tools, which runs what the command's menu +//! item runs (`toolbar.addCommand`, `toolbar.removeCommand`); command buttons are VectorCraft's own. +//! Its title bar moves it, its × hides it and its double arrow shows its tools in one column or +//! two. Each toolbar is listed under Window › Toolbars, where its item shows or hides it, and is +//! kept with the workspace it was made in (`Workspace::toolbars`). //! Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames, copies and deletes them. //! //! A toolbar docks in a lane along the window's left or right edge (on the left, right of the Tools @@ -42,6 +45,8 @@ use crate::{VectorcraftApp, icons, widgets}; pub(crate) const MAX: usize = 64; /// The most characters a toolbar's name has. const MAX_NAME: usize = 200; +/// The most command buttons a toolbar holds. +const MAX_COMMANDS: usize = 200; /// Width of a toolbar of one column of tool buttons, inside its border. const WIDTH: f32 = 44.0; /// Width a second column of tool buttons adds. @@ -129,6 +134,7 @@ pub(crate) fn create(ui: &mut UiState, name: &str) -> Result { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], }); show_alone_after_tab(ui, name); Ok(name.to_string()) @@ -333,8 +339,10 @@ pub(crate) fn delete(ui: &mut UiState, ctx: Option<&egui::Context>, name: &str) /// Keep named toolbars, each name once whatever its case and at most [`MAX_NAME`] characters, of /// known tools, each once in its toolbar, at a position that is a number, with one strip per group -/// torn off them, each group's tool chosen last only when the group holds it, and the docked ones -/// numbered 0, 1, 2… at each edge (a hand-edited preferences file or workspace). +/// torn off them, each group's tool chosen last only when the group holds it, at most +/// [`MAX_COMMANDS`] command buttons, each command once and none for a tool, and the docked ones +/// numbered 0, 1, 2… at each edge (a hand-edited preferences file or workspace). A command that is +/// not known now stays: it may be an uninstalled plug-in's. pub(crate) fn sanitize(bars: &mut Vec) { let mut names = std::collections::BTreeSet::new(); bars.retain_mut(|b| { @@ -344,6 +352,9 @@ pub(crate) fn sanitize(bars: &mut Vec) { s.retain(|id| tool_info(id).is_some() && seen.insert(id.clone())); } b.slots.retain(|s| !s.is_empty()); + let mut commands = std::collections::BTreeSet::new(); + b.commands.retain(|id| !id.trim().is_empty() && !id.starts_with("tool:") && commands.insert(id.clone())); + b.commands.truncate(MAX_COMMANDS); let slots = &b.slots; b.slot_tool.retain(|first, id| slots.iter().any(|s| s.first() == Some(first) && s.contains(id))); crate::state::FloatingFlyout::sanitize(&mut b.floating); @@ -371,6 +382,41 @@ pub(crate) fn keep_strips(bar: &mut CustomToolbar) { }); } +/// The toolbar the `toolbar` param of `toolbar.addCommand` and `toolbar.removeCommand` names, +/// which must be one made with New Toolbar: the Tools panel's toolbar holds tools only. +fn command_target(ui: &UiState, p: &Value) -> Result { + let name = target(ui, p)?.ok_or("toolbar (a toolbar's name) is required: only toolbars made with New Toolbar hold commands")?; + index(ui, &name) +} + +/// Put the command button for the Command Palette result `id` in `bar`, moving it if it is there +/// already: at place `at` among its command buttons (0 = the first; none: at the end). A command +/// that is gone (an uninstalled plug-in's) can still move, but not be added. A tool, and a UI +/// command that fails without params, can't be added. +pub(crate) fn add_command(bar: &mut CustomToolbar, id: &str, at: Option) -> Result<(), String> { + if id.starts_with("tool:") { + return Err(format!("`{id}` is a tool: toolbar.addTool adds tools")); + } + if crate::shortcut_editor::ui_command_needs_params(id) { + return Err(format!("`{id}` needs params, which a click on a button does not give")); + } + if !bar.commands.iter().any(|c| c == id) && !crate::palette::is_command(id) { + return Err(format!("unknown command `{id}`")); + } + let mut list: Vec = bar.commands.iter().filter(|c| *c != id).cloned().collect(); + if list.len() >= MAX_COMMANDS { + return Err(format!("a toolbar holds at most {MAX_COMMANDS} commands")); + } + let at = match at { + None => list.len(), + Some(n) if n <= list.len() => n, + Some(n) => return Err(format!("`at` must be a whole number from 0 to {} (got {n})", list.len())), + }; + list.insert(at, id.to_string()); + bar.commands = list; + Ok(()) +} + /// The commands of the toolbars made with New Toolbar; `None` for other ids. pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { Some(match id { @@ -464,13 +510,30 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| format!("`at` must be 0 or a larger whole number (got {v})"))?), + }; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + add_command(bar, id, at).map(|_| json!(bar.commands)) + })(), + "toolbar.removeCommand" => (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + bar.commands.retain(|c| c != id); + Ok(json!(bar.commands)) + })(), "window.toolbar.list" => Ok(json!( app.ui .custom_toolbars .iter() .map(|b| { let side = if b.dock_right { "right" } else { "left" }; - json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots, "floating": b.dock.is_none(), "side": side, "order": b.dock}) + json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots, "commands": b.commands, "floating": b.dock.is_none(), "side": side, "order": b.dock}) }) .collect::>() )), @@ -730,6 +793,130 @@ enum Action { Dock(String, bool), /// Float Toolbar in the title bar's context menu. Float(String), + /// A click on a command button: the Command Palette result it runs. + RunCommand(String), + /// A command picked in the Add Command submenu of Add Tool…'s menu, added at the end of the + /// toolbar named. + AddCommand(String, String), + /// A command button moved to another place among the toolbar's command buttons (Move Up and + /// Move Down in its context menu). + MoveCommand(String, String, usize), + /// A command taken out of the toolbar named: Remove Command in Add Tool…'s menu, or Remove + /// from Toolbar in the button's context menu. + RemoveCommand(String, String), +} + +/// What a command button shows, worked out before its toolbar is drawn. +#[derive(Clone, Debug)] +struct CommandLook { + /// The Command Palette result it runs. + id: String, + /// Its label, name and shortcut; none while the palette lists no result with its id (an + /// uninstalled plug-in's command). + text: Option, + /// Why it can't run now, in English; none while it can. + why: Option, +} + +impl CommandLook { + /// The label the button shows: the command's, or its id while the command is gone. + fn label(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.label.as_str()) + } + + /// Its full name, with the menu path that tells it apart from a command of the same label, or + /// its id while the command is gone. + fn name(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.name.as_str()) + } +} + +/// The most commands the toolbars ask in one frame whether they can run. An engine check can take +/// tens of milliseconds on a large selection, and during a drag the state changes on every frame. +const ASKS_PER_FRAME: usize = 12; + +/// The command buttons' [`crate::palette::unavailable`] answers for the state `key` they were read +/// in ([`crate::palette::availability_key`]): each command is asked once per state, and at most +/// [`ASKS_PER_FRAME`] are asked in a frame. A command not asked yet in this state shows its answer +/// from an earlier state (`stale`), or is dimmed when it has none, and is asked in a later frame. +#[derive(Clone, Default)] +struct Known { + key: u64, + why: std::collections::HashMap>, + stale: std::collections::HashMap>, + /// How many more commands this frame may ask. + budget: usize, + /// Is a command still waiting to be asked in this state? + pending: bool, +} + +impl Known { + /// The answers for the state now. The state leaves out a panel shown and a tool chosen, so a + /// frame with a pointer button release or a key press asks every command again, as the Command + /// Palette asks its results again on a click. + fn load(app: &VectorcraftApp, ctx: &egui::Context) -> Known { + let key = crate::palette::availability_key(app); + let mut known = ctx.data(|d| d.get_temp::(known_id())).unwrap_or_default(); + let again = ctx.input(|i| { + i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: true, .. })) + }); + if known.key != key || again { + let old = std::mem::take(&mut known.why); + known.stale.extend(old); + known.key = key; + } + known.budget = ASKS_PER_FRAME; + known.pending = false; + known + } + + /// Why the result `id`, shown as `name`, can't run now, in English, or `None` while it can. + fn why(&mut self, app: &VectorcraftApp, id: &str, name: &str) -> Option { + if let Some(why) = self.why.get(id) { + return why.clone(); + } + if self.budget == 0 { + // Dimmed until it is asked, unless an earlier state's answer is known. + self.pending = true; + return self.stale.get(id).cloned().unwrap_or_else(|| Some(format!("checking whether `{id}` can run"))); + } + self.budget -= 1; + let why = crate::palette::unavailable(app, id, name); + self.stale.remove(id); + self.why.insert(id.to_string(), why.clone()); + why + } +} + +fn known_id() -> egui::Id { + egui::Id::unique("custom-toolbar-command-availability") +} + +/// How many commands have their answer for the state now, and is one still waiting to be asked? +#[cfg(test)] +pub(crate) fn asked(ctx: &egui::Context) -> (usize, bool) { + ctx.data(|d| d.get_temp::(known_id())).map_or((0, false), |k| (k.why.len(), k.pending)) +} + +/// How each command button of `bar` looks now, its answers kept in `known` (read for the current +/// state the first time a toolbar with command buttons is drawn in a frame). +fn command_looks(app: &VectorcraftApp, ctx: &egui::Context, bar: &CustomToolbar, known: &mut Option) -> Vec { + if bar.commands.is_empty() { + return vec![]; + } + let known = known.get_or_insert_with(|| Known::load(app, ctx)); + let native = app.services.native_menu.is_some(); + bar.commands + .iter() + .map(|id| { + let text = crate::palette::is_command(id).then(|| crate::palette::button_text(ctx, native, id)).flatten(); + let why = match &text { + None => Some(format!("command `{id}` is not available right now")), + Some(t) => known.why(app, id, &t.name), + }; + CommandLook { id: id.clone(), text, why } + }) + .collect() } /// The lane along the window's right edge (true) or left edge where docked toolbars show, as last @@ -1001,9 +1188,14 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Where the drawer opens (the toolbar's bounds and its ••• button): beside the toolbar it // edits, or beside the one whose ••• button was just clicked. let (mut anchor, mut clicked_anchor) = (None, None); + let mut known = None; + let native = app.services.native_menu.is_some(); for k in 0..app.ui.custom_toolbars.len() { let Some(bar) = app.ui.custom_toolbars.get(k).filter(|b| b.shown).cloned() else { continue }; let id = area_id(&bar.name); + let looks = command_looks(app, ctx, &bar, &mut known); + // Add Tool…'s menu lists them under Remove Command and searches the commands it can add. + ctx.data_mut(|d| d.insert_temp(add_menu_id(&bar.name).with("commands"), (native, looks.clone()))); let cols = if bar.double { 2 } else { 1 }; let width = WIDTH + BUTTON * (cols - 1) as f32; // Docked: where its lane puts it, its tools scrolling in its share of the lane, or only its @@ -1137,6 +1329,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); } + // The command buttons, after its tools. + command_buttons(ui, &t, width - 6.0, middle, &bar.name, &looks, &mut actions); ui.add_space(4.0); // Add Tool…: a menu of the tools, which adds one to this toolbar or takes one out. let add = ui.vertical_centered(|ui| widgets::icon_button(ui, "plus", "Add Tool…", false, 26.0)).inner; @@ -1182,6 +1376,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } } } + if let Some(known) = known { + // The commands not asked yet are asked in the next frames. + if known.pending { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp(known_id(), known)); + } if let Some((bounds, button)) = clicked_anchor.or(anchor) { ctx.data_mut(|d| { d.insert_temp(crate::edit_toolbar::toolbar_id(), bounds); @@ -1245,6 +1446,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { app.status(e); } } + a @ (Action::RunCommand(_) | Action::AddCommand(..) | Action::MoveCommand(..) | Action::RemoveCommand(..)) => command_action(app, a), } } end_move(); @@ -1369,6 +1571,143 @@ pub(crate) fn shown_tool(bar: &CustomToolbar, active: &'static str, tools: &[&'s Some(bar.slot_tool.get(first).and_then(|id| tools.iter().copied().find(|t| t == id)).unwrap_or(first)) } +/// What a press on a command button, its context menu or Add Tool…'s command rows did. +fn command_action(app: &mut VectorcraftApp, a: Action) { + let done = match a { + // It runs what the command's menu item runs, as a pick in the Command Palette does: a + // command whose item ends in … opens its dialog, and a dimmed one runs nothing and the + // status line says why. + Action::RunCommand(id) if crate::palette::is_command(&id) => { + crate::palette::run_pick(app, &id); + Ok(Value::Null) + } + Action::RunCommand(id) => Err(format!("command `{id}` is not available right now")), + Action::AddCommand(name, id) => app.run("toolbar.addCommand", json!({ "command": id, "toolbar": name })), + Action::MoveCommand(name, id, at) => app.run("toolbar.addCommand", json!({ "command": id, "toolbar": name, "at": at })), + Action::RemoveCommand(name, id) => app.run("toolbar.removeCommand", json!({ "command": id, "toolbar": name })), + _ => Ok(Value::Null), + }; + if let Err(e) = done { + app.status(e); + } +} + +/// The command buttons of the toolbar named `bar` (`looks`), one per row across its `width`, with +/// `middle` the toolbar's middle: [`command_button`]. +fn command_buttons(ui: &mut egui::Ui, t: &Tokens, width: f32, middle: f32, bar: &str, looks: &[CommandLook], actions: &mut Vec) { + if looks.is_empty() { + return; + } + ui.add_space(4.0); + for (i, look) in looks.iter().enumerate() { + ui.horizontal(|ui| { + ui.add_space((middle - width / 2.0 - ui.cursor().min.x).max(0.0)); + command_button(ui, t, width, bar, look, (i, looks.len()), actions); + }); + } +} + +/// Height of a command button. +const COMMAND_HEIGHT: f32 = 30.0; + +/// A command button `width` points wide on the toolbar named `bar`: the command's label, on up to +/// two lines and cut short with … when it is longer; its name and shortcut on hover. A click runs +/// the command. While the command can't run now, the button is dimmed and its hover says why. Its +/// context menu moves it up or down among the toolbar's command buttons (`place`: its place and +/// how many there are) and takes it out. +fn command_button(ui: &mut egui::Ui, t: &Tokens, width: f32, bar: &str, look: &CommandLook, place: (usize, usize), actions: &mut Vec) { + let (rect, resp) = ui.allocate_exact_size(vec2(width, COMMAND_HEIGHT), Sense::click()); + let on = look.why.is_none(); + if resp.hovered() || resp.has_focus() { + ui.painter().rect_filled(rect.shrink(1.0), CornerRadius::same(4), t.hover); + } + let color = if on { t.text } else { t.text_disabled }; + let font = egui::FontId::proportional(10.0); + let mut job = egui::text::LayoutJob::simple(look.label().to_owned(), font, color, rect.width() - 4.0); + job.wrap = egui::text::TextWrapping { max_width: rect.width() - 4.0, max_rows: 2, break_anywhere: false, overflow_character: Some('…') }; + job.halign = egui::Align::Center; + let galley = ui.painter().layout_job(job); + ui.painter().galley(pos2(rect.center().x, rect.center().y - galley.size().y / 2.0), galley, color); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, on, look.label())); + let mut tip = look.text.as_ref().map_or(look.id.clone(), |t| t.name.clone()); + if let Some(shortcut) = look.text.as_ref().map(|t| t.shortcut.as_str()).filter(|s| !s.is_empty()) { + tip = format!("{tip} {shortcut}"); + } + if let Some(why) = &look.why { + tip = format!("{tip}\n{}", crate::i18n::msg(why)); + } + let resp = resp.on_hover_text(tip); + if resp.clicked() { + actions.push(Action::RunCommand(look.id.clone())); + } + let (i, n) = place; + resp.context_menu(|ui| { + if widgets::menu_item(ui, tl!("Move Up"), i > 0, false) { + actions.push(Action::MoveCommand(bar.to_string(), look.id.clone(), i.saturating_sub(1))); + ui.close(); + } + if widgets::menu_item(ui, tl!("Move Down"), i + 1 < n, false) { + actions.push(Action::MoveCommand(bar.to_string(), look.id.clone(), i + 1)); + ui.close(); + } + if widgets::menu_item(ui, tl!("Remove from Toolbar"), true, false) { + actions.push(Action::RemoveCommand(bar.to_string(), look.id.clone())); + ui.close(); + } + }); +} + +/// The most commands Add Tool…'s menu lists for a search. +const COMMAND_RESULTS: usize = 30; + +/// Add Tool…'s command rows, for the toolbar named `bar`: under Remove Command the toolbar's +/// command buttons by their full names, which a click takes out, then the Add Command submenu +/// ([`command_search`]). +fn command_section(ui: &mut egui::Ui, t: &Tokens, bar: &str, actions: &mut Vec) { + let Some((native, looks)) = ui.data(|d| d.get_temp::<(bool, Vec)>(add_menu_id(bar).with("commands"))) else { return }; + ui.separator(); + if !looks.is_empty() { + ui.label(egui::RichText::new(crate::i18n::colon(tl!("Remove Command"))).size(12.0).color(t.text_strong)); + for look in &looks { + if widgets::menu_item_name(ui, look.name(), true, false) { + actions.push(Action::RemoveCommand(bar.to_string(), look.id.clone())); + } + } + ui.separator(); + } + // A click in the search field leaves the submenu open; a pick closes the whole menu. + let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + egui::containers::menu::SubMenuButton::new(tl!("Add Command")).config(config).ui(ui, |ui| command_search(ui, t, bar, native, &looks, actions)); +} + +/// The Add Command submenu: a search field over the Command Palette's results other than tools +/// (`native`: with the native menu bar), whose first [`COMMAND_RESULTS`] matches a click adds at +/// the end of the toolbar named `bar` (dimmed: one of its command buttons, `looks`, already). +fn command_search(ui: &mut egui::Ui, t: &Tokens, bar: &str, native: bool, looks: &[CommandLook], actions: &mut Vec) { + widgets::menu_min_width(ui, 260.0); + let q = widgets::search_field(ui, command_query_id(bar), tl!("Search Commands")); + if q.trim().is_empty() { + ui.label(egui::RichText::new(tl!("Type to find a command")).color(t.text_dim)); + return; + } + let found = crate::palette::command_matches(ui.ctx(), native, &q, COMMAND_RESULTS); + if found.is_empty() { + ui.label(egui::RichText::new(tl!("No matching commands")).color(t.text_dim)); + } + for (id, name) in found { + let held = looks.iter().any(|l| l.id == id); + if widgets::menu_item_name(ui, &name, !held, false) { + actions.push(Action::AddCommand(bar.to_string(), id)); + ui.close(); + } + } +} + +/// Where Add Tool…'s menu on the toolbar named `name` keeps the text of its command search field. +pub(crate) fn command_query_id(name: &str) -> egui::Id { + add_menu_id(name).with("query") +} + /// The area of Add Tool…'s menu on the toolbar named `name`. pub(crate) fn add_menu_id(name: &str) -> egui::Id { egui::Id::unique(("custom-toolbar-add", key(name))) @@ -1376,8 +1715,9 @@ pub(crate) fn add_menu_id(name: &str) -> egui::Id { /// Add Tool…'s menu, which the + button on the toolbar `bar` opens: under Remove Tool the tools in /// the toolbar, where a click takes one out; then every tool under the All Tools drawer's headings, -/// where a click adds one at the end (dimmed: in the toolbar already). It scrolls past the window's -/// bottom bars, as other long menus do ([`widgets::menu_scroll`]). +/// where a click adds one at the end (dimmed: in the toolbar already); then its command rows +/// ([`command_section`]). It scrolls past the window's bottom bars, as other long menus do +/// ([`widgets::menu_scroll`]). fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: &mut Vec) { egui::Popup::menu(button).id(add_menu_id(&bar.name)).show(|ui| { widgets::menu_min_width(ui, 200.0); @@ -1401,6 +1741,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & } } } + command_section(ui, t, &bar.name, actions); }); }); } @@ -1480,7 +1821,7 @@ mod tests { let names: Vec<&str> = toolbars_menu(&app).into_iter().filter(|(_, id, _)| *id == "window.toolbar.custom").map(|(l, ..)| l).collect(); assert_eq!(names, ["Mine", "Toolbar 1"]); let list = app.run("window.toolbar.list", json!({})).unwrap(); - let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "floating": true, "side": "left", "order": null}); + let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "commands": [], "floating": true, "side": "left", "order": null}); assert_eq!(list, json!([blank("Mine"), blank("Toolbar 1")])); } @@ -1579,7 +1920,10 @@ mod tests { assert!(app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Nope"})).is_err()); let r = app.run("toolbar.removeTool", json!({"tool": "artboard", "toolbar": "Mine"})).unwrap(); assert_eq!(r, json!([["pen", "curvature"]])); + // Its command buttons go with it. + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); let mine = find(&app.ui, "Mine").cloned().unwrap(); + assert_eq!(mine.commands, ["object.group"]); // Another workspace has its own toolbars (none); coming back brings Mine back. app.run("window.workspace", json!({"name": "Essentials"})).unwrap(); assert!(app.ui.custom_toolbars.is_empty()); @@ -2253,6 +2597,7 @@ mod tests { .iter() .map(|id| crate::state::FloatingFlyout { tools: vec![id.to_string(), "curvature".into()], pos: [0.0, 0.0] }) .collect(), + commands: vec![], }; let long = "x".repeat(MAX_NAME + 1); let mut bars = vec![ diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 5c1fa8f6ed..9d9d38b09d 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -304,7 +304,11 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { if let Some(name) = crate::custom_toolbars::target(&app.ui, p)? { - // A toolbar made with New Toolbar goes back to blank, as it was made. + // A toolbar made with New Toolbar goes back to blank, as it was made, without its + // command buttons too. + if let Some(bar) = crate::custom_toolbars::find_mut(&mut app.ui, &name) { + bar.commands.clear(); + } return edit_custom(app, &name, |cats| { cats.clear(); Ok(()) diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 0973a752b2..5184fdbf36 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -668,7 +668,7 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { let list = app.run("window.toolbar.list", json!({})).unwrap(); assert_eq!( list, - json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "floating": true, "side": "left", "order": null}]) + json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "commands": [], "floating": true, "side": "left", "order": null}]) ); // A second tool goes after the first. let shown = open(&mut app, 19.0); @@ -891,3 +891,241 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert!(slot_of(&app, tool).is_some(), "{tool}"); } } + +/// The command buttons of the toolbar made with New Toolbar called Mine. +fn mine_commands(app: &VectorcraftApp) -> Vec { + crate::custom_toolbars::find(&app.ui, "Mine").unwrap().commands.clone() +} + +/// `toolbar.addCommand` puts command buttons on a toolbar made with New Toolbar and moves them, +/// `toolbar.removeCommand` takes them off, and a bad call changes nothing. Manage Toolbars' copy +/// keeps them, and `toolbar.reset` takes them off with the tools. +#[test] +fn command_buttons_are_added_moved_and_removed_by_their_commands() { + let mut app = app(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let added = app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + assert_eq!(added, json!(["object.group"])); + app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine", "at": 0})).unwrap(); + assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "moved, not added twice"); + for (p, why) in [ + (json!({"command": "no.such", "toolbar": "Mine"}), "an unknown command"), + (json!({"command": "tool:pen", "toolbar": "Mine"}), "a tool"), + (json!({"command": "object.group", "toolbar": "Mine", "at": 2}), "a place past the end"), + (json!({"command": "object.group", "toolbar": "Mine", "at": -1}), "a negative place"), + (json!({"command": "toolbar.addTool", "toolbar": "Mine"}), "a command that needs params"), + (json!({"command": "object.group"}), "no toolbar"), + (json!({"toolbar": "Mine"}), "no command"), + ] { + assert!(app.run("toolbar.addCommand", p.clone()).is_err(), "{why}: {p}"); + assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "{why} changes nothing"); + } + assert!(app.run("toolbar.removeCommand", json!({"command": "object.group"})).is_err(), "no toolbar"); + let list = app.run("window.toolbar.list", json!({})).unwrap(); + assert_eq!(list[0]["commands"], json!(["object.path.cleanUp", "object.group"])); + let copy = app.run("window.toolbar.duplicate", json!({"name": "Mine"})).unwrap(); + let copy = copy["toolbar"].as_str().unwrap().to_string(); + assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands, mine_commands(&app), "the copy has them"); + let left = app.run("toolbar.removeCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + assert_eq!(left, json!(["object.path.cleanUp"])); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.reset", json!({"toolbar": "Mine"})).unwrap(); + assert!(mine_commands(&app).is_empty(), "Reset makes the toolbar blank"); + assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands.len(), 2, "the copy keeps its own"); +} + +/// The text painted inside the toolbar called Mine that starts with `text`: a point inside it and +/// its color. +fn on_mine(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, text: &str) -> Option<(Pos2, Color32)> { + let shown = frame(app, ctx, time, vec![]); + let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine")))?; + shown.into_iter().find(|(s, p, _)| s.starts_with(text) && bar.contains(*p)).map(|(_, p, c)| (p, c)) +} + +/// A command button shows its command's label, without the ellipsis, and a click runs what the +/// command's menu item runs. While that item would be dimmed, the button is dimmed too and a click +/// runs nothing. A command whose item ends in … opens its dialog. +#[test] +fn a_command_button_runs_its_command_and_is_dimmed_while_it_cannot() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let t = Tokens::get(&ctx); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + for c in ["object.group", "object.path.cleanUp"] { + app.run("toolbar.addCommand", json!({"command": c, "toolbar": "Mine"})).unwrap(); + } + let undo = |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.history.undo.len()); + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let (at, color) = on_mine(&mut app, &ctx, 0.1, "Group").expect("the button shows Group"); + assert_eq!(color, t.text_disabled, "dimmed with nothing selected"); + let before = undo(&app); + app.ui.status.clear(); + click(&mut app, &ctx, 1.0, at); + assert_eq!(undo(&app), before, "a dimmed button runs nothing"); + assert!(!app.ui.status.is_empty(), "the status line says why"); + app.run("select.all", json!({})).unwrap(); + let (at, color) = on_mine(&mut app, &ctx, 2.0, "Group").expect("the button shows Group"); + assert_eq!(color, t.text, "not dimmed with objects selected"); + click(&mut app, &ctx, 3.0, at); + assert!(undo(&app) > before, "Group ran"); + let (at, _) = on_mine(&mut app, &ctx, 4.0, "Clean Up").expect("the button shows Clean Up"); + assert!(on_mine(&mut app, &ctx, 4.1, "Clean Up…").is_none(), "without the ellipsis"); + assert!(app.ui.dialog.is_none()); + click(&mut app, &ctx, 5.0, at); + assert!(app.ui.dialog.is_some(), "Clean Up… opens its dialog"); +} + +/// Command buttons are kept with the preferences, and a toolbar saved before toolbars held commands +/// loads with none. A command that is gone, such as an uninstalled plug-in's, stays: its button is +/// dimmed and shows its id, a click runs nothing and says so, and Remove Command takes it off. +#[test] +fn a_missing_command_stays_dimmed_until_it_is_removed() { + let mut app = app(); + let ctx = ctx(); + let t = Tokens::get(&ctx); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push("plugin:x".into()); + let kept = app.ui.custom_toolbars.clone(); + let prefs: crate::state::UiState = serde_json::from_slice(&serde_json::to_vec(&app.ui).unwrap()).unwrap(); + assert_eq!(prefs.sanitized().custom_toolbars, kept, "kept with the preferences, the missing command too"); + let mut old = serde_json::to_value(&kept[0]).unwrap(); + old.as_object_mut().unwrap().remove("commands"); + let old: crate::state::CustomToolbar = serde_json::from_value(old).unwrap(); + assert!(old.commands.is_empty(), "an older toolbar loads without commands"); + frame(&mut app, &ctx, 0.0, vec![]); + let (at, color) = on_mine(&mut app, &ctx, 0.1, "plug").expect("the button shows the command's id"); + assert_eq!(color, t.text_disabled); + app.ui.status.clear(); + click(&mut app, &ctx, 1.0, at); + assert!(app.ui.status.contains("plugin:x"), "the status line names it: {}", app.ui.status); + let left = app.run("toolbar.removeCommand", json!({"command": "plugin:x", "toolbar": "Mine"})).unwrap(); + assert_eq!(left, json!(["object.group"])); +} + +/// Add Tool…'s menu lists a toolbar's command buttons under Remove Command, where a click takes one +/// off, and its Add Command submenu searches the menu commands: a click on a match adds its button +/// at the end of the toolbar. +#[test] +fn the_add_tool_menu_adds_and_removes_commands() { + let mut app = app(); + let ctx = ctx(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + // The + button, which moves down as command buttons are added above it. + let plus = || { + let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine"))).expect("the toolbar is shown"); + crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().find(|r| bar.contains(r.center())).expect("the + button") + }; + // The menu's text named `name`, opened with a click on the + button unless it is open. + let menu_text = |app: &mut VectorcraftApp, time: f64, name: &str| { + let mut shown = frame(app, &ctx, time, vec![]); + if !shown.iter().any(|(s, ..)| s == "Select:") { + click(app, &ctx, time + 0.2, plus().center()); + frame(app, &ctx, time + 0.5, vec![]); + shown = frame(app, &ctx, time + 0.6, vec![]); + } + let menu = ctx.memory(|m| m.area_rect(crate::custom_toolbars::add_menu_id("Mine")))?; + shown.into_iter().find(|(s, p, _)| s.trim() == name && menu.contains(*p)).map(|(_, p, _)| p) + }; + assert!(menu_text(&mut app, 1.0, "Remove Command:").is_some(), "a heading over the toolbar's commands"); + // The Add Command submenu opens under the pointer and searches as text is typed. + let row = menu_text(&mut app, 2.0, "Add Command").expect("the Add Command row"); + frame(&mut app, &ctx, 3.0, vec![Event::PointerMoved(row)]); + frame(&mut app, &ctx, 3.5, vec![Event::PointerMoved(row)]); + let field = crate::custom_toolbars::command_query_id("Mine").with("edit"); + ctx.memory_mut(|m| m.request_focus(field)); + frame(&mut app, &ctx, 4.0, vec![]); + frame(&mut app, &ctx, 4.1, vec![Event::Text("clean up".into())]); + frame(&mut app, &ctx, 4.2, vec![]); + let shown = frame(&mut app, &ctx, 4.3, vec![]); + let at = shown.iter().find(|(s, ..)| s.trim().ends_with("Clean Up…")).map(|(_, p, _)| *p).expect("Clean Up… is found"); + click(&mut app, &ctx, 5.0, at); + assert_eq!(mine_commands(&app), ["object.group", "object.path.cleanUp"], "added at the end"); + let pen = crate::palette::command_matches(&ctx, false, "pen", 30); + assert!(!pen.is_empty() && pen.iter().all(|(id, _)| !id.starts_with("tool:")), "tools are not listed among the commands: {pen:?}"); + let toolbar = crate::palette::command_matches(&ctx, false, "toolbar add", 30); + assert!(toolbar.iter().all(|(id, _)| id != "toolbar.addTool" && id != "toolbar.addCommand"), "commands that need params: {toolbar:?}"); + // Under Remove Command, Group is listed by its full name, and a click takes it off. + let name = crate::palette::button_text(&ctx, false, "object.group").expect("Group's result").name; + let group = menu_text(&mut app, 10.0, &name).unwrap_or_else(|| panic!("{name} under Remove Command")); + click(&mut app, &ctx, 11.0, group); + assert_eq!(mine_commands(&app), ["object.path.cleanUp"]); +} + +/// A button for a panel shows the panel, as the panel's Command Palette result does. +#[test] +fn a_panel_button_shows_its_panel() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let panel = crate::state::all_panels() + .map(|(id, _)| id) + .find(|id| !crate::panel_docking::visible(&app.ui, id) && crate::palette::is_command(&format!("panel:{id}"))) + .expect("a hidden panel"); + let id = format!("panel:{panel}"); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let label = crate::palette::button_text(&ctx, false, &id).expect("the panel's result").label; + let start: String = label.chars().take(3).collect(); + let (at, _) = on_mine(&mut app, &ctx, 0.1, &start).unwrap_or_else(|| panic!("the button shows {label}")); + click(&mut app, &ctx, 1.0, at); + frame(&mut app, &ctx, 1.5, vec![]); + assert!(crate::panel_docking::visible(&app.ui, panel), "{panel} is shown"); +} + +/// A button for a plug-in's command that is not installed is dimmed and shows the command's id; +/// once the plug-in is installed it shows the plug-in's name and can run, and when the plug-in is +/// removed again it is dimmed again. +#[test] +fn a_plugin_command_button_works_again_when_the_plugin_returns() { + use vectorcraft_plugins::wat as tpl; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let t = Tokens::get(&ctx); + // A name no other test gives a plug-in. + let filter = "test.UI.toolbar_command-probe"; + let id = format!("plugin:{filter}"); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push(id.clone()); + app.run("select.all", json!({})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let gone = on_mine(&mut app, &ctx, 0.1, "plugin:").map(|(_, c)| c); + let manifest = format!(r#"{{"id":"{filter}","name":"Toolbar Probe","version":"1","kind":"filter","params":{{}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + frame(&mut app, &ctx, 1.0, vec![]); + let back = on_mine(&mut app, &ctx, 1.1, "Toolbar").map(|(_, c)| c); + let added = app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine", "at": 0})); + vectorcraft_plugins::registry::remove(filter); + frame(&mut app, &ctx, 2.0, vec![]); + let gone_again = on_mine(&mut app, &ctx, 2.1, "plugin:").map(|(_, c)| c); + assert_eq!(gone, Some(t.text_disabled), "dimmed, with its id, while it is not installed"); + assert_eq!(back, Some(t.text), "its name, and it can run, once it is installed"); + assert!(added.is_ok(), "an installed plug-in's command can be added: {added:?}"); + assert_eq!(gone_again, Some(t.text_disabled), "dimmed again once it is removed"); +} + +/// The toolbars ask only a few command buttons in a frame whether they can run, and the others in +/// the next frames. +#[test] +fn command_buttons_ask_whether_they_can_run_a_few_at_a_time() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let ids: Vec = crate::palette::command_matches(&ctx, false, "object", 40).into_iter().map(|(id, _)| id).take(20).collect(); + assert_eq!(ids.len(), 20); + for id in &ids { + app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap(); + } + frame(&mut app, &ctx, 0.0, vec![]); + let (first, waiting) = crate::custom_toolbars::asked(&ctx); + assert!(first < ids.len() && waiting, "{first} asked in the first frame"); + for k in 1..5 { + frame(&mut app, &ctx, f64::from(k), vec![]); + } + assert_eq!(crate::custom_toolbars::asked(&ctx), (ids.len(), false), "every button was asked in the next frames"); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..cd7cb481cc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -614,6 +614,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", ), + ( + "toolbar.addCommand", + "Toolbar: Add Command", + "", + "{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:`, `effect:` or `panel:`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands", + ), + ( + "toolbar.removeCommand", + "Toolbar: Remove Command", + "", + "{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands", + ), ( "toolbar.reset", "Toolbar: Reset", @@ -672,7 +684,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..b103caef50 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -327,6 +327,8 @@ pub(crate) struct Catalog { list: Vec, index: search::Index, ranked: std::sync::Mutex>, + /// Where each id is in `list`. + by_id: std::collections::HashMap, } impl std::ops::Deref for Catalog { @@ -375,7 +377,69 @@ fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog { // A group's row in the `search` context gives its words in `lang`; a plain row is not read. let search_row = |key: &str| crate::i18n::tr_ctx_row(lang, words::CONTEXT, key).map(str::to_string); let index = search::Index::build(&list, &shown_homes, ¶ms_texts(&list), search_row); - Catalog { list, index, ranked: std::sync::Mutex::new(None) } + let by_id = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + Catalog { list, index, ranked: std::sync::Mutex::new(None), by_id } +} + +/// What a command button on a toolbar made with New Toolbar shows for the result `id` +/// ([`button_text`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ButtonText { + /// The result's label in the interface language, without the menu path in front of it and + /// without a closing ellipsis. + pub label: String, + /// The result's full name in the interface language, as the palette lists it. + pub name: String, + /// The shortcut as the menus show it, or empty. + pub shortcut: String, +} + +/// The label and shortcut of the palette result `id` in the interface language, from the entries +/// built once per language, plug-in set and shortcut set (`native`: with the native menu bar); none +/// when the palette lists no result with that id now (an uninstalled plug-in's command). +pub(crate) fn button_text(ctx: &egui::Context, native: bool, id: &str) -> Option { + let entries = entries_in(ctx, crate::i18n::current(), native); + let e = entries.by_id.get(id).and_then(|&i| entries.list.get(i))?; + let label = label_of(e).trim_end(); + let label = label.strip_suffix('…').or_else(|| label.strip_suffix("...")).unwrap_or(label).trim_end(); + Some(ButtonText { label: label.to_string(), name: e.shown.clone(), shortcut: menus::shown_shortcut(&e.shortcut) }) +} + +/// The results a toolbar made with New Toolbar can hold as command buttons that the query `q` +/// matches, best first, at most `most`: the results [`is_command`] allows. Each is its id and its +/// name in the interface language (`native`: as [`button_text`]). +pub(crate) fn command_matches(ctx: &egui::Context, native: bool, q: &str, most: usize) -> Vec<(String, String)> { + let entries = entries_in(ctx, crate::i18n::current(), native); + matching(&entries, q, &[], &CommandUses::default()) + .into_iter() + .filter(|e| is_command(&e.id)) + .take(most) + .map(|e| (e.id.clone(), e.shown.clone())) + .collect() +} + +/// Can a toolbar made with New Toolbar hold the result `id` as a command button now: is it a +/// palette result other than a tool, and not a UI command that fails without params a click does +/// not give ([`crate::shortcut_editor::ui_command_needs_params`]: `toolbar.addTool` needs a +/// `tool`)? The ids are listed again when the plug-ins or the shortcuts change, not on every call. +pub(crate) fn is_command(id: &str) -> bool { + type Ids = ((u64, u64), Arc>); + static IDS: std::sync::Mutex> = std::sync::Mutex::new(None); + if id.starts_with("tool:") { + return false; + } + let key = (menus::plugin_revision(), crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed)); + let kept = IDS.lock().ok().and_then(|ids| ids.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v.clone())); + let ids = kept.unwrap_or_else(|| { + let filters: Vec = crate::shortcut_editor::filter_items().iter().map(|f| format!("plugin:{}", f.id)).collect(); + let ids = drafts().into_iter().map(|d| d.id).filter(|id| !id.starts_with("tool:") && !crate::shortcut_editor::ui_command_needs_params(id)); + let ids: Arc> = Arc::new(ids.chain(filters).collect()); + if let Ok(mut kept) = IDS.lock() { + *kept = Some((key, ids.clone())); + } + ids + }); + ids.contains(id) } /// The params text of each entry's command, which the index reads a description from @@ -531,7 +595,7 @@ pub(crate) enum Picked { /// ([`crate::shortcut_editor::dimmed`]), with the engine's reason when it gives one and `name` in /// place of the command's id. A panel can't be shown in Presentation Mode, a tool can always be /// chosen, and every other result asks about the command its pick runs. -fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { +pub(crate) fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { if id.starts_with("tool:") { return None; } @@ -585,7 +649,7 @@ impl Availability { /// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces /// that run or show their progress. A click asks again for what it leaves out (a panel shown, a /// tool chosen) without changing it ([`show`]); typing in the search field does not. -fn availability_key(app: &VectorcraftApp) -> u64 { +pub(crate) fn availability_key(app: &VectorcraftApp) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); crate::native_menu::state_hash(app, None).hash(&mut h); @@ -4016,6 +4080,7 @@ mod tests { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], }; // Window › Tools hides the Tools panel while a toolbar made with New Toolbar holds the Pen // Tool: the row names that toolbar. @@ -5301,6 +5366,7 @@ mod tests { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], } } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index ed49600660..adad0d4e4e 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -1004,7 +1004,7 @@ mod tests { /// `entries` with their index, the params text of each in `params`. fn described(entries: Vec, params: &[&str]) -> Catalog { let index = Index::build(&entries, &[], params, |_| None); - Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) } + Catalog { list: entries, index, ranked: std::sync::Mutex::new(None), by_id: Default::default() } } /// Where `id` is among the results of `query`. @@ -1464,7 +1464,7 @@ mod tests { #[test] fn without_an_index_only_the_substring_rule_matches() { let entries = vec![entry("Remove Background…", "a.one"), entry("Zz Group", "b.two")]; - let c = Catalog { list: entries, index: Index::default(), ranked: std::sync::Mutex::new(None) }; + let c = Catalog { list: entries, index: Index::default(), ranked: std::sync::Mutex::new(None), by_id: Default::default() }; assert!(ranked(&c, "mov.nd").is_empty(), "{:?}", ranked(&c, "mov.nd")); assert_eq!(ranked(&c, "background mov"), ["a.one"]); } @@ -1519,7 +1519,12 @@ mod tests { fn a_catalog_row_adds_words_to_a_group() { let entries = || vec![entry("Zz Delete", "a.one")]; let row = |key: &str| (key == "remove, delete, erase, clear").then(|| "Entfernen, ganz weg, text".to_string()); - let with = Catalog { list: entries(), index: Index::build(&entries(), &[], &[], row), ranked: std::sync::Mutex::new(None) }; + let with = Catalog { + list: entries(), + index: Index::build(&entries(), &[], &[], row), + ranked: std::sync::Mutex::new(None), + by_id: Default::default(), + }; assert_eq!(ranked(&with, "entfernen"), ["a.one"]); assert!(ranked(&with, "ganz weg").is_empty(), "two words are left out"); assert!(ranked(&with, "text").is_empty(), "text stays in its own group"); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a9d7b022a7..c4bfb9f835 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -991,6 +991,16 @@ fn a_menu_bar_item_runs(id: &str, params: &str) -> bool { || menu_target(id).is_some_and(|(target, _)| target != id || !names_a_required_field(params)) } +/// Is `id` a UI command that fails when it runs with no params: its params doc names a field a call +/// must give, no item of the menu bar runs it ([`a_menu_bar_item_runs`]), and a key press does not +/// run it on its own ([`ui_listed_on_its_own`])? `toolbar.addTool` needs a `tool`. +pub(crate) fn ui_command_needs_params(id: &str) -> bool { + crate::menus::UI_COMMANDS + .iter() + .find(|c| c.0 == id) + .is_some_and(|c| names_a_required_field(c.3) && !a_menu_bar_item_runs(c.0, c.3) && !ui_listed_on_its_own(c.0, c.2, c.3)) +} + /// Is engine command `c` listed in Edit › Keyboard Shortcuts whether or not an item of the menu bar /// runs it? A command with a menu path of its own is. One without (a panel menu item) is when a key /// alone can run it: it has a default key, or it is an undoable command, not an alias, whose params diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..a2284e3b6f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1087,6 +1087,11 @@ pub struct CustomToolbar { /// The groups torn off it, each floating as its own strip; they show while it does. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub floating: Vec, + /// Its command buttons, after its tools: Command Palette result ids (a command's id, or + /// `plugin:`, `effect:` or `panel:` and an id). A command that is gone, such as an uninstalled + /// plug-in's, is kept and shows as unavailable until it comes back. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub commands: Vec, } /// A category of an edited toolbar: its name (one of the Basic toolbar's; none in the Advanced diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..6d2998e113 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -479,8 +479,17 @@ toolbars Tab hid are turned off. A toolbar's ••• button button (Add Tool…) opens a menu of every tool under the drawer's headings: a click on a tool runs `toolbar.addTool {tool, toolbar}`, which puts it at the end, and the tools under its Remove Tool heading run `toolbar.removeTool {tool, toolbar}`; the tools already in the toolbar are dimmed under their headings. The drawer has no Show section -there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with -it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, +there. The same menu's Add Command submenu searches the Command Palette's results other than tools, and a pick runs +`toolbar.addCommand {command, toolbar}`, which puts a command button at the end of the toolbar, after its tools; +`toolbar.addCommand {command, toolbar, at}` moves one to place `at` among the command buttons (Move Up and Move Down +in the button's context menu), and `toolbar.removeCommand {command, toolbar}` takes one off (Remove Command in the +menu, Remove from Toolbar in the context menu). `command` is a palette result's id: a command's id, or +`plugin:`, `effect:` or `panel:`. A click on the button runs what the command's menu item runs, and the +button is dimmed while that item is. An unknown command, a tool, a command that needs params a click does not give +(`toolbar.addTool`), a place past the end or a missing `toolbar` is an error and changes nothing. A command that is +no longer installed keeps its button, dimmed, and `toolbar.removeCommand` still takes it off. +`window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. +`window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, commands, shown flag, two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). `window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and `window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..bcdbcab44c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3678,6 +3678,26 @@ own layout rules. {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} ``` +## Command buttons on toolbars made with New Toolbar + +A toolbar made with New Toolbar holds command buttons after its tools. `toolbar.addCommand {command, toolbar, at?}` +(Add Command in the toolbar's Add Tool… menu, remote mode, `invoke_menu`) puts a button for `command` on the toolbar +named `toolbar`, or moves the button when the toolbar has it already: at place `at` among its command buttons, 0 for +the first, or at the end without `at`. `command` is a Command Palette result's id: a command's id, or +`plugin:`, `effect:` or `panel:`. `toolbar.removeCommand {command, toolbar}` takes a button off. Both +answer with the toolbar's command buttons, and `window.toolbar.list` reports `commands` for each toolbar. An unknown +command, a tool, a command that needs params a click does not give (`toolbar.addTool`), an `at` past the end or a +missing `toolbar` is an error and changes nothing. A click on a button runs what the command's menu item runs, so a +command whose item ends in … opens its dialog, and the button is dimmed while that item is. A command that is no +longer installed, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it is +installed again or removed. `toolbar.reset {toolbar}` takes the buttons off with the tools. The buttons are kept with +the workspace, and toolbars saved before command buttons existed load without any. Command buttons are VectorCraft's +own. + +```json +{"name":"invoke_menu","arguments":{"command":"toolbar.addCommand","params":{"command":"object.group","toolbar":"Toolbar 1"}}} +``` + ## Help search Help › VectorCraft Help… and F1 show the Help panel. `help.discover {query?}` opens it without diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..7c0e29b42d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,6 +1132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done. - Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`). - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). + - A toolbar made with New Toolbar also holds command buttons, after its tools. The Add Command submenu at the end of its Add Tool… menu searches every Command Palette result other than a tool (menu commands, plug-in commands, effects and panels), and a pick adds a button at the end; Remove Command in the same menu lists the buttons and takes one off. A button shows its command's label without the ellipsis, on up to two lines, and its full name and shortcut on hover. A click runs what the command's menu item runs, so a command whose item ends in … opens its dialog. While that item is dimmed the button is dimmed and runs nothing. The button's context menu has Move Up, Move Down and Remove from Toolbar. The buttons are kept with the toolbar in the workspace, Manage Toolbars' copy keeps them, and a toolbar saved without them loads unchanged. A command that is gone, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it comes back or is removed. Not done: dragging a menu item or a Command Palette result onto a toolbar, an Add to Toolbar item in the palette, dragging command buttons to reorder or remove them, and command icons (a button shows its label). Command buttons are VectorCraft's own (`toolbar.addCommand`, `toolbar.removeCommand`; `command_buttons_are_added_moved_and_removed_by_their_commands`, `a_command_button_runs_its_command_and_is_dimmed_while_it_cannot`, `a_missing_command_stays_dimmed_until_it_is_removed`, `a_plugin_command_button_works_again_when_the_plugin_returns`, `a_panel_button_shows_its_panel`, `command_buttons_ask_whether_they_can_run_a_few_at_a_time`, `the_add_tool_menu_adds_and_removes_commands`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - In the All Tools drawer a tool the toolbar holds is drawn throughout — name, shortcut and icon — in the dim text colour, one step dimmer than a tool not in it, so it still reads as in the toolbar while its name stays readable against the panel; the disabled colour it was drawn in before was about 2.6:1 on the panel, unreadable at the drawer's 12.5 px (#8294; `tools_in_the_toolbar_are_dimmed_in_the_drawer` in `crates/ui-egui/src/edit_toolbar/tests.rs`, which asserts the painted colour's contrast). The dimming is VectorCraft's own (#1018). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). From 82e3d6dac34458445d9bf5511a55957a323e2294 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 09:11:54 -0800 Subject: [PATCH 07/50] Plug-ins: the web build checks plug-ins and runs filters in a Web Worker On the web, a plug-in being installed ran its start function and vc_manifest on the page, and a filter ran on the page for its whole budget, so a slow or looping module froze the tab for up to a minute (five for a heavy filter), and Cancel could not stop it. - A second wasm, apps/vectorcraft-plugin-worker, is built by Trunk as a worker (data-type="worker" with data-loader-shim in index.html). The page starts one worker for each check and each run, and terminates it on Cancel, when the document or the plug-in changes, and 5 s past the run's time budget, also while a dialog is open. Each worker's inbox holds its latest progress report and at most 8 other messages. - crates/plugins/src/worker.rs holds the messages and the worker's side. Runs can pause at each vc_call (Plugin::begin_run and resume_run), which the desktop's synchronous calls now use too. - Install Plug-in... and File > Open check a module in a worker first; the page then loads it with Plugin::load_checked, which runs none of its code. - A filter that calls commands sends each call to the page. The session holds the run's undo step open and refuses other edits with "a plug-in is running: cancel it or wait for it to finish" until the run ends; the progress window shows at once with Cancel only. - On the web every filter and plug-in command started from the menus or their dialogs runs in a worker, and the dialogs have no Preview. A plug-in command applies as itself, one undo step named after it. Commands that automation runs directly still run where they are called and return their result. - packaging/web: the worker files carry no hash, so the sample cache rules make only the hashed app files immutable. --- Cargo.lock | 10 + apps/vectorcraft-plugin-worker/Cargo.toml | 20 + apps/vectorcraft-plugin-worker/src/main.rs | 37 ++ apps/vectorcraft-web/Cargo.toml | 2 +- apps/vectorcraft-web/index.html | 2 + apps/vectorcraft-web/src/main.rs | 4 + apps/vectorcraft-web/src/plugin_workers.rs | 72 +++ apps/vectorcraft-web/src/web.rs | 3 + crates/engine/src/cmd/plugin.rs | 207 +++++++- crates/engine/src/cmd/plugin_call.rs | 97 ++-- crates/engine/src/error.rs | 7 + crates/engine/src/lib.rs | 6 + crates/engine/src/session/documents.rs | 2 + crates/engine/src/session/edit.rs | 6 + crates/engine/src/session/execute.rs | 5 + crates/engine/src/tests/plugins.rs | 128 +++++ crates/plugins/src/host.rs | 2 +- crates/plugins/src/lib.rs | 6 +- crates/plugins/src/runtime.rs | 396 ++++++++++---- crates/plugins/src/worker.rs | 533 +++++++++++++++++++ crates/plugins/tests/call.rs | 10 + crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/app/commands.rs | 9 + crates/ui-egui/src/dialogs/plugin.rs | 29 +- crates/ui-egui/src/io.rs | 2 +- crates/ui-egui/src/io/open.rs | 16 +- crates/ui-egui/src/plugin_runs.rs | 566 +++++++++++++++++++-- crates/ui-egui/src/services.rs | 4 + crates/ui-egui/src/tests/plugin_runs.rs | 435 ++++++++++++++++ docs/plugins.md | 32 +- packaging/web/.htaccess | 4 +- packaging/web/README.md | 19 +- packaging/web/_headers | 6 +- xtask/src/layers.rs | 1 + xtask/src/main.rs | 7 +- 35 files changed, 2489 insertions(+), 198 deletions(-) create mode 100644 apps/vectorcraft-plugin-worker/Cargo.toml create mode 100644 apps/vectorcraft-plugin-worker/src/main.rs create mode 100644 apps/vectorcraft-web/src/plugin_workers.rs create mode 100644 crates/plugins/src/worker.rs diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..55f7f18d34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7132,6 +7132,16 @@ dependencies = [ "vectorcraft-text", ] +[[package]] +name = "vectorcraft-plugin-worker" +version = "0.24.1" +dependencies = [ + "js-sys", + "vectorcraft-plugins", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "vectorcraft-plugins" version = "0.24.1" diff --git a/apps/vectorcraft-plugin-worker/Cargo.toml b/apps/vectorcraft-plugin-worker/Cargo.toml new file mode 100644 index 0000000000..a2dfc0b944 --- /dev/null +++ b/apps/vectorcraft-plugin-worker/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "vectorcraft-plugin-worker" +description = "The web build's plug-in worker: checks plug-in modules being installed and runs filters off the page" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +[[bin]] +name = "vectorcraft-plugin-worker" +path = "src/main.rs" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +vectorcraft-plugins = { workspace = true } +wasm-bindgen = "0.2" +js-sys = "0.3" +web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] } diff --git a/apps/vectorcraft-plugin-worker/src/main.rs b/apps/vectorcraft-plugin-worker/src/main.rs new file mode 100644 index 0000000000..4699ca2e3f --- /dev/null +++ b/apps/vectorcraft-plugin-worker/src/main.rs @@ -0,0 +1,37 @@ +//! The web build's plug-in worker ([`vectorcraft_plugins::worker`]). Trunk builds it beside the +//! app (`data-type="worker"` in `apps/vectorcraft-web/index.html`), and the page starts one for each +//! module it checks and each filter it runs, through the loader Trunk writes for it +//! (`vectorcraft-plugin-worker_loader.js`). Each message, both ways, is one `Uint8Array`. + +#[cfg(target_arch = "wasm32")] +fn main() { + use std::cell::RefCell; + use std::rc::Rc; + + use wasm_bindgen::JsCast as _; + use wasm_bindgen::prelude::Closure; + use web_sys::{DedicatedWorkerGlobalScope, MessageEvent}; + + let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into(); + let poster = scope.clone(); + let post = Rc::new(move |msg: Vec| { + let bytes = js_sys::Uint8Array::from(msg.as_slice()); + // A message that can't be posted leaves the page waiting, and its time budget ends the run. + let _ = poster.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer())); + }); + let worker = Rc::new(RefCell::new(vectorcraft_plugins::worker::Worker::new(post))); + let handler = Rc::clone(&worker); + let on_message = Closure::::new(move |e: MessageEvent| { + let msg = js_sys::Uint8Array::new(&e.data()).to_vec(); + handler.borrow_mut().handle(&msg); + }); + scope.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + // The handler lives as long as the worker. + on_message.forget(); + worker.borrow().ready(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn main() { + eprintln!("vectorcraft-plugin-worker only runs in the browser, as the web build's plug-in worker"); +} diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 9569d2b3f3..7907ecc476 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -31,4 +31,4 @@ wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal", "Node", "Worker", "MessageEvent", "ErrorEvent", "Performance"] } diff --git a/apps/vectorcraft-web/index.html b/apps/vectorcraft-web/index.html index 2ccfc271b0..965bd03ebd 100644 --- a/apps/vectorcraft-web/index.html +++ b/apps/vectorcraft-web/index.html @@ -17,6 +17,8 @@ + +