From 3607c70efe0f97404f11e13068e3b96482d24202 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:25:04 -0800 Subject: [PATCH 1/5] Glyphs: a cell's corner triangle opens a pop-up of its glyph's alternates A Glyphs panel cell whose glyph has alternates shows a small triangle in its lower right corner. A click on it opens a pop-up of that glyph and its alternates in the font's order. Picking one inserts the character at the Type tool's caret drawn with that glyph, or draws the selected character with it, in one undo step; the cell's own glyph inserts the character as a double-click does. In Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does. A pick is tried on a copy of the document first, so one the character cannot be drawn with (All Caps, for example) changes nothing and the status says why. A Select All over a threaded story is replaced as typing replaces it. The triangle's size and the pop-up's eight columns and six rows are VectorCraft's own. --- crates/text/src/fontdb/gsub.rs | 7 + crates/text/src/tests/alternates.rs | 19 + crates/ui-egui/src/panels/glyphs.rs | 572 +++++++++++++++++++++++++++- docs/type-parity.md | 2 +- 4 files changed, 591 insertions(+), 9 deletions(-) diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index a245efeea2..815eefd569 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -344,6 +344,13 @@ impl FontFace { self.gsub_index().by_input.get(&gid).cloned().unwrap_or_default() } + /// Do [`Self::substitutions`] of glyph `gid` give a glyph other than `gid` itself? It reads the + /// face's index without copying the substitutions, so the Glyphs panel asks it for each cell it + /// draws. + pub fn has_alternates(&self, gid: u32) -> bool { + self.gsub_index().by_input.get(&gid).is_some_and(|subs| subs.iter().any(|s| s.glyphs.iter().any(|&g| g != gid))) + } + /// The feature of the `GSUB` table that gives glyph `gid` as a substitute (by a single, /// multiple, alternate or ligature substitution), a listed feature ([`Self::substitutions`]) /// before another (`init`, `liga`), if any does. Not read through a contextual lookup. diff --git a/crates/text/src/tests/alternates.rs b/crates/text/src/tests/alternates.rs index cc70780eb3..48f621555d 100644 --- a/crates/text/src/tests/alternates.rs +++ b/crates/text/src/tests/alternates.rs @@ -40,6 +40,25 @@ fn alternates_come_in_feature_order_once_each() { assert!(bundled.alternates('a').iter().all(|a| a.gid < bundled.glyph_count())); } +/// A glyph has alternates when a listed feature gives it another glyph: `a` has them in both +/// faces, `b` and the alternates of `a` have none, and a glyph past the face has none. +#[test] +fn has_alternates_follows_the_listed_substitutions() { + let db = db(); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + for aalt in [true, false] { + let face = db.face(alternates_family(aalt), "Regular").expect("the test face"); + assert!(face.has_alternates(face.glyph_for('a')), "a, aalt {aalt}"); + assert!(!face.has_alternates(face.glyph_for('b')), "b, aalt {aalt}"); + assert!(!face.has_alternates(u1), "an alternate of a has none of its own, aalt {aalt}"); + assert!(!face.has_alternates(face.glyph_count() + 10), "a glyph past the face, aalt {aalt}"); + } + let bundled = db.face(FALLBACK_FAMILY, "Regular").expect("the bundled face"); + let with = bundled.chars().into_iter().filter(|(_, g)| bundled.has_alternates(*g)).count(); + let listed = bundled.chars().into_iter().filter(|(c, g)| bundled.alternates(*c).iter().any(|a| a.gid != *g)).count(); + assert_eq!(with, listed, "the same characters as the alternates lists say"); +} + /// The cap on lookups read in all leaves out the lowest ranked features: `salt` is read even when /// the `cv01` records before it list more lookups than the cap. #[test] diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index cac85259f3..ea26dfec76 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -2,6 +2,10 @@ //! outlines; Show › Entire Font adds the glyphs no character maps, by glyph id. Double-click //! inserts the character at the Type tool's caret (or appends it to the selected text objects). //! The character selected with the Type tool is highlighted in the grid. +//! A character whose glyph has alternates has a triangle in its cell's lower right corner, and a +//! click on it opens a pop-up of those alternates ([`alternates_popup`]); picking one inserts the +//! character drawn with it ([`insert_alternate`]). In Entire Font a glyph no character maps has the +//! triangle too, and a pick goes on the selected character as a double-click on its cell does. //! Show › Alternates for Current Selection lists that character's alternate glyphs instead (as it //! stands in its word), and a double-click applies the OpenType feature that draws one to that //! character alone, so the text stays real text that joins its neighbors. A double-click on a @@ -284,6 +288,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let row_h = cell + ui.spacing().item_spacing.y; area = area.vertical_scroll_offset((((i / cols) as f32 + 0.5) * row_h - list_h * 0.5).max(0.0)); } + // A pick in a cell's pop-up of alternates: the character (none for a glyph no character maps), + // the glyph of its cell, the glyph picked. + let mut popup_pick: Option<(Option, u32, u32)> = None; let shown = area.show_rows(ui, cell, rows, |ui, range| { for r in range.clone() { @@ -312,6 +319,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let ink = if matches!(pick, Some(None)) { t.text_disabled } else { t.text_strong }; let tex = glyph_texture(ui.ctx(), &face, gid, px); ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), ink); + // Only the cells drawn ask whether their glyph has alternates. + if face.has_alternates(gid) + && let Some(picked) = corner_popup(ui, &face, c, gid, rect, cell) + { + popup_pick = Some((c, gid, picked)); + } // The tooltip is made when it is shown: working out why a glyph cannot be // applied reads the font, which hundreds of cells cannot do each frame. let resp = resp.on_hover_ui(|ui| { @@ -354,6 +367,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { range }); ui.ctx().data_mut(|d| d.insert_temp(follow_id, (selected, shown.inner))); + match (popup_pick, &fit) { + (Some((Some(c), cell_gid, picked)), _) => insert_alternate(app, ui.ctx(), &face, c, cell_gid, picked), + // A glyph no character maps goes on the selected character as a double-click on its cell + // in Entire Font puts it. + (Some((None, _, picked)), Some(fit)) => match fit.pick(&face, picked) { + Some(pick) => fit.apply(app, pick), + None => app.status(fit.why(&face, picked)), + }, + _ => {} + } ui.add_space(4.0); let info = ui.ctx().data(|d| d.get_temp::<(Option, u32)>(hover_id)); let count = crate::i18n::tn(total as u64, "{n} glyph", "{n} glyphs"); @@ -541,15 +564,34 @@ fn alternates(app: &mut VectorcraftApp, ui: &mut Ui, w: f32) { /// goes through `text.setRangeStyle` on exactly the character (its other alternate features are /// turned off, a glyph choice is taken away); a glyph no feature draws through /// `text.setGlyphAlternate`. The default glyph, or a variant the character already has, changes -/// nothing. -fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), features: &[String], has_choice: bool, pick: Pick) { - let (cmd, params) = match pick { +/// nothing. Whether the command ran or nothing needed to change; a failed command's error goes to +/// the status. +fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), features: &[String], has_choice: bool, pick: Pick) -> bool { + let Some((cmd, params)) = alternate_command(id, bytes, features, has_choice, pick) else { return true }; + match app.run(cmd, params) { + Ok(_) => true, + Err(e) => { + app.status(e.to_string()); + false + } + } +} + +/// The command and parameters [`apply_alternate`] runs; `None` when nothing needs to change. +fn alternate_command( + id: NodeId, + bytes: (usize, usize), + features: &[String], + has_choice: bool, + pick: Pick, +) -> Option<(&'static str, serde_json::Value)> { + Some(match pick { Pick::Glyph(gid) => ("text.setGlyphAlternate", json!({"id": id.0, "start": bytes.0, "gid": gid})), Pick::Default | Pick::Feature(_) => { let tag = if let Pick::Feature(tag) = &pick { Some(tag.as_str()) } else { None }; let changes = vectorcraft_text::alternate_changes(features, tag); if changes.is_empty() && !has_choice { - return; + return None; } let mut params = json!({"id": id.0, "start": bytes.0, "end": bytes.1}); if !changes.is_empty() { @@ -560,10 +602,7 @@ fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), } ("text.setRangeStyle", params) } - }; - if let Err(e) = app.run(cmd, params) { - app.status(e.to_string()); - } + }) } /// The most alternate glyphs the canvas shows beside a selected character. Public behavior: at @@ -855,6 +894,250 @@ fn insert_character(app: &mut VectorcraftApp, ctx: &egui::Context, face: &vector } } +/// The side of the triangle in the lower right corner of a grid cell `cell` points wide whose glyph +/// has alternates: a quarter of the cell, from 5 to 10 points (VectorCraft's own size). +fn corner_side(cell: f32) -> f32 { + (cell * 0.25).clamp(5.0, 10.0) +} + +/// The most columns, and the most rows before it scrolls, of a cell's pop-up of alternates +/// (VectorCraft's own numbers). +const POPUP_COLUMNS: usize = 8; +const POPUP_ROWS: usize = 6; + +/// The triangle in the lower right corner of the grid cell `rect` of character `c` (none for a +/// glyph no character maps), whose glyph `gid` has alternates, and the pop-up a click on it opens +/// ([`alternates_popup`]). Public +/// behavior: a pop-up of alternate glyphs opens from the triangle in the lower right corner of a +/// glyph's box where the glyph has alternates +/// ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)). +/// Returns the glyph picked in the pop-up, in the frame it is picked. +fn corner_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option, gid: u32, rect: egui::Rect, cell: f32) -> Option { + let t = Tokens::get(ui.ctx()); + let side = corner_side(cell); + let corner = egui::Rect::from_min_max(rect.max - vec2(side + 1.0, side + 1.0), rect.max - vec2(1.0, 1.0)); + let resp = ui.interact(corner, egui::Id::unique(("gl-alternates-corner", face.id(), c, gid)), Sense::click()); + let fill = if resp.hovered() { t.accent } else { t.text_dim }; + ui.painter().add(egui::Shape::convex_polygon(vec![corner.right_top(), corner.right_bottom(), corner.left_bottom()], fill, Stroke::NONE)); + let resp = resp.on_hover_text(tl!("Show Character Alternates")); + let mut picked = None; + egui::Popup::menu(&resp).show(|ui| picked = alternates_popup(ui, face, c, gid, cell.max(CELL_STEPS[CELL_DEFAULT]))); + picked +} + +/// The pop-up of the alternates of glyph `gid`: that glyph first, then the alternates +/// [`vectorcraft_text::FontFace::alternates`] lists for character `c`, or for a glyph no character +/// maps the glyphs [`vectorcraft_text::FontFace::substitutions`] gives it, in the font's order, in +/// cells `cell` points wide, [`POPUP_COLUMNS`] to a row and [`POPUP_ROWS`] rows before it scrolls. +/// The glyph clicked. +fn alternates_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option, gid: u32, cell: f32) -> Option { + let t = Tokens::get(ui.ctx()); + let mut list: Vec<(u32, Option<[u8; 4]>)> = vec![(gid, None)]; + match c { + Some(c) => list.extend(face.alternates(c).into_iter().map(|a| (a.gid, Some(a.feature)))), + None => list.extend(face.substitutions(gid).into_iter().flat_map(|s| s.glyphs.into_iter().map(move |g| (g, Some(s.feature))))), + } + let mut seen = std::collections::HashSet::new(); + list.retain(|(g, _)| seen.insert(*g)); + let cols = list.len().clamp(1, POPUP_COLUMNS); + let rows = list.len().div_ceil(cols); + let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; + let mut picked = None; + let area = egui::ScrollArea::vertical().id_salt(("gl-alternates-popup", face.id(), c, gid)).max_height(cell * POPUP_ROWS as f32); + area.show_rows(ui, cell, rows, |ui, range| { + for r in range { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + for &(g, feature) in list.iter().skip(r * cols).take(cols) { + let (rect, resp) = ui.allocate_exact_size(vec2(cell, cell), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 2, t.hover); + } + ui.painter().rect_stroke(rect.shrink(0.5), 0, Stroke::new(0.5, t.border), StrokeKind::Inside); + let tex = glyph_texture(ui.ctx(), face, g, px); + ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), t.text_strong); + let glyph = crate::i18n::fmt(tl!("glyph {id}"), &[("id", &g.to_string())]); + let tip = match feature { + Some(f) => format!("{glyph} ({})", String::from_utf8_lossy(&f)), + None => glyph, + }; + if resp.on_hover_text(tip).clicked() { + picked = Some(g); + } + } + }); + } + }); + picked +} + +/// A pick in the pop-up of character `c`'s cell, whose glyph is `gid` ([`alternates_popup`]). +/// The cell's own glyph inserts the character as a double-click on the cell does +/// ([`insert_character`]). An alternate needs the Type tool's caret or selection in text set in +/// `face`: when the selection is exactly one `c`, that character is drawn with the glyph; else `c` +/// goes in at the caret, in place of the selection, and is drawn with it, the two as one undo +/// step. The glyph goes on as a double-click in Show › Alternates for Current Selection puts it +/// ([`draw_selected_with`]). An Arabic presentation form goes in as its base letter, as a +/// double-click on its cell puts it, drawn with the glyph where the font gives it that glyph in its +/// word. Without a caret, with text in another font, or with a glyph the character cannot be drawn +/// with there, the status says why and nothing changes. +fn insert_alternate(app: &mut VectorcraftApp, ctx: &egui::Context, face: &vectorcraft_text::FontFace, c: char, gid: u32, picked: u32) { + if picked == gid { + return insert_character(app, ctx, face, c, gid); + } + let db = FontDb::global(); + let Some((editing, a, b)) = super::character::text_editing(app) else { + app.ui.status = "Select text or click into text with the Type tool to insert glyphs".into(); + return; + }; + let style = super::character::text_style(app).map(|(s, _)| s); + let text_face = style.as_ref().filter(|s| db.has_family(&s.font_family)).and_then(|s| db.style_face(s)); + if text_face.as_ref().map(|f| f.id()) != Some(face.id()) { + let text_font = match &text_face { + Some(f) => format!("{} {}", f.family, f.style), + None => style.map(|s| s.font_family).unwrap_or_default(), + }; + app.status(crate::i18n::fmt( + tl!("{glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font})."), + &[("glyph", &glyph_label(face, picked)), ("font", &format!("{} {}", face.family, face.style)), ("text_font", &text_font)], + )); + return; + } + let c = base_letter(face, c, gid).unwrap_or(c); + // Typing in progress stays a step of its own. + super::character::end_typing(app); + let one = selected_target(app).is_some_and(|t| t.ch == c && (a.min(b), a.max(b)) == (t.byte, t.byte + c.len_utf8())); + if one { + draw_selected_with(app, face, c, picked); + return; + } + // Inside an undo group that is already open, the insertion and the glyph are part of that + // group's step; else they are one step of their own. + let open = app.session.active().is_some_and(|st| st.undo_group.is_some()); + if !open { + app.session.begin_named_undo_group(None); + } + // After Select All in a threaded story, the other frames' text goes too, as typing removes it. + let story = super::character::text_story(app).unwrap_or_default(); + put_alternate(app, face, c, picked, editing, (a.min(b), a.max(b)), &story); + if !open && let Some(st) = app.session.active_mut() { + st.undo_group = None; + } +} + +/// The insertion of [`insert_alternate`]: `c` takes the place of the Type tool's selection `lo..hi` +/// of text `id` (with the text of the other frames of `story` when the Type tool has the whole +/// threaded story selected), in the style of the selection's first character, and is drawn with +/// glyph `picked`. The edits are tried on a copy of the document first, and a pick the copy refuses +/// changes nothing, the undo history included. +fn put_alternate( + app: &mut VectorcraftApp, + face: &vectorcraft_text::FontFace, + c: char, + picked: u32, + id: NodeId, + (lo, hi): (usize, usize), + story: &[NodeId], +) { + let style = if lo < hi { + match app.run("text.getRange", json!({"id": id.0, "start": lo, "end": hi})) { + Ok(v) => v.pointer("/runs/0/style").cloned(), + Err(e) => { + app.status(e.to_string()); + return; + } + } + } else { + None + }; + let clear: Vec = story.iter().filter(|f| **f != id).map(|f| f.0).collect(); + let mut edit = json!({"id": id.0, "start": lo, "end": hi, "clear": clear}); + match style { + Some(style) => edit["runs"] = json!([{"text": c.to_string(), "style": style}]), + None => edit["insert"] = json!(c.to_string()), + } + if let Err(e) = try_on_a_copy(app, face, c, picked, (id, lo), &edit) { + app.status(e); + return; + } + if let Err(e) = app.run("text.editRange", edit) { + app.status(e.to_string()); + return; + } + app.session.set_tool_option("select", &json!({"start": lo, "end": lo + c.len_utf8()})); + if draw_selected_with(app, face, c, picked) { + app.session.set_tool_option("select", &json!({"start": lo + c.len_utf8(), "end": lo + c.len_utf8()})); + } +} + +/// The edits of [`put_alternate`] on a copy of the active document in a session of its own: `edit` +/// (`text.editRange`) puts `c` in at byte `at` of text `id`, and glyph `picked` of `face` goes on +/// it. The error of the step that fails; an error too when the character is not where the edit put +/// it. +fn try_on_a_copy( + app: &VectorcraftApp, + face: &vectorcraft_text::FontFace, + c: char, + picked: u32, + (id, at): (NodeId, usize), + edit: &serde_json::Value, +) -> Result<(), String> { + let Some(st) = app.session.active() else { return Ok(()) }; + let mut copy = vectorcraft_engine::Session::new(); + copy.add_document(vectorcraft_doc::Document::clone(&st.doc), None); + copy.execute("text.editRange", edit).map_err(|e| e.to_string())?; + let n = c.len_utf8(); + let step = match copy.active().and_then(|s| s.doc.node(id)).map(|node| &node.kind) { + Some(NodeKind::Text(text)) if text.plain_text().get(at..at + n) == Some(c.encode_utf8(&mut [0; 4])) => style_at(text, at).and_then(|style| { + alternate_command(id, (at, at + n), &style.features, style.glyph_alternate.is_some(), pick_for(text, at, face, picked)) + }), + _ => return Err("Select text or click into text with the Type tool to insert glyphs".into()), + }; + if let Some((cmd, params)) = step { + copy.execute(cmd, ¶ms).map_err(|e| e.to_string())?; + } + Ok(()) +} + +/// Draw the Type tool's selected character, `c` (a range's first character, else the one before +/// the caret), with glyph `picked` of `face`: through the OpenType feature that draws that glyph +/// on it in its word when one does, else as a glyph choice ([`apply_alternate`]). Whether it +/// worked; nothing changes when the character already has that glyph. +fn draw_selected_with(app: &mut VectorcraftApp, face: &vectorcraft_text::FontFace, c: char, picked: u32) -> bool { + let Some(t) = selected_target(app).filter(|t| t.ch == c) else { return false }; + let (id, byte, features, has_choice) = (t.id, t.byte, t.style.features.clone(), t.style.glyph_alternate.is_some()); + let pick = match app.session.active().and_then(|s| s.doc.node(id)).map(|node| &node.kind) { + Some(NodeKind::Text(text)) => pick_for(text, byte, face, picked), + _ => Pick::Glyph(picked), + }; + super::character::end_typing(app); + apply_alternate(app, id, (byte, byte + c.len_utf8()), &features, has_choice, pick) +} + +/// How glyph `picked` of `face` goes on the character at `byte` of `text`: the OpenType feature +/// that draws it there in its word, the default glyph, else a glyph choice. +fn pick_for(text: &vectorcraft_text::TextObject, byte: usize, face: &vectorcraft_text::FontFace, picked: u32) -> Pick { + match vectorcraft_text::alternates_in_context(FontDb::global(), text, byte).filter(|f| f.font_id == face.id()) { + Some(f) if f.default == picked => Pick::Default, + Some(f) => f.alternates.iter().find(|x| x.gid == picked).and_then(|x| x.apply.clone()).map_or(Pick::Glyph(picked), Pick::Feature), + None => Pick::Glyph(picked), + } +} + +/// The style of the character at `byte` of `text`. +fn style_at(text: &vectorcraft_text::TextObject, byte: usize) -> Option<&CharStyle> { + let mut start = 0; + text.runs + .iter() + .find(|run| { + let end = start + run.text.len(); + let found = (start..end).contains(&byte); + start = end; + found + }) + .map(|run| &run.style) +} + /// The tooltip of a glyph no character maps (Show › Entire Font): its name from the font, `gid N` /// when it has none, its id, and the feature that gives it, if one does. fn unencoded_tip(face: &vectorcraft_text::FontFace, gid: u32) -> String { @@ -1611,6 +1894,279 @@ mod tests { } } + /// The corner triangles of the grid cells whose glyph has alternates: right-angled, with the + /// right angle at the cell's lower right corner. + fn corner_triangles(shapes: &[Shape]) -> Vec { + fn walk(s: &Shape, out: &mut Vec) { + match s { + Shape::Path(p) if p.points.len() == 3 && p.points[0].x == p.points[1].x && p.points[1].y == p.points[2].y => { + out.push(Rect::from_points(&p.points)); + } + Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut out = vec![]; + shapes.iter().for_each(|s| walk(s, &mut out)); + out + } + + /// The Type tool editing `text` set in the alternates test font, the panel on Basic Latin, and + /// the egui context it is drawn in. + fn basic_latin_of_the_alternates_font(text: &str) -> (VectorcraftApp, serde_json::Value, egui::Context) { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let (mut app, id) = editing(text); + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + (app, id, ctx) + } + + /// Click the one corner triangle of the grid, and return the glyph cells of the pop-up it + /// opens (drawn after the panel, on top of it). + fn open_corner_popup(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec { + let before = squares(&shapes(ctx, app, vec![])); + let corners = corner_triangles(&shapes(ctx, app, vec![])); + assert_eq!(corners.len(), 1, "only a has alternates among Basic Latin: {corners:?}"); + click(ctx, app, corners[0].center() + vec2(1.0, 1.0)); + let after = squares(&shapes(ctx, app, vec![])); + assert!(after.len() > before.len(), "the pop-up drew its glyphs: {} then {}", before.len(), after.len()); + after[after.len() - (after.len() - before.len())..].to_vec() + } + + /// A cell whose glyph has alternates has a corner triangle; a click on it opens a pop-up of the + /// glyph and its alternates in the font's order, and picking an alternate inserts the + /// character at the caret drawn with it, as one undo step. + #[test] + fn a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one() { + use vectorcraft_text::test_fonts::{alternates_family, unencoded_glyphs}; + let [u1, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xy"); + let face = FontDb::global().face(alternates_family(true), "Regular").expect("the test face"); + let a = face.glyph_for('a'); + assert!(face.has_alternates(a)); + let drawn = shapes(&ctx, &mut app, vec![]); + let (cells, triangle) = (squares(&drawn), corner_triangles(&drawn)); + assert_eq!(triangle.len(), 1); + assert!( + cells.iter().any(|c| c.contains(triangle[0].center()) && (c.max - triangle[0].max).length() < 2.0), + "in a cell's lower right corner: {triangle:?} among {cells:?}" + ); + select(&mut app, 1, 1); + let popup = open_corner_popup(&ctx, &mut app); + assert_eq!(popup.len(), 7, "a and its six alternates"); + let plain = glyph_ids(&app, &id); + let undo = app.session.active().unwrap().history.undo.len(); + // a, u1, b, u2: the fourth cell is ss01's u2. + click(&ctx, &mut app, popup[3].center()); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "xay", "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[1]], "the inserted a is drawn with the pick"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&app, &id), plain, "undo takes the character back out"); + // The cell's own glyph inserts the plain character, as a double-click does. + select(&mut app, 1, 1); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[0].center()); + assert_eq!(glyph_ids(&app, &id), [plain[0], a, plain[1]]); + // An alternate with no feature that draws it here (u1 is listed by aalt) still goes on. + select(&mut app, 2, 2); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(glyph_ids(&app, &id), [plain[0], a, u1, plain[1]], "status: {}", app.ui.status); + } + + /// With the Type tool's selection exactly the cell's character, a pick draws that character + /// with the glyph and keeps the text; picking the glyph it already has adds no undo step. + /// Without the Type tool, and with text in another font, the status says why and nothing + /// changes. + #[test] + fn a_pick_replaces_the_selected_character_and_says_why_when_it_cannot() { + use vectorcraft_text::test_fonts::{alternates_family, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xay"); + let plain = glyph_ids(&app, &id); + select(&mut app, 1, 2); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "xay", "the selected a stays: status {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[2]]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + select(&mut app, 1, 2); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the glyph it already has changes nothing"); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[2]]); + + // Text set in another font than the one the panel browses. + let family = alternates_family(true); + set_pstate(&ctx, "gl-font", Some((family.to_string(), "Regular".to_string()))); + app.run("text.setRangeStyle", json!({"id": id, "font": vectorcraft_text::FALLBACK_FAMILY})).unwrap(); + select(&mut app, 3, 3); + let undo = app.session.active().unwrap().history.undo.len(); + let before = glyph_ids(&app, &id); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(glyph_ids(&app, &id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.ui.status.contains("not of the font the selected text is set in"), "{}", app.ui.status); + + // No Type tool caret. + app.session.select_tool("select", Default::default()).unwrap(); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(glyph_ids(&app, &id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "Select text or click into text with the Type tool to insert glyphs"); + } + + /// A pick the inserted character cannot be drawn with (All Caps keeps a glyph choice from + /// being drawn) takes the character back out and keeps the status that says why: on its own, + /// and inside an undo group that is already open, which stays open with its earlier edit and + /// takes a pick that can be drawn in place of the selection. + #[test] + fn a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was() { + let [_, u2, ..] = vectorcraft_text::test_fonts::unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xy"); + let text = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + app.run("text.setFormat", json!({"ids": [id], "allCaps": true})).unwrap(); + // A step to redo, which the failed pick keeps. + app.run("text.setFormat", json!({"ids": [id], "underline": true})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + select(&mut app, 1, 1); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step is left"); + assert_eq!(app.session.active().unwrap().history.redo.len(), 1, "the redo step stays"); + assert!(!app.ui.status.is_empty(), "the status says why"); + + // In an open group with no edit yet, the failed pick leaves the group with nothing to undo. + app.run("edit.undoGroup.begin", json!({})).unwrap(); + select(&mut app, 0, 1); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy"); + assert!(!app.ui.status.is_empty(), "the status says why"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the empty group adds no step"); + + app.run("edit.undoGroup.begin", json!({})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "underline": true})).unwrap(); + select(&mut app, 0, 1); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy", "the replaced x is back: status {}", app.ui.status); + assert!(!app.ui.status.is_empty(), "the status says why"); + assert!(app.session.active().unwrap().undo_group.is_some(), "the group stays open"); + // A pick that can be drawn replaces the selection inside the group. + app.run("text.setFormat", json!({"ids": [id], "allCaps": false})).unwrap(); + select(&mut app, 0, 1); + let plain = glyph_ids(&app, &id); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(text(&app), "ay", "status {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [u2, plain[1]]); + assert!(app.session.active().unwrap().undo_group.is_some(), "the group stays open"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the group is one step"); + } + + /// After Select All in a threaded story, a pick replaces the whole story's text, as typing + /// does: the character drawn with the glyph stays, in one undo step. + #[test] + fn a_pick_replaces_a_threaded_story_that_select_all_selected() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let story = "a bad cab ".repeat(30); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b, c] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + assert_eq!(super::super::character::text_story(&app).map(|s| s.len()), Some(3), "the whole story is selected"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + let texts: String = [a, b, c].iter().map(|id| plain(&app, *id)).collect(); + assert_eq!(texts, "a", "status: {}", app.ui.status); + let first = [a, b, c].into_iter().find(|id| !plain(&app, *id).is_empty()).expect("a frame with the character"); + assert_eq!(glyph_ids(&app, &json!(first)), [u2]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + + /// In Entire Font, a glyph no character maps whose substitutions give other glyphs has the + /// corner triangle too: its pop-up lists it and those glyphs, and a pick goes on the selected + /// character as a double-click on that glyph's cell would put it. + #[test] + fn an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection() { + 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}"); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 2, 4); + let ctx = egui::Context::default(); + choose(&ctx, &mut app, "Entire Font"); + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let medial = g('u'); + assert!(face.unencoded_glyphs().contains(&medial) && face.has_alternates(medial), "the medial teh is unencoded and has alternates"); + // A screen tall enough for every cell of the font. + let run = |ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec| { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 200_000.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes.into_iter().map(|c| c.shape).collect::>() + }; + let click_at = |ctx: &egui::Context, app: &mut VectorcraftApp, at: Pos2| { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(ctx, app, vec![egui::Event::PointerMoved(at), button(true)]); + run(ctx, app, vec![button(false)]); + }; + let drawn = run(&ctx, &mut app, vec![]); + let (cells, corners) = (squares(&drawn), corner_triangles(&drawn)); + let chars = face.chars().into_iter().filter(|(c, _)| !c.is_control() && !c.is_whitespace()).count(); + let unencoded = face.unencoded_glyphs(); + assert_eq!(cells.len(), chars + unencoded.len(), "every glyph has a cell"); + let cell = cells[chars + unencoded.iter().position(|g| *g == medial).expect("an unencoded glyph")]; + let corner = corners.iter().find(|t| cell.contains(t.center())).expect("its corner triangle"); + let undo = app.session.active().unwrap().history.undo.len(); + click_at(&ctx, &mut app, corner.center() + vec2(1.0, 1.0)); + let after = squares(&run(&ctx, &mut app, vec![])); + let popup = &after[cells.len()..]; + assert_eq!(popup.len(), 4, "the medial teh and its three alternates"); + click_at(&ctx, &mut app, popup[2].center()); + assert_eq!(glyph_ids(&app, &id), [g('B'), g('x'), g('M')], "status: {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// Show › Entire Font also lists the glyphs no character maps. #[test] fn entire_font_lists_the_unencoded_glyphs() { diff --git a/docs/type-parity.md b/docs/type-parity.md index 5b332efd5e..9924ce4e43 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -32,7 +32,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | -| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. The glyph-cell pop-up of alternates is not there yet | +| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. A grid cell whose glyph has alternates shows a triangle in its lower right corner; a click on it opens a pop-up of that glyph and its alternates in the font's order, and a pick inserts the character at the caret drawn with that glyph, or draws the selected character with it, in one undo step; in Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)); the triangle's size and the pop-up's eight columns and six rows are VectorCraft's own (`panels::glyphs` tests `a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one`, `a_pick_replaces_the_selected_character_and_says_why_when_it_cannot`, `a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was`, `an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection`; `has_alternates_follows_the_listed_substitutions` in the text crate) | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | | OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice). | From 78268e6db5ca025d9d1074f7f8b182b3dcee8459 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:20:19 -0800 Subject: [PATCH 2/5] Glyphs: a pick after Select All replaces a threaded story whose first frame holds one character When Select All covered a threaded story and the edited frame held only the picked character, the pick drew that character with the glyph and left the other frames' text. The one-character path now applies only to a selection in one type object, so the pick replaces the whole story as typing does. --- crates/ui-egui/src/panels/glyphs.rs | 52 +++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index ea26dfec76..1de977dd36 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -974,9 +974,10 @@ fn alternates_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option t.plain_text(), + _ => panic!("text"), + }; + assert_eq!((plain(&app, a), plain(&app, b)), ("a".to_string(), "中中中".to_string())); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + assert_eq!(super::super::character::text_editing(&app), Some((NodeId(a), 0, 1)), "the selection is the one character"); + assert_eq!(super::super::character::text_story(&app).map(|s| s.len()), Some(2), "the whole story is selected"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let texts: String = [a, b].iter().map(|id| plain(&app, *id)).collect(); + assert_eq!(texts, "a", "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &json!(a)), [u2]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// In Entire Font, a glyph no character maps whose substitutions give other glyphs has the /// corner triangle too: its pop-up lists it and those glyphs, and a pick goes on the selected /// character as a double-click on that glyph's cell would put it. From 31d28a0a06540bca743ef857f92d696296b48985 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:47:21 -0800 Subject: [PATCH 3/5] Glyphs: a pick at the end of a full frame follows its character to the next frame When a pick put a character in at the end of a full frame of threaded text, the text flowed the character on to the next frame, and the pick looked for it only in the frame it was typed in: it refused the pick and changed nothing. The pick now finds the character by its place in the story, draws it with the glyph in the frame it went to, and the Type tool edits that frame with the caret after the character. --- crates/ui-egui/src/panels/glyphs.rs | 123 ++++++++++++++++++++++++---- 1 file changed, 109 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 1de977dd36..7c8614d3fc 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -1052,13 +1052,15 @@ fn put_alternate( } else { None }; - let clear: Vec = story.iter().filter(|f| **f != id).map(|f| f.0).collect(); - let mut edit = json!({"id": id.0, "start": lo, "end": hi, "clear": clear}); + let clear: Vec = story.iter().copied().filter(|f| *f != id).collect(); + let mut edit = json!({"id": id.0, "start": lo, "end": hi, "clear": clear.iter().map(|f| f.0).collect::>()}); match style { Some(style) => edit["runs"] = json!([{"text": c.to_string(), "style": style}]), None => edit["insert"] = json!(c.to_string()), } - if let Err(e) = try_on_a_copy(app, face, c, picked, (id, lo), &edit) { + // The character's place in the story: a full frame of threaded text flows it on to the next. + let Some(at) = app.session.active().map(|st| story_start(&st.doc, id, &clear) + lo) else { return }; + if let Err(e) = try_on_a_copy(app, face, c, picked, (id, at), &edit) { app.status(e); return; } @@ -1066,16 +1068,68 @@ fn put_alternate( app.status(e.to_string()); return; } - app.session.set_tool_option("select", &json!({"start": lo, "end": lo + c.len_utf8()})); - if draw_selected_with(app, face, c, picked) { - app.session.set_tool_option("select", &json!({"start": lo + c.len_utf8(), "end": lo + c.len_utf8()})); + let n = c.len_utf8(); + if select_in_story(app, (id, at), c, (0, n)) && draw_selected_with(app, face, c, picked) { + // The glyph can change the character's width and flow it on again: find it again. + select_in_story(app, (id, at), c, (n, n)); } } +/// The Type tool's selection becomes bytes `start..end` from character `c` at byte `at` of the +/// story of text `id`, in the frame that holds the character; whether it is there. When that +/// frame is not the one the Type tool edits, the tool edits it, and it is selected, as a click in +/// it selects it (`move_editing_selection` in the engine's `panelcmds.rs`). +fn select_in_story(app: &mut VectorcraftApp, (id, at): (NodeId, usize), c: char, (start, end): (usize, usize)) -> bool { + let Some((frame, byte)) = app.session.active().and_then(|st| story_place(&st.doc, id, at, c)) else { return false }; + if super::character::text_editing(app).is_some_and(|(editing, ..)| editing == frame) { + app.session.set_tool_option("select", &json!({"start": byte + start, "end": byte + end})); + return true; + } + app.session.set_tool_option("textSelection", &json!({"editing": frame.0, "anchor": byte + start, "caret": byte + end})); + let selected = + app.session.active().is_some_and(|st| std::iter::successors(Some(frame), |f| st.doc.parent_of(*f)).any(|f| st.selection.contains(f))); + if !selected && let Err(e) = app.session.select(|_, sel| sel.set([frame])) { + app.status(e.to_string()); + return false; + } + true +} + +/// The bytes of the text of the frames before frame `id` in its story ([`Document::story_of`]), +/// without the frames of `clear`, whose text an edit removes. +/// +/// [`Document::story_of`]: vectorcraft_doc::Document::story_of +fn story_start(doc: &vectorcraft_doc::Document, id: NodeId, clear: &[NodeId]) -> usize { + doc.story_of(id) + .into_iter() + .take_while(|f| *f != id) + .filter(|f| !clear.contains(f)) + .filter_map(|f| match doc.node(f).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t.plain_text().len()), + _ => None, + }) + .sum() +} + +/// The frame of the story of text `id` that holds the character at byte `at` of the story's text, +/// and that character's byte in the frame; `None` unless that character is `c`. +fn story_place(doc: &vectorcraft_doc::Document, id: NodeId, at: usize, c: char) -> Option<(NodeId, usize)> { + let mut start = 0; + for f in doc.story_of(id) { + let Some(NodeKind::Text(t)) = doc.node(f).map(|n| &n.kind) else { continue }; + let text = t.plain_text(); + if at < start + text.len() { + return text.get(at - start..)?.starts_with(c).then_some((f, at - start)); + } + start += text.len(); + } + None +} + /// The edits of [`put_alternate`] on a copy of the active document in a session of its own: `edit` -/// (`text.editRange`) puts `c` in at byte `at` of text `id`, and glyph `picked` of `face` goes on -/// it. The error of the step that fails; an error too when the character is not where the edit put -/// it. +/// (`text.editRange`) puts `c` in at byte `at` of the story of text `id` (in whichever frame the +/// text flows it to), and glyph `picked` of `face` goes on it. The error of the step that fails; an +/// error too when the character is not where the edit put it. fn try_on_a_copy( app: &VectorcraftApp, face: &vectorcraft_text::FontFace, @@ -1089,11 +1143,15 @@ fn try_on_a_copy( copy.add_document(vectorcraft_doc::Document::clone(&st.doc), None); copy.execute("text.editRange", edit).map_err(|e| e.to_string())?; let n = c.len_utf8(); - let step = match copy.active().and_then(|s| s.doc.node(id)).map(|node| &node.kind) { - Some(NodeKind::Text(text)) if text.plain_text().get(at..at + n) == Some(c.encode_utf8(&mut [0; 4])) => style_at(text, at).and_then(|style| { - alternate_command(id, (at, at + n), &style.features, style.glyph_alternate.is_some(), pick_for(text, at, face, picked)) - }), - _ => return Err("Select text or click into text with the Type tool to insert glyphs".into()), + let doc = copy.active().map(|s| &s.doc); + let step = match doc.and_then(|d| story_place(d, id, at, c).and_then(|(f, byte)| Some((f, byte, d.node(f)?)))) { + Some((f, byte, node)) => match &node.kind { + NodeKind::Text(text) => style_at(text, byte).and_then(|style| { + alternate_command(f, (byte, byte + n), &style.features, style.glyph_alternate.is_some(), pick_for(text, byte, face, picked)) + }), + _ => return Err("Select text or click into text with the Type tool to insert glyphs".into()), + }, + None => return Err("Select text or click into text with the Type tool to insert glyphs".into()), }; if let Some((cmd, params)) = step { copy.execute(cmd, ¶ms).map_err(|e| e.to_string())?; @@ -2161,6 +2219,43 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); } + /// A pick at the caret at the end of a full frame of threaded text puts the character in, and + /// the text flows it on to the next frame: it is drawn with the glyph there, and the Type tool + /// edits that frame with the caret after it. + #[test] + fn a_pick_at_the_end_of_a_full_frame_follows_the_character_to_the_next_frame() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + // The first frame is wide enough for "a" and one ideograph only. + let area = json!({"x": 10, "y": 10, "text": "a中中中", "size": 12, "area": {"width": 20, "height": 16}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + assert_eq!((plain(&app, a), plain(&app, b)), ("a中".to_string(), "中中".to_string())); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let end = "a中".len(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": end, "caret": end})); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!((plain(&app, a), plain(&app, b)), ("a中".to_string(), "a中中".to_string()), "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &json!(b))[0], u2); + assert_eq!(super::super::character::text_editing(&app), Some((NodeId(b), 1, 1)), "the caret is after the character"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// In Entire Font, a glyph no character maps whose substitutions give other glyphs has the /// corner triangle too: its pop-up lists it and those glyphs, and a pick goes on the selected /// character as a double-click on that glyph's cell would put it. From b21cc967bfc7980a7edc463ad07ec8c131f0bddb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:27:40 -0800 Subject: [PATCH 4/5] Glyphs: the selection follows a picked character that flows to the next frame When a pick draws the selected character with a wider glyph and the text flows it on to the next frame of threaded text, the Type tool now edits that frame with the character still selected. --- crates/ui-egui/src/panels/glyphs.rs | 59 ++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 7c8614d3fc..755983151e 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -975,7 +975,7 @@ fn alternates_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option face.advance(plain_a), "an alternate wider than the a"); + // The first frame holds "x a" with the plain a, and not with the wider glyph. + let pt = |g: u32| face.advance(g) * 12.0 / face.units_per_em(); + let width = pt(gid('x')) + pt(gid(' ')) + (pt(plain_a) + pt(wide)) / 2.0; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let area = json!({"x": 10, "y": 10, "text": "x a", "size": 12, "area": {"width": width, "height": 16}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + assert_eq!((plain(&app, a), plain(&app, b)), ("x a".to_string(), String::new())); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 2, "caret": 3})); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[index].center()); + assert_eq!((plain(&app, a), plain(&app, b)), ("x ".to_string(), "a".to_string()), "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &json!(b)), [wide]); + assert_eq!(super::super::character::text_editing(&app), Some((NodeId(b), 0, 1)), "the character stays selected"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// In Entire Font, a glyph no character maps whose substitutions give other glyphs has the /// corner triangle too: its pop-up lists it and those glyphs, and a pick goes on the selected /// character as a double-click on that glyph's cell would put it. From 81556496f525ad72c2e46614bf21a787463e4eae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:46:22 -0800 Subject: [PATCH 5/5] Glyphs: the end-of-frame pick test measures its frame with the test font's own characters The test set its first frame to 20 by 16 pt and relied on a fallback face for the ideographs. With craft-fonts loaded, the CJK fallback face makes the line with the ideograph taller than the frame, so the frame held only the "a". The test now uses the characters a, x and space, which the test font maps, and sets the frame width from their advances. --- crates/ui-egui/src/panels/glyphs.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 755983151e..155c12ac2f 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -2232,10 +2232,15 @@ mod tests { use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let face = FontDb::global().face(alternates_family(true), "Regular").expect("the test face"); + let gid = |c| face.chars().into_iter().find(|(x, _)| *x == c).map(|(_, g)| g).expect("a glyph"); + let pt = |c| face.advance(gid(c)) * 12.0 / face.units_per_em(); + // The first frame holds the line "a xx " and not the next word. Every character is in the + // test font, so no fallback face measures the line. + let width = pt('a') + 2.0 * pt(' ') + 2.0 * pt('x') + pt('x') / 2.0; let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); - // The first frame is wide enough for "a" and one ideograph only. - let area = json!({"x": 10, "y": 10, "text": "a中中中", "size": 12, "area": {"width": 20, "height": 16}}); + let area = json!({"x": 10, "y": 10, "text": "a xx xx", "size": 12, "area": {"width": width, "height": 16}}); let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); for id in [a, b] { @@ -2245,17 +2250,17 @@ mod tests { NodeKind::Text(t) => t.plain_text(), _ => panic!("text"), }; - assert_eq!((plain(&app, a), plain(&app, b)), ("a中".to_string(), "中中".to_string())); + assert_eq!((plain(&app, a), plain(&app, b)), ("a xx ".to_string(), "xx".to_string())); app.run("select.set", json!({"ids": [a]})).unwrap(); app.session.select_tool("type", Default::default()).unwrap(); - let end = "a中".len(); + let end = "a xx ".len(); app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": end, "caret": end})); let ctx = egui::Context::default(); set_pstate(&ctx, "gl-subset", 1usize); let undo = app.session.active().unwrap().history.undo.len(); let popup = open_corner_popup(&ctx, &mut app); click(&ctx, &mut app, popup[3].center()); - assert_eq!((plain(&app, a), plain(&app, b)), ("a中".to_string(), "a中中".to_string()), "status: {}", app.ui.status); + assert_eq!((plain(&app, a), plain(&app, b)), ("a xx ".to_string(), "axx".to_string()), "status: {}", app.ui.status); assert_eq!(glyph_ids(&app, &json!(b))[0], u2); assert_eq!(super::super::character::text_editing(&app), Some((NodeId(b), 1, 1)), "the caret is after the character"); assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step");