DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #1012: Text: Digits setting in the Character panel and character styles; page numbers and list numbers follow it
aiongg3d0b778f5392
diff --cc crates/compose/src/lib.rsindex 60fa11cca,c959030e4..249603eb9--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -1161,13 -832,14 +1161,21 @@@ fn compose_with_db(doc: &Document, storNone}};- if let Some(label) = list_label {+ // The label's glyphs at the paragraph start, and how many of them (up to its first tab)+ // the list alignment places.+ let mut label_aligned = 0usize;+ let mut label_tab = false;+ if let Some(label) = &list_label {- let chars = label_chars(doc, &pp, &base_chars);++ let mut chars = label_chars(doc, &pp, &base_chars);+ // The number is drawn in the Digits of the paragraph's first run, so Persian text- // gets Persian numbers whether Digits is set on the paragraph style or on the text.- let mut label_chars = base_chars.clone();- if let Some((_, fmt)) = story.runs().find(|(rr, _)| rr.end > prange.start && rr.start < prange.end) {- label_chars.digits = doc.styles.resolve_char(&base_chars, fmt).digits;++ // gets Persian numbers whether Digits is set on the paragraph style or on the text++ // (unless the number's character style sets its own).++ if chars.digits == base_chars.digits++ && let Some((_, fmt)) = story.runs().find(|(rr, _)| rr.end > prange.start && rr.start < prange.end)++ {++ chars.digits = doc.styles.resolve_char(&base_chars, fmt).digits;+ }- let n = prepend_label(db, &mut sp.glyphs, &label, prange.start, &label_chars, label_env, &mut table);+ let n = prepend_label(db, &mut sp.glyphs, label, prange.start, &chars, label_env, &mut table);for g in sp.glyphs.iter_mut().take(n) {g.list_label = true;}diff --cc crates/compose/src/shape.rsindex f608c139f,3f034c97d..ffbc4857d--- a/crates/compose/src/shape.rs+++ b/crates/compose/src/shape.rs@@@ -873,15 -656,16 +861,16 @@@ fn shape_run_raw} else {sub.page_name.clone().unwrap_or_else(|| "#".into())};+ // Page numbers follow the text's Digits setting like typed figures do.+ let mode = digit_mode(p, arabic_context);+ let s: String = s.chars().map(|ch| mode.map(ch, &p.language)).collect();if s.is_empty() {// A section without marker text: the character takes no space.- let mut g = control_glyph(&primary, p, auto_leading, style, i, c);+ let mut g = control_glyph(&primary, p, auto_leading, styles.at(i), i, c);g.adv = 0.0;out.push(g);} else {- // Page numbers take the digits of the text they stand in.- let s: String = s.chars().map(|ch| digits.map(ch, &p.language)).collect();- shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, style, out, sub.vertical);+ shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, styles, out, sub.upright());}}designcraft_doc::OBJECT_MARK => {@@@ -1387,8 -1040,19 +1376,22 @@@ pub(crate) fn hyphen_after(g: &Glyph) -h.byte = g.byte + g.len;h.len = 0;h.ch = '-';+ h.rendered_char = '-';+ h.moji = Default::default();+ h.generated_text = None;h}++ /// How figures 0–9 are drawn for text with these properties: the Digits setting, or, when it is+ /// Default, by the preceding strong script (`Some(true)` Arabic-script, `Some(false)` other).+ fn digit_mode(p: &designcraft_doc::CharProps, arabic_context: Option<bool>) -> designcraft_doc::Digits {+ use designcraft_doc::Digits;+ if p.digits != Digits::Default {+ return p.digits;+ }+ match arabic_context {+ Some(false) => Digits::Arabic,+ Some(true) if Digits::Native.map('0', &p.language) == '0' => Digits::Hindi,+ _ => Digits::Native,+ }+ }diff --cc crates/compose/src/tests.rsindex 034c45f90,1aba2a3b9..ad22f577b--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -2041,25 -1668,24 +2041,43 @@@ fn digits_option_draws_figures_in_anothassert_ne!(gid(&plain, 4), gid(&hindi, 4));}+#[test]+fn page_numbers_take_the_digits_option() {+ use designcraft_fonts::testing::font_mapping;+ // Draws ١ as X, every other character as itself.+ let glyphs = [('N', 'N'), ('o', 'o'), ('.', '.'), (' ', ' '), ('1', '1'), ('\u{661}', 'X')];+ designcraft_fonts::FontDb::global().add_font(font_mapping("DC Test Page Digits", &glyphs).unwrap());+ // The glyph drawn at byte 4: the page number, or a typed Arabic-Indic one.+ let fourth = |text: &str| {+ let (mut d, sid, _) = doc_with(text, Rect::new(100.0, 100.0, 400.0, 200.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {+ f.over.font_family = Some("DC Test Page Digits".into());+ f.over.digits = Some(designcraft_doc::Digits::Hindi);+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ cs.frames[0].lines[0].glyphs.iter().find(|g| g.byte == 4).map(|g| g.gid).unwrap()+ };+ assert_eq!(fourth(&format!("No. {}", story::PAGE_NUMBER)), fourth("No. \u{661}"));+}++ #[test]+ fn digits_option_draws_page_numbers_and_list_numbers_in_that_script() {+ use designcraft_doc::{Digits, ListType};+ let gids = |text: &str, list: Option<ListType>, digits: Option<Digits>| {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs { list_type: list, ..Default::default() });+ if let Some(dg) = digits {+ let n = text.len();+ d.story_mut(sid).unwrap().format_chars(0..n, |f| f.over.digits = Some(dg));+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs)[0].glyphs.iter().map(|g| g.gid).collect::<Vec<_>>()+ };+ let pn = story::PAGE_NUMBER.to_string();+ assert_ne!(gids(&pn, None, None), gids(&pn, None, Some(Digits::Farsi)), "page number marker");+ // Digits set on the text (not on the paragraph style) reach the list number too.+ assert_ne!(gids("Item", Some(ListType::Numbers), None), gids("Item", Some(ListType::Numbers), Some(Digits::Farsi)), "list number");+ }+#[test]fn ruby_and_kenten_sit_over_their_text() {let mut d = Document::new(&designcraft_doc::build::NewDocument::default());diff --cc crates/ui-egui/src/dialogs.rsindex 935d88d26,a98febbc3..9b0961f4d--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -5195,116 -4188,123 +5195,132 @@@ fn basic_character_formats(app: &mut De});}-/// One parameter of a command, parsed from its params documentation-/// (`{name, type?: a|b|c, count?, flag?: bool, …}`).-#[derive(Clone, Debug, PartialEq)]-pub struct CommandField {- pub key: String,- pub optional: bool,- /// Enumerated values (`a|b|c`).- pub choices: Vec<String>,- pub boolean: bool,- /// The documented value spec (shown as a hint).- pub hint: String,-}--/// Parameters of a command from its documentation string: the top-level keys of the first `{…}`.-pub fn command_fields(doc: &str) -> Vec<CommandField> {- let Some(start) = doc.find('{') else { return vec![] };- let mut depth = 0i32;- let mut end = doc.len();- for (i, c) in doc[start..].char_indices() {- match c {- '{' | '[' | '(' => depth += 1,- '}' | ']' | ')' => {- depth -= 1;- if depth == 0 {- end = start + i;- break;+/// Advanced Character Formats: scaling, baseline shift, skew and language.+fn advanced_character_formats(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {+ egui::Grid::new("csa").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Horizontal Scale:"));+ char_number(ui, d, cf, "hScale", "%", 100.0, (1.0, 1000.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Vertical Scale:"));+ char_number(ui, d, cf, "vScale", "%", 100.0, (1.0, 1000.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Baseline Shift:"));+ char_number(ui, d, cf, "baselineShift", " pt", 1.0, (-5000.0, 5000.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Skew:"));+ char_number(ui, d, cf, "skew", "°", 1.0, (-85.0, 85.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Language:"));+ let opts: Vec<(Value, &str)> = crate::panels::properties::LANGUAGES.iter().map(|l| (json!(l), *l)).collect();+ char_choice(lang, ui, d, cf, "language", &opts);+ ui.end_row();++ // Digits (World-Ready): Farsi draws 0-9 as Persian ۰-۹.++ crate::rtl::label(ui, crate::i18n::tr(lang, "Digits:"));++ let labels: Vec<String> = crate::panels::properties::DIGIT_OPTIONS.iter().map(|o| crate::panels::properties::digit_label(lang, *o)).collect();++ let cur = cf.get(d, "digits");++ let shown = crate::panels::properties::DIGIT_OPTIONS.iter().position(|o| json!(o.0) == cur).map_or(String::new(), |i| labels[i].clone());++ egui::ComboBox::from_id_salt(("cs", "digits")).selected_text(crate::rtl::widget(ui, &shown)).width(200.0).show_ui(ui, |ui| {++ if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() {++ cf.set(d, "digits", Value::Null);++ }++ for (o, label) in crate::panels::properties::DIGIT_OPTIONS.iter().zip(&labels) {++ if ui.selectable_label(json!(o.0) == cur, crate::rtl::widget(ui, label)).clicked() {++ cf.set(d, "digits", json!(o.0));+ }+ }- _ => {}- }- }- let body = &doc[start + 1..end];- let mut parts = Vec::new();- let (mut depth, mut from) = (0i32, 0usize);- for (i, c) in body.char_indices() {- match c {- '{' | '[' | '(' => depth += 1,- '}' | ']' | ')' => depth -= 1,- ',' if depth == 0 => {- parts.push(&body[from..i]);- from = i + 1;++ });++ ui.end_row();+ });+}++/// Character Color: the fill or stroke swatch, its tint and the stroke weight.+fn character_color(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document) {+ let stroke = d.s("colorTarget") == "stroke";+ ui.horizontal(|ui| {+ for (target, label) in [("fill", "Fill"), ("stroke", "Stroke")] {+ if ui.selectable_label((target == "stroke") == stroke, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ d.fields.insert("colorTarget".into(), json!(target));}- _ => {}}- }- parts.push(&body[from..]);- let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !s.starts_with(|c: char| c.is_ascii_digit());- let mut out = Vec::new();- for part in parts {- // `key`, `key?`, `key: spec` or `key (spec)`: the key is the leading word.- let part = part.trim();- let k_end = part.find(|c: char| c.is_whitespace() || c == ':' || c == '(').unwrap_or(part.len());- let (k, rest) = part.split_at(k_end);- let rest = rest.trim_start();- let spec = match rest.strip_prefix(':') {- Some(v) => v.trim(),- None => rest.strip_prefix('(').and_then(|r| r.strip_suffix(')')).unwrap_or(rest).trim(),- };- let optional = k.ends_with('?');- let key = k.trim_end_matches('?');- if !ident(key) || out.iter().any(|f: &CommandField| f.key == key) {- continue;+ });+ let key = if stroke { "stroke" } else { "fill" };+ let cur = cf.get(d, key).as_str().unwrap_or("").to_string();+ egui::ScrollArea::vertical().id_salt(("cscolor", key)).max_height(220.0).show(ui, |ui| {+ for sw in &doc.swatches {+ let (c, g) = crate::widgets::swatch_colors(doc, &sw.name, 1.0);+ ui.horizontal(|ui| {+ let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover());+ crate::widgets::paint_chip(ui.painter(), r, c, g);+ if ui.selectable_label(sw.name == cur, &sw.name).clicked() {+ // A character style's chosen swatch, clicked again, is no longer set.+ cf.set(d, key, if cf.sparse && sw.name == cur { Value::Null } else { json!(sw.name) });+ }+ });}- let word = spec.split_whitespace().next().unwrap_or("");- let choices: Vec<String> =- if word.contains('|') && word.split('|').all(ident) { word.split('|').map(str::to_string).collect() } else { vec![] };- let boolean = spec.starts_with("bool") || spec.starts_with("true|false") || spec.starts_with("true") && spec.len() <= 5;- out.push(CommandField { key: key.into(), optional, choices: if boolean { vec![] } else { choices }, boolean, hint: spec.into() });- }- out+ });+ egui::Grid::new("cscg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));+ char_number(ui, d, cf, if stroke { "strokeTint" } else { "fillTint" }, "%", 100.0, (0.0, 100.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));+ char_number(ui, d, cf, "strokeWeight", " pt", 1.0, (0.0, 800.0));+ ui.end_row();+ ui.label("");+ char_check(ui, d, cf, "strokeBehindFill", crate::i18n::tr(lang, "Stroke Behind Fill"));+ ui.end_row();+ });}-fn humanize(key: &str) -> String {- let mut s = String::new();- for (i, c) in key.chars().enumerate() {- if i == 0 {- s.extend(c.to_uppercase());- } else if c.is_uppercase() {- s.push(' ');- s.extend(c.to_lowercase());- } else {- s.push(c);+/// OpenType Features: the feature switches, figure style and stylistic sets (one `otfFeatures`+/// list: changing any feature sets the whole list).+fn open_type_features(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {+ use designcraft_doc::otf;+ let mut list: Vec<String> =+ cf.get(d, "otfFeatures").as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();+ let mut changed = false;+ egui::Grid::new("csot").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| {+ for (i, (tag, label, _)) in otf::TOGGLES.iter().enumerate() {+ let mut on = otf::is_on(&list, tag);+ if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).changed() {+ otf::set(&mut list, tag, on);+ changed = true;+ }+ if i % 2 == 1 {+ ui.end_row();+ }}- }- s-}--/// A form for any command, from its parameter documentation.-fn command_form(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- let doc = designcraft_engine::find_command(&d.id[4..]).map_or("", |c| c.params);- let fields = command_fields(doc);- let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;- egui::Grid::new("cmdform").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- for f in &fields {- ui.label(crate::rtl::widget(- ui,- format!("{}{}", crate::i18n::tr(&app.ui.language, &humanize(&f.key)), if f.optional { "" } else { " *" }),- ));- if f.boolean {- check(ui, d, &f.key, "");- } else if !f.choices.is_empty() {- let mut opts: Vec<(&str, &str)> = vec![("", "—")];- let labels: Vec<_> = f.choices.iter().map(|c| humanize(c)).collect();- opts.extend(f.choices.iter().zip(&labels).map(|(value, label)| (value.as_str(), crate::i18n::tr(&app.ui.language, label))));- combo(ui, d, &f.key, &opts);- } else {- let mut s = d.s(&f.key);- let hint = if f.hint.is_empty() { String::new() } else { f.hint.clone() };- if ui.add(egui::TextEdit::singleline(&mut s).hint_text(egui::RichText::new(hint).color(dim)).desired_width(240.0)).changed() {- d.fields.insert(f.key.clone(), Value::String(s));+ });+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Figure Style:"));+ let fig = otf::figures(&list);+ let shown = otf::FIGURES.iter().find(|f| f.0 == fig).map_or("", |f| f.1);+ egui::ComboBox::from_id_salt("csfig").selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, shown))).width(180.0).show_ui(ui, |ui| {+ for (id, label, ..) in otf::FIGURES {+ if ui.selectable_label(fig == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() && otf::set_figures(&mut list, id)+ {+ changed = true;}}- ui.end_row();+ });+ });+ ui.add_space(4.0);+ crate::rtl::label(ui, crate::i18n::tr(lang, "Stylistic Sets"));+ let mask = otf::stylistic_sets(&list);+ egui::Grid::new("csss").num_columns(10).spacing([2.0, 2.0]).show(ui, |ui| {+ for n in 1..=20u32 {+ let bit = 1u32 << (n - 1);+ if ui.add_sized([28.0, 20.0], egui::Button::selectable(mask & bit != 0, format!("{n}"))).clicked() {+ otf::set_stylistic_sets(&mut list, mask ^ bit);+ changed = true;+ }+ if n % 10 == 0 {+ ui.end_row();+ }}});- if let Some(st) = d.fields.get("status").and_then(Value::as_str) {- ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));+ if changed {+ cf.set(d, "otfFeatures", json!(list));}}diff --cc crates/ui-egui/src/i18n.rsindex 6d4913c77,baa2df67d..3b8159714--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@@ -3231,36 -2513,31 +3231,37 @@@ const TABLE: &[(&str, [&str; 5])] = &),("Advanced Character Formats",- ["Advanced Character Formats", "Advanced Character Formats", "Advanced Character Formats", "Advanced Character Formats", "高级字符格式"],+ ["Advanced Character Formats", "Formats de caractère avancés", "Advanced Character Formats", "Advanced Character Formats", "高级字符格式"],),- ("OpenType Features", ["OpenType Features", "OpenType Features", "OpenType Features", "OpenType Features", "OpenType 功能"]),- ("Style Settings:", ["Style Settings:", "Style Settings:", "Style Settings:", "Style Settings:", "样式设置:"]),- ("Kerning:", ["Kerning:", "Kerning:", "Kerning:", "Kerning:", "字偶间距:"]),- ("Case:", ["Case:", "Case:", "Case:", "Case:", "大小写:"]),+ ("OpenType Features", ["OpenType Features", "Fonctions OpenType", "OpenType Features", "OpenType Features", "OpenType 功能"]),+ ("Style Settings:", ["Style Settings:", "Paramètres du style :", "Style Settings:", "Style Settings:", "样式设置:"]),+ ("Kerning:", ["Kerning:", "Crénage :", "Kerning:", "Kerning:", "字偶间距:"]),+ ("Case:", ["Case:", "Casse :", "Case:", "Case:", "大小写:"]),("OpenType All Small Caps",- ["OpenType All Small Caps", "OpenType All Small Caps", "OpenType All Small Caps", "OpenType All Small Caps", "OpenType 全部小型大写字母"],+ [+ "OpenType All Small Caps",+ "Tout en petites capitales OpenType",+ "OpenType All Small Caps",+ "OpenType All Small Caps",+ "OpenType 全部小型大写字母",+ ],),- ("Subscript", ["Subscript", "Subscript", "Subscript", "Subscript", "下标"]),- ("OpenType Subscript", ["OpenType Subscript", "OpenType Subscript", "OpenType Subscript", "OpenType Subscript", "OpenType 下标"]),- ("OpenType Numerator", ["OpenType Numerator", "OpenType Numerator", "OpenType Numerator", "OpenType Numerator", "OpenType 分子"]),- ("OpenType Denominator", ["OpenType Denominator", "OpenType Denominator", "OpenType Denominator", "OpenType Denominator", "OpenType 分母"]),+ ("Subscript", ["Subscript", "Indice", "Subscript", "Subscript", "下标"]),+ ("OpenType Subscript", ["OpenType Subscript", "Indice OpenType", "OpenType Subscript", "OpenType Subscript", "OpenType 下标"]),+ ("OpenType Numerator", ["OpenType Numerator", "Numérateur OpenType", "OpenType Numerator", "OpenType Numerator", "OpenType 分子"]),+ ("OpenType Denominator", ["OpenType Denominator", "Dénominateur OpenType", "OpenType Denominator", "OpenType Denominator", "OpenType 分母"]),("Ligatures", ["Ligatures", "Ligatures", "Ligatures", "Ligatures", "连字"]),- ("No Break", ["No Break", "No Break", "No Break", "No Break", "不换行"]),- ("Horizontal Scale:", ["Horizontal Scale:", "Horizontal Scale:", "Horizontal Scale:", "Horizontal Scale:", "水平缩放:"]),- ("Vertical Scale:", ["Vertical Scale:", "Vertical Scale:", "Vertical Scale:", "Vertical Scale:", "垂直缩放:"]),- ("Baseline Shift:", ["Baseline Shift:", "Baseline Shift:", "Baseline Shift:", "Baseline Shift:", "基线偏移:"]),- ("Skew:", ["Skew:", "Skew:", "Skew:", "Skew:", "倾斜:"]),- ("Language:", ["Language:", "Language:", "Language:", "Language:", "语言:"]),+ ("No Break", ["No Break", "Sans retour automatique", "No Break", "No Break", "不换行"]),+ ("Horizontal Scale:", ["Horizontal Scale:", "Échelle horizontale :", "Horizontal Scale:", "Horizontal Scale:", "水平缩放:"]),+ ("Vertical Scale:", ["Vertical Scale:", "Échelle verticale :", "Vertical Scale:", "Vertical Scale:", "垂直缩放:"]),+ ("Baseline Shift:", ["Baseline Shift:", "Décalage vertical :", "Baseline Shift:", "Baseline Shift:", "基线偏移:"]),+ ("Skew:", ["Skew:", "Inclinaison :", "Skew:", "Skew:", "倾斜:"]),+ ("Language:", ["Language:", "Langue :", "Language:", "Language:", "语言:"]),+ ("Digits:", ["Ziffern:", "Chiffres :", "Dígitos:", "数字:", "数字:"]),- ("Figure Style:", ["Figure Style:", "Figure Style:", "Figure Style:", "Figure Style:", "数字样式:"]),- ("Underline On", ["Underline On", "Underline On", "Underline On", "Underline On", "启用下划线"]),- ("Strikethrough On", ["Strikethrough On", "Strikethrough On", "Strikethrough On", "Strikethrough On", "启用删除线"]),+ ("Figure Style:", ["Figure Style:", "Style de chiffres :", "Figure Style:", "Figure Style:", "数字样式:"]),+ ("Underline On", ["Underline On", "Souligné activé", "Underline On", "Underline On", "启用下划线"]),+ ("Strikethrough On", ["Strikethrough On", "Barré activé", "Strikethrough On", "Strikethrough On", "启用删除线"]),("Edit \"{name}\"…", ["„{name}“ bearbeiten…", "Modifier « {name} »…", "Editar \"{name}\"…", "\"{name}\" を編集…", "编辑\"{name}\"…"]),("Discretionary Ligatures",diff --cc crates/ui-egui/src/panels/properties.rsindex 0daf680d7,0daee3ecd..87781fed4--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@@ -1420,51 -1335,46 +1420,48 @@@ pub fn character_panel(app: &mut Design.width(170.0).show_ui(ui, |ui| language_menu(app, ui, &lang));});- // Digits (World-Ready): shown for right-to-left paragraphs or once set.+ // Digits (World-Ready): how the figures 0-9 are drawn (English 0123, Arabic ٠١٢٣, Persian ۰۱۲۳).let digits = c["digits"].as_str().unwrap_or("default").to_string();- if digits != "default" || a["para"]["direction"].as_str() == Some("rightToLeft") {- ui.horizontal(|ui| {- caption(ui, crate::i18n::tr(&app.ui.language, "Digits"));- let opts = [("default", "Default"), ("arabic", "Arabic"), ("hindi", "Hindi"), ("farsi", "Farsi"), ("native", "Native")];- let cur = opts.iter().find(|o| o.0 == digits).map_or("Default", |o| o.1);- egui::ComboBox::from_id_salt("char_digits")- .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, cur)))- .width(120.0)- .show_ui(ui, |ui| {- for (k, l) in opts {- if ui.selectable_label(k == digits, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() {- let _ = app.run("type.char", json!({"attrs": {"digits": k}}));- }- }- });+ ui.horizontal(|ui| {+ caption(ui, crate::i18n::tr(&app.ui.language, "Digits"));+ let cur = DIGIT_OPTIONS+ .iter()+ .find(|o| o.0 == digits)+ .map_or_else(|| digit_label(&app.ui.language, DIGIT_OPTIONS[0]), |o| digit_label(&app.ui.language, *o));+ egui::ComboBox::from_id_salt("char_digits").selected_text(crate::rtl::widget(ui, cur)).width(150.0).show_ui(ui, |ui| {+ for o in DIGIT_OPTIONS {+ if ui.selectable_label(o.0 == digits, crate::rtl::widget(ui, digit_label(&app.ui.language, o))).clicked() {+ let _ = app.run("type.char", json!({"attrs": {"digits": o.0}}));+ }+ }});- }+ });- egui::Grid::new("chargrid").num_columns(4).spacing(vec2(6.0, 4.0)).show(ui, |ui| {- caption(ui, crate::i18n::tr(&app.ui.language, "Size"));- if let Some(v) = number(ui, "pcs", c["size"].as_f64(), " pt", 60.0, 2) {+ // Two columns: Size, Kerning and Baseline on the left, Leading and Tracking on the right. A+ // column's captions share the width of its widest one and each field takes the rest of the+ // column, so they line up.+ let auto = c["leading"]["kind"].as_str() != Some("points");+ let lv = if auto { c["size"].as_f64().map(|s| s * a["para"]["autoLeading"].as_f64().unwrap_or(1.2)) } else { c["leading"]["value"].as_f64() };+ let (left_w, right_w) = (caption_width(app, ui, &["Size", "Kerning", "Baseline"]), caption_width(app, ui, &["Leading", "Tracking"]));+ ui.columns(2, |cols| {+ let [left, right] = cols else { return };+ if let Some(v) = char_field(app, left, "Size", left_w, NumField::number("pcs", c["size"].as_f64(), " pt", 2)) {let _ = app.run("type.char", json!({"attrs": {"size": v}}));}- caption(ui, crate::i18n::tr(&app.ui.language, "Leading"));- let auto = c["leading"]["kind"].as_str() != Some("points");- let lv = if auto { c["size"].as_f64().map(|s| s * a["para"]["autoLeading"].as_f64().unwrap_or(1.2)) } else { c["leading"]["value"].as_f64() };- if let Some(v) = number(ui, "pcl", lv, if auto { crate::i18n::tr(&app.ui.language, " (auto)") } else { " pt" }, 70.0, 2) {+ left.horizontal(|ui| {+ caption_cell(ui, crate::i18n::tr(&app.ui.language, "Kerning"), left_w);+ let width = (ui.available_width() - ui.spacing().item_spacing.x).max(40.0);+ kerning_control(app, ui, "pck", &c["kerning"], width);+ });+ if let Some(v) = char_field(app, left, "Baseline", left_w, NumField::number("pcb", c["baselineShift"].as_f64(), " pt", 2)) {+ let _ = app.run("type.char", json!({"attrs": {"baselineShift": v}}));+ }+ // Auto leading is shown in parentheses, as the Paragraph panel shows it.+ if let Some(v) = char_field(app, right, "Leading", right_w, NumField::number("pcl", lv, " pt", 2).parens(auto)) {let _ = app.run("type.char", json!({"attrs": {"leading": {"kind": "points", "value": v}}}));}- ui.end_row();- caption(ui, crate::i18n::tr(&app.ui.language, "Kerning"));- kerning_control(app, ui, "pck", &c["kerning"], 60.0);- caption(ui, crate::i18n::tr(&app.ui.language, "Tracking"));- if let Some(v) = number(ui, "pct", c["tracking"].as_f64(), "", 70.0, 0) {+ if let Some(v) = char_field(app, right, "Tracking", right_w, NumField::number("pct", c["tracking"].as_f64(), "", 0)) {let _ = app.run("type.char", json!({"attrs": {"tracking": v}}));}- ui.end_row();- caption(ui, crate::i18n::tr(&app.ui.language, "Baseline"));- if let Some(v) = number(ui, "pcb", c["baselineShift"].as_f64(), " pt", 70.0, 2) {- let _ = app.run("type.char", json!({"attrs": {"baselineShift": v}}));- }- ui.end_row();});ui.horizontal(|ui| {caption(ui, crate::i18n::tr(&app.ui.language, "Color"));@@@ -2612,113 -2452,35 +2609,125 @@@ fn variable_font_axes(app: &mut DesignAlet face = db.face(family, style);let cur = |tag: &str, default: f32| face.coords.iter().find(|(t, _)| t == tag.as_bytes()).map_or(default, |c| c.1);let mut values: Vec<(String, f32)> = axes.iter().map(|a| (a.0.clone(), cur(&a.0, a.3))).collect();- let mut changed = false;crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Variable Font")).size(11.0));- egui::Grid::new("vf_axes").num_columns(2).spacing(vec2(6.0, 2.0)).show(ui, |ui| {- for (i, (_, name, min, _, max)) in axes.iter().enumerate() {- caption(ui, name);- if ui.add(egui::Slider::new(&mut values[i].1, *min..=*max).step_by(1.0)).drag_stopped() {- changed = true;+ // What the sliders did this frame, gathered over every axis before anything is run.+ let (mut held, mut dragged, mut applied) = (false, false, false);+ let names: Vec<&str> = axes.iter().map(|a| a.1.as_str()).collect();+ let label_w = caption_width(app, ui, &names);+ for ((tag, name, min, _, max), value) in axes.iter().zip(values.iter_mut()) {+ // Caption, a slider filling the middle, then the value field: every slider is as long.+ ui.horizontal(|ui| {+ caption_cell(ui, name, label_w);+ ui.spacing_mut().slider_width = (ui.available_width() - PANEL_FIELD_W - ui.spacing().item_spacing.x * 2.0).max(40.0);+ let (step, decimals) = axis_step(*min, *max);+ // The field beside the slider takes typed values, so the slider's own is hidden.+ let slider = ui.add(egui::Slider::new(&mut value.1, *min..=*max).step_by(f64::from(step)).show_value(false));+ // Only the user's own change counts: the slider also reports one when it snaps a value+ // that is off its steps, which it would then do on every frame.+ let pressed = slider.is_pointer_button_down_on() || slider.dragged();+ let changed = slider.changed() && (pressed || slider.has_focus());+ held |= pressed;+ dragged |= changed && pressed;+ applied |= changed && !pressed;+ if let Some(v) = number(ui, &format!("vf{tag}"), Some(f64::from(value.1)), "", PANEL_FIELD_W, decimals).filter(|v| v.is_finite()) {+ value.1 = (v as f32).clamp(*min, *max);+ applied = true;}- ui.end_row();- }- });- if changed {- let spec = values.iter().map(|(t, v)| format!("{t}:{}", v.round())).collect::<Vec<_>>().join(",");- let _ = app.run("type.char", json!({"attrs": {"fontStyle": format!("{base} {{{spec}}}")}}));+ });}+ let attrs = json!({"attrs": {"fontStyle": variable_font_style(&base, &values)}});+ if applied {+ app.end_live_preview();+ let _ = app.run("type.char", attrs);+ } else if dragged {+ app.live_preview("Variable Font", "type.char", attrs);+ } else if held {+ app.hold_live_preview();+ }+ // Let go, the preview is committed at the start of the next frame (DesignApp::ui).+}++/// The slider step and the field's decimals for an axis: whole units, or hundredths for an axis+/// whose whole range is a few units (Skia's weight runs 0.48–3.2).+/// The axes a slider can show: a malformed font's axis whose minimum lies above its maximum (or+/// isn't a number) is left out, since no value fits its range.+fn usable_axes(axes: Vec<(String, String, f32, f32, f32)>) -> Vec<(String, String, f32, f32, f32)> {+ axes.into_iter().filter(|a| a.2 <= a.4).collect()+}++fn axis_step(min: f32, max: f32) -> (f32, usize) {+ if max - min >= 10.0 { (1.0, 0) } else { (0.01, 2) }+}++/// The style for the axis values: `base {tag:value,…}`, each value to at most two decimals.+fn variable_font_style(base: &str, values: &[(String, f32)]) -> String {+ let spec = values+ .iter()+ .map(|(t, v)| {+ let v = format!("{v:.2}");+ format!("{t}:{}", v.trim_end_matches('0').trim_end_matches('.'))+ })+ .collect::<Vec<_>>()+ .join(",");+ format!("{base} {{{spec}}}")+}++/// The width of the axis sliders' value fields, so the sliders end at the same place.+const PANEL_FIELD_W: f32 = 52.0;++/// The caption font of the Character panel's rows.+fn caption_font() -> egui::FontId {+ egui::FontId::proportional(11.5)+}++/// The width of the widest of `labels` in the interface language: a column's caption cells.+fn caption_width(app: &DesignApp, ui: &Ui, labels: &[&str]) -> f32 {+ let t = Tokens::get(ui.ctx());+ labels+ .iter()+ .map(|l| ui.painter().layout_no_wrap(crate::i18n::tr(&app.ui.language, l).to_string(), caption_font(), t.text).size().x)+ .fold(0.0, f32::max)+ .ceil()+}++/// A Character panel column row: a caption cell `label_w` wide, then the number field filling the+/// rest of the column. Returns the value committed.+fn char_field(app: &DesignApp, ui: &mut Ui, label: &str, label_w: f32, field: NumField<'_>) -> Option<f64> {+ ui.horizontal(|ui| {+ caption_cell(ui, crate::i18n::tr(&app.ui.language, label), label_w);+ let width = (ui.available_width() - ui.spacing().item_spacing.x).max(40.0);+ field.width(width).show(ui)+ })+ .inner+}++/// A left-aligned caption in a cell of fixed width, so the field after it lines up.+fn caption_cell(ui: &mut Ui, text: &str, width: f32) {+ let t = Tokens::get(ui.ctx());+ let (r, _) = ui.allocate_exact_size(vec2(width, crate::widgets::FIELD_H), Sense::hover());+ crate::rtl::paint(ui.painter(), pos2(r.min.x, r.center().y), egui::Align2::LEFT_CENTER, text, caption_font(), t.text);+}++/// Whether `composer` (a paragraph's `composer` attribute) is a single-line composer, and the+/// paragraph and single-line composers of its kind (Japanese or not), for the composer choice.+pub(crate) fn composer_choice(composer: Option<&str>) -> (bool, [&'static str; 2]) {+ let single = matches!(composer, Some("singleLine" | "japaneseSingleLine"));+ let kind = if composer.is_some_and(|c| c.starts_with("japanese")) { ["japanese", "japaneseSingleLine"] } else { ["paragraph", "singleLine"] };+ (single, kind)}+ /// The Digits choices: (value, caption, sample of 0–3). The values are the file format's:+ /// `arabic` is 0123, `hindi` the Arabic-Indic ٠١٢٣ and `farsi` the Persian/Urdu ۰۱۲۳; the captions+ /// name them by the script's users.+ pub const DIGIT_OPTIONS: [(&str, &str, &str); 5] =+ [("default", "Default", ""), ("arabic", "English", "0123"), ("hindi", "Arabic", "٠١٢٣"), ("farsi", "Persian", "۰۱۲۳"), ("native", "Native", "")];++ /// A Digits choice as shown: its translated caption and a sample of the figures.+ pub fn digit_label(lang: &str, o: (&str, &str, &str)) -> String {+ let name = crate::i18n::tr(lang, o.1);+ if o.2.is_empty() { name.to_string() } else { format!("{name} {}", o.2) }+ }+#[cfg(test)]mod tests {use egui_kittest::{Harness, kittest::Queryable};