From f5962eb16158d9ebec028b9df05ca3a06cd1340d Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:32:27 +0530 Subject: [PATCH 1/7] A right-click on a Glyphs cell inserts or applies that glyph. The menu item does what a double-click does, and stays disabled when the glyph cannot be applied. Co-authored-by: Cursor --- crates/ui-egui/src/panels/glyphs.rs | 35 +++++++- crates/ui-egui/src/panels/glyphs/tests.rs | 101 ++++++++++++++++++++++ docs/gaps.md | 2 + 3 files changed, 134 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index e639ae3ea4..4d60dd59ef 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -15,6 +15,8 @@ //! as one of its alternates in its word. A glyph no feature reaches whose name does not belong to //! another letter is applied as a glyph choice, which may not join. Other glyphs are drawn dimmed, //! and their notes say why they cannot be applied to the selection. +//! A right-click on a character offers Insert Glyph. A right-click on a glyph without a +//! character offers Apply Alternate. Both use the same text target as double-click or Enter. //! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph //! form ([`menu_rows`]). //! After the framework's categories, the Show menu lists the OpenType categories the browsed font @@ -24,10 +26,10 @@ use std::collections::HashSet; use std::sync::Arc; -use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsWords}; +use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphCellMenu, GlyphSource, GlyphsPanel, GlyphsWords}; use craft::keymap::CommandRef; -use craft::ui::contract::Bind; -use craft::ui::menu::PanelRow; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::Env; use egui::{Color32, ColorImage, Ui}; @@ -483,7 +485,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if out.font_changed { app.ui.glyphs_font = Some((family, style)); } - if let Some(cell) = out.activated { + let menu_cell = out + .menu + .as_ref() + .filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)) + .map(|menu| menu.cell); + if let Some(cell) = menu_cell.or(out.activated) { activate(app, cell); } if let Some(pick) = out.alternate { @@ -491,6 +498,26 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Offer the action for the clicked cell using the grid's face and text context for this pass. +fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphCellMenu) -> bool { + let Some(face) = &source.face else { return false }; + let (label, enabled) = match menu.cell { + GlyphCell::Char(c) => (tl!("Insert Glyph"), source.listing.is_none() && gid_of(face, c).is_some()), + GlyphCell::Glyph(gid) => { + let applies = match &source.listing { + Some(listing) => listing.variants.iter().any(|variant| variant.gid == gid), + None => source.fit.as_ref().is_some_and(|fit| fit.pick(face, gid).is_some()), + }; + (tl!("Apply Alternate"), applies) + } + _ => return false, + }; + Menu::context(label, &menu.opener) + .show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran) + .inner + .unwrap_or(false) +} + /// A double-click or Enter on `cell`: insert the character (its letter for an Arabic presentation /// form), or put the glyph on the selected character. pub(crate) fn activate(app: &mut VectorcraftApp, cell: GlyphCell) { diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index 0886975276..a4f6635324 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -1102,3 +1102,104 @@ fn the_grid_lists_the_same_cells_from_the_character_list_read_once() { assert!(list.iter().all(|c| matches!(c, GlyphCell::Glyph(_))), "no character is listed"); assert!(!list.is_empty(), "the glyphs are listed by glyph id"); } + +/// The name a glyph-id cell shows, as the grid names it. +fn glyph_cell_name(face: &vectorcraft_text::FontFace, gid: u32) -> String { + let name = face.glyph_name(gid).unwrap_or_else(|| format!("gid {gid}")); + format!("{name}, glyph {gid}") +} + +/// A right-click on an encoded cell offers Insert Glyph, and choosing it inserts that character in one undo step. +#[test] +fn right_clicking_a_glyph_cell_offers_insert_glyph() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let (mut app, id) = editing("a"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": ALIASED_JOINING_FAMILY})).unwrap(); + select(&mut app, 1, 1); + crate::panels::character::end_typing(&mut app); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(panel.menu_item_enabled("Insert Glyph")); + assert!(!panel.shows("Apply Alternate"), "a character cell offers Insert Glyph"); + panel.click_menu_item("Insert Glyph"); + { + let mut app = panel.app(); + crate::panels::character::end_typing(&mut app); + } + let app = panel.app(); + assert_eq!(plain_of(&app, id), "aB"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(plain_of(&panel.app(), id), "a"); +} + +#[test] +fn insert_glyph_is_disabled_without_a_text_target() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(!panel.menu_item_enabled("Insert Glyph")); +} + +/// In Alternates for Selection a right-click offers Apply Alternate in one undo step. +#[test] +fn right_clicking_an_alternate_cell_offers_apply_alternate() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 2, 4); + show_category(&mut app, "Alternates for Selection"); + let list = listed(&mut app, "Alternates for Selection"); + let GlyphCell::Glyph(gid) = list[2] else { panic!("an alternate is a glyph") }; + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let name = glyph_cell_name(&face, gid); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(panel.menu_item_enabled("Apply Alternate")); + assert!(!panel.shows("Insert Glyph"), "an alternate cell offers Apply Alternate"); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(glyph_ids(&app, &json!(id)), [g('B'), g('x'), g('M')]); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&panel.app(), &json!(id)), [g('B'), g('u'), g('M')]); +} + +/// A glyph a double-click would only explain has a disabled menu item, and choosing it changes nothing. +#[test] +fn a_glyph_that_cannot_be_applied_disables_the_menu_item() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let (mut app, id) = editing("\u{0627}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 0, 2); + show_category(&mut app, "stylisticAlternates"); + let gid = u32::from(source_sans_gid('w').expect("a glyph")); + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + assert!(cell_info(&mut app, GlyphCell::Glyph(gid)).dimmed, "w is not an alternate of alef"); + let name = glyph_cell_name(&face, gid); + let (undo, status, plain) = (undo_len(&app), app.ui.status.clone(), glyph_ids(&app, &json!(id))); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(!panel.menu_item_enabled("Apply Alternate")); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(glyph_ids(&app, &json!(id)), plain); + assert_eq!(undo_len(&app), undo); + assert_eq!(app.ui.status, status); +} diff --git a/docs/gaps.md b/docs/gaps.md index 35587afab4..02049a64b7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -551,6 +551,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- Glyphs cells have an item context menu. A character offers **Insert Glyph** at the Type caret or in selected text. A glyph without a mapped character offers **Apply Alternate** for the character selected with the Type tool. The menu uses the same actions as Enter and double-click and disables the item when its text target cannot accept the glyph. + - **Implemented and tested (2026-11-21):** Properties panel Quick Actions follow every selected object. Ungroup (`object.ungroup`) is offered when any selected object is a group, including several groups, a group selected after a path, and a group that holds another group. Isolate Group (`object.isolate`) is offered only when that one group is the whole selection. Unite (`object.pathfinder.unite`) appears only for selections of at least two objects, each a non-guide path or a compound path. It appears alongside Group and Make Clipping Mask. Headless regressions: `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group` and `several_paths_offer_group_clipping_mask_and_unite`. Other G12 gaps remain; scores and estimates unchanged. - **Implemented and tested (2026-11-21):** Document Info's panel menu Selection Only (`ui.docInfo.selectionOnly`; kept in memory for the session, not stored) asks `document.info` for the selection: object counts cover the selected nodes and their descendants, and with no artwork selected it shows `(No artwork selected)` instead of the document's counts, while artboards the Artboard tool has selected still show under Document. With the item off, counts stay for the whole document. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard` and `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. From 07acf0bf370b7e1631a8e039997ac2898d5f4069 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:50:07 +0530 Subject: [PATCH 2/7] Keep Glyphs menus open across unrelated font changes --- crates/ui-egui/src/panels/glyphs.rs | 51 +++++++++++++---------- crates/ui-egui/src/panels/glyphs/tests.rs | 10 ++++- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 4d60dd59ef..ad1bc48c1f 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -24,6 +24,7 @@ //! as Entire Font shows them. use std::collections::HashSet; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphCellMenu, GlyphSource, GlyphsPanel, GlyphsWords}; @@ -299,11 +300,11 @@ fn insert(app: &mut VectorcraftApp, ch: char) -> bool { /// character, all read when it is made, so it borrows nothing from the app. Every method uses the /// held face whatever family and style it is given: the face of the canvas row or of the selected /// text can be an instance of variable axes that no family and style name reaches. -pub(crate) struct VcGlyphs<'a> { - db: &'a FontDb, +pub(crate) struct VcGlyphs { family: String, style: String, face: Option>, + revision: u64, /// What a glyph no character maps can do to the selected character; none for a face without one /// and in Alternates for Selection. fit: Option, @@ -313,7 +314,7 @@ pub(crate) struct VcGlyphs<'a> { empty: Option, } -impl VcGlyphs<'static> { +impl VcGlyphs { /// The source of the panel: the browsed face, or the face of the selected character's alternates /// in Alternates for Selection. pub(crate) fn of(app: &mut VectorcraftApp) -> Self { @@ -321,44 +322,42 @@ impl VcGlyphs<'static> { if app.ui.glyphs_panel.category == ALTERNATES { return match alternates_listing(app) { Ok(listing) => VcGlyphs { - db: FontDb::global(), family: listing.face.family.clone(), style: listing.face.style.clone(), face: Some(listing.face.clone()), + revision: listing.revision(), fit: None, listing: Some(listing), empty: None, }, - Err(note) => VcGlyphs { db: FontDb::global(), family, style, face: None, fit: None, listing: None, empty: Some(note) }, + Err(note) => VcGlyphs { family, style, face: None, revision: 0, fit: None, listing: None, empty: Some(note) }, }; } let fit = face.as_ref().map(|f| Fit::of(app, f)); let empty = face.is_none().then(|| tl!("No fonts are available.").to_string()); - VcGlyphs { db: FontDb::global(), family, style, face, fit, listing: None, empty } + let revision = face.as_ref().map_or(0, |face| u64::from(face.id())); + VcGlyphs { family, style, face, revision, fit, listing: None, empty } } /// The source of `face` alone: it draws glyphs and describes nothing about the selection. fn bare(face: Arc) -> Self { VcGlyphs { - db: FontDb::global(), family: face.family.clone(), style: face.style.clone(), + revision: u64::from(face.id()), face: Some(face), fit: None, listing: None, empty: None, } } -} - -impl VcGlyphs<'_> { /// The family and style the panel shows. fn font(&self) -> (&str, &str) { (&self.family, &self.style) } } -impl GlyphSource for VcGlyphs<'_> { +impl GlyphSource for VcGlyphs { fn cells(&self, _family: &str, _style: &str, category: &str) -> Vec { let Some(face) = &self.face else { return vec![] }; if category == ALTERNATES { @@ -398,7 +397,9 @@ impl GlyphSource for VcGlyphs<'_> { } fn revision(&self) -> u64 { - self.db.generation() + // The grid uses this for both cached cells and open glyph-ID menus. Changes + // elsewhere in the font catalog leave the displayed face and its glyph IDs valid. + self.revision } fn categories(&self, _family: &str, _style: &str) -> Vec<(String, String)> { @@ -485,11 +486,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if out.font_changed { app.ui.glyphs_font = Some((family, style)); } - let menu_cell = out - .menu - .as_ref() - .filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)) - .map(|menu| menu.cell); + let menu_cell = out.menu.as_ref().filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)).map(|menu| menu.cell); if let Some(cell) = menu_cell.or(out.activated) { activate(app, cell); } @@ -499,7 +496,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// Offer the action for the clicked cell using the grid's face and text context for this pass. -fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphCellMenu) -> bool { +fn cell_menu(ui: &mut Ui, source: &VcGlyphs, can_insert: bool, menu: &GlyphCellMenu) -> bool { let Some(face) = &source.face else { return false }; let (label, enabled) = match menu.cell { GlyphCell::Char(c) => (tl!("Insert Glyph"), source.listing.is_none() && gid_of(face, c).is_some()), @@ -512,10 +509,7 @@ fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphC } _ => return false, }; - Menu::context(label, &menu.opener) - .show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran) - .inner - .unwrap_or(false) + Menu::context(label, &menu.opener).show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran).inner.unwrap_or(false) } /// A double-click or Enter on `cell`: insert the character (its letter for an Arabic presentation @@ -648,6 +642,17 @@ struct Listing { } impl Listing { + /// The visible alternates can change at another text target in the same face. + fn revision(&self) -> u64 { + let mut revision = DefaultHasher::new(); + (self.face.id(), self.id, self.bytes, self.variants.len()).hash(&mut revision); + for variant in &self.variants { + variant.gid.hash(&mut revision); + } + // Face-only revisions are u32 IDs. Keep a listing in a separate range. + revision.finish() | (1 << 63) + } + /// Draw the character with glyph `gid` of the listing, as one undo step. fn apply(&self, app: &mut VectorcraftApp, gid: u32) { if let Some(variant) = self.variants.iter().find(|v| v.gid == gid) { @@ -775,7 +780,7 @@ impl OnCanvas { } /// The source that draws the offered glyphs ([`Self::face`]). - pub fn source(&self) -> VcGlyphs<'static> { + pub fn source(&self) -> VcGlyphs { VcGlyphs::bare(self.face.clone()) } diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index a4f6635324..8a797f4fec 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -43,7 +43,7 @@ fn browsed(app: &VectorcraftApp) -> (String, String) { } /// The panel's cell source, as the panel builds it. -fn source(app: &mut VectorcraftApp) -> VcGlyphs<'static> { +fn source(app: &mut VectorcraftApp) -> VcGlyphs { VcGlyphs::of(app) } @@ -1153,7 +1153,7 @@ fn insert_glyph_is_disabled_without_a_text_target() { /// In Alternates for Selection a right-click offers Apply Alternate in one undo step. #[test] fn right_clicking_an_alternate_cell_offers_apply_alternate() { - use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid, thai_font}; FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); @@ -1170,6 +1170,12 @@ fn right_clicking_an_alternate_cell_offers_apply_alternate() { panel.secondary_click(&name); assert!(panel.menu_item_enabled("Apply Alternate")); assert!(!panel.shows("Insert Glyph"), "an alternate cell offers Apply Alternate"); + // Registering a different family between the menu's opening and the click + // must leave its glyph-ID target valid. + let unrelated = thai_font("VectorCraft Glyph Menu Unrelated Fixture", true).expect("the unrelated test font builds"); + assert!(FontDb::global().add_font(unrelated) > 0); + panel.frame(); + assert!(panel.menu_item_enabled("Apply Alternate")); panel.click_menu_item("Apply Alternate"); let app = panel.app(); assert_eq!(undo_len(&app), undo + 1, "one undo step"); From d61d946a3df86a41ff24b6fb2648c5b725e29533 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:59:45 +0530 Subject: [PATCH 3/7] Color Themes: add a context menu to saved theme rows --- crates/ui-egui/src/panels/color_themes.rs | 106 ++++++++++++++++------ docs/target-app-parity.md | 1 + 2 files changed, 80 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index 3d1b32f037..7ba34fe65a 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -10,7 +10,7 @@ // framework crates' layout (racheck-fw); none of them is imported anywhere else in the app yet. use std::borrow::Cow; -use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange}; +use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange, keyed}; use craft::color_ui::ui::{ChannelRow, ColorPanelMode, HarmonyWheel}; use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; @@ -19,7 +19,7 @@ use craft::ui::choice::{SwatchSpacing, SwatchTable}; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; use craft::ui::pickers::Select; use craft::ui::primitives::IconSpec; @@ -592,44 +592,45 @@ fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { } else if rows.is_empty() { Notice::new(Tone::Neutral, tl!("No matches.")).show(ui); } else { - let names: Vec = rows.iter().map(|(n, _)| n.clone()).collect(); - let mut selection = app - .ui - .color_themes_panel - .picked - .as_ref() - .and_then(|p| names.iter().position(|n| n == p)) - .map_or_else(Selection::default, Selection::single); - let out = List::new(tl!("My Themes")).select(craft::ui::contract::SelectMode::Single).selection(Bind::bound(&mut selection)).show_items( - ui, - &Names(&names), - &mut |key, _| { - let colors = rows.get(*key).map(|(_, c)| c.clone()).unwrap_or_default(); - let name = names.get(*key).cloned().unwrap_or_default(); - ListRow::new(name).thumb(ThumbSize::Small, move |cx, rect| { + let document = app.session.active().map(|st| st.uid); + let selection = picked(app).map_or_else(Selection::default, Selection::single); + let out = List::new(tl!("My Themes")) + .id(ui.scope_id().with(("my-themes", document))) + .select(craft::ui::contract::SelectMode::Single) + .selection(Bind::given(selection)) + .row_menu() + .show_items(ui, &keyed(&rows, |(name, _)| name.clone()), &mut |name, icx| { + let colors = rows[icx.at].1.clone(); + ListRow::new(name.clone()).thumb(ThumbSize::Small, move |cx, rect| { let w = rect.width() / colors.len().max(1) as f32; cx.data_shapes(colors.iter().enumerate().map(|(i, c)| { egui::Shape::rect_filled(Rect::from_min_size(rect.min + vec2(i as f32 * w, 0.0), vec2(w, rect.height())), 0.0, c32(c)) })); }) - }, - ); + }); for event in out.events { match event { CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => { - if let Some(name) = keys.last().and_then(|k| names.get(*k)) { - app.ui.color_themes_panel.picked = Some(name.clone()); - } + app.ui.color_themes_panel.picked = keys.last().cloned(); } + CollectionEvent::ContextMenu(request) => app.ui.color_themes_panel.picked = Some(request.key), // Enter and a double click edit the theme. - CollectionEvent::Activate(key) => { - if let Some(name) = names.get(key) { - edit_saved(app, name); - } - } + CollectionEvent::Activate(name) => edit_saved(app, &name), _ => {} } } + if let Some(request) = out.menu + && app.ui.color_themes_panel.tab == MY_THEMES + && app.ui.color_themes_panel.picked.as_ref() == Some(&request.key) + { + Menu::context(request.key, &out.response).show(ui, |ui, _| { + for (id, label) in [(EDIT, tl!("Edit Theme")), (ADD_TO_SWATCHES, tl!("Add to Swatches")), (DELETE, tl!("Delete Theme"))] { + if MenuItem::new(label).enabled(enabled(app, id)).show(ui).ran { + run(app, id, &Value::Null); + } + } + }); + } } let labels = vec![Label::from(tl!("Delete theme")), Label::from(tl!("Add to Swatches")), Label::from(tl!("Edit theme"))]; footer(app, ui, &[DELETE, ADD_TO_SWATCHES, EDIT], &["trash-2", "dc-folder", "pencil"], labels); @@ -831,6 +832,57 @@ mod tests { assert_eq!(picked(&app), None); } + #[test] + fn the_theme_menu_follows_its_row_when_the_list_is_filtered() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + app.ui.color_themes_panel.picked = Some("Forest".into()); + let mut panel = Panel::new(app, show); + panel.secondary_click("Harvest"); + assert_eq!(picked(&panel.app()).as_deref(), Some("Harvest")); + panel.app().ui.color_themes_panel.find = "vest".into(); + panel.frame(); + panel.click_menu_item("Delete Theme"); + assert_eq!(themes(&panel.app()).iter().map(|t| t.name.as_str()).collect::>(), ["Harbor", "Forest"]); + } + + #[test] + fn keyboard_theme_menu_uses_the_focused_row_without_a_document() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + assert!(app.session.close_document(0)); + let mut panel = Panel::new(app, show); + panel.click("Forest"); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + assert!(panel.menu_item_enabled("Edit Theme")); + assert!(panel.menu_item_enabled("Delete Theme")); + assert!(!panel.menu_item_enabled("Add to Swatches")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + assert!(panel.focused("Forest")); + } + + #[test] + fn the_theme_menu_closes_when_its_row_disappears_or_the_document_changes() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(three_themes(""), show); + panel.secondary_click("Harbor"); + assert!(panel.menu_item_enabled("Edit Theme")); + panel.app().ui.color_themes_panel.find = "Forest".into(); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + panel.secondary_click("Forest"); + assert!(panel.menu_item_enabled("Add to Swatches")); + panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap(); + panel.frame(); + assert!(!panel.shows_role("Add to Swatches", Role::MENU_ITEM)); + } + /// The find field lists the themes whose names hold its text, in any letter case, anywhere in /// the name, in their saved order; it reads names only, and its text is plain text. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5f5f9644d5..1eac724072 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2203,6 +2203,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (), which ships unmodified: the measured paper, solids and overprints, a tone curve fitted to each ink's ramp, and a smoothed Lab correction lattice fitted to all 1,617 patches. The models reproduce the patches within a mean ΔE2000 of 0.04 (largest 0.37), and patches left out of the fit within 0.15 to 0.17 (largest 1.67). A PDF/X output intent made with one embeds the profile; with the condition identifier left blank it names `FOGRA51` or `FOGRA52`, in the `http://www.color.org` registry unless the settings give a registry, and an identifier the settings give is written as given. The 300% ink limit and black generation are VectorCraft's own values. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **My Themes row menu:** Opening a saved theme's row menu selects it and offers Edit Theme, Add to Swatches and Delete Theme. Add to Swatches requires an active document. - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. - **Color Themes sliders:** on the Color Themes panel's Create tab, a Color Mode menu (CMYK, RGB, Lab and HSB) shows a rail and a number field for each component of the selected theme color, beside its hex field; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221) describes changing the selected color's values in these color systems or as hex while making a theme. VectorCraft's own rules: the menu starts in the selected color's own model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color; the ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127), a number past the range sets its end and text that is not a number changes nothing; a CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, while RGB and HSB edits make it RGB, and the theme saves and goes to Swatches in those models; an edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. Tests: `the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders`, `a_slider_edit_changes_only_the_selected_custom_color`, `the_sliders_keep_the_numbers_they_set`, `with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color` and `cmyk_and_lab_slider_edits_keep_their_models` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. From 68a104ba8f2305839a3f1dd278fb3ef41152f4d5 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:00:18 +0530 Subject: [PATCH 4/7] Add item context menus to resource library panels --- crates/ui-egui/src/panels/library_panel.rs | 14 ++++++-- .../ui-egui/src/panels/library_panel/tests.rs | 36 +++++++++++++++++++ docs/ui-parity.md | 1 + 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index e9fc506ec0..1cd5502a2b 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -22,7 +22,7 @@ use std::collections::HashMap; use craft::behavior::{IconId, Selection, SelectionModel}; use craft::host::PickRequest; use craft::theme::variant::Tone; -use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; +use craft::ui::contract::{Bind, Entry, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::{Notice, NoticeAction, NoticeLayout}; use craft::ui::patterns::presets::{ @@ -675,7 +675,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { let title = library_name(id, &name).to_string(); // The footer stays under the browser, which scrolls in the room left above it. let footer_out = RefCell::new(None); - let any = !selection.items.is_empty() && can_add(app, K::KIND); + let can_add = can_add(app, K::KIND); + let any = !selection.items.is_empty() && can_add; let mut shown = Panel::new(title.clone()) .collection_body() .footer(|ui, _| *footer_out.borrow_mut() = Some(footer_bar::(any).show_footer(ui))) @@ -686,7 +687,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { .select(SelectMode::Multi) .selection(Bind::given(selection.clone())) .empty(tl!("This library is empty.")) - .row_menu(PresetRowMenu::Off) + .row_menu(PresetRowMenu::Host) + .row_items(move |_: &LibraryKey| vec![Entry::new("ui.libraryPanel.add".to_owned(), K::ADD).enabled(can_add)]) + .host_version(u64::from(can_add)) .drags(K::drags()) .show(ui) }); @@ -696,6 +699,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { for event in events { match event { PresetEvent::Selection(change) => chosen.apply(change), + PresetEvent::Menu { target, command, .. } if command == "ui.libraryPanel.add" && can_add => { + let names = + if chosen.items.contains(&target) { chosen.items.iter().map(|key| key.name.clone()).collect() } else { vec![target.name] }; + K::add(app, id, names); + } // A plain click on an item also adds and applies it; folders and modifier clicks only select. PresetEvent::Select { key, mods, .. } if !key.folder && !mods.shift && !mods.cmd => clicked = Some(key.name), _ => {} diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..58b0effd84 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -182,6 +182,42 @@ fn modifier_clicks_select_and_add_to_swatches_adds_the_selection() { assert!(selected_names(&app, "library:swatches:brights").is_empty()); } +#[test] +fn library_item_menu_adds_the_target_or_its_selection_without_applying_paint() { + for view in ["smallList", "smallThumb"] { + for target in ["Clay 1", "Clay 3"] { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = shown(&app); + app.run("ui.libraryPanel", json!({"panel": panel, "view": view})).unwrap(); + click(&mut app, &ctx, "Clay 1", Modifiers::COMMAND, 0.0); + click(&mut app, &ctx, "Clay 2", Modifiers::COMMAND, 1.0); + let paint = app.session.paint.fill.clone(); + let undo = undo_len(&app); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let (_, at) = control(&mut app, &ctx, &draw, target); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; + draw_frame(&mut app, &ctx, &draw, vec![Event::PointerMoved(at)]); + draw_frame(&mut app, &ctx, &draw, vec![button(true)]); + draw_frame(&mut app, &ctx, &draw, vec![button(false)]); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + let (_, row) = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::MenuItem && n.label() == Some("Add to Swatches")).unwrap(); + let bounds = row.bounds().unwrap(); + assert_eq!(undo_len(&app), undo, "opening the item menu must not edit the drawing"); + let expected = if target == "Clay 1" { vec!["Clay 1", "Clay 2"] } else { vec!["Clay 3"] }; + assert_eq!(selected_names(&app, &panel), expected); + click_at(&mut app, &ctx, &draw, Pos2::new((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5)); + for name in ["Clay 1", "Clay 2", "Clay 3"] { + assert_eq!(app.session.doc().unwrap().doc.swatch(name).is_some(), expected.contains(&name), "{view}: {target}: {name}"); + } + assert_eq!(app.session.paint.fill, paint); + } + } +} + #[test] fn adding_selected_library_items_requires_an_open_drawing() { let mut app = app(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8bb6c7b87a..775f91c648 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -526,6 +526,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fifteen built-in libraries (original, generated in code) | +| Swatch, Brush, Symbol and Graphic Style Library item menus | done | In list and thumbnail views, the item menu offers the same Add to action as the footer. It adds the current selection when the target is selected or the target alone otherwise. The action requires an open drawing. | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its fill or stroke (solid, gradient or pattern) and the Transparency panel setting its opacity and blend, is on canvas (#6308); `.ai` editing data keeps dynamic symbols and their instance changes when VectorCraft writes and reads it (#8747); on-canvas editing beyond fill, stroke, opacity and blend, and reading other apps' dynamic symbol records, remain | From 8ff9f4cba2ff5d99f4585f249fe8658dc7cecc83 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 1 Dec 2026 23:33:48 +0530 Subject: [PATCH 5/7] .ai import: a visibility variable on hidden styled type binds the group that hides it Since #9228 hidden styled type whose look has its own transparency comes in as a group of the look and the type, and the group holds the hidden and locked state. A visibility variable bound to the type's XML id still bound the type, so showing it left the type hidden. The reader now records the text slot each such group wraps, and a visibility binding on that slot binds the group; text bindings stay on the type. --- crates/eps/src/import/ai/read.rs | 10 ++++--- crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ai/read/ops.rs | 6 ++--- crates/eps/src/import/native/build.rs | 17 +++++++++--- crates/eps/src/import/tests_native.rs | 32 +++++++++++++++++++++++ 5 files changed, 56 insertions(+), 10 deletions(-) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 17d9896ab9..8a29eec63e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -248,6 +248,9 @@ pub struct Structure { /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an /// id two objects have. pub xml_ids: HashMap>, + /// The group of a styled text object and its look, by the text object's slot id. The group, + /// not the type in it, is hidden or locked where the text object was. + pub text_looks: HashMap, /// The objects the variable library binds to its variables, by their XML ids: the importer /// binds those it keeps. pub bindings: Vec, @@ -664,8 +667,9 @@ struct Reader<'a> { ruler_guides: HashMap, /// Legacy compound member groups, even when followed by the generic `9 () XW` marker. compound_groups: HashSet, - /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look. - text_looks: HashSet, + /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look, each + /// with the text object's slot id. + text_looks: HashMap, /// Objects followed by samples of the pen (`(…) Xt n XD`), which aren't read: such an object /// whose style has a Calligraphic brush that varies with the pen keeps its drawn look (see /// [`Self::style_marker`]). @@ -911,7 +915,7 @@ impl<'a> Reader<'a> { looks: HashSet::new(), ruler_guides: HashMap::new(), compound_groups: HashSet::new(), - text_looks: HashSet::new(), + text_looks: HashMap::new(), pen_samples: HashSet::new(), group_ended: false, mesh_ended: false, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 20102b29c4..ec14b864d9 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1485,6 +1485,7 @@ impl<'a> Reader<'a> { canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, + text_looks: self.text_looks.into_iter().map(|(group, slot)| (slot, group)).collect(), bindings, bindings_skipped, warnings, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index bb5343e4f4..1b9d6aa20b 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -822,7 +822,7 @@ impl<'a> Reader<'a> { // The look is a group of paths, or one image where an effect (a blur, a shadow) rasterizes it. if !self.hidden_ids.contains(&object.id) || self.hidden_ids.contains(&look.id) != hidden - || self.text_looks.contains(&look.id) + || self.text_looks.contains_key(&look.id) || !matches!(look.kind, NodeKind::Group { clip: false, .. } | NodeKind::Image(_)) { return; @@ -978,7 +978,7 @@ impl<'a> Reader<'a> { let Some(mut look) = f.children.pop() else { return }; let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); - let (visible, locked) = (object.visible, object.locked); + let (visible, locked, slot) = (object.visible, object.locked, object.id); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); object.visible = true; object.locked = false; @@ -986,7 +986,7 @@ impl<'a> Reader<'a> { (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; group.visible = visible; group.locked = locked; - self.text_looks.insert(group.id); + self.text_looks.insert(group.id, slot); if let Some(f) = self.frames.last_mut() { f.children.push(group); } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 0637e8e079..9daa57bfd8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -350,6 +350,7 @@ pub(super) fn build_weighing( canvas_scale, symbols_own_size, xml_ids, + text_looks, bindings, bindings_skipped, warped_type, @@ -653,7 +654,7 @@ pub(super) fn build_weighing( None => unmark(&mut doc.layers, true, true, &mut vec![]), } doc.limit_depth_noting(&mut notes); - bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); + bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &text_looks, &mut notes); if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) { notes.push(ai::LINKED_PREVIEWS.to_string()); } @@ -731,7 +732,9 @@ fn to_placed_documents( /// Bind the objects of `doc` to the variables of its library that `bindings` binds them to, each /// object named by its XML id (`ids`: the object read with that id, or what `filled` made of a text /// object's slot: for a visibility variable every object that took the slot's place, for a text -/// variable the one text object among them). An object is bound when it is of the variable's kind: +/// variable the one text object among them). A visibility variable binds a styled text object's +/// group with its look (`text_looks`, by slot) in place of the type: the group is what is hidden or +/// shown. An object is bound when it is of the variable's kind: /// type for a text variable, a linked image for an image variable, any object for a visibility /// variable. Locked and hidden objects, objects in locked or hidden layers and groups, and objects /// on locked artboards keep their bindings. Graph variables and @@ -743,6 +746,7 @@ fn bind_variables( skipped: usize, ids: &std::collections::HashMap>, filled: &std::collections::HashMap, + text_looks: &std::collections::HashMap, notes: &mut Vec, ) { let mut skipped = skipped; @@ -753,7 +757,12 @@ fn bind_variables( let mut bound = vec![]; for b in bindings { let kind = doc.variables.variable(&b.variable).map(|v| v.kind); - let targets = match (b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()), kind) { + let target = b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()); + let target = match kind { + Some(VariableKind::Visibility) => target.map(|id| text_looks.get(&id).copied().unwrap_or(id)), + _ => target, + }; + let targets = match (target, kind) { (Some(id), Some(kind)) => match filled.get(&id) { Some(f) if kind == VariableKind::Visibility => f.objects.clone(), Some(f) => match f.text.as_slice() { @@ -2819,7 +2828,7 @@ mod candidate_tests { bind("v_graph", "path"), ]; let mut notes = vec![]; - bind_variables(&mut doc, &refs, 3, &ids, &filled, &mut notes); + bind_variables(&mut doc, &refs, 3, &ids, &filled, &Default::default(), &mut notes); let sorted = |mut v: Vec| { v.sort(); v diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index c5b6b61d58..d51573877a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2240,6 +2240,38 @@ fn ai_variable_bindings_bind_the_objects_they_name() { assert!(!r.warnings.iter().any(|w| w.contains("variable library")), "{:?}", r.warnings); } +/// Hidden, locked type whose style comes in as a group of its drawn look and the type (the look has +/// its own transparency) is hidden and locked on that group. A visibility variable bound to the +/// type binds the group, so showing it shows the type; a text variable still binds the type. +#[test] +fn a_visibility_variable_on_hidden_styled_type_binds_the_group_that_hides_it() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let declare = |name: &str, t: &str| { + let uid = "/XMLUIDREF : (type_x5F_1) ;"; + let attributes = [("trait", XmlValue::Str(t)), ("varName", XmlValue::Unicode(name)), ("docRef", XmlValue::Raw(uid))]; + xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }; + let declared = vec![declare("v_shown", "visibility"), declare("v_text", "textcontent")]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf"; + // The look at half opacity; the type hidden (`1 Xw`) and locked (`1 A`), with its XML id. + let look = format!("0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{drawing}\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n"); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let styled = format!("{look}1 Xw\n1 A\n{own}{}1 (Unlisted) XW\n0 Xw\n0 A\n", named("type_x5F_1")); + let art = native_with_text(&(library + &layer("Art", true, &styled)), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let a = d.layers[0].children().unwrap(); + let [group] = a.as_slice() else { panic!("one group of the look and the type: {a:#?} {notes:?}") }; + assert!(matches!(group.kind, NodeKind::Group { .. }) && !group.visible && group.locked, "{group:#?}"); + let type_id = group.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id); + assert!(type_id.is_some(), "{group:#?}"); + let vars = &d.variables; + assert_eq!(vars.objects_of("v_shown"), [group.id], "the hidden group, not the type in it: {notes:?}"); + assert_eq!(vars.objects_of("v_text").first().copied(), type_id, "{notes:?}"); +} + /// An EPS whose editing data can't be used, a palette with no layers among others, comes in as its /// page with the swatches and color groups of that palette in place of the defaults. #[test] From 82cb6ef291580f4a897998b8eabf7ed14e5d0aa5 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 1 Dec 2026 23:46:40 +0530 Subject: [PATCH 6/7] .ai import: hold the page type's word searches to their own budget #9228 let a file with many text objects whose type is made be weighed by where its pieces of type lie, up to four times the comparisons word matching may make. The page's type lying where made type draws was still searched word by word in every made text object there, and in the lines of hidden made type, so those searches could run to the larger limit. They are now counted on their own, up to MAX_PAIRS. Past it, type where made type that shows draws is taken as that type, type over hidden made type only stays on the page, and the page's type is noted as unchecked. The letters of hidden made type's lines are worked out once. --- crates/eps/src/import/native/plan.rs | 183 +++++++++++++++++++++++---- 1 file changed, 160 insertions(+), 23 deletions(-) diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index a23e8ea324..a15c272222 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -154,8 +154,19 @@ pub(super) fn made_only( if looks && infos.len().saturating_mul(shown.len()) <= MAX_PAIRS { let spelled: Vec = content.iter().map(|c| if let Content::Made(node, ..) = c { spelling(&plain_text(node)) } else { String::new() }).collect(); - let made_type = |o: &[Arc]| covered(o, &content, |_| true) && has_made_words(o, &content, &spelled); + // Past the word searches, type where made type draws is taken to be that type. + let (mut checks, mut unchecked) = (WordChecks::new(), false); + let mut made_type = |o: &[Arc]| { + covered(o, &content, |_| true) + && has_made_words(o, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }) + }; let mut spare: Vec>> = shown.iter().filter(|o| !made_type(o)).cloned().collect(); + if unchecked { + note_unchecked(warn); + } fill_look_slots(infos, &mut content, &mut spare); for c in &content { if let Content::Page(parts) = c { @@ -173,7 +184,7 @@ pub(super) fn made_only( match see_page_type(&mut content, untaken) { Some(0) => {} Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()), - None => warn.push(PAGE_TYPE_UNCHECKED.into()), + None => note_unchecked(warn), } drop_look_slots(infos, &mut content); fill_hidden(infos, stories, &mut content, hidden); @@ -274,17 +285,64 @@ fn fill_look_slots(infos: &[SlotInfo], content: &mut [Content], spare: &mut Vec< drop_look_slots(infos, content); } +/// How many more times a word of the page's type may be looked for in a text object's type. The +/// page's type is weighed against where every text object lies up to `MAX_PLACE_PAIRS` pairs, a box +/// against a box, but each text object a piece of it lies on can be searched for each of its words: +/// those searches are held to `MAX_PAIRS` of their own. +struct WordChecks(usize); + +impl WordChecks { + fn new() -> Self { + WordChecks(MAX_PAIRS) + } + + /// One more search, if any are left. + fn spend(&mut self) -> Option<()> { + self.0 = self.0.checked_sub(1)?; + Some(()) + } + + /// Are no searches left? + fn spent(&self) -> bool { + self.0 == 0 + } +} + /// Has made type that shows and draws where the page's text object `object` lies every word of it -/// ([`spelling`], each slot's in `spelled`), in any order? -fn has_made_words(object: &[Arc], content: &[Content], spelled: &[String]) -> bool { - let Some(r) = extent(object) else { return true }; +/// ([`spelling`], each slot's in `spelled`), in any order? `None` once `checks` runs out before +/// that is known. +fn has_made_words(object: &[Arc], content: &[Content], spelled: &[String], checks: &mut WordChecks) -> Option { + let Some(r) = extent(object) else { return Some(true) }; + if checks.spent() { + return None; + } let near: Vec<&String> = content .iter() .zip(spelled) .filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area())) .map(|(_, s)| s) .collect(); - object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str()))) + for w in object_words(object) { + let mut found = false; + for s in &near { + checks.spend()?; + if s.contains(w.as_str()) { + found = true; + break; + } + } + if !found { + return Some(false); + } + } + Some(true) +} + +/// Note once in `warn` that some of the page's type wasn't checked against the text objects. +fn note_unchecked(warn: &mut Vec) { + if !warn.iter().any(|w| w == PAGE_TYPE_UNCHECKED) { + warn.push(PAGE_TYPE_UNCHECKED.into()); + } } /// The text slots for type that a look draws and that have nothing have no type of their own to hold @@ -438,9 +496,16 @@ pub(super) fn plan( let made_stories: std::collections::BTreeSet = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect(); let open: Vec = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect(); let owner = match_page_objects(infos, &lines, &open, shown); - // Where the made type that doesn't show lies, by slot. - let hidden_at: Vec<(usize, Rect)> = - infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); + // Where the made type that doesn't show lies, and the letters of its lines (it has lines). + let hidden_at: Vec<(Rect, Vec)> = infos + .iter() + .zip(&made) + .enumerate() + .filter_map(|(k, (info, m))| { + let place = m.as_ref().filter(|_| !info.shown)?.1?; + Some((place, lines.get(k)?.as_ref()?.iter().map(|(text, _)| letters(text)).collect())) + }) + .collect(); // Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box // stays that of type without a layout here: with text objects whose type isn't made stacked on // made type that has their words (the copies of an outlined heading), the page's pieces in the @@ -448,17 +513,34 @@ pub(super) fn plan( let mut content = made_content(infos, made, false); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) - let hidden_type = |object: &[Arc]| { - let Some(r) = extent(object) else { return false }; + // `None` once `checks` runs out before that is known. + let hidden_type = |object: &[Arc], checks: &mut WordChecks| -> Option { + let Some(r) = extent(object) else { return Some(false) }; let texts: Vec> = object.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text())) } else { None }).collect(); - hidden_at.iter().any(|(k, place)| { - place.intersect(r).area() >= 0.5 * r.area().max(1e-9) - && lines.get(*k).and_then(Option::as_ref).is_some_and(|l| { - !texts.is_empty() - && texts.iter().all(|ws| !ws.is_empty() && ws.iter().all(|w| l.iter().any(|(text, _)| letters(text).contains(w.as_str())))) - }) - }) + if texts.is_empty() || texts.iter().any(Vec::is_empty) { + return Some(false); + } + for (place, l) in &hidden_at { + if place.intersect(r).area() < 0.5 * r.area().max(1e-9) { + continue; + } + let mut all = true; + 'words: for w in texts.iter().flatten() { + for text in l { + checks.spend()?; + if text.contains(w.as_str()) { + continue 'words; + } + } + all = false; + break; + } + if all { + return Some(true); + } + } + Some(false) }; // The letters and digits of each slot's made type that shows, in any script, in lower case. let spelled: Vec = content @@ -472,6 +554,10 @@ pub(super) fn plan( }) .collect(); let mut spare: Vec>> = vec![]; + // The word searches below are held to their own budget: past it, type where made type that shows + // draws is taken to be that type (made type is there either way), and type where only made type + // that doesn't show lies stays on the page (it would not show otherwise). + let (mut checks, mut unchecked) = (WordChecks::new(), false); for (j, object) in shown.iter().enumerate() { match owner.get(j).copied().flatten() { Some(k) => match content.get_mut(k) { @@ -479,13 +565,28 @@ pub(super) fn plan( Some(c) => *c = Content::Page(object.clone()), None => {} }, - // What lies where made type draws, with its words, is that type as the page draws it (in - // another font, maybe, and in any script). - None if covered(object, &content, |_| true) && has_made_words(object, &content, &spelled) => {} - None if hidden_type(object) => {} - None => spare.push(object.clone()), + None => { + // What lies where made type draws, with its words, is that type as the page draws it + // (in another font, maybe, and in any script). + let theirs = covered(object, &content, |_| true) + && has_made_words(object, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }); + let hidden = !theirs + && hidden_type(object, &mut checks).unwrap_or_else(|| { + unchecked = true; + false + }); + if !theirs && !hidden { + spare.push(object.clone()); + } + } } } + if unchecked { + note_unchecked(warn); + } // The page's type that no made type takes is the spare type below. let _ = see_page_type(&mut content, shown); for (k, c) in content.iter_mut().enumerate() { @@ -600,3 +701,39 @@ fn fill_hidden(infos: &[SlotInfo], stories: &[Option>], content: &mut } } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{CharStyle, TextObject}; + + fn text(id: u64, s: &str) -> Node { + let style = CharStyle { size: 12.0, ..CharStyle::default() }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(100.0, 100.0), s, style)))) + } + + /// The page's type is searched for in every made text object that draws where it lies, word by + /// word: those searches stop when their budget runs out, saying they didn't finish, however many + /// made text objects lie there. A word is searched for only until a text object has it. + #[test] + fn word_searches_of_the_page_s_type_stop_when_their_budget_runs_out() { + let everywhere = Rect::new(-1e4, -1e4, 1e4, 1e4); + let slots = 50; + let content: Vec = (0..slots).map(|k| Content::Made(Box::new(text(k, "Other type")), Some(everywhere), false)).collect(); + let spelled: Vec = + content.iter().map(|c| if let Content::Made(n, ..) = c { spelling(&plain_text(n)) } else { String::new() }).collect(); + // A word no made type has is searched for in each of them. + let missing = vec![Arc::new(text(1000, "Alpha beta"))]; + let one_word_everywhere = slots as usize; + let mut short = WordChecks(one_word_everywhere - 1); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut short), None, "past the budget the answer isn't known"); + assert!(short.spent()); + let mut enough = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut enough), Some(false)); + // Words that the first made type has are found there, without searching the others. + let present = vec![Arc::new(text(1001, "other TYPE"))]; + let mut few = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true)); + assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0); + } +} From 450a821ae4dfc2bc75123ec6bef7ccf0ec8f96bf Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 2 Dec 2026 07:35:21 +0530 Subject: [PATCH 7/7] .ai import: say where unchecked page type over hidden type goes --- crates/eps/src/import/native/plan.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index a15c272222..f2dfba3377 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -556,7 +556,9 @@ pub(super) fn plan( let mut spare: Vec>> = vec![]; // The word searches below are held to their own budget: past it, type where made type that shows // draws is taken to be that type (made type is there either way), and type where only made type - // that doesn't show lies stays on the page (it would not show otherwise). + // that doesn't show lies is spare type, as any type no text object takes: it goes into a slot + // or with another text object's type, else it is left out with a note (taken as the hidden + // type, it would be dropped unnoted). let (mut checks, mut unchecked) = (WordChecks::new(), false); for (j, object) in shown.iter().enumerate() { match owner.get(j).copied().flatten() {