mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-26 13:22:39 +00:00
## What **A text behaviour suite written from the public documentation, and fixes for every divergence it found.** Each documented rule (Auto / % / px line height and how the leading is split, letter spacing in % and px, paragraph spacing and indent, auto width / auto height / fixed / truncate with max lines, vertical trim, decorations from the font's metrics) is a table-driven case with the numbers the rule implies and a one-line derivation, read from the face actually used so it holds on any machine with a font. CJK line breaking follows UAX #14 and the CJK line-start / line-end rules; caret steps follow UAX #29 grapheme clusters. Where the documentation is silent the case says so and pins today's behaviour. **Fixes (6 of the 13 text cases fail on the old layout; the break and caret rules are new functions)** - **CJK line breaking**: lines break between ideographs, kana and Hangul and before or after a Latin word next to them (before: no break before an ideograph that follows Latin, none after `。`, full-width forms, CJK punctuation or Extension B ideographs), never inside a Latin word, with kinsoku: closing brackets and quotes, `、。,.!?`, small kana, the prolonged sound mark and iteration marks never start a line (the character before moves down with them), opening brackets never end one. The ideographic space hangs at the line's end like a space. One small break-class table in `crates/text/src/breaks.rs`, no new crate. - **Fallback fonts no longer move the baseline**: a style's ascent, descent, line height and cap height come from its own font, not the fallback face that drew some of its characters, so a line with CJK or emoji keeps the height and baseline of a Latin line (with a fixed line height the mixed line's baseline used to shift by the CJK face's taller metrics; with Auto the line grew). Decorations likewise use the style's font and size, so an underline runs at one height and weight through mixed scripts (and isn't thinned by synthesised small caps). - **Paragraph indent applies to left-aligned text only** (documented); right-to-left paragraphs keep it when right-aligned (their start). The Type settings field is disabled with a hint otherwise. - **Carets by grapheme cluster**: Left / Right, Delete and Backspace step over a whole emoji ZWJ sequence, flag, skin-tone sequence or letter with combining marks (they moved one code point at a time, leaving the caret inside an emoji and deleting half of it). A cluster is also shaped with one font, so a joiner or variation selector no longer splits an emoji sequence across faces. - **Words by script**: double-click and word moves (Alt on macOS, Ctrl on Windows and Linux) take one script's run in text without spaces (`日本語` | `の` | `テキスト`), Hangul words end at spaces, and a Latin word keeps its combining marks (before: a whole CJK sentence was one word, and `cafe` + combining acute split at the accent). **Missing documented setting, added** - **Vertical trim** (cap height to baseline): `leadingTrim: none | capHeight` (`CAP_HEIGHT` from REST JSON) through `node.set`, a Standard / cap-height segmented control in Type settings, `inspect_document` and Dev Mode properties, CSS `text-box: trim-both cap alphabetic` in generated code. The box runs from the first line's cap height to the last baseline (auto height shrinks, auto layout parents follow); truncation counts the trimmed bottom; exports reach past the box so descenders below the last baseline aren't clipped. Canvas, PNG, SVG and PDF all draw from the same layout. New strings go through `tr(...)` with `en.toml` / `es.toml` entries; the new segmented control reuses the Type settings one (accessible toggle names). Each edit is one undo step. `unicode-segmentation` (already in `Cargo.lock` through egui and winit) became a direct dependency of `figcraft-text`. ## Verified - **Desktop app** over the control channel (own target dir, separate `APPDATA`, stopped by PID): a 200 px auto-height box of Japanese wraps with no line starting with `、。」` and `「` never ending a line (`…テスト` / `を折り返す、テスト` / `です。「括弧」は行` / `末に来ません。漢` / `字とかなとカタカ` / `ナ。`, the last `ナ` carried down with `。`); a Latin / CJK / Latin paragraph at 36 px line height is 108 px with evenly spaced baselines; the same text with vertical trim is 89.45 px (cap height 17.45 + 2 × 36), its box running from the cap height to the last baseline, and the Type settings control turns it off (108 px) and undo brings it back in one step; one Right arrow from after `a` in `a👨👩👧b` lands after the whole family emoji and Shift+Right then selects `b`; a double click selects the katakana run テキスト. - **MCP**: `figcraft-cli mcp` (headless) built the same three texts; `inspect_document` reports 108 px for the 36 px paragraph and 89.42 px with `leadingTrim: capHeight` for the trimmed one (cap height of the headless font), the PNG export wraps the Japanese by the same rules and keeps the trimmed text's descenders, and `inspect.code` emits `text-box: trim-both cap alphabetic`. - **Web**: `cargo xtask wasm` passes (part of the gate). - **Performance**: text layout of a 2,250-char Latin and a 2,000-char Japanese paragraph wrapped at 300 px (release, median of 7 × 30 runs) before and after on the same machine: Latin 0.70 → 0.42–0.50 ms, Japanese 0.46 → 0.37–0.47 ms (within noise or faster: line metrics are now computed once per style change instead of per glyph). All-ASCII text skips grapheme segmentation. - `cargo +1.99.0 xtask ci` passes (fmt, clippy, tests, layers, assets, wasm), after merging #131 and #132. ## Tests - `text` (`behaviour_tests`, 13 tests): line height Auto / % / px; leading split above and below every line (positive and negative); letter spacing % / px / negative; paragraph spacing and indent by alignment; resizing and truncation with max lines; vertical trim (heights, first baseline, glyph spacing kept, truncation); decorations from the font's metrics through mixed scripts; fallback fonts keep line height and baseline (Auto, px, %); 22 break-opportunity cases; CJK wrapping with kinsoku, Latin words in CJK and Korean; the ideographic space hanging; grapheme steps over ZWJ families, flags, combining marks, skin tones and emoji presentation; one face per cluster. Font-dependent cases skip on a machine without fonts. - `engine` (`text_behaviour_tests`, 5): arrows, Shift+arrows, Delete and Backspace by cluster; double-click and word moves by script (and through `keymap::text_motion` for Ctrl and Alt); IME composition with CJK wrapping and growing the box before commit; vertical trim through `node.set` (box size, PNG ink at the top, export bounds below the box, SVG and PDF, CSS, inspect, undo, junk refused, REST spelling); paragraph indent only on left-aligned text. - `format` REST import test covers `leadingTrim: CAP_HEIGHT`. ## Not in this PR - Documented but not modelled yet: list spacing, hanging quotes and hanging lists, underline style / thickness / offset / skip ink. - Documentation silent, behaviour pinned: Korean wraps by syllable (no word mode); Han compounds next to each other are one word (no dictionary segmentation); letter spacing is added after the last character too; a fallback font's taller glyphs may overflow the line rather than grow it. - `.fig` import doesn't read vertical trim yet (the field wasn't checked against real files). - Spell check (on hold, #113). - Progress docs: target-app-parity area 10 85%/64% → 87%/68%, 7–13 h → 5–10 h with the suite listed under text editing depth; feature breadth and ready for real work unchanged at this rounding; full parity ~323–621 h → ~321–618 h (target-app-parity, ROADMAP); ui-parity text row.
636 lines
23 KiB
Rust
636 lines
23 KiB
Rust
//! Text node data: characters plus a base style and styled runs.
|
|
|
|
use figcraft_color::Paint;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
|
#[serde(tag = "unit", content = "value", rename_all = "camelCase")]
|
|
#[derive(Default)]
|
|
pub enum LineHeight {
|
|
#[default]
|
|
Auto,
|
|
Pixels(f64),
|
|
Percent(f64),
|
|
}
|
|
|
|
impl LineHeight {
|
|
/// Resolved line height in px for `font_size` (`auto` uses the font's natural ratio).
|
|
pub fn resolve(self, font_size: f64, natural_ratio: f64) -> f64 {
|
|
match self {
|
|
LineHeight::Auto => font_size * natural_ratio,
|
|
LineHeight::Pixels(v) => v.max(0.0),
|
|
LineHeight::Percent(p) => font_size * p.max(0.0) / 100.0,
|
|
}
|
|
}
|
|
pub fn label(self) -> String {
|
|
match self {
|
|
LineHeight::Auto => "Auto".into(),
|
|
LineHeight::Pixels(v) => trim_num(v),
|
|
LineHeight::Percent(p) => format!("{}%", trim_num(p)),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
|
#[serde(tag = "unit", content = "value", rename_all = "camelCase")]
|
|
pub enum LetterSpacing {
|
|
Pixels(f64),
|
|
Percent(f64),
|
|
}
|
|
|
|
impl Default for LetterSpacing {
|
|
fn default() -> Self {
|
|
LetterSpacing::Percent(0.0)
|
|
}
|
|
}
|
|
|
|
impl LetterSpacing {
|
|
pub fn resolve(self, font_size: f64) -> f64 {
|
|
match self {
|
|
LetterSpacing::Pixels(v) => v,
|
|
LetterSpacing::Percent(p) => font_size * p / 100.0,
|
|
}
|
|
}
|
|
pub fn label(self) -> String {
|
|
match self {
|
|
LetterSpacing::Pixels(v) => trim_num(v),
|
|
LetterSpacing::Percent(p) => format!("{}%", trim_num(p)),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn trim_num(v: f64) -> String {
|
|
let r = (v * 100.0).round() / 100.0;
|
|
if r.fract().abs() < 1e-9 { format!("{}", r as i64) } else { format!("{r}") }
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum TextDecoration {
|
|
#[default]
|
|
None,
|
|
Underline,
|
|
Strikethrough,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum TextCase {
|
|
#[default]
|
|
Original,
|
|
Upper,
|
|
Lower,
|
|
Title,
|
|
SmallCaps,
|
|
}
|
|
|
|
impl TextCase {
|
|
pub fn apply(self, s: &str) -> String {
|
|
self.apply_after(s, None)
|
|
}
|
|
|
|
/// Apply the case to `s`, which follows `prev` in the text (so title case only capitalises
|
|
/// the first letter of each word even when a word spans several styled runs).
|
|
pub fn apply_after(self, s: &str, prev: Option<char>) -> String {
|
|
match self {
|
|
TextCase::Original | TextCase::SmallCaps => s.to_string(),
|
|
TextCase::Upper => s.to_uppercase(),
|
|
TextCase::Lower => s.to_lowercase(),
|
|
TextCase::Title => {
|
|
let mut out = String::with_capacity(s.len());
|
|
let mut start = prev.is_none_or(|c| !is_word_char(c));
|
|
for ch in s.chars() {
|
|
if start && ch.is_alphanumeric() {
|
|
out.extend(ch.to_uppercase());
|
|
start = false;
|
|
} else {
|
|
out.push(ch);
|
|
start = !is_word_char(ch);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether the char at a position preceded by `prev` starts a word (for title case).
|
|
pub fn starts_word(prev: Option<char>) -> bool {
|
|
prev.is_none_or(|c| !is_word_char(c))
|
|
}
|
|
}
|
|
|
|
/// Letters, digits and apostrophes continue a word (so "don't" stays "Don't").
|
|
fn is_word_char(c: char) -> bool {
|
|
c.is_alphanumeric() || matches!(c, '\'' | '\u{2019}')
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum TextAlignH {
|
|
#[default]
|
|
Left,
|
|
Center,
|
|
Right,
|
|
Justified,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum TextAlignV {
|
|
#[default]
|
|
Top,
|
|
Middle,
|
|
Bottom,
|
|
}
|
|
|
|
/// How a text box resizes as its content changes.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum TextAutoResize {
|
|
/// Auto width: one line per paragraph, box grows both ways.
|
|
#[default]
|
|
WidthAndHeight,
|
|
/// Fixed width, height grows.
|
|
Height,
|
|
/// Fixed size.
|
|
None,
|
|
/// Fixed size, truncate with an ellipsis.
|
|
Truncate,
|
|
}
|
|
|
|
/// Vertical trim: what bounds a text box vertically.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum LeadingTrim {
|
|
/// The full line height of the first and last lines.
|
|
#[default]
|
|
None,
|
|
/// From the first line's cap height to the last line's baseline.
|
|
CapHeight,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum ListStyle {
|
|
#[default]
|
|
None,
|
|
Bulleted,
|
|
Numbered,
|
|
}
|
|
|
|
/// Character style. In runs, every field is an override; `None` means "inherit the base".
|
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct TextStyle {
|
|
pub font_family: String,
|
|
/// The style name, e.g. "Regular", "Bold", "Semi Bold Italic".
|
|
pub font_style: String,
|
|
pub font_size: f64,
|
|
pub line_height: LineHeight,
|
|
pub letter_spacing: LetterSpacing,
|
|
pub decoration: TextDecoration,
|
|
pub case: TextCase,
|
|
/// Run fills (None = node fills).
|
|
pub fills: Option<Vec<Paint>>,
|
|
/// Hyperlink.
|
|
pub link: Option<String>,
|
|
/// Variable font axis values in user space, keyed by 4-char OpenType axis tag (e.g. `wght`:
|
|
/// 550, `wdth`: 85). Empty = what the style name implies; axes the face lacks are ignored.
|
|
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
|
pub variations: std::collections::BTreeMap<String, f64>,
|
|
/// The text style (shared style id) these chars are linked to. A layer's chars can link to
|
|
/// different styles; editing what a style sets unlinks the chars edited.
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub style_id: Option<String>,
|
|
}
|
|
|
|
impl Default for TextStyle {
|
|
fn default() -> Self {
|
|
Self {
|
|
font_family: "Inter".into(),
|
|
font_style: "Regular".into(),
|
|
font_size: 12.0,
|
|
line_height: LineHeight::Auto,
|
|
letter_spacing: LetterSpacing::default(),
|
|
decoration: TextDecoration::None,
|
|
case: TextCase::Original,
|
|
fills: None,
|
|
link: None,
|
|
variations: std::collections::BTreeMap::new(),
|
|
style_id: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Axes a style name implies (weight, italic, slant): picking a named style clears their custom values.
|
|
pub const STYLE_AXES: [&str; 3] = ["wght", "ital", "slnt"];
|
|
|
|
impl TextStyle {
|
|
/// Numeric weight: a custom `wght` axis value, else the one implied by the style name.
|
|
pub fn weight(&self) -> u16 {
|
|
match self.variations.get("wght") {
|
|
Some(w) if w.is_finite() => w.round().clamp(1.0, 1000.0) as u16,
|
|
_ => style_weight(&self.font_style),
|
|
}
|
|
}
|
|
pub fn italic(&self) -> bool {
|
|
self.font_style.to_ascii_lowercase().contains("italic")
|
|
|| self.variations.get("ital").is_some_and(|v| *v >= 0.5)
|
|
|| self.variations.get("slnt").is_some_and(|v| *v != 0.0)
|
|
}
|
|
|
|
/// Take what text style `def` sets (font, size, line height, letter spacing, decoration, case
|
|
/// and axis values) and link to it as `id`; fills and hyperlinks stay.
|
|
pub fn take_text_style(&mut self, def: &TextStyle, id: &str) {
|
|
*self = TextStyle { fills: self.fills.take(), link: self.link.take(), style_id: Some(id.to_string()), ..def.clone() };
|
|
}
|
|
|
|
/// Whether these chars show what text style `def` sets.
|
|
pub fn shows_text_style(&self, def: &TextStyle) -> bool {
|
|
self.font_family == def.font_family
|
|
&& self.font_style == def.font_style
|
|
&& self.font_size == def.font_size
|
|
&& self.line_height == def.line_height
|
|
&& self.letter_spacing == def.letter_spacing
|
|
&& self.decoration == def.decoration
|
|
&& self.case == def.case
|
|
&& self.variations == def.variations
|
|
}
|
|
|
|
/// This style as a text style's definition (linked to nothing).
|
|
pub fn as_text_style(&self) -> TextStyle {
|
|
TextStyle { style_id: None, link: None, ..self.clone() }
|
|
}
|
|
|
|
/// Switch to the named style, dropping custom values of the axes the name implies.
|
|
pub fn set_font_style(&mut self, name: impl Into<String>) {
|
|
self.font_style = name.into();
|
|
for tag in STYLE_AXES {
|
|
self.variations.remove(tag);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Weight from a style name ("Semi Bold Italic" → 600).
|
|
pub fn style_weight(style: &str) -> u16 {
|
|
let s = style.to_ascii_lowercase().replace([' ', '-'], "");
|
|
let table: [(&str, u16); 10] = [
|
|
("thin", 100),
|
|
("extralight", 200),
|
|
("ultralight", 200),
|
|
("light", 300),
|
|
("medium", 500),
|
|
("semibold", 600),
|
|
("demibold", 600),
|
|
("extrabold", 800),
|
|
("ultrabold", 800),
|
|
("black", 900),
|
|
];
|
|
for (k, w) in table {
|
|
if s.contains(k) {
|
|
return w;
|
|
}
|
|
}
|
|
if s.contains("bold") {
|
|
return 700;
|
|
}
|
|
if s.contains("heavy") {
|
|
return 900;
|
|
}
|
|
400
|
|
}
|
|
|
|
/// A styled range of characters (char indices, end exclusive).
|
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
pub struct StyleRun {
|
|
pub start: usize,
|
|
pub end: usize,
|
|
pub style: TextStyle,
|
|
}
|
|
|
|
/// Text node content.
|
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
|
#[serde(default)]
|
|
pub struct TextData {
|
|
pub characters: String,
|
|
pub style: TextStyle,
|
|
/// Ranges whose style differs from `style`; full styles (already merged), non-overlapping, sorted.
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub runs: Vec<StyleRun>,
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub auto_resize: TextAutoResize,
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub align_h: TextAlignH,
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub align_v: TextAlignV,
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub paragraph_spacing: f64,
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub paragraph_indent: f64,
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub list: ListStyle,
|
|
/// Vertical trim (`capHeight`: the box runs from the first line's cap height to the last
|
|
/// line's baseline).
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub leading_trim: LeadingTrim,
|
|
/// Max lines when truncating (0 = as many as fit).
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub max_lines: u32,
|
|
/// OpenType feature toggles (e.g. "liga": false).
|
|
#[serde(skip_serializing_if = "crate::node::is_default")]
|
|
pub features: std::collections::BTreeMap<String, bool>,
|
|
/// The path the text follows (text on a path); `None`: lines in the box.
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub path: Option<TextPath>,
|
|
}
|
|
|
|
/// Text on a path: the baseline follows `d`. The text starts at `start` (aligned there by the
|
|
/// horizontal alignment: left starts, centre centres, right ends at it); glyphs past an open
|
|
/// path's ends are hidden, a closed path wraps them around.
|
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
|
#[serde(default)]
|
|
pub struct TextPath {
|
|
/// SVG path data in the layer's own space.
|
|
pub d: String,
|
|
/// Where the text starts along the path, 0..1 by length.
|
|
pub start: f64,
|
|
/// On the other side of the path, running the other way.
|
|
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
|
pub flip: bool,
|
|
}
|
|
|
|
impl TextPath {
|
|
/// A text path following `path` (layer space).
|
|
pub fn new(path: &figcraft_geom::BezPath) -> Self {
|
|
Self { d: path.to_svg(), start: 0.0, flip: false }
|
|
}
|
|
|
|
/// The path (empty when `d` doesn't parse).
|
|
pub fn path(&self) -> figcraft_geom::BezPath {
|
|
figcraft_geom::BezPath::from_svg(&self.d).unwrap_or_default()
|
|
}
|
|
|
|
/// The start offset clamped into 0..1 (NaN: 0).
|
|
pub fn start(&self) -> f64 {
|
|
if self.start.is_finite() { self.start.clamp(0.0, 1.0) } else { 0.0 }
|
|
}
|
|
|
|
/// Scale the path by `sx`, `sy` (the layer was resized).
|
|
pub fn scale(&mut self, sx: f64, sy: f64) {
|
|
if sx.is_finite() && sy.is_finite() {
|
|
let mut p = self.path();
|
|
p.apply_affine(figcraft_geom::Affine::scale_non_uniform(sx, sy));
|
|
self.d = p.to_svg();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether `tag` is a valid OpenType feature tag (four printable ASCII chars).
|
|
pub fn valid_feature_tag(tag: &str) -> bool {
|
|
tag.len() == 4 && tag.bytes().all(|b| (0x20..0x7f).contains(&b))
|
|
}
|
|
|
|
/// Whether `tag` is a valid OpenType variation axis tag (same shape as a feature tag).
|
|
pub fn valid_axis_tag(tag: &str) -> bool {
|
|
valid_feature_tag(tag)
|
|
}
|
|
|
|
impl TextData {
|
|
pub fn new(characters: impl Into<String>) -> Self {
|
|
Self { characters: characters.into(), ..Default::default() }
|
|
}
|
|
|
|
/// How far text on a path paints past its path's box (glyphs stand on the path, lines after
|
|
/// the first run beside it): about one and a half of the largest size per line; 0 off a path.
|
|
pub fn path_reach(&self) -> f64 {
|
|
if self.path.is_none() {
|
|
return 0.0;
|
|
}
|
|
let lines = self.characters.lines().count().clamp(1, 10_000) as f64;
|
|
self.max_size() * 1.5 * lines
|
|
}
|
|
|
|
/// How far vertically trimmed text paints past its box (descenders below the last baseline,
|
|
/// accents above the first cap height): half the largest size; 0 untrimmed.
|
|
pub fn trim_reach(&self) -> f64 {
|
|
if self.leading_trim == LeadingTrim::None { 0.0 } else { self.max_size() * 0.5 }
|
|
}
|
|
|
|
/// The largest font size used (capped like layout caps it).
|
|
fn max_size(&self) -> f64 {
|
|
self.spans().iter().map(|(_, _, s)| s.font_size).filter(|v| v.is_finite()).fold(0.0, f64::max).min(5000.0)
|
|
}
|
|
|
|
pub fn char_count(&self) -> usize {
|
|
self.characters.chars().count()
|
|
}
|
|
|
|
/// The style at char index `i`.
|
|
pub fn style_at(&self, i: usize) -> &TextStyle {
|
|
self.runs.iter().find(|r| r.start <= i && i < r.end).map(|r| &r.style).unwrap_or(&self.style)
|
|
}
|
|
|
|
/// Spans of uniform style covering the whole text: (start, end, style).
|
|
pub fn spans(&self) -> Vec<(usize, usize, &TextStyle)> {
|
|
let n = self.char_count();
|
|
let mut out = Vec::new();
|
|
let mut pos = 0;
|
|
let mut runs: Vec<&StyleRun> = self.runs.iter().filter(|r| r.start < r.end && r.start < n).collect();
|
|
runs.sort_by_key(|r| r.start);
|
|
for r in runs {
|
|
let start = r.start.max(pos);
|
|
let end = r.end.min(n);
|
|
if start >= end {
|
|
continue;
|
|
}
|
|
if start > pos {
|
|
out.push((pos, start, &self.style));
|
|
}
|
|
out.push((start, end, &r.style));
|
|
pos = end;
|
|
}
|
|
if pos < n || out.is_empty() {
|
|
out.push((pos, n, &self.style));
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Apply `f` to the style of chars `start..end` (all text when the range is the whole text or
|
|
/// empty text), splitting runs as needed and merging equal neighbours.
|
|
pub fn restyle(&mut self, start: usize, end: usize, f: impl Fn(&mut TextStyle)) {
|
|
let n = self.char_count();
|
|
let (start, end) = (start.min(n), end.min(n));
|
|
if n == 0 || (start == 0 && end >= n) {
|
|
f(&mut self.style);
|
|
for r in &mut self.runs {
|
|
f(&mut r.style);
|
|
}
|
|
self.normalize();
|
|
return;
|
|
}
|
|
if start >= end {
|
|
return;
|
|
}
|
|
// Expand to per-char styles, modify, re-compress.
|
|
let mut per: Vec<TextStyle> = (0..n).map(|i| self.style_at(i).clone()).collect();
|
|
for s in per.iter_mut().take(end).skip(start) {
|
|
f(s);
|
|
}
|
|
self.runs.clear();
|
|
let mut i = 0;
|
|
while i < n {
|
|
let Some(s) = per.get(i) else { break };
|
|
let mut j = i + 1;
|
|
while per.get(j).is_some_and(|t| t == s) {
|
|
j += 1;
|
|
}
|
|
if *s != self.style {
|
|
self.runs.push(StyleRun { start: i, end: j, style: s.clone() });
|
|
}
|
|
i = j;
|
|
}
|
|
}
|
|
|
|
/// Drop empty/out-of-range runs and runs equal to the base style.
|
|
pub fn normalize(&mut self) {
|
|
let n = self.char_count();
|
|
let base = self.style.clone();
|
|
self.runs.retain(|r| r.start < r.end && r.start < n && r.style != base);
|
|
for r in &mut self.runs {
|
|
r.end = r.end.min(n);
|
|
}
|
|
self.runs.sort_by_key(|r| r.start);
|
|
}
|
|
|
|
/// Replace chars `start..end` with `text`, shifting runs (inserted text takes the style at `start`).
|
|
pub fn replace_range(&mut self, start: usize, end: usize, text: &str) {
|
|
let n = self.char_count();
|
|
let (start, end) = (start.min(n), end.min(n).max(start.min(n)));
|
|
let byte = |i: usize| self.characters.char_indices().nth(i).map(|(b, _)| b).unwrap_or(self.characters.len());
|
|
let (bs, be) = (byte(start), byte(end));
|
|
let mut s = String::with_capacity(self.characters.len() + text.len());
|
|
s.push_str(self.characters.get(..bs).unwrap_or(""));
|
|
s.push_str(text);
|
|
s.push_str(self.characters.get(be..).unwrap_or(""));
|
|
self.characters = s;
|
|
let inserted = text.chars().count();
|
|
let removed = end - start;
|
|
for r in &mut self.runs {
|
|
let shift = |p: usize| -> usize {
|
|
if p <= start {
|
|
p
|
|
} else if p >= end {
|
|
p - removed + inserted
|
|
} else {
|
|
start + inserted
|
|
}
|
|
};
|
|
// A run touching the insertion point at its end grows with the typed text.
|
|
let new_start = shift(r.start);
|
|
let new_end = if r.end == start && r.start < start { start + inserted } else { shift(r.end) };
|
|
r.start = new_start;
|
|
r.end = new_end;
|
|
}
|
|
self.normalize();
|
|
}
|
|
|
|
/// Link chars `start..end` (all of them when the range is empty or the whole text) to text
|
|
/// style `id`, defined as `def`.
|
|
pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) {
|
|
self.restyle(start, end, |s| s.take_text_style(def, id));
|
|
}
|
|
|
|
/// Unlink chars `start..end` (all when empty or whole) from their text styles; values stay.
|
|
pub fn unlink_text_style(&mut self, start: usize, end: usize) {
|
|
self.restyle(start, end, |s| s.style_id = None);
|
|
}
|
|
|
|
/// The text style every char is linked to: `Some(None)` when none is, None when they differ.
|
|
pub fn text_style_link(&self) -> Option<Option<&str>> {
|
|
let mut spans = self.spans().into_iter().map(|(_, _, s)| s.style_id.as_deref());
|
|
let first = spans.next()?;
|
|
spans.all(|s| s == first).then_some(first)
|
|
}
|
|
|
|
/// Apply `f` to every distinct style (the base and each run) and merge runs that became equal.
|
|
pub(crate) fn each_style(&mut self, mut f: impl FnMut(&mut TextStyle)) {
|
|
f(&mut self.style);
|
|
for r in &mut self.runs {
|
|
f(&mut r.style);
|
|
}
|
|
self.normalize();
|
|
}
|
|
|
|
/// Whether any char links to text style `id`.
|
|
pub fn links_text_style(&self, id: &str) -> bool {
|
|
std::iter::once(&self.style).chain(self.runs.iter().map(|r| &r.style)).any(|s| s.style_id.as_deref() == Some(id))
|
|
}
|
|
|
|
/// Follow text style `id`'s new definition wherever chars link to it.
|
|
pub fn update_text_style(&mut self, id: &str, def: &TextStyle) {
|
|
self.each_style(|s| {
|
|
if s.style_id.as_deref() == Some(id) {
|
|
s.take_text_style(def, id);
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Point text style links elsewhere: `f(id)` gives the new id, None unlinks (values stay).
|
|
pub fn map_text_styles(&mut self, f: impl Fn(&str) -> Option<String>) {
|
|
self.each_style(|s| s.style_id = s.style_id.as_deref().and_then(&f));
|
|
}
|
|
|
|
/// Unlink chars whose style is gone (`def` gives None) or that no longer show it (edited since).
|
|
pub fn check_text_styles<'a>(&mut self, def: impl Fn(&str) -> Option<&'a TextStyle>) {
|
|
self.each_style(|s| {
|
|
if s.style_id.as_deref().is_some_and(|id| !def(id).is_some_and(|d| s.shows_text_style(d))) {
|
|
s.style_id = None;
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Whether every char shares one style (the panel shows "Mixed" otherwise).
|
|
pub fn is_uniform(&self) -> bool {
|
|
self.runs.is_empty()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod case_tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn title_case_respects_context() {
|
|
assert_eq!(TextCase::Title.apply("hello wORLD don't 3d x-ray"), "Hello WORLD Don't 3d X-Ray");
|
|
// Continuing a word from a previous run: no capital.
|
|
assert_eq!(TextCase::Title.apply_after("lo world", Some('l')), "lo World");
|
|
assert_eq!(TextCase::Title.apply_after("lo", Some(' ')), "Lo");
|
|
assert_eq!(TextCase::Upper.apply_after("ß", Some('a')), "SS");
|
|
assert!(valid_feature_tag("liga") && valid_feature_tag("ss01"));
|
|
assert!(!valid_feature_tag("lig") && !valid_feature_tag("ligatures") && !valid_feature_tag("li\u{e9}"));
|
|
}
|
|
|
|
#[test]
|
|
fn variations_are_backward_compatible_and_imply_weight() {
|
|
// Files written before variable fonts load with no custom axes, and stay byte-identical.
|
|
let old = r#"{"font_family":"Inter","font_style":"Bold","font_size":12.0}"#;
|
|
let st: TextStyle = serde_json::from_str(old).unwrap();
|
|
assert!(st.variations.is_empty());
|
|
assert!(!serde_json::to_string(&st).unwrap().contains("variations"));
|
|
let mut st = TextStyle { font_style: "Regular".into(), ..Default::default() };
|
|
st.variations.insert("wght".into(), 640.0);
|
|
st.variations.insert("wdth".into(), 80.0);
|
|
assert_eq!(st.weight(), 640);
|
|
assert!(!st.italic());
|
|
st.variations.insert("slnt".into(), -8.0);
|
|
assert!(st.italic());
|
|
let round: TextStyle = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap();
|
|
assert_eq!(round, st);
|
|
// Picking a named style drops the axes its name implies, keeps the others.
|
|
st.set_font_style("Bold");
|
|
assert_eq!(st.weight(), 700);
|
|
assert_eq!(st.variations.keys().collect::<Vec<_>>(), ["wdth"]);
|
|
assert!(valid_axis_tag("wght") && !valid_axis_tag("weight"));
|
|
}
|
|
}
|