diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 28662f013c..541cdd1118 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -53,6 +53,15 @@ pub fn specs() -> Vec { always, font_list ), + cmd!( + query "text.glyphCategories", + "Glyph Categories", + [], + None, + "{family, style?} the OpenType categories of the font's glyphs, what the Glyphs panel's Show menu lists after Alternates for Current Selection: from the font's GSUB table, the glyphs that the single, alternate, multiple and ligature substitutions of each kind's features give, each glyph once by id, in this order: `ligatures` (liga, dlig, hlig), `swashes` (swsh, cswh), `stylisticAlternates` (salt), `ss01` to `ss20`, `smallCaps` (smcp, c2sc), `ornaments` (ornm), `fractions` (frac, afrc, numr, dnom) and `figures` (lnum, onum, pnum, tnum); a kind without glyphs is left out; contextual lookups are not followed → {family, style, categories: [{id, name?: a stylistic set's name in the font, glyphs: [glyph id]}]} (style omitted: the family's first style; an error when the family or style isn't available)", + always, + glyph_categories + ), cmd!( "text.rescanFonts", "Refresh Font List", @@ -1137,6 +1146,44 @@ fn font_list(_: &mut Session, p: &Value) -> Result { } } +/// `text.glyphCategories`: the OpenType categories of a font's glyphs +/// ([`vectorcraft_text::FontFace::glyph_categories`]). +fn glyph_categories(_: &mut Session, p: &Value) -> Result { + const C: &str = "text.glyphCategories"; + let text = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.as_str())), + Some(_) => Err(bad(C, format!("`{key}` must be a string"))), + }; + let family = text("family")?.ok_or_else(|| bad(C, "missing `family`"))?; + let db = vectorcraft_text::FontDb::global(); + if !db.has_family(family) { + return Err(bad(C, format!("font family `{family}` is not available"))); + } + let styles = db.styles(family); + let style = match text("style")? { + Some(style) => styles + .iter() + .find(|s| s.eq_ignore_ascii_case(style)) + .cloned() + .ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?, + None => styles.first().cloned().unwrap_or_else(|| "Regular".into()), + }; + let face = db.face(family, &style).ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?; + let categories: Vec = face + .glyph_categories() + .iter() + .map(|c| { + let mut v = json!({"id": c.kind.id(), "glyphs": c.glyphs}); + if let Some(name) = &c.name { + v["name"] = json!(name); + } + v + }) + .collect(); + Ok(json!({"family": face.family, "style": face.style, "categories": categories})) +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f445237d83..6c7be12540 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -624,6 +624,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.fonts", "text.getRange", "text.glyphAlternates", + "text.glyphCategories", "text.insertInline", "text.missingFonts", "text.replaceFont", diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 6202a8ce70..5eb059bd3b 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -49,6 +49,41 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() { assert!(!d.is_dirty(), "nothing to save"); } +/// `text.glyphCategories` lists the kinds of glyph a font's OpenType features give, with a +/// stylistic set's name, and refuses a font that isn't available and params that aren't strings. +#[test] +fn glyph_categories_list_the_glyphs_of_each_kind_of_feature() { + use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid}; + FontDb::global().add_font(categories_font().expect("the test font builds")); + let mut s = Session::new(); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let mut figures = vec![g('7'), g('8')]; + figures.sort_unstable(); + let r = s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY})).unwrap(); + assert_eq!(r["family"], CATEGORIES_FAMILY); + assert_eq!(r["style"], "Regular"); + assert_eq!( + r["categories"], + json!([ + {"id": "ligatures", "glyphs": [g('L')]}, + {"id": "ss02", "name": "Round Dots", "glyphs": [g('G')]}, + {"id": "smallCaps", "glyphs": [g('B')]}, + {"id": "figures", "glyphs": figures}, + ]) + ); + assert_eq!(s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY, "style": "regular"})).unwrap(), r); + for (p, says) in [ + (json!({}), "missing `family`"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": "Black"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": true}), "`style` must be a string"), + ] { + let e = s.execute("text.glyphCategories", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } +} + /// Refreshing the font list while a background save writes the file leaves the document saved /// once the file is written. #[test] diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index e96e1d0fae..b45564c887 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -54,7 +54,7 @@ pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins}; pub(crate) use glyph_pen::FlipPen; -pub use gsub::{GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index a245efeea2..a88d4ed86a 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -94,6 +94,211 @@ pub(super) struct GsubIndex { /// The first feature, listed ones first, that gives each glyph: by a single, multiple, /// alternate or ligature substitution, and the glyph it replaces (not known for a ligature). reached: HashMap)>, + /// The face's glyph categories ([`FontFace::glyph_categories`]), read the first time they are + /// asked for. + categories: std::sync::OnceLock>, +} + +/// A kind of glyph that the Glyphs panel's Show menu lists by OpenType feature +/// ([`FontFace::glyph_categories`]). The kinds, the features in each and their order are +/// VectorCraft's own. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum GlyphCategoryKind { + /// `liga`, `dlig` and `hlig`. + Ligatures, + /// `swsh` and `cswh`. + Swashes, + /// `salt`. + StylisticAlternates, + /// One of `ss01` to `ss20`, by its number. + StylisticSet(u8), + /// `smcp` and `c2sc`. + SmallCaps, + /// `ornm`. + Ornaments, + /// `frac`, `afrc`, `numr` and `dnom`. + Fractions, + /// `lnum`, `onum`, `pnum` and `tnum`. + Figures, +} + +impl GlyphCategoryKind { + /// Every kind in the order the Show menu lists them, the stylistic sets by number. + pub fn all() -> Vec { + let sets = (1..=20).map(Self::StylisticSet); + [Self::Ligatures, Self::Swashes, Self::StylisticAlternates] + .into_iter() + .chain(sets) + .chain([Self::SmallCaps, Self::Ornaments, Self::Fractions, Self::Figures]) + .collect() + } + + /// The `GSUB` features whose substitutions give the kind's glyphs. + pub fn features(self) -> Vec<[u8; 4]> { + match self { + Self::Ligatures => vec![*b"liga", *b"dlig", *b"hlig"], + Self::Swashes => vec![*b"swsh", *b"cswh"], + Self::StylisticAlternates => vec![*b"salt"], + Self::StylisticSet(n) => { + let [a, b] = [b'0' + n / 10 % 10, b'0' + n % 10]; + vec![[b's', b's', a, b]] + } + Self::SmallCaps => vec![*b"smcp", *b"c2sc"], + Self::Ornaments => vec![*b"ornm"], + Self::Fractions => vec![*b"frac", *b"afrc", *b"numr", *b"dnom"], + Self::Figures => vec![*b"lnum", *b"onum", *b"pnum", *b"tnum"], + } + } + + /// The kind's id: `ligatures`, `swashes`, `stylisticAlternates`, `ss01` to `ss20`, `smallCaps`, + /// `ornaments`, `fractions` or `figures`. + pub fn id(self) -> String { + match self { + Self::Ligatures => "ligatures".into(), + Self::Swashes => "swashes".into(), + Self::StylisticAlternates => "stylisticAlternates".into(), + Self::StylisticSet(n) => format!("ss{n:02}"), + Self::SmallCaps => "smallCaps".into(), + Self::Ornaments => "ornaments".into(), + Self::Fractions => "fractions".into(), + Self::Figures => "figures".into(), + } + } + + /// The kind whose [`Self::id`] is `id`. + pub fn from_id(id: &str) -> Option { + Self::all().into_iter().find(|k| k.id() == id) + } +} + +/// The glyphs of one [`GlyphCategoryKind`] that a face has ([`FontFace::glyph_categories`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GlyphCategory { + pub kind: GlyphCategoryKind, + /// A stylistic set's name from the font's `name` table, when the font gives one. + pub name: Option, + /// The glyphs the kind's features give, each once, by glyph id. + pub glyphs: Vec, +} + +/// Read `face`'s glyph categories ([`FontFace::glyph_categories`]). The caps of [`GsubIndex::read`] +/// bound what a damaged table makes it read, and all the lookups together give at most +/// `MAX_ENTRIES` glyphs. +fn read_categories(face: &FontFace) -> Vec { + let Some(font) = face.skrifa() else { return vec![] }; + let Ok(gsub) = font.gsub() else { return vec![] }; + let (Ok(features), Ok(lookups)) = (gsub.feature_list(), gsub.lookup_list()) else { return vec![] }; + let glyphs = font.maxp().map_or(0, |m| u32::from(m.num_glyphs())); + let kinds = GlyphCategoryKind::all(); + // The lookups of each kind's features, in every script's feature records. + let mut wanted: Vec> = vec![vec![]; kinds.len()]; + let mut total = 0_usize; + for record in features.feature_records().iter().take(MAX_FEATURES) { + let tag = record.feature_tag().to_be_bytes(); + let Some(k) = kinds.iter().position(|kind| kind.features().contains(&tag)) else { continue }; + let Ok(feature) = record.feature(features.offset_data()) else { continue }; + for i in feature.lookup_list_indices().iter().take(MAX_FEATURE_LOOKUPS) { + if total >= MAX_LOOKUPS { + break; + } + if !wanted[k].contains(&i.get()) { + wanted[k].push(i.get()); + total += 1; + } + } + } + let all = lookups.lookups(); + let mut reads = MAX_SUBTABLE_READS; + // What each lookup gives, read once when several kinds share it. + let mut read: HashMap> = HashMap::new(); + // The glyphs all the lookups read together may give: at most `MAX_ENTRIES`. + let mut left = MAX_ENTRIES; + let mut outputs = |lookup: u16, reads: &mut usize| -> Vec { + if let Some(out) = read.get(&lookup) { + return out.clone(); + } + // A lookup not read yet once the read budget is spent gives nothing, and is not cached. + if *reads == 0 || left == 0 { + return vec![]; + } + // Each subtable adds only what still fits in what is left of the glyph budget. + let cap = left; + let mut out: Vec = vec![]; + // The glyphs an earlier subtable of the lookup covers: OpenType applies the first subtable + // that covers a glyph, so a later one's substitution of it is never made. + let mut covered: std::collections::HashSet = std::collections::HashSet::new(); + let mut first = |from: u32| covered.insert(from); + if let Ok(subtables) = all.get(usize::from(lookup)).and_then(|l| l.subtables()) { + let n = MAX_SUBTABLES.min(*reads); + let room = |out: &Vec| cap.saturating_sub(out.len()); + match subtables { + SubstitutionSubtables::Single(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(single_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).map(|(_, to)| to).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Alternate(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(alternate_sets(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, set)| set).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Multiple(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(multiple_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, to)| to).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Ligature(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(ligature_glyphs(&t, r).into_iter().take(r)); + if room(&out) == 0 { + break; + } + } + } + _ => {} + } + } + left = left.saturating_sub(out.len()); + read.insert(lookup, out.clone()); + out + }; + let names = face.stylistic_sets(); + let mut categories = vec![]; + for (kind, lookups) in kinds.into_iter().zip(wanted) { + let mut found: Vec = vec![]; + for lookup in lookups { + let room = MAX_ENTRIES.saturating_sub(found.len()); + found.extend(outputs(lookup, &mut reads).into_iter().filter(|g| *g != 0 && *g < glyphs).take(room)); + if found.len() >= MAX_ENTRIES { + break; + } + } + found.sort_unstable(); + found.dedup(); + found.truncate(MAX_ENTRIES); + if found.is_empty() { + continue; + } + let name = match kind { + GlyphCategoryKind::StylisticSet(n) => names.iter().find(|s| s.number == n).and_then(|s| s.name.clone()), + _ => None, + }; + categories.push(GlyphCategory { kind, name, glyphs: found }); + } + categories } /// The glyph single substitution `t` puts in place of each glyph its coverage holds. @@ -383,4 +588,70 @@ impl FontFace { let name = font.glyph_names().get(skrifa::GlyphId::new(gid))?; (!name.is_synthesized()).then(|| name.as_str().to_string()) } + + /// The kinds of glyph the face's `GSUB` table gives ([`GlyphCategoryKind`]), in the order of + /// [`GlyphCategoryKind::all`], each with the glyphs that the single, alternate, multiple and + /// ligature substitutions of its features put in place of others (in extension lookups too), + /// each glyph once by id, `.notdef` and ids past the face's glyph count left out. A single, + /// alternate or multiple substitution of a glyph an earlier subtable of its lookup covers is + /// left out, since that substitution is never made. A kind + /// without glyphs is left out. A stylistic set takes its name from the font's `name` table, + /// when the font gives one. Contextual lookups are not followed, nor is the choice of a + /// variable font's instance of `FeatureVariations`. Read once for the face; empty when it has + /// no `GSUB` table or the table cannot be read. + pub fn glyph_categories(&self) -> &[GlyphCategory] { + self.gsub_index().categories.get_or_init(|| read_categories(self)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The test font lists ligatures, stylistic set 2 with its name, small caps and figures, by + /// glyph id; its `cswh` feature has no lookups, so it lists no swashes, and small caps leave out + /// the C of a substitution an earlier subtable shadows. + #[test] + fn categories_list_the_glyphs_each_kind_of_feature_gives() { + use crate::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid}; + let db = super::super::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(categories_font().expect("the test font builds")), 1); + let face = db.face(CATEGORIES_FAMILY, "Regular").expect("the test face"); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let mut figures = vec![g('7'), g('8')]; + figures.sort_unstable(); + let found: Vec<(String, Option, Vec)> = + face.glyph_categories().iter().map(|c| (c.kind.id(), c.name.clone(), c.glyphs.clone())).collect(); + assert_eq!( + found, + [ + ("ligatures".to_string(), None, vec![g('L')]), + ("ss02".to_string(), Some("Round Dots".to_string()), vec![g('G')]), + ("smallCaps".to_string(), None, vec![g('B')]), + ("figures".to_string(), None, figures), + ] + ); + assert!(std::ptr::eq(face.glyph_categories(), face.glyph_categories()), "read once"); + } + + /// A face whose `GSUB` table has no features has no categories. + #[test] + fn a_face_without_features_has_no_categories() { + use crate::test_fonts::{HALF_FORM_FAMILY, half_form_font}; + let db = super::super::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(half_form_font(false).expect("the test font builds")), 1); + let face = db.face(HALF_FORM_FAMILY, "Regular").expect("the test face"); + assert!(face.glyph_categories().is_empty()); + } + + #[test] + fn kinds_round_trip_through_their_ids() { + for kind in GlyphCategoryKind::all() { + assert_eq!(GlyphCategoryKind::from_id(&kind.id()), Some(kind)); + } + assert_eq!(GlyphCategoryKind::StylisticSet(7).features(), [*b"ss07"]); + assert_eq!(GlyphCategoryKind::StylisticSet(20).features(), [*b"ss20"]); + assert_eq!(GlyphCategoryKind::from_id("ss21"), None); + assert_eq!(GlyphCategoryKind::from_id("Ligatures"), None); + } } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..d9b4fb47b5 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -41,10 +41,10 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use fontdb::{ - CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, JoiningPosition, - LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, - user_font_dirs, + CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, GlyphCategoryKind, + GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, + WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, + style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d17ce78603..578651672f 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -901,6 +901,66 @@ pub fn capped_candidates_font() -> Option> { Some(builder.build()) } +/// The family of [`categories_font`]. +pub const CATEGORIES_FAMILY: &str = "Categorytest Sans"; + +/// The bundled Source Sans 3 Regular, its `cmap` kept, with a `GSUB` table of a `liga` ligature of +/// f and i into L, an `onum` alternate substitution of 1 by 7 and 8, an `smcp` single substitution +/// of a by B (a second subtable's substitution of a by C is shadowed by it), an `ss02` single substitution of g by G named "Round Dots" (name id 256), and a +/// `cswh` feature without lookups. Family [`CATEGORIES_FAMILY`]. `None` when it can't be built. +pub fn categories_font() -> Option> { + use write_fonts::tables::gsub::{ + AlternateSet, AlternateSubstFormat1, Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SingleSubst, SingleSubstFormat2, SubstitutionLookup, + SubstitutionLookupList, + }; + use write_fonts::tables::layout::{ + CoverageFormat1, Feature, FeatureList, FeatureParams, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord, StylisticSetParams, + }; + use write_fonts::types::GlyphId16; + + let font = skrifa::FontRef::new(SOURCE_SANS).ok()?; + let charmap = font.charmap(); + let name = name_table(&[ + (1, CATEGORIES_FAMILY), + (2, "Regular"), + (4, "Categorytest Sans Regular"), + (6, "CategorytestSans-Regular"), + (256, "Round Dots"), + ])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let cover = |c| Some(CoverageFormat1::new(vec![gid(c)?])); + let single = |from, to| Some(SingleSubst::from(SingleSubstFormat2::new(cover(from)?.into(), vec![gid(to)?]))); + let liga = LigatureSubstFormat1::new(cover('f')?.into(), vec![LigatureSet::new(vec![Ligature::new(gid('L')?, vec![gid('i')?])])]); + let onum = AlternateSubstFormat1::new(cover('1')?.into(), vec![AlternateSet::new(vec![gid('7')?, gid('8')?])]); + let lookups = SubstitutionLookupList::new(vec![ + SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![liga])), + SubstitutionLookup::Alternate(Lookup::new(Default::default(), vec![onum])), + // The second subtable's substitution of a is never made: the first one covers a. + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('a', 'B')?, single('a', 'C')?])), + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('g', 'G')?])), + ]); + let named = Some(FeatureParams::StylisticSet(StylisticSetParams::new(NameId::new(256)))); + // Features sorted by tag, as OpenType requires. + let records = vec![ + FeatureRecord::new(Tag::new(b"cswh"), Feature::new(None, vec![])), + FeatureRecord::new(Tag::new(b"liga"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"onum"), Feature::new(None, vec![1])), + FeatureRecord::new(Tag::new(b"smcp"), Feature::new(None, vec![2])), + FeatureRecord::new(Tag::new(b"ss02"), Feature::new(named, vec![3])), + ]; + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0, 1, 2, 3, 4])), vec![]))]); + builder.add_table(&Gsub::new(scripts, FeatureList::new(records), lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`joining_alternates_font`]. pub const JOINING_ALTERNATES_FAMILY: &str = "Jointest Sans"; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a6a69d9100..922e0d854f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3574,6 +3574,9 @@ digits Malayalam Малаялам Show Import Options Показване на опциите за импортиране Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Питане за опциите за импортиране на всеки PDF, DXF или текстов файл преди поставянето му; изключено: използват се последно избраните опции Stylistic Alternates Стилистични алтернативи + Ligatures Лигатури + Ornaments Орнаменти + Figures Цифри Set {n} Набор {n} Swash Декоративен елемент Swatch Conflict Конфликт на образци diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5da48b6cff..db4923e526 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2035,6 +2035,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Odaberite tekst da postavite njegove OpenType mogućnosti. Standard Ligatures Standardne ligature Stylistic Alternates Stilske alternative + Ligatures Ligature + Ornaments Ornamenti + Figures Brojke Set {n} Skup {n} Swash Ukrasni potez Tabular Lining Tabelarne brojke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e861e61fec..aca3d80f3b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4667,6 +4667,9 @@ digits Malayalam Malaiàlam Show Import Options Mostra les opcions d’importació Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demana les opcions d’importació de cada fitxer PDF, DXF o de text abans de col·locar-lo; desactivat: s’usen les últimes opcions triades Stylistic Alternates Alternatives estilístiques + Ligatures Lligadures + Ornaments Ornaments + Figures Xifres Swash Volada Swatch Conflict Conflicte de mostres Swatch Conflicts Conflictes de mostres diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1a4d359b93..bad5c0f127 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2109,6 +2109,9 @@ digits Malayalam Malajálamské Select text to set its OpenType features. Vyberte text, abyste mohli nastavit jeho funkce OpenType. Standard Ligatures Standardní ligatury Stylistic Alternates Stylistické alternativy + Ligatures Ligatury + Ornaments Ornamenty + Figures Číslice Swash Ozdobné tvary Tabular Lining Tabulkové verzálkové Tabular Oldstyle Tabulkové minuskové diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 723766f020..5ff1b8726a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2532,6 +2532,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Markér tekst for at angive dens OpenType-funktioner. Standard Ligatures Standardligaturer Stylistic Alternates Stilistiske alternativer + Ligatures Ligaturer + Ornaments Ornamenter + Figures Cifre Set {n} Sæt {n} Swash Sving Tabular Lining Tabulære versalcifre diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21a07e09e5..ac0c3f4309 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3636,6 +3636,9 @@ effect Points Punkte Show Import Options Importoptionen anzeigen Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Vor dem Platzieren nach den Importoptionen jeder PDF-, DXF- oder Textdatei fragen; aus: die zuletzt gewählten Optionen verwenden Stylistic Alternates Stilistische Varianten + Ligatures Ligaturen + Ornaments Ornamente + Figures Ziffern Swash Schwungschrift Swatch Conflict Farbfeldkonflikt Swatch Conflicts Farbfeldkonflikte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ebd167f397..e117d1b3e7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2209,6 +2209,9 @@ font-technology Variable Μεταβλητές Superscript Εκθέτης Superscript: Εκθέτης: Stylistic Alternates Εναλλακτικοί χαρακτήρες στυλ + Ligatures Συμπλέγματα χαρακτήρων + Ornaments Κοσμήματα + Figures Αριθμοί Swash Διακοσμητικά τελειώματα Swatches Δείγματα χρωμάτων New Group Νέα ομάδα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 27d7d4aaf8..2ca472a528 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3666,6 +3666,9 @@ digits Malayalam Malayálam Show Import Options Mostrar opciones de importación Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Preguntar las opciones de importación de cada archivo PDF, DXF o de texto antes de colocarlo; desactivado: usar las últimas opciones elegidas Stylistic Alternates Alternativas estilísticas + Ligatures Ligaduras + Ornaments Ornamentos + Figures Cifras Swash Decorativa Swatch Conflict Conflicto de muestras Swatch Conflicts Conflictos de muestras diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3f29fd7f7a..7792f5edce 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2070,6 +2070,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Valitse teksti, jonka OpenType-ominaisuudet haluat asettaa. Standard Ligatures Vakioligatuurit Stylistic Alternates Tyylivaihtoehdot + Ligatures Ligatuurit + Ornaments Ornamentit + Figures Numerot Swash Koukerot Tabular Lining Taulukkonumerot Tabular Oldstyle Vanhanaikaiset taulukkonumerot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20e94749c5..33ac258c2d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3658,6 +3658,9 @@ digits Malayalam Malayalam Show Import Options Afficher les options d’importation Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demander les options d’importation de chaque fichier PDF, DXF ou texte avant de le placer, sinon utiliser les dernières options choisies Stylistic Alternates Variantes stylistiques + Ligatures Ligatures + Ornaments Ornements + Figures Chiffres Swash Lettres ornées Swatch Conflict Conflit de nuances Swatch Conflicts Conflits de nuances diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ff59a464c5..011f73a64c 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3768,6 +3768,9 @@ Styling: સ્ટાઇલિંગ: Stylistic સ્ટાઇલિસ્ટિક Stylistic Alternates સ્ટાઇલિસ્ટિક વિકલ્પી + Ligatures લિગેચર્સ + Ornaments અલંકારો + Figures અંકો Stylistic Sets સ્ટાઇલિસ્ટિક સેટ Stylize સ્ટાઇલાઇઝ Subdivisions ઉપવિભાગો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6fe8f254f4..8cdf86d7ff 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5013,6 +5013,9 @@ antiAlias Sharp शार्प Styling: स्टाइल: Stylistic स्टाइलिस्ट Stylistic Alternates शैलीगत ऑप्शन + Ligatures लिगेचर + Ornaments अलंकरण + Figures अंक Stylistic Sets स्टाइलिस्टिक सेट्स Stylize शैलीबद्ध करें Subdivisions उप-विभाजन diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a93411b47..dd65c65cb4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4361,6 +4361,9 @@ mark-style Japanese Japán Show Import Options Importálási beállítások megjelenítése Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Elhelyezés előtt rákérdez minden PDF-, DXF- vagy szövegfájl importálási beállításaira; kikapcsolva a legutóbb választott beállításokat használja Stylistic Alternates Stilisztikai változatok + Ligatures Ligatúrák + Ornaments Díszek + Figures Számjegyek Swash Cifra változatok Swatch Conflict Színminta-ütközés Swatch Conflicts Színminta-ütközések diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bf029526f7..00012d12fc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1866,6 +1866,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Pilih teks untuk mengatur fitur OpenType-nya. Standard Ligatures Ligatur standar Stylistic Alternates Alternatif gaya + Ligatures Ligatur + Ornaments Ornamen + Figures Angka Set {n} Set {n} Swash Swash Tabular Lining Lining tabular diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 360ec1d5ba..894e502236 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3712,6 +3712,9 @@ digits Malayalam Malayalam Show Import Options Mostra opzioni di importazione Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Chiedi le opzioni di importazione di ogni file PDF, DXF o di testo prima di inserirlo; disattivato: usa le ultime opzioni scelte Stylistic Alternates Alternative stilistiche + Ligatures Legature + Ornaments Ornamenti + Figures Cifre Swash Ornamentale Swatch Conflict Conflitto campioni Swatch Conflicts Conflitti campioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37089bb835..9b42649b67 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3412,6 +3412,9 @@ mark-style Japanese 日本式 Swap Fill and Stroke 塗りと線を入れ替え Swap start and end arrowheads 始点と終点の矢印を入れ替え Stylistic Alternates スタイル代替字 + Ligatures 合字 + Ornaments 装飾 + Figures 数字 Swash スワッシュ Swatch Conflict スウォッチの競合 Swatch Conflicts スウォッチの競合 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25fb4f87ed..b6eeb283db 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3923,6 +3923,9 @@ digits Malayalam მალაიალამური Select text to set its OpenType features. OpenType შესაძლებლობების დასაყენებლად მონიშნეთ ტექსტი. Standard Ligatures სტანდარტული ლიგატურები Stylistic Alternates სტილისტური ალტერნატივები + Ligatures ლიგატურები + Ornaments ორნამენტები + Figures ციფრები Swash მოხატული ასოები (swash) Tabular Lining ცხრილური ხაზოვანი Tabular Oldstyle ცხრილური ძველებური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0787180a1c..69e7fde641 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3401,6 +3401,9 @@ mark-style Japanese 일본식 Swap Fill and Stroke 칠과 선 바꾸기 Swap start and end arrowheads 시작과 끝 화살촉 바꾸기 Stylistic Alternates 스타일 대체 글자 + Ligatures 합자 + Ornaments 장식 + Figures 숫자 Swash 스워시 Swatch Conflict 견본 충돌 Swatch Conflicts 견본 충돌 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ab30a3639f..793363b741 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2428,6 +2428,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Selecteer tekst om de OpenType-functies in te stellen. Standard Ligatures Standaardligaturen Stylistic Alternates Stilistische alternatieven + Ligatures Ligaturen + Ornaments Ornamenten + Figures Cijfers Set {n} Set {n} Swash Swash Tabular Lining Tabulaire lining diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 085935a9bd..b0cb52b855 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2027,6 +2027,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Zaznacz tekst, aby ustawić jego funkcje OpenType. Standard Ligatures Ligatury standardowe Stylistic Alternates Alternatywy stylistyczne + Ligatures Ligatury + Ornaments Ornamenty + Figures Cyfry Swash Ozdobniki Tabular Lining Tabelaryczne nowoczesne Tabular Oldstyle Tabelaryczne nautyczne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0289161fe4..4b8043cb30 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3050,6 +3050,9 @@ digits Malayalam Malaiala Swap Fill and Stroke Trocar Preenchimento e Traçado Swap start and end arrowheads Trocar pontas de seta inicial e final Stylistic Alternates Variantes Estilísticas + Ligatures Ligações + Ornaments Ornamentos + Figures Algarismos Swash Ornamento Swatch Conflict Conflito de Amostra Swatch Conflicts Conflitos de Amostra diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e45ac9423a..729d308aa4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3698,6 +3698,9 @@ digits Malayalam Малаялам Show Import Options Показывать параметры импорта Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запрашивать параметры импорта каждого файла PDF, DXF или текстового файла перед помещением; если выключено, используются последние выбранные параметры Stylistic Alternates Стилистические альтернативы + Ligatures Лигатуры + Ornaments Орнаменты + Figures Цифры Swash Росчерк Swatch Conflict Конфликт образцов Swatch Conflicts Конфликты образцов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 95e7c34b47..4c8c718a61 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3588,6 +3588,9 @@ digits Malayalam Malayalam Show Import Options Visa importalternativ Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Fråga efter importalternativ för varje PDF-, DXF- eller textfil innan den placeras; av: använd de senast valda alternativen Stylistic Alternates Stilistiska alternativ + Ligatures Ligaturer + Ornaments Ornament + Figures Siffror Swash Swash Swatch Conflict Färgrutekonflikt Swatch Conflicts Färgrutekonflikter diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d8249b1c79..c0a5ece8c4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3444,6 +3444,9 @@ digits Malayalam Malayalam Show Import Options İçe Aktarma Seçeneklerini Göster Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Her PDF, DXF veya metin dosyasını yerleştirmeden önce içe aktarma seçeneklerini sor; kapalıyken son seçilen seçenekleri kullan Stylistic Alternates Stilistik Alternatifler + Ligatures Bitişik Harfler + Ornaments Süslemeler + Figures Rakamlar Swash çalkalama Swatch Conflict Renk Örneği Çatışması Swatch Conflicts Renk Örneği Çatışmaları diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8ebb97a5be..3f7148382d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3705,6 +3705,9 @@ effect Points Точки Show Import Options Показувати параметри імпорту Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запитувати параметри імпорту кожного файлу PDF, DXF чи текстового файлу перед розміщенням; якщо вимкнено, використовуються останні вибрані параметри Stylistic Alternates Стилістичні альтернативи + Ligatures Лігатури + Ornaments Орнаменти + Figures Цифри Swash Розчерк Swatch Conflict Конфлікт зразків Swatch Conflicts Конфлікти зразків diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a9a9cb140a..49af3b033f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4086,6 +4086,9 @@ mark-style Japanese Kiểu Nhật Show Import Options Hiện tùy chọn nhập Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Hỏi tùy chọn nhập của từng tệp PDF, DXF hoặc văn bản trước khi đặt; khi tắt, dùng các tùy chọn đã chọn gần nhất Stylistic Alternates Ký tự thay thế theo phong cách + Ligatures Chữ ghép + Ornaments Hoa văn + Figures Chữ số Swash Swash Swatch Conflict Xung đột mẫu màu Swatch Conflicts Xung đột mẫu màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3a87e6b84..a2a371e4b5 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3525,6 +3525,9 @@ digits Malayalam 马拉雅拉姆数字 Show Import Options 显示导入选项 Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前询问每个 PDF、DXF 或文本文件的导入选项;关闭时使用上次选择的选项 Stylistic Alternates 风格替代字 + Ligatures 连字 + Ornaments 装饰字 + Figures 数字 Swash 花饰字 Swatch Conflict 色板冲突 Swatch Conflicts 色板冲突 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52715f8360..9edc6c105b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4788,6 +4788,9 @@ digits Malayalam 馬來亞拉姆數字 Show Import Options 顯示讀入選項 Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前詢問每個 PDF、DXF 或文字檔案的讀入選項;關閉時使用上次選擇的選項 Stylistic Alternates 風格替代字 + Ligatures 連字 + Ornaments 裝飾字 + Figures 數字 Swash 花體字 Swatch Conflict 色票衝突 Swatch Conflicts 色票衝突 diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index cac85259f3..d99d4ad068 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -11,8 +11,11 @@ //! are drawn dimmed, and their tooltips say why they cannot be applied to the selection. //! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph //! form ([`glyph_form_items`]). +//! After its Unicode ranges and Alternates for Current Selection, the Show menu lists the OpenType +//! categories the browsed font has ([`vectorcraft_text::FontFace::glyph_categories`]): each shows +//! the glyphs its features give, as Entire Font shows them. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; @@ -72,6 +75,75 @@ const SUBSETS: [(&str, u32, u32); 7] = [ /// double-click the glyph to replace it). const ALTERNATES: &str = "Alternates for Current Selection"; +/// The Show menu's choice of an OpenType category of the browsed font, after [`ALTERNATES`]; the +/// panel state `gl-category` holds the category's id ([`vectorcraft_text::GlyphCategoryKind::id`]). +/// Public behavior: [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) +/// (with an OpenType font, a category chosen from the Show menu restricts the kinds of glyphs the +/// panel displays). Which categories are offered, their names and their order are ours. +const CATEGORY: usize = SUBSETS.len() + 1; + +/// The Show menu label of `category`: a stylistic set by the font's name for it, else `Set N`, as +/// the OpenType panel names it. +fn category_label(category: &vectorcraft_text::GlyphCategory) -> String { + use vectorcraft_text::GlyphCategoryKind as K; + match category.kind { + K::Ligatures => tl!("Ligatures").to_string(), + K::Swashes => tl!("Swash").to_string(), + K::StylisticAlternates => tl!("Stylistic Alternates").to_string(), + K::StylisticSet(number) => super::opentype::set_label(&vectorcraft_text::StylisticSet { number, name: category.name.clone() }), + K::SmallCaps => tl!("Small Caps").to_string(), + K::Ornaments => tl!("Ornaments").to_string(), + K::Fractions => tl!("Fractions").to_string(), + K::Figures => tl!("Figures").to_string(), + } +} + +/// The ids and Show menu labels of `face`'s OpenType categories, in the menu's order. +fn categories(face: Option<&vectorcraft_text::FontFace>) -> Vec<(String, String)> { + face.map(|f| f.glyph_categories().iter().map(|c| (c.kind.id(), category_label(c))).collect()).unwrap_or_default() +} + +/// The Show menu's choice: the entry index (a Unicode range, [`ALTERNATES`] or [`CATEGORY`]) and, +/// for a category, its place in `cats`. A category the browsed font does not have is Entire Font, +/// and so is an index past the entries. +fn shown(ctx: &egui::Context, cats: &[(String, String)]) -> (usize, Option) { + let subset: usize = pstate(ctx, "gl-subset"); + match subset { + CATEGORY => { + let id: String = pstate(ctx, "gl-category"); + match cats.iter().position(|c| c.0 == id) { + Some(i) => (CATEGORY, Some(i)), + None => (0, None), + } + } + s if s > CATEGORY => (0, None), + s => (s, None), + } +} + +/// Show category `id` of the browsed font. +fn show_category(ctx: &egui::Context, id: &str) { + set_pstate(ctx, "gl-category", id.to_string()); + set_pstate(ctx, "gl-subset", CATEGORY); +} + +/// The face the panel browses: the font picked in the panel, else the current text's font, else +/// the fallback family, with that family and style. The same family and style can have a different +/// face id at the selection's version or axes; that instance is used when the Type tool's selected +/// character is set in the font. +fn browsed_face(app: &VectorcraftApp, ctx: &egui::Context) -> (String, String, Option>) { + let db = FontDb::global(); + let current = super::character::text_style(app).map(|(s, _)| (s.font_family, s.font_style)); + // The panel browses the current text's font unless another font was picked here. + let picked: Option<(String, String)> = pstate(ctx, "gl-font"); + let (family, style) = picked.or(current).unwrap_or_else(|| (vectorcraft_text::FALLBACK_FAMILY.to_string(), "Regular".to_string())); + let face = selected_target(app) + .filter(|t| t.style.font_family.eq_ignore_ascii_case(&family) && t.style.font_style.eq_ignore_ascii_case(&style)) + .and_then(|t| db.style_face(t.style)) + .or_else(|| db.face(&family, &style)); + (family, style, face) +} + thread_local! { static TEX: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } @@ -226,41 +298,58 @@ fn insert(app: &mut VectorcraftApp, ctx: &egui::Context, ch: char) -> bool { /// Browse and insert glyphs from the chosen font, with font controls below the glyph grid. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - let db = FontDb::global(); - let current = super::character::text_style(app).map(|(s, _)| (s.font_family, s.font_style)); - // The panel browses the current text's font unless another font was picked here. - let picked: Option<(String, String)> = pstate(ui.ctx(), "gl-font"); - let (family, style) = picked.or(current).unwrap_or_else(|| (vectorcraft_text::FALLBACK_FAMILY.to_string(), "Regular".to_string())); - let subset: usize = pstate(ui.ctx(), "gl-subset"); + // The same family and style can have a different face id at the selection's version or axes. + // That instance is used for both the previews and Fit's applicability check. + let (family, style, face) = browsed_face(app, ui.ctx()); + let cats = categories(face.as_deref()); + let (subset, category) = shown(ui.ctx(), &cats); let (_, lo, hi) = SUBSETS[subset.min(SUBSETS.len() - 1)]; let w = ui.available_width(); - let names: Vec<&str> = SUBSETS.iter().map(|s| s.0).chain([ALTERNATES]).collect(); + // A stylistic set's name is the font's, shown as it is: the built-in labels are translated here. + let labels: Vec = + SUBSETS.iter().map(|s| tl!(s.0).to_string()).chain([tl!(ALTERNATES).to_string()]).chain(cats.iter().map(|c| c.1.clone())).collect(); + let names: Vec<&str> = labels.iter().map(String::as_str).collect(); + let current = match category { + Some(i) => CATEGORY + i, + None => subset, + }; ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Show:")).color(t.text_dim)); - if let Some(i) = widgets::dropdown(ui, "gl-subset", names[subset.min(names.len() - 1)], &names, (w - 50.0).max(80.0)) { - set_pstate(ui.ctx(), "gl-subset", i); + if let Some(i) = widgets::dropdown_names(ui, "gl-subset", names[current.min(names.len() - 1)], &names, (w - 50.0).max(80.0)) { + match i.checked_sub(CATEGORY).and_then(|k| cats.get(k)) { + Some((id, _)) => show_category(ui.ctx(), id), + None => set_pstate(ui.ctx(), "gl-subset", i), + } } }); - if subset >= SUBSETS.len() { + if subset == SUBSETS.len() { alternates(app, ui, w); font_row(app, ui, &family, &style, w); return; } - // The same family and style can have a different face id at the selection's version or axes. - // Use that instance for both the previews and Fit's applicability check. - let face = selected_target(app) - .filter(|t| t.style.font_family.eq_ignore_ascii_case(&family) && t.style.font_style.eq_ignore_ascii_case(&style)) - .and_then(|t| db.style_face(t.style)) - .or_else(|| db.face(&family, &style)); let Some(face) = face else { ui.label(egui::RichText::new(tl!("No fonts are available.")).color(t.text_dim)); return; }; - let chars: Vec<(char, u32)> = - face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect(); - // Entire Font also lists the glyphs no character maps (positional forms, alternates, - // ligatures) by glyph id, after the characters. - let unencoded = if subset == 0 { face.unencoded_glyphs() } else { Default::default() }; + let (chars, unencoded): (Vec<(char, u32)>, Vec) = match category.and_then(|i| face.glyph_categories().get(i)) { + // A category lists its glyphs that a character maps by that character, and the others by + // glyph id after them. + Some(c) => { + let wanted: HashSet = c.glyphs.iter().copied().collect(); + // A glyph several characters map is listed once, by the first of them; a glyph only a + // space or control character maps is listed by glyph id, as no character it can insert. + let mut mapped: HashSet = HashSet::new(); + let chars: Vec<(char, u32)> = + face.chars().into_iter().filter(|(c, g)| !c.is_control() && !c.is_whitespace() && wanted.contains(g) && mapped.insert(*g)).collect(); + (chars, c.glyphs.iter().copied().filter(|g| !mapped.contains(g)).collect()) + } + None => { + let chars = face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect(); + // Entire Font also lists the glyphs no character maps (positional forms, alternates, + // ligatures) by glyph id, after the characters. + (chars, if subset == 0 { face.unencoded_glyphs().to_vec() } else { vec![] }) + } + }; let total = chars.len() + unencoded.len(); let cell = CELL_STEPS[cell_index(app)]; let cols = ((w / cell).floor() as usize).max(1); @@ -1046,16 +1135,25 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { glyph_form_items(app, ui); ui.separator(); } + let (_, _, face) = browsed_face(app, ui.ctx()); + let cats = categories(face.as_deref()); + let (cur, category) = shown(ui.ctx(), &cats); for (i, (name, _, _)) in SUBSETS.iter().enumerate() { - let cur: usize = pstate(ui.ctx(), "gl-subset"); if menu_item(ui, tl!(name), true, cur == i) { set_pstate(ui.ctx(), "gl-subset", i); } } - let cur: usize = pstate(ui.ctx(), "gl-subset"); - if menu_item(ui, tl!("Alternates for Current Selection"), true, cur >= SUBSETS.len()) { + if menu_item(ui, tl!("Alternates for Current Selection"), true, cur == SUBSETS.len()) { set_pstate(ui.ctx(), "gl-subset", SUBSETS.len()); } + if !cats.is_empty() { + ui.separator(); + } + for (i, (id, label)) in cats.iter().enumerate() { + if menu_item(ui, label, true, category == Some(i)) { + show_category(ui.ctx(), id); + } + } } #[cfg(test)] @@ -1628,6 +1726,34 @@ mod tests { assert!(face.glyph_name(unencoded[0]).is_some(), "the font names its glyphs"); } + /// The panel menu lists the browsed font's OpenType categories after Alternates for Current + /// Selection, a stylistic set by the font's name for it; choosing one shows the glyphs its + /// features give and names it in Show. A font without that category shows Entire Font. + #[test] + fn the_show_menu_lists_the_fonts_opentype_categories() { + use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, HALF_FORM_FAMILY, categories_font, half_form_font}; + FontDb::global().add_font(categories_font().expect("the test font builds")); + FontDb::global().add_font(half_form_font(false).expect("the test font builds")); + let (mut app, _) = editing("a"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-font", Some((CATEGORIES_FAMILY.to_string(), "Regular".to_string()))); + let items: Vec = menu_texts(&ctx, &mut app, vec![]).into_iter().map(|(t, _)| t.trim_start_matches(['✓', ' ']).to_string()).collect(); + let at = items.iter().position(|t| t == "Alternates for Current Selection").expect("the alternates item"); + assert_eq!(items[at + 1..], ["Ligatures", "Round Dots", "Small Caps", "Figures"]); + choose(&ctx, &mut app, "Figures"); + assert_eq!(pstate::(&ctx, "gl-category"), "figures"); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "2 glyphs") && all.iter().any(|s| s == "Figures"), "{all:?}"); + choose(&ctx, &mut app, "Round Dots"); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "1 glyph") && all.iter().any(|s| s == "Round Dots"), "{all:?}"); + set_pstate(&ctx, "gl-font", Some((HALF_FORM_FAMILY.to_string(), "Regular".to_string()))); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "Entire Font") && !all.iter().any(|s| s == "Round Dots"), "{all:?}"); + let items: Vec = menu_texts(&ctx, &mut app, vec![]).into_iter().map(|(t, _)| t.trim_start_matches(['✓', ' ']).to_string()).collect(); + assert_eq!(items.last().map(String::as_str), Some("Alternates for Current Selection"), "{items:?}"); + } + #[test] fn zoom_stops_at_the_ends() { assert_eq!(nudge_cell(CELL_DEFAULT, 1), CELL_DEFAULT + 1); diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 5db4cfbd17..fe144edbf9 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -312,8 +312,9 @@ fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { } /// A Stylistic Sets menu entry: the font's own name for the set, shown as the font gives it, or -/// `Set 1` through `Set 20` in the UI language. -fn set_label(set: &StylisticSet) -> String { +/// `Set 1` through `Set 20` in the UI language. The Glyphs panel's Show menu names its stylistic +/// set entries the same way. +pub(super) fn set_label(set: &StylisticSet) -> String { match &set.name { Some(name) => name.clone(), None => crate::i18n::fmt(tl!("Set {n}"), &[("n", &set.number.to_string())]), diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..9b98451ce2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10213,6 +10213,24 @@ off. {"name":"run_command","arguments":{"command":"text.setGlyphAlternate","params":{"id":7,"start":2,"gid":1043}}} ``` +After Alternates for Current Selection, the Glyphs panel's Show menu and panel menu list the OpenType categories the +browsed font has, and choosing one shows the glyphs its features give: characters first, then glyphs no character maps, +which a double-click applies to the selected character as Entire Font does. `text.glyphCategories {family, style?}` +lists them: `{family, style, categories: [{id, name?, glyphs: [glyph id]}]}`, from the single, alternate, multiple and +ligature substitutions of the font's `GSUB` features, each glyph once, in this order: `ligatures` (`liga`, `dlig`, +`hlig`), `swashes` (`swsh`, `cswh`), `stylisticAlternates` (`salt`), `ss01` to `ss20`, `smallCaps` (`smcp`, `c2sc`), +`ornaments` (`ornm`), `fractions` (`frac`, `afrc`, `numr`, `dnom`) and `figures` (`lnum`, `onum`, `pnum`, `tnum`). A +category without glyphs is left out, a stylistic set carries the font's name for it as `name` when the font gives one +(the menu shows that name, else Set N), and contextual lookups are not followed. Without `style` the family's first +style is used. The command refuses a family or style that is not available and a `family` or `style` that is not a +string. The categories, their features, their names and their order are VectorCraft's own; the panel restricting its +glyphs to a category chosen from the Show menu is described in [Glyphs panel +overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html). + +```json +{"name":"run_command","arguments":{"command":"text.glyphCategories","params":{"family":"Source Sans 3","style":"Regular"}}} +``` + ### Alternates as OpenType feature values `text.setGlyphAlternate`'s choice swaps a glyph id into one character and shapes that character apart from its neighbours. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..14d8c0e5f9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1428,6 +1428,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Glyphs panel's Show menu and panel menu have Alternates for Current Selection, 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. The grid lists the selected character's alternate glyphs from `GSUB` single and alternate substitutions of `aalt`, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99` and a few other alternate features, each glyph once. A double-click applies the feature that draws the variant, or a glyph choice if no supported feature draws it, as detailed below. The list uses the font of the character's text even when the panel browses another font, and the panel shows a note when the character has no alternates, its font is missing or no character is selected; these rules are VectorCraft's own. Native files keep a glyph choice with the face it was made in; another font or version draws the default glyph. Tests: `panels::glyphs::tests`, `tests::alternates`, `tests::textedit::a_glyph_alternate_replaces_one_character_through_undo_and_reopen`. The Glyphs panel's Alternates for Current Selection (#5514) applies the OpenType feature that draws the glyph to the selected character alone, 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 (Alternates For Current Selection in the Show menu; double-click the glyph to replace the selected character). One deliberate difference from a literal reading: the text keeps the Unicode character and gains a character-style feature with a value (`salt=2`, `ss03`; `text.setRangeStyle {featureChanges}`) instead of taking an unencoded glyph in its place. The grid lists the alternates of the glyph the shaper makes for the character in its word (a medial letter shows its medial variants; the default glyph comes first and the current glyph is highlighted); a variant no supported feature draws there stays enabled as a replacement glyph (`text.setGlyphAlternate`, including positional alternates), and its tooltip says it may not join its neighbors; the default glyph takes the character's alternate features off again. Runs that differ only in their OpenType features are shaped as one piece of text, each run's features over its own characters, so the letters of an Arabic word keep their joining forms. Show › Entire Font also lists the glyphs no character maps, with the font's name for them (or `gid N`) and the feature that gives them. It applies the selected letter's contextual alternates the same way, and applies a glyph no feature reaches whose name does not belong to another letter as a glyph choice; other glyphs are dimmed with the reason. An Arabic presentation form picked there inserts its base letter. These rules are VectorCraft's own. Tests: `tests::glyph_alternates` in the text crate (a fixture font; Kufi Murabba PIIIX when it is installed), `panels::glyphs::tests` (including positional glyph choices, unlisted glyph name ownership, apply and Undo), `tests::textedit::feature_values_are_set_replaced_and_saved`. With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, 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 ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. + With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`.