diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 4936b33c635..7dadaf1bd54 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -27,38 +27,26 @@ use skrifa::raw::types::Tag; use crate::fonts::FontDb; -/// Photoshop synthesizes small caps for faces without an OpenType `smcp` table. Keep the same -/// readable hierarchy for every font instead of silently rendering lowercase text unchanged. -const SYNTHETIC_SMALL_CAPS_SCALE: f32 = 0.7; +mod area; +mod navigate; +mod paragraphs; +mod style; +mod vertical; -/// Photoshop's default superscript / subscript size and position (Type preferences, stored in a -/// PSD's text resources as `SuperscriptSize` .583, `SuperscriptPosition` .333 and their -/// `Subscript` twins): the run is drawn at 58.3% of its size and moved by 33.3% of its size. -const SCRIPT_SIZE: f32 = 0.583; -const SCRIPT_POSITION: f32 = 0.333; - -/// The style a run is drawn with: superscript and subscript shrink it and shift its baseline. -fn drawn_style(s: &mut CharStyle) { - let dir = match s.baseline { - FontBaseline::Normal => return, - FontBaseline::Superscript => 1.0, - FontBaseline::Subscript => -1.0, - }; - s.baseline_shift_pt += dir * SCRIPT_POSITION * s.size_pt; - s.size_pt *= SCRIPT_SIZE; -} - -/// Photoshop's default tab stops: every half inch, measured from the anchor of point text or the -/// left edge of a paragraph box. PSD type carries no custom tab stops, so these are the only ones. -pub const DEFAULT_TAB_STOP_PT: f32 = 36.0; - -/// The rendering path for a `SmallCaps` character style. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum SmallCapsMode { - None, - OpenType, - Synthetic, -} +#[cfg(test)] +pub(crate) use area::AREA_PASSES; +use area::{LineMetrics, MAX_AREA_PASSES, area_metrics, break_area, line_metrics}; +pub use navigate::{byte_index, char_index, hit_char, line_edge, line_index, line_step, text_point_inside, word_boundary}; +pub use paragraphs::{DEFAULT_TAB_STOP_PT, split_paragraphs}; +use paragraphs::{next_tab_stop, strip_break, tab_widths}; +#[cfg(test)] +use style::{SMCP_PROBES, variation_list}; +use style::{ + SYNTHETIC_SMALL_CAPS_SCALE, SmallCapsMode, drawn_style, effective_horizontal_scale, feature_list, first_ascent, probe_smcp, small_caps_mode, style_props, +}; +pub(crate) use style::{hangul_runs, squeeze_punctuation, synthetic_bold}; +pub use vertical::{VClass, vertical_class}; +use vertical::{VGlyph, VMetrics}; /// Index of the run containing byte offset `off`, given each run's start offset (non-decreasing): /// the last run starting at or before `off`, or 0 when none does. Binary search, so a layer with @@ -67,83 +55,11 @@ fn run_index_at(run_starts: &[usize], off: usize) -> usize { run_starts.partition_point(|&s| s <= off).saturating_sub(1) } -/// Whether the style's selected face has an `smcp` feature (a font load and GSUB parse). -fn probe_smcp(fonts: &mut FontDb, style: &CharStyle) -> bool { - #[cfg(test)] - SMCP_PROBES.with(|c| c.set(c.get() + 1)); - fonts.selected_face_has_feature(&style.font_family, style.weight, style.italic, Tag::new(b"smcp")) -} - -#[cfg(test)] -thread_local! { - static SMCP_PROBES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -fn small_caps_mode(caps: Caps, face_has_smcp: bool) -> SmallCapsMode { - match caps { - Caps::SmallCaps if face_has_smcp => SmallCapsMode::OpenType, - Caps::SmallCaps => SmallCapsMode::Synthetic, - _ => SmallCapsMode::None, - } -} - /// Index of the character run whose style a glyph uses, plus the vertical-type class of its /// characters ([`VClass`] as `u8`; always 0 in horizontal type). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct RunBrush(pub u32, pub u8); -/// How a character is set in vertical type (a simplification of Unicode's -/// `Vertical_Orientation`, UAX #50). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum VClass { - /// Rotated 90° clockwise (Latin, digits, most symbols). - Rotate = 0, - /// Upright (ideographs, kana, Hangul, full-width forms, CJK punctuation such as 、。), - /// using a vertical alternate when the font has one. - Upright = 1, - /// Upright through its vertical alternate (brackets, the long-vowel mark, dashes); rotated - /// when the font has none. - AlternateOrRotate = 2, -} - -/// The vertical-type class of a character. -pub fn vertical_class(c: char) -> VClass { - let u = c as u32; - let alt = matches!( - u, - 0x2014..=0x2016 - | 0x2025 - | 0x2026 - | 0x2329 - | 0x232A - | 0x3008..=0x3011 - | 0x3014..=0x301F - | 0x3030 - | 0x30A0 - | 0x30FC - | 0xFE59..=0xFE5E - | 0xFF08 - | 0xFF09 - | 0xFF0D - | 0xFF1A..=0xFF1E - | 0xFF3B - | 0xFF3D - | 0xFF3F - | 0xFF5B..=0xFF60 - | 0xFFE3 - ); - if alt { - return VClass::AlternateOrRotate; - } - // Half-width katakana and Hangul rotate like other half-width text. - if (0xFF61..=0xFFDC).contains(&u) { - return VClass::Rotate; - } - let upright = crate::cjk::classify(c).is_some() - || matches!(u, 0xA7 | 0xA9 | 0xAE | 0xB1 | 0xBC..=0xBE | 0xD7 | 0xF7 | 0x2E80..=0x2EFF | 0xFE10..=0xFE1F | 0xFE30..=0xFE4F | 0x1F000..=0x1FAFF); - if upright { VClass::Upright } else { VClass::Rotate } -} - /// How a placed glyph's outline is oriented in text space. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum GlyphOrient { @@ -344,96 +260,6 @@ impl TextLayout { } } -/// Byte offset of character `index` (the text length when `index` is past the end). -pub fn byte_index(text: &str, index: usize) -> usize { - text.char_indices().nth(index).map_or(text.len(), |(b, _)| b) -} - -/// Character index of byte `byte`, floored to a char boundary so a bad offset never panics. -pub fn char_index(text: &str, byte: usize) -> usize { - let mut byte = byte.min(text.len()); - while byte > 0 && !text.is_char_boundary(byte) { - byte -= 1; - } - text[..byte].chars().count() -} - -/// Line containing a byte offset. At a shared wrap boundary the caret belongs to -/// the following line, while an offset at the end of the text stays on the last. -pub fn line_index(layout: &TextLayout, byte: usize) -> usize { - layout.lines.iter().rposition(|ln| byte >= ln.range.start && byte <= ln.range.end).unwrap_or_else(|| layout.lines.len().saturating_sub(1)) -} - -/// Nearest caret to a text-space point: character index and the line it sits on. -pub fn hit_char(layout: &TextLayout, text: &str, x: f32, y: f32) -> (usize, usize) { - let byte = layout.hit_test(x, y); - // At a soft-wrap boundary either visual line can share this byte offset. The - // pointer's line, not the caret's preferred (following) line, is authoritative. - let (_, line_y) = layout.to_line(x, y); - let line = layout.closest_line(line_y).map_or_else(|| line_index(layout, byte), |(index, _)| index); - (char_index(text, byte), line) -} - -/// Text-space point inside the laid-out line boxes, expanded by `slop` px on every side. -pub fn text_point_inside(layout: &TextLayout, x: f32, y: f32, slop: f32) -> bool { - let slop = if slop.is_finite() { slop.max(0.0) } else { 0.0 }; - layout.bounds().is_some_and(|b| x >= b[0] - slop && x <= b[2] + slop && y >= b[1] - slop && y <= b[3] + slop) -} - -/// Character index of the word boundary before (`forward` is false) or after `idx`. -/// -/// A word is a run of alphanumeric characters, the rule the Type tool has always used. -pub fn word_boundary(text: &str, idx: usize, forward: bool) -> usize { - let chars: Vec = text.chars().collect(); - let mut i = idx.min(chars.len()); - if forward { - while i < chars.len() && !chars[i].is_alphanumeric() { - i += 1; - } - while i < chars.len() && chars[i].is_alphanumeric() { - i += 1; - } - } else { - while i > 0 && !chars[i - 1].is_alphanumeric() { - i -= 1; - } - while i > 0 && chars[i - 1].is_alphanumeric() { - i -= 1; - } - } - i -} - -/// Caret on the neighbouring line (`dir` < 0 previous, otherwise next), keeping `x` -/// (line space: the position along the line). Past the first or last line the caret -/// goes to the start or end of the text. Line space is the same for both orientations, -/// so a column of vertical type steps the same way a line of horizontal type does. -pub fn line_step(layout: &TextLayout, text: &str, idx: usize, x: f32, dir: i32) -> usize { - let n = text.chars().count(); - let idx = idx.min(n); - if layout.lines.is_empty() { - return idx; - } - let current_line = line_index(layout, byte_index(text, idx)); - let target_line = if dir < 0 { - let Some(target) = current_line.checked_sub(1) else { return 0 }; - target - } else { - let Some(target) = current_line.checked_add(1).filter(|target| *target < layout.lines.len()) else { return n }; - target - }; - char_index(text, layout.hit_test_x_on_line(target_line, x)) -} - -/// Line start (`end` false) or end for the line containing `idx`, as a character index. -pub fn line_edge(layout: &TextLayout, text: &str, idx: usize, end: bool) -> usize { - let n = text.chars().count(); - let idx = idx.min(n); - let byte = byte_index(text, idx); - let line = layout.lines.get(line_index(layout, byte)); - line.map_or(idx, |ln| char_index(text, if end { ln.range.end } else { ln.range.start })) -} - const LRM: &str = "\u{200E}"; const RLM: &str = "\u{200F}"; /// A line break inside a paragraph (Shift+Return), stored as U+0003 in PSD type. @@ -1119,16 +945,6 @@ impl Layouter { } } -/// A style's horizontal scale; unset (zero or negative) is 100%. -fn effective_horizontal_scale(st: &CharStyle) -> f32 { - if st.horizontal_scale > 0.0 && st.horizontal_scale.is_finite() { st.horizontal_scale } else { 1.0 } -} - -/// The first tab stop after `pos` (px from the anchor or box edge); stops are `interval` apart. -fn next_tab_stop(pos: f32, interval: f32) -> f32 { - if interval > 0.0 && pos.is_finite() { ((pos + 1e-3) / interval).floor() * interval + interval } else { pos } -} - /// Where one line of area type goes: its baseline, the left edge of its span, and the width /// it may fill (the span less the paragraph's indents), plus the row and span it came from. #[derive(Clone, Copy, Debug, PartialEq)] @@ -1140,579 +956,6 @@ struct Slot { span: usize, } -/// A line's ascent, descent and leading (px); for area type, the largest over a paragraph. -#[derive(Clone, Copy, Debug)] -struct LineMetrics { - ascent: f32, - descent: f32, - leading: f32, -} - -/// Most line-breaking passes area type makes for one paragraph, over all its plans (each span -/// left empty for a word that doesn't fit costs a pass). Past it, words overflow their spans. -const MAX_AREA_PASSES: usize = 32; -/// Most rows one area paragraph is planned on. -const MAX_AREA_ROWS: usize = 4096; - -#[cfg(test)] -thread_local! { - /// Area line-breaking passes made on this thread, for tests. - pub(crate) static AREA_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// The rows an area paragraph's lines go on: baselines from `next` down, one leading apart, -/// each with its spans left to right. They don't depend on the text, so they are found once -/// (lazily) and shared by every pass. -struct AreaRows<'a> { - area: &'a crate::area::AreaShape, - m: LineMetrics, - min_width: f32, - /// Where the search for the next row starts. - next: f32, - rows: Vec<(f32, Vec<(f32, f32)>)>, - done: bool, -} - -impl AreaRows<'_> { - /// Row `i`: its baseline and spans; `None` past the shape. - fn get(&mut self, i: usize) -> Option<&(f32, Vec<(f32, f32)>)> { - while self.rows.len() <= i && !self.done { - match self.area.next_row(self.next, self.m.ascent, self.m.descent, self.min_width) { - Some((b, spans)) if self.rows.len() < MAX_AREA_ROWS => { - self.next = b + self.m.leading; - self.rows.push((b, spans)); - } - _ => self.done = true, - } - } - self.rows.get(i) - } - - /// The first span, from span `span` of row `row` on, that leaves at least `width` once - /// `inset` (the paragraph's indents) is taken off: its row and span. - fn first_fit(&mut self, row: usize, span: usize, width: f32, inset: f32) -> Option<(usize, usize)> { - let (mut r, mut first) = (row, span); - while let Some((_, spans)) = self.get(r) { - if let Some(j) = spans.iter().skip(first).position(|&(x0, x1)| x1 - x0 - inset + 0.5 >= width) { - return Some((r, first + j)); - } - r += 1; - first = 0; - } - None - } -} - -/// A line wider than the span it fell in, that a later span can hold: the line's index in the -/// paragraph, where its text starts, and its width. -#[derive(Clone, Copy, Debug)] -struct Need { - line: usize, - start: usize, - width: f32, -} - -/// Breaks one paragraph of area type a line at a time, each line as wide as the next span the -/// shape leaves (rows from `from` down, spans left to right). Returns each line's slot and -/// whether text was left over because the shape ran out (hidden, like box overflow). -/// -/// A span too narrow for the word that would start it (the narrow top of an ellipse) is left -/// empty and the word goes to the first later span that holds it, as Photoshop does. A word no -/// later span holds but another span of the shape would means the shape is full: it and the rest are -/// hidden. Only a word no span holds overflows its span. Parley doesn't report a line's -/// trailing whitespace while breaking, so overflowing lines are found after a pass and the -/// paragraph broken again; `budget` (shared by the paragraph's calls) bounds the passes. -/// -/// Horizontal scale applies after shaping, so each line breaks at its span width divided by -/// `scale`; widths compared with spans are the scaled ones. -#[allow(clippy::too_many_arguments)] -fn break_area( - layout: &mut Layout, - area: &crate::area::AreaShape, - from: f32, - m: LineMetrics, - indents: (f32, f32), - min_width: f32, - scale: f32, - budget: &std::cell::Cell, -) -> (Vec, bool) { - let inset = indents.0 + indents.1; - let mut rows = AreaRows { area, m, min_width, next: from, rows: Vec::new(), done: false }; - // Every row of the shape from its top, whatever paragraph came before (found lazily). - let mut shape_rows = AreaRows { area, m, min_width, next: area.bounds[1], rows: Vec::new(), done: false }; - let mut needs: Vec = Vec::new(); - loop { - let (slots, overflow) = break_area_pass(layout, &mut rows, inset, scale, &needs); - budget.set(budget.get().saturating_sub(1)); - // Each line's text start and scaled width without its trailing whitespace. - let lines: Vec<(usize, f32)> = layout - .lines() - .map(|l| { - let lm = l.metrics(); - (l.text_range().start, (lm.advance - lm.trailing_whitespace) * scale) - }) - .collect(); - // A line still wider than its span that some span of the shape would hold: the shape ran - // out of room for it (the narrow bottom of a full bubble). It and the rest are hidden, as - // overflow; only a word no span holds overflows its span. - let mut ran_out = |slots: Vec, overflow: bool| match lines - .iter() - .zip(&slots) - .position(|(&(_, width), s)| width > s.width + 0.5 && shape_rows.first_fit(0, 0, width, inset).is_some()) - { - Some(li) => (slots.into_iter().take(li).collect(), true), - None => (slots, overflow), - }; - if budget.get() == 0 { - return ran_out(slots, overflow); - } - // A line that now starts elsewhere (an earlier line changed) no longer needs its span. - let kept = needs.len(); - needs.retain(|n| lines.get(n.line).is_some_and(|l| l.0 == n.start)); - if needs.len() != kept { - continue; - } - let mut new = None; - for (li, (&(start, width), s)) in lines.iter().zip(&slots).enumerate() { - if width > s.width + 0.5 && !needs.iter().any(|n| n.line == li) && rows.first_fit(s.row, s.span + 1, width, inset).is_some() { - new = Some(Need { line: li, start, width }); - break; - } - } - if let Some(n) = new { - needs.push(n); - continue; - } - return ran_out(slots, overflow); - } -} - -/// One pass of [`break_area`]: each line in the next span, skipping spans too narrow for a -/// line in `needs` when a later span holds it. -fn break_area_pass(layout: &mut Layout, rows: &mut AreaRows<'_>, inset: f32, scale: f32, needs: &[Need]) -> (Vec, bool) { - #[cfg(test)] - AREA_PASSES.with(|c| c.set(c.get() + 1)); - let mut slots: Vec = Vec::new(); - let mut br = layout.break_lines(); - // Per-line widths below are never wider than this, as parley requires. - br.state_mut().set_layout_max_advance(f32::INFINITY); - let (mut row, mut span) = (0, 0); - let mut overflow = false; - while !br.is_done() { - let Some((baseline, spans)) = rows.get(row) else { - overflow = true; - break; - }; - let baseline = *baseline; - let Some(&(x0, x1)) = spans.get(span) else { - row += 1; - span = 0; - continue; - }; - let width = (x1 - x0 - inset).max(1.0); - // A line known to be too wide here moves on to the first span that holds it. - if let Some(w) = needs.iter().find(|n| n.line == slots.len()).map(|n| n.width) - && w > width + 0.5 - && let Some((r, j)) = rows.first_fit(row, span + 1, w, inset) - { - (row, span) = (r, j); - continue; - } - br.state_mut().set_line_max_advance(width / scale); - if br.break_next().is_none() { - break; - } - // Parley aligns each line within the width it was broken at. - br.set_prior_line_width(width / scale); - slots.push(Slot { baseline, x: x0, width, row, span }); - span += 1; - } - br.finish(); - (slots, overflow) -} - -/// One laid-out line's ascent, descent and leading, as the line loop stacks it. `fallback` is -/// the paragraph's first style, used for a line with no glyph runs. -fn line_metrics(line: &parley::Line<'_, RunBrush>, styles: &[CharStyle], ps: &ParagraphStyle, k: f32, fallback: &CharStyle, vertical: bool) -> LineMetrics { - let first_px = fallback.size_pt * k; - let m = line.metrics(); - // Largest leading among the glyph runs, and half the largest em (a vertical column's half width). - let mut leading = 0.0f32; - let mut half = 0.0f32; - for item in line.items() { - if let PositionedLayoutItem::GlyphRun(gr) = item { - let px = gr.run().font_size(); - half = half.max(px * 0.5); - let lp = styles.get(gr.style().brush.0 as usize).and_then(|st| st.leading_pt); - leading = leading.max(lp.map_or(ps.auto_leading * px, |l| l * k)); - } - } - if leading == 0.0 { - leading = fallback.leading_pt.map_or(ps.auto_leading * first_px, |l| l * k); - } - let (ascent, descent) = if vertical { - let h = if half > 0.0 { half } else { first_px * 0.5 }; - (h, h) - } else if m.ascent > 0.0 || m.descent > 0.0 { - (m.ascent, m.descent) - } else { - (first_px * 0.8, first_px * 0.2) - }; - LineMetrics { ascent, descent, leading } -} - -/// Largest ascent, descent and leading over the lines of a broken paragraph, by -/// [`line_metrics`], so an area paragraph's rows are planned with the metrics it is stacked with. -fn area_metrics(layout: &Layout, styles: &[CharStyle], ps: &ParagraphStyle, k: f32, fallback: &CharStyle, vertical: bool) -> LineMetrics { - layout.lines().map(|line| line_metrics(&line, styles, ps, k, fallback, vertical)).fold(LineMetrics { ascent: 0.0, descent: 0.0, leading: 0.0 }, |a, b| { - LineMetrics { ascent: a.ascent.max(b.ascent), descent: a.descent.max(b.descent), leading: a.leading.max(b.leading) } - }) -} - -/// A tab as line breaking saw it: its shaped advance (before horizontal scale), the horizontal -/// scale, and the width that takes it to its tab stop on its line. -struct TabWidth { - advance: f32, - scale: f32, - width: f32, -} - -/// The width of each tab (offsets `tabs` in the paragraph text) on the broken lines of `layout`, -/// before kerning and alignment. -fn tab_widths(layout: &Layout, tabs: &[usize], styles: &[CharStyle], indent: f32, first_indent: f32, interval: f32) -> Vec { - let mut out: Vec = tabs.iter().map(|_| TabWidth { advance: interval, scale: 1.0, width: interval }).collect(); - for (li, line) in layout.lines().enumerate() { - let mut pos = indent + if li == 0 { first_indent } else { 0.0 }; - let mut seen: Vec = Vec::new(); - for item in line.items() { - let PositionedLayoutItem::GlyphRun(gr) = item else { - continue; - }; - let run = gr.run(); - if seen.contains(&run.index()) { - continue; - } - seen.push(run.index()); - let scale = styles.get(gr.style().brush.0 as usize).map_or(1.0, |st| if st.horizontal_scale > 0.0 { st.horizontal_scale } else { 1.0 }); - for c in run.visual_clusters() { - let advance = c.advance(); - match tabs.binary_search(&c.text_range().start).ok().and_then(|i| out.get_mut(i)) { - Some(t) => { - let stop = next_tab_stop(pos, interval); - *t = TabWidth { advance, scale, width: stop - pos }; - pos = stop; - } - None => pos += advance * scale, - } - } - } - } - out -} - -/// Byte ranges of paragraphs (each including its `\r`, `\n` or `\r\n` terminator). Text ending -/// with a break yields a final empty paragraph, like Photoshop's trailing empty line. -pub fn split_paragraphs(text: &str) -> Vec> { - let b = text.as_bytes(); - let mut v = Vec::new(); - let mut start = 0; - let mut i = 0; - while i < b.len() { - match b[i] { - b'\r' => { - let end = if b.get(i + 1) == Some(&b'\n') { i + 2 } else { i + 1 }; - v.push(start..end); - start = end; - i = end; - } - b'\n' => { - v.push(start..i + 1); - start = i + 1; - i += 1; - } - _ => i += 1, - } - } - v.push(start..b.len()); - v -} - -fn strip_break(text: &str, r: &Range) -> usize { - let s = &text[r.clone()]; - r.start + s.trim_end_matches(['\r', '\n']).len() -} - -fn quote(s: &str) -> String { - format!("\"{}\"", s.replace(['\\', '"'], "")) -} - -/// Placement data of one vertical-type glyph (before mapping to text space). -struct VGlyph { - upright: bool, - /// Advance along the column (px). - advance: f32, - /// Upright: distance from the top of the glyph's cell down to its baseline (px). - origin: f32, - /// Rotated: distance from the column centre line to the glyph's baseline (px). - centre: f32, -} - -/// Vertical metrics of a font instance: `VORG`, `vhea`/`vmtx`, else the ideographic em box. -struct VMetrics<'a> { - font: Option>, - coords: Vec, - /// px per font unit. - scale: f32, - /// Em-box fallback origin (px below the cell top). - em_origin: f32, -} - -impl<'a> VMetrics<'a> { - fn new(fd: &'a FontData, coords: &[i16], size: f32) -> Self { - use skrifa::MetadataProvider; - let font = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index).ok(); - let coords: Vec = coords.iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); - let (scale, em_origin) = match &font { - Some(f) => { - let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&coords)); - let upem = f32::from(m.units_per_em).max(1.0); - let (asc, desc) = (m.ascent, -m.descent); - // Ideographic em box: the em centred on the font's ascent/descent span. - let r = if asc + desc > 0.0 && asc.is_finite() && desc.is_finite() { (asc / (asc + desc)).clamp(0.0, 1.0) } else { 0.88 }; - (size / upem, size * r) - } - None => (0.0, size * 0.88), - }; - Self { font, coords, scale, em_origin } - } - - fn cmap(&self, c: char) -> Option { - use skrifa::MetadataProvider; - self.font.as_ref()?.charmap().map(c).map(|g| g.to_u32()) - } - - /// Distance from the top of an upright glyph's cell to its baseline (px). - fn origin(&self, gid: u32) -> f32 { - self.vertical_origin(gid).filter(|v| v.is_finite()).unwrap_or(self.em_origin) - } - - fn vertical_origin(&self, gid: u32) -> Option { - use skrifa::MetadataProvider; - use skrifa::raw::TableProvider; - let f = self.font.as_ref()?; - let g = skrifa::GlyphId::new(gid); - if let Ok(vorg) = f.vorg() { - return Some(f32::from(vorg.vertical_origin_y(g)) * self.scale); - } - let tsb = f.vmtx().ok()?.side_bearing(g)?; - // Top of the outline (font units), from the outline itself (glyf and CFF alike). - let outline = f.outline_glyphs().get(g)?; - let mut pen = YMax(None); - let settings = skrifa::outline::DrawSettings::unhinted(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&self.coords)); - outline.draw(settings, &mut pen).ok()?; - Some((pen.0? + f32::from(tsb)) * self.scale) - } -} - -/// Outline pen recording the largest y. -struct YMax(Option); - -impl YMax { - fn add(&mut self, y: f32) { - self.0 = Some(self.0.map_or(y, |m| m.max(y))); - } -} - -impl skrifa::outline::OutlinePen for YMax { - fn move_to(&mut self, _x: f32, y: f32) { - self.add(y); - } - fn line_to(&mut self, _x: f32, y: f32) { - self.add(y); - } - fn quad_to(&mut self, _cx0: f32, cy0: f32, _x: f32, y: f32) { - self.add(cy0); - self.add(y); - } - fn curve_to(&mut self, _cx0: f32, cy0: f32, _cx1: f32, cy1: f32, _x: f32, y: f32) { - self.add(cy0); - self.add(cy1); - self.add(y); - } - fn close(&mut self) {} -} - -/// OpenType feature settings of a character style (CSS `font-feature-settings` items). -fn feature_list(st: &CharStyle, small_caps: SmallCapsMode) -> Vec { - let mut feats: Vec = Vec::new(); - // Optical and manual kerning replace the font's kerning table; a character with a manual - // kern is manually kerned whatever its mode (as in Photoshop). - if st.kerning != Kerning::Metrics || st.kern != 0.0 { - feats.push("\"kern\" 0".into()); - } - if !st.ligatures { - feats.push("\"liga\" 0".into()); - feats.push("\"clig\" 0".into()); - } - if st.discretionary_ligatures { - feats.push("\"dlig\" 1".into()); - } - if small_caps == SmallCapsMode::OpenType { - feats.push("\"smcp\" 1".into()); - } - for f in &st.features { - if f.tag.len() == 4 && f.tag.is_ascii() { - feats.push(format!("\"{}\" {}", f.tag, f.value)); - } - } - feats -} - -/// The font variations for a run: the explicit axis values, plus `opsz` at the type size when the -/// style doesn't set it (as CSS `font-optical-sizing: auto`). A font without an `opsz` axis -/// ignores it. -fn variation_list(st: &CharStyle) -> Vec { - let mut vars: Vec = - st.variations.iter().filter(|v| v.axis.len() == 4 && v.axis.is_ascii() && v.value.is_finite()).map(|v| format!("\"{}\" {}", v.axis, v.value)).collect(); - if st.size_pt.is_finite() && !st.variations.iter().any(|v| v.axis == "opsz") { - vars.push(format!("\"opsz\" {}", st.size_pt.max(0.01))); - } - vars -} - -fn style_props(st: &CharStyle, k: f32, fallback: &[String], idx: u32, small_caps: SmallCapsMode) -> Vec> { - let px = (st.size_pt * k).max(0.01); - let mut fam: Vec = Vec::new(); - if !st.font_family.is_empty() { - fam.push(quote(&st.font_family)); - } - // Serif runs fall back to a Mincho face for Japanese (craft-fonts), others to a Gothic one. - if crate::craft_fonts::is_serif_family(&st.font_family) { - fam.extend(crate::craft_fonts::mincho_first(fallback).iter().map(|f| quote(f))); - } else { - fam.extend(fallback.iter().map(|f| quote(f))); - } - fam.push("sans-serif".into()); - let feats = feature_list(st, small_caps); - let vars = variation_list(st); - vec![ - StyleProperty::FontFamily(FontFamily::Source(Cow::Owned(fam.join(", ")))), - StyleProperty::FontSize(px), - StyleProperty::FontWeight(FontWeight::new(st.weight.clamp(1, 1000) as f32)), - StyleProperty::FontStyle(if st.italic { FontStyle::Italic } else { FontStyle::Normal }), - StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), - StyleProperty::FontVariations(FontVariations::Source(Cow::Owned(vars.join(", ")))), - StyleProperty::LetterSpacing(st.tracking / 1000.0 * px), - StyleProperty::Underline(st.underline), - StyleProperty::Strikethrough(st.strikethrough), - StyleProperty::Brush(RunBrush(idx, 0)), - StyleProperty::Locale(st.language.as_deref().and_then(|l| parley::fontique::Language::parse(l).ok())), - ] -} - -/// Closing CJK punctuation: its full-width cell has blank space after the mark. -fn is_closing(c: char) -> bool { - matches!(c, '、' | '。' | ',' | '.' | '」' | '』' | ')' | '〕' | '】' | '〉' | '》' | '〙' | '〗' | ']' | '}') -} - -/// Opening CJK brackets: blank space before the mark. -fn is_opening(c: char) -> bool { - matches!(c, '「' | '『' | '(' | '〔' | '【' | '〈' | '《' | '〘' | '〖' | '[' | '{') -} - -/// Basic Japanese punctuation squeeze (JIS X 4051 style) for one line in line space: between a -/// closing mark and a following opening or closing mark, the closing mark's trailing half-em -/// blank is removed; between two opening brackets, the second one's leading half-em. Clusters and -/// glyphs from the squeezed point on move back. Returns the total length removed. -pub(crate) fn squeeze_punctuation(text: &str, clusters: &mut [ClusterInfo], glyphs: &mut [PlacedGlyph]) -> f32 { - let first = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next()); - let last = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next_back()); - // Shift to apply from each cluster on. - let mut shifts = vec![0.0f32; clusters.len()]; - let mut total = 0.0f32; - for i in 1..clusters.len() { - let (Some(prev), Some(cur)) = (clusters.get(i - 1), clusters.get(i)) else { continue }; - if prev.rtl || cur.rtl { - continue; - } - let (Some(a), Some(b)) = (last(prev), first(cur)) else { continue }; - let cut = if is_closing(a) && (is_opening(b) || is_closing(b)) { - prev.advance * 0.5 - } else if is_opening(a) && is_opening(b) { - cur.advance * 0.5 - } else { - 0.0 - }; - if cut.is_finite() && cut > 0.0 { - total += cut; - } - if let Some(s) = shifts.get_mut(i) { - *s = total; - } - } - if total <= 0.0 { - return 0.0; - } - let starts: Vec = clusters.iter().map(|c| c.x).collect(); - for (c, s) in clusters.iter_mut().zip(&shifts) { - c.x -= s; - } - for g in glyphs.iter_mut() { - let i = starts.iter().rposition(|&s| s <= g.x + 1e-3).unwrap_or(0); - g.x -= shifts.get(i).copied().unwrap_or(0.0); - } - total -} - -/// Whether to embolden a face synthetically. Font matching (fontique) asks for it whenever the -/// requested weight is above the face's, so Regular (400) from a family with only W3 (300) and W6 -/// (600), like Hiragino Mincho ProN, came out as a smeared bold W3. Like Photoshop and CSS, only -/// a bold request (≥ 600) on a face that isn't bold (≤ 500) is emboldened; anything else uses the -/// nearest face as it is (Faux Bold stays a separate, explicit style). -pub(crate) fn synthetic_bold(matcher_says: bool, requested: u16, face_weight: f32) -> bool { - matcher_says && requested >= 600 && face_weight <= 500.0 -} - -/// Height of the lowercase ascender ('d') of the tallest run on the line. -fn first_ascent(line: &parley::Line<'_, RunBrush>) -> Option { - use skrifa::MetadataProvider; - let mut best: Option = None; - for run in line.runs() { - let fd = run.font(); - let Ok(font) = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index) else { - continue; - }; - let coords: Vec = run.normalized_coords().iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); - let loc = skrifa::instance::LocationRef::new(&coords); - let size = skrifa::instance::Size::new(run.font_size()); - let h = font.charmap().map('d').and_then(|g| font.glyph_metrics(size, loc).bounds(g)).map(|b| b.y_max).or_else(|| { - let m = font.metrics(size, loc); - m.cap_height.or(Some(m.ascent * 0.75)) - }); - if let Some(h) = h { - best = Some(best.map_or(h, |b: f32| b.max(h))); - } - } - best -} - -/// Hangul (syllables and jamo). -fn is_hangul(c: char) -> bool { - matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7AF}' | '\u{D7B0}'..='\u{D7FF}') -} - -/// The byte ranges of `text` made of Hangul, each as long as it runs. -pub(crate) fn hangul_runs(text: &str) -> Vec> { - let mut runs: Vec> = Vec::new(); - for (i, c) in text.char_indices().filter(|&(_, c)| is_hangul(c)) { - match runs.last_mut() { - Some(r) if r.end == i => r.end = i + c.len_utf8(), - _ => runs.push(i..i + c.len_utf8()), - } - } - runs -} - #[cfg(test)] mod tests { use super::{SmallCapsMode, feature_list, small_caps_mode, variation_list}; diff --git a/crates/text/src/layout/area.rs b/crates/text/src/layout/area.rs new file mode 100644 index 00000000000..d91d497e26d --- /dev/null +++ b/crates/text/src/layout/area.rs @@ -0,0 +1,238 @@ +use super::*; + +/// A line's ascent, descent and leading (px); for area type, the largest over a paragraph. +#[derive(Clone, Copy, Debug)] +pub(super) struct LineMetrics { + pub(super) ascent: f32, + pub(super) descent: f32, + pub(super) leading: f32, +} + +/// Most line-breaking passes area type makes for one paragraph, over all its plans (each span +/// left empty for a word that doesn't fit costs a pass). Past it, words overflow their spans. +pub(super) const MAX_AREA_PASSES: usize = 32; + +/// Most rows one area paragraph is planned on. +const MAX_AREA_ROWS: usize = 4096; + +#[cfg(test)] +thread_local! { + /// Area line-breaking passes made on this thread, for tests. + pub(crate) static AREA_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The rows an area paragraph's lines go on: baselines from `next` down, one leading apart, +/// each with its spans left to right. They don't depend on the text, so they are found once +/// (lazily) and shared by every pass. +struct AreaRows<'a> { + area: &'a crate::area::AreaShape, + m: LineMetrics, + min_width: f32, + /// Where the search for the next row starts. + next: f32, + rows: Vec<(f32, Vec<(f32, f32)>)>, + done: bool, +} + +impl AreaRows<'_> { + /// Row `i`: its baseline and spans; `None` past the shape. + fn get(&mut self, i: usize) -> Option<&(f32, Vec<(f32, f32)>)> { + while self.rows.len() <= i && !self.done { + match self.area.next_row(self.next, self.m.ascent, self.m.descent, self.min_width) { + Some((b, spans)) if self.rows.len() < MAX_AREA_ROWS => { + self.next = b + self.m.leading; + self.rows.push((b, spans)); + } + _ => self.done = true, + } + } + self.rows.get(i) + } + + /// The first span, from span `span` of row `row` on, that leaves at least `width` once + /// `inset` (the paragraph's indents) is taken off: its row and span. + fn first_fit(&mut self, row: usize, span: usize, width: f32, inset: f32) -> Option<(usize, usize)> { + let (mut r, mut first) = (row, span); + while let Some((_, spans)) = self.get(r) { + if let Some(j) = spans.iter().skip(first).position(|&(x0, x1)| x1 - x0 - inset + 0.5 >= width) { + return Some((r, first + j)); + } + r += 1; + first = 0; + } + None + } +} + +/// A line wider than the span it fell in, that a later span can hold: the line's index in the +/// paragraph, where its text starts, and its width. +#[derive(Clone, Copy, Debug)] +struct Need { + line: usize, + start: usize, + width: f32, +} + +/// Breaks one paragraph of area type a line at a time, each line as wide as the next span the +/// shape leaves (rows from `from` down, spans left to right). Returns each line's slot and +/// whether text was left over because the shape ran out (hidden, like box overflow). +/// +/// A span too narrow for the word that would start it (the narrow top of an ellipse) is left +/// empty and the word goes to the first later span that holds it, as Photoshop does. A word no +/// later span holds but another span of the shape would means the shape is full: it and the rest are +/// hidden. Only a word no span holds overflows its span. Parley doesn't report a line's +/// trailing whitespace while breaking, so overflowing lines are found after a pass and the +/// paragraph broken again; `budget` (shared by the paragraph's calls) bounds the passes. +/// +/// Horizontal scale applies after shaping, so each line breaks at its span width divided by +/// `scale`; widths compared with spans are the scaled ones. +#[allow(clippy::too_many_arguments)] +pub(super) fn break_area( + layout: &mut Layout, + area: &crate::area::AreaShape, + from: f32, + m: LineMetrics, + indents: (f32, f32), + min_width: f32, + scale: f32, + budget: &std::cell::Cell, +) -> (Vec, bool) { + let inset = indents.0 + indents.1; + let mut rows = AreaRows { area, m, min_width, next: from, rows: Vec::new(), done: false }; + // Every row of the shape from its top, whatever paragraph came before (found lazily). + let mut shape_rows = AreaRows { area, m, min_width, next: area.bounds[1], rows: Vec::new(), done: false }; + let mut needs: Vec = Vec::new(); + loop { + let (slots, overflow) = break_area_pass(layout, &mut rows, inset, scale, &needs); + budget.set(budget.get().saturating_sub(1)); + // Each line's text start and scaled width without its trailing whitespace. + let lines: Vec<(usize, f32)> = layout + .lines() + .map(|l| { + let lm = l.metrics(); + (l.text_range().start, (lm.advance - lm.trailing_whitespace) * scale) + }) + .collect(); + // A line still wider than its span that some span of the shape would hold: the shape ran + // out of room for it (the narrow bottom of a full bubble). It and the rest are hidden, as + // overflow; only a word no span holds overflows its span. + let mut ran_out = |slots: Vec, overflow: bool| match lines + .iter() + .zip(&slots) + .position(|(&(_, width), s)| width > s.width + 0.5 && shape_rows.first_fit(0, 0, width, inset).is_some()) + { + Some(li) => (slots.into_iter().take(li).collect(), true), + None => (slots, overflow), + }; + if budget.get() == 0 { + return ran_out(slots, overflow); + } + // A line that now starts elsewhere (an earlier line changed) no longer needs its span. + let kept = needs.len(); + needs.retain(|n| lines.get(n.line).is_some_and(|l| l.0 == n.start)); + if needs.len() != kept { + continue; + } + let mut new = None; + for (li, (&(start, width), s)) in lines.iter().zip(&slots).enumerate() { + if width > s.width + 0.5 && !needs.iter().any(|n| n.line == li) && rows.first_fit(s.row, s.span + 1, width, inset).is_some() { + new = Some(Need { line: li, start, width }); + break; + } + } + if let Some(n) = new { + needs.push(n); + continue; + } + return ran_out(slots, overflow); + } +} + +/// One pass of [`break_area`]: each line in the next span, skipping spans too narrow for a +/// line in `needs` when a later span holds it. +fn break_area_pass(layout: &mut Layout, rows: &mut AreaRows<'_>, inset: f32, scale: f32, needs: &[Need]) -> (Vec, bool) { + #[cfg(test)] + AREA_PASSES.with(|c| c.set(c.get() + 1)); + let mut slots: Vec = Vec::new(); + let mut br = layout.break_lines(); + // Per-line widths below are never wider than this, as parley requires. + br.state_mut().set_layout_max_advance(f32::INFINITY); + let (mut row, mut span) = (0, 0); + let mut overflow = false; + while !br.is_done() { + let Some((baseline, spans)) = rows.get(row) else { + overflow = true; + break; + }; + let baseline = *baseline; + let Some(&(x0, x1)) = spans.get(span) else { + row += 1; + span = 0; + continue; + }; + let width = (x1 - x0 - inset).max(1.0); + // A line known to be too wide here moves on to the first span that holds it. + if let Some(w) = needs.iter().find(|n| n.line == slots.len()).map(|n| n.width) + && w > width + 0.5 + && let Some((r, j)) = rows.first_fit(row, span + 1, w, inset) + { + (row, span) = (r, j); + continue; + } + br.state_mut().set_line_max_advance(width / scale); + if br.break_next().is_none() { + break; + } + // Parley aligns each line within the width it was broken at. + br.set_prior_line_width(width / scale); + slots.push(Slot { baseline, x: x0, width, row, span }); + span += 1; + } + br.finish(); + (slots, overflow) +} + +/// One laid-out line's ascent, descent and leading, as the line loop stacks it. `fallback` is +/// the paragraph's first style, used for a line with no glyph runs. +pub(super) fn line_metrics( + line: &parley::Line<'_, RunBrush>, + styles: &[CharStyle], + ps: &ParagraphStyle, + k: f32, + fallback: &CharStyle, + vertical: bool, +) -> LineMetrics { + let first_px = fallback.size_pt * k; + let m = line.metrics(); + // Largest leading among the glyph runs, and half the largest em (a vertical column's half width). + let mut leading = 0.0f32; + let mut half = 0.0f32; + for item in line.items() { + if let PositionedLayoutItem::GlyphRun(gr) = item { + let px = gr.run().font_size(); + half = half.max(px * 0.5); + let lp = styles.get(gr.style().brush.0 as usize).and_then(|st| st.leading_pt); + leading = leading.max(lp.map_or(ps.auto_leading * px, |l| l * k)); + } + } + if leading == 0.0 { + leading = fallback.leading_pt.map_or(ps.auto_leading * first_px, |l| l * k); + } + let (ascent, descent) = if vertical { + let h = if half > 0.0 { half } else { first_px * 0.5 }; + (h, h) + } else if m.ascent > 0.0 || m.descent > 0.0 { + (m.ascent, m.descent) + } else { + (first_px * 0.8, first_px * 0.2) + }; + LineMetrics { ascent, descent, leading } +} + +/// Largest ascent, descent and leading over the lines of a broken paragraph, by +/// [`line_metrics`], so an area paragraph's rows are planned with the metrics it is stacked with. +pub(super) fn area_metrics(layout: &Layout, styles: &[CharStyle], ps: &ParagraphStyle, k: f32, fallback: &CharStyle, vertical: bool) -> LineMetrics { + layout.lines().map(|line| line_metrics(&line, styles, ps, k, fallback, vertical)).fold(LineMetrics { ascent: 0.0, descent: 0.0, leading: 0.0 }, |a, b| { + LineMetrics { ascent: a.ascent.max(b.ascent), descent: a.descent.max(b.descent), leading: a.leading.max(b.leading) } + }) +} diff --git a/crates/text/src/layout/navigate.rs b/crates/text/src/layout/navigate.rs new file mode 100644 index 00000000000..e7d9c003338 --- /dev/null +++ b/crates/text/src/layout/navigate.rs @@ -0,0 +1,91 @@ +use super::*; + +/// Byte offset of character `index` (the text length when `index` is past the end). +pub fn byte_index(text: &str, index: usize) -> usize { + text.char_indices().nth(index).map_or(text.len(), |(b, _)| b) +} + +/// Character index of byte `byte`, floored to a char boundary so a bad offset never panics. +pub fn char_index(text: &str, byte: usize) -> usize { + let mut byte = byte.min(text.len()); + while byte > 0 && !text.is_char_boundary(byte) { + byte -= 1; + } + text[..byte].chars().count() +} + +/// Line containing a byte offset. At a shared wrap boundary the caret belongs to +/// the following line, while an offset at the end of the text stays on the last. +pub fn line_index(layout: &TextLayout, byte: usize) -> usize { + layout.lines.iter().rposition(|ln| byte >= ln.range.start && byte <= ln.range.end).unwrap_or_else(|| layout.lines.len().saturating_sub(1)) +} + +/// Nearest caret to a text-space point: character index and the line it sits on. +pub fn hit_char(layout: &TextLayout, text: &str, x: f32, y: f32) -> (usize, usize) { + let byte = layout.hit_test(x, y); + // At a soft-wrap boundary either visual line can share this byte offset. The + // pointer's line, not the caret's preferred (following) line, is authoritative. + let (_, line_y) = layout.to_line(x, y); + let line = layout.closest_line(line_y).map_or_else(|| line_index(layout, byte), |(index, _)| index); + (char_index(text, byte), line) +} + +/// Text-space point inside the laid-out line boxes, expanded by `slop` px on every side. +pub fn text_point_inside(layout: &TextLayout, x: f32, y: f32, slop: f32) -> bool { + let slop = if slop.is_finite() { slop.max(0.0) } else { 0.0 }; + layout.bounds().is_some_and(|b| x >= b[0] - slop && x <= b[2] + slop && y >= b[1] - slop && y <= b[3] + slop) +} + +/// Character index of the word boundary before (`forward` is false) or after `idx`. +/// +/// A word is a run of alphanumeric characters, the rule the Type tool has always used. +pub fn word_boundary(text: &str, idx: usize, forward: bool) -> usize { + let chars: Vec = text.chars().collect(); + let mut i = idx.min(chars.len()); + if forward { + while i < chars.len() && !chars[i].is_alphanumeric() { + i += 1; + } + while i < chars.len() && chars[i].is_alphanumeric() { + i += 1; + } + } else { + while i > 0 && !chars[i - 1].is_alphanumeric() { + i -= 1; + } + while i > 0 && chars[i - 1].is_alphanumeric() { + i -= 1; + } + } + i +} + +/// Caret on the neighbouring line (`dir` < 0 previous, otherwise next), keeping `x` +/// (line space: the position along the line). Past the first or last line the caret +/// goes to the start or end of the text. Line space is the same for both orientations, +/// so a column of vertical type steps the same way a line of horizontal type does. +pub fn line_step(layout: &TextLayout, text: &str, idx: usize, x: f32, dir: i32) -> usize { + let n = text.chars().count(); + let idx = idx.min(n); + if layout.lines.is_empty() { + return idx; + } + let current_line = line_index(layout, byte_index(text, idx)); + let target_line = if dir < 0 { + let Some(target) = current_line.checked_sub(1) else { return 0 }; + target + } else { + let Some(target) = current_line.checked_add(1).filter(|target| *target < layout.lines.len()) else { return n }; + target + }; + char_index(text, layout.hit_test_x_on_line(target_line, x)) +} + +/// Line start (`end` false) or end for the line containing `idx`, as a character index. +pub fn line_edge(layout: &TextLayout, text: &str, idx: usize, end: bool) -> usize { + let n = text.chars().count(); + let idx = idx.min(n); + let byte = byte_index(text, idx); + let line = layout.lines.get(line_index(layout, byte)); + line.map_or(idx, |ln| char_index(text, if end { ln.range.end } else { ln.range.start })) +} diff --git a/crates/text/src/layout/paragraphs.rs b/crates/text/src/layout/paragraphs.rs new file mode 100644 index 00000000000..2be1fbbc5ae --- /dev/null +++ b/crates/text/src/layout/paragraphs.rs @@ -0,0 +1,87 @@ +use super::*; + +/// Photoshop's default tab stops: every half inch, measured from the anchor of point text or the +/// left edge of a paragraph box. PSD type carries no custom tab stops, so these are the only ones. +pub const DEFAULT_TAB_STOP_PT: f32 = 36.0; + +/// The first tab stop after `pos` (px from the anchor or box edge); stops are `interval` apart. +pub(super) fn next_tab_stop(pos: f32, interval: f32) -> f32 { + if interval > 0.0 && pos.is_finite() { ((pos + 1e-3) / interval).floor() * interval + interval } else { pos } +} + +/// A tab as line breaking saw it: its shaped advance (before horizontal scale), the horizontal +/// scale, and the width that takes it to its tab stop on its line. +pub(super) struct TabWidth { + pub(super) advance: f32, + pub(super) scale: f32, + pub(super) width: f32, +} + +/// The width of each tab (offsets `tabs` in the paragraph text) on the broken lines of `layout`, +/// before kerning and alignment. +pub(super) fn tab_widths(layout: &Layout, tabs: &[usize], styles: &[CharStyle], indent: f32, first_indent: f32, interval: f32) -> Vec { + let mut out: Vec = tabs.iter().map(|_| TabWidth { advance: interval, scale: 1.0, width: interval }).collect(); + for (li, line) in layout.lines().enumerate() { + let mut pos = indent + if li == 0 { first_indent } else { 0.0 }; + let mut seen: Vec = Vec::new(); + for item in line.items() { + let PositionedLayoutItem::GlyphRun(gr) = item else { + continue; + }; + let run = gr.run(); + if seen.contains(&run.index()) { + continue; + } + seen.push(run.index()); + let scale = styles.get(gr.style().brush.0 as usize).map_or(1.0, |st| if st.horizontal_scale > 0.0 { st.horizontal_scale } else { 1.0 }); + for c in run.visual_clusters() { + let advance = c.advance(); + match tabs.binary_search(&c.text_range().start).ok().and_then(|i| out.get_mut(i)) { + Some(t) => { + let stop = next_tab_stop(pos, interval); + *t = TabWidth { advance, scale, width: stop - pos }; + pos = stop; + } + None => pos += advance * scale, + } + } + } + } + out +} + +/// Byte ranges of paragraphs (each including its `\r`, `\n` or `\r\n` terminator). Text ending +/// with a break yields a final empty paragraph, like Photoshop's trailing empty line. +pub fn split_paragraphs(text: &str) -> Vec> { + let b = text.as_bytes(); + let mut v = Vec::new(); + let mut start = 0; + let mut i = 0; + while i < b.len() { + match b[i] { + b'\r' => { + let end = if b.get(i + 1) == Some(&b'\n') { i + 2 } else { i + 1 }; + v.push(start..end); + start = end; + i = end; + } + b'\n' => { + v.push(start..i + 1); + start = i + 1; + i += 1; + } + _ => i += 1, + } + } + v.push(start..b.len()); + v +} + +pub(super) fn strip_break(text: &str, r: &Range) -> usize { + let s = &text[r.clone()]; + r.start + s.trim_end_matches(['\r', '\n']).len() +} + +pub(super) fn quote(s: &str) -> String { + format!("\"{}\"", s.replace(['\\', '"'], "")) +} diff --git a/crates/text/src/layout/style.rs b/crates/text/src/layout/style.rs new file mode 100644 index 00000000000..fc5b775a7d0 --- /dev/null +++ b/crates/text/src/layout/style.rs @@ -0,0 +1,228 @@ +use super::paragraphs::quote; +use super::*; + +/// Photoshop synthesizes small caps for faces without an OpenType `smcp` table. Keep the same +/// readable hierarchy for every font instead of silently rendering lowercase text unchanged. +pub(super) const SYNTHETIC_SMALL_CAPS_SCALE: f32 = 0.7; + +/// Photoshop's default superscript / subscript size and position (Type preferences, stored in a +/// PSD's text resources as `SuperscriptSize` .583, `SuperscriptPosition` .333 and their +/// `Subscript` twins): the run is drawn at 58.3% of its size and moved by 33.3% of its size. +const SCRIPT_SIZE: f32 = 0.583; + +const SCRIPT_POSITION: f32 = 0.333; + +/// The style a run is drawn with: superscript and subscript shrink it and shift its baseline. +pub(super) fn drawn_style(s: &mut CharStyle) { + let dir = match s.baseline { + FontBaseline::Normal => return, + FontBaseline::Superscript => 1.0, + FontBaseline::Subscript => -1.0, + }; + s.baseline_shift_pt += dir * SCRIPT_POSITION * s.size_pt; + s.size_pt *= SCRIPT_SIZE; +} + +/// The rendering path for a `SmallCaps` character style. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SmallCapsMode { + None, + OpenType, + Synthetic, +} + +/// Whether the style's selected face has an `smcp` feature (a font load and GSUB parse). +pub(super) fn probe_smcp(fonts: &mut FontDb, style: &CharStyle) -> bool { + #[cfg(test)] + SMCP_PROBES.with(|c| c.set(c.get() + 1)); + fonts.selected_face_has_feature(&style.font_family, style.weight, style.italic, Tag::new(b"smcp")) +} + +#[cfg(test)] +thread_local! { + pub(super) static SMCP_PROBES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(super) fn small_caps_mode(caps: Caps, face_has_smcp: bool) -> SmallCapsMode { + match caps { + Caps::SmallCaps if face_has_smcp => SmallCapsMode::OpenType, + Caps::SmallCaps => SmallCapsMode::Synthetic, + _ => SmallCapsMode::None, + } +} + +/// A style's horizontal scale; unset (zero or negative) is 100%. +pub(super) fn effective_horizontal_scale(st: &CharStyle) -> f32 { + if st.horizontal_scale > 0.0 && st.horizontal_scale.is_finite() { st.horizontal_scale } else { 1.0 } +} + +/// OpenType feature settings of a character style (CSS `font-feature-settings` items). +pub(super) fn feature_list(st: &CharStyle, small_caps: SmallCapsMode) -> Vec { + let mut feats: Vec = Vec::new(); + // Optical and manual kerning replace the font's kerning table; a character with a manual + // kern is manually kerned whatever its mode (as in Photoshop). + if st.kerning != Kerning::Metrics || st.kern != 0.0 { + feats.push("\"kern\" 0".into()); + } + if !st.ligatures { + feats.push("\"liga\" 0".into()); + feats.push("\"clig\" 0".into()); + } + if st.discretionary_ligatures { + feats.push("\"dlig\" 1".into()); + } + if small_caps == SmallCapsMode::OpenType { + feats.push("\"smcp\" 1".into()); + } + for f in &st.features { + if f.tag.len() == 4 && f.tag.is_ascii() { + feats.push(format!("\"{}\" {}", f.tag, f.value)); + } + } + feats +} + +/// The font variations for a run: the explicit axis values, plus `opsz` at the type size when the +/// style doesn't set it (as CSS `font-optical-sizing: auto`). A font without an `opsz` axis +/// ignores it. +pub(super) fn variation_list(st: &CharStyle) -> Vec { + let mut vars: Vec = + st.variations.iter().filter(|v| v.axis.len() == 4 && v.axis.is_ascii() && v.value.is_finite()).map(|v| format!("\"{}\" {}", v.axis, v.value)).collect(); + if st.size_pt.is_finite() && !st.variations.iter().any(|v| v.axis == "opsz") { + vars.push(format!("\"opsz\" {}", st.size_pt.max(0.01))); + } + vars +} + +pub(super) fn style_props(st: &CharStyle, k: f32, fallback: &[String], idx: u32, small_caps: SmallCapsMode) -> Vec> { + let px = (st.size_pt * k).max(0.01); + let mut fam: Vec = Vec::new(); + if !st.font_family.is_empty() { + fam.push(quote(&st.font_family)); + } + // Serif runs fall back to a Mincho face for Japanese (craft-fonts), others to a Gothic one. + if crate::craft_fonts::is_serif_family(&st.font_family) { + fam.extend(crate::craft_fonts::mincho_first(fallback).iter().map(|f| quote(f))); + } else { + fam.extend(fallback.iter().map(|f| quote(f))); + } + fam.push("sans-serif".into()); + let feats = feature_list(st, small_caps); + let vars = variation_list(st); + vec![ + StyleProperty::FontFamily(FontFamily::Source(Cow::Owned(fam.join(", ")))), + StyleProperty::FontSize(px), + StyleProperty::FontWeight(FontWeight::new(st.weight.clamp(1, 1000) as f32)), + StyleProperty::FontStyle(if st.italic { FontStyle::Italic } else { FontStyle::Normal }), + StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), + StyleProperty::FontVariations(FontVariations::Source(Cow::Owned(vars.join(", ")))), + StyleProperty::LetterSpacing(st.tracking / 1000.0 * px), + StyleProperty::Underline(st.underline), + StyleProperty::Strikethrough(st.strikethrough), + StyleProperty::Brush(RunBrush(idx, 0)), + StyleProperty::Locale(st.language.as_deref().and_then(|l| parley::fontique::Language::parse(l).ok())), + ] +} + +/// Closing CJK punctuation: its full-width cell has blank space after the mark. +fn is_closing(c: char) -> bool { + matches!(c, '、' | '。' | ',' | '.' | '」' | '』' | ')' | '〕' | '】' | '〉' | '》' | '〙' | '〗' | ']' | '}') +} + +/// Opening CJK brackets: blank space before the mark. +fn is_opening(c: char) -> bool { + matches!(c, '「' | '『' | '(' | '〔' | '【' | '〈' | '《' | '〘' | '〖' | '[' | '{') +} + +/// Basic Japanese punctuation squeeze (JIS X 4051 style) for one line in line space: between a +/// closing mark and a following opening or closing mark, the closing mark's trailing half-em +/// blank is removed; between two opening brackets, the second one's leading half-em. Clusters and +/// glyphs from the squeezed point on move back. Returns the total length removed. +pub(crate) fn squeeze_punctuation(text: &str, clusters: &mut [ClusterInfo], glyphs: &mut [PlacedGlyph]) -> f32 { + let first = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next()); + let last = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next_back()); + // Shift to apply from each cluster on. + let mut shifts = vec![0.0f32; clusters.len()]; + let mut total = 0.0f32; + for i in 1..clusters.len() { + let (Some(prev), Some(cur)) = (clusters.get(i - 1), clusters.get(i)) else { continue }; + if prev.rtl || cur.rtl { + continue; + } + let (Some(a), Some(b)) = (last(prev), first(cur)) else { continue }; + let cut = if is_closing(a) && (is_opening(b) || is_closing(b)) { + prev.advance * 0.5 + } else if is_opening(a) && is_opening(b) { + cur.advance * 0.5 + } else { + 0.0 + }; + if cut.is_finite() && cut > 0.0 { + total += cut; + } + if let Some(s) = shifts.get_mut(i) { + *s = total; + } + } + if total <= 0.0 { + return 0.0; + } + let starts: Vec = clusters.iter().map(|c| c.x).collect(); + for (c, s) in clusters.iter_mut().zip(&shifts) { + c.x -= s; + } + for g in glyphs.iter_mut() { + let i = starts.iter().rposition(|&s| s <= g.x + 1e-3).unwrap_or(0); + g.x -= shifts.get(i).copied().unwrap_or(0.0); + } + total +} + +/// Whether to embolden a face synthetically. Font matching (fontique) asks for it whenever the +/// requested weight is above the face's, so Regular (400) from a family with only W3 (300) and W6 +/// (600), like Hiragino Mincho ProN, came out as a smeared bold W3. Like Photoshop and CSS, only +/// a bold request (≥ 600) on a face that isn't bold (≤ 500) is emboldened; anything else uses the +/// nearest face as it is (Faux Bold stays a separate, explicit style). +pub(crate) fn synthetic_bold(matcher_says: bool, requested: u16, face_weight: f32) -> bool { + matcher_says && requested >= 600 && face_weight <= 500.0 +} + +/// Height of the lowercase ascender ('d') of the tallest run on the line. +pub(super) fn first_ascent(line: &parley::Line<'_, RunBrush>) -> Option { + use skrifa::MetadataProvider; + let mut best: Option = None; + for run in line.runs() { + let fd = run.font(); + let Ok(font) = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index) else { + continue; + }; + let coords: Vec = run.normalized_coords().iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); + let loc = skrifa::instance::LocationRef::new(&coords); + let size = skrifa::instance::Size::new(run.font_size()); + let h = font.charmap().map('d').and_then(|g| font.glyph_metrics(size, loc).bounds(g)).map(|b| b.y_max).or_else(|| { + let m = font.metrics(size, loc); + m.cap_height.or(Some(m.ascent * 0.75)) + }); + if let Some(h) = h { + best = Some(best.map_or(h, |b: f32| b.max(h))); + } + } + best +} + +/// Hangul (syllables and jamo). +fn is_hangul(c: char) -> bool { + matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7AF}' | '\u{D7B0}'..='\u{D7FF}') +} + +/// The byte ranges of `text` made of Hangul, each as long as it runs. +pub(crate) fn hangul_runs(text: &str) -> Vec> { + let mut runs: Vec> = Vec::new(); + for (i, c) in text.char_indices().filter(|&(_, c)| is_hangul(c)) { + match runs.last_mut() { + Some(r) if r.end == i => r.end = i + c.len_utf8(), + _ => runs.push(i..i + c.len_utf8()), + } + } + runs +} diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs new file mode 100644 index 00000000000..beabcfbf05d --- /dev/null +++ b/crates/text/src/layout/vertical.rs @@ -0,0 +1,149 @@ +use super::*; + +/// How a character is set in vertical type (a simplification of Unicode's +/// `Vertical_Orientation`, UAX #50). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VClass { + /// Rotated 90° clockwise (Latin, digits, most symbols). + Rotate = 0, + /// Upright (ideographs, kana, Hangul, full-width forms, CJK punctuation such as 、。), + /// using a vertical alternate when the font has one. + Upright = 1, + /// Upright through its vertical alternate (brackets, the long-vowel mark, dashes); rotated + /// when the font has none. + AlternateOrRotate = 2, +} + +/// The vertical-type class of a character. +pub fn vertical_class(c: char) -> VClass { + let u = c as u32; + let alt = matches!( + u, + 0x2014..=0x2016 + | 0x2025 + | 0x2026 + | 0x2329 + | 0x232A + | 0x3008..=0x3011 + | 0x3014..=0x301F + | 0x3030 + | 0x30A0 + | 0x30FC + | 0xFE59..=0xFE5E + | 0xFF08 + | 0xFF09 + | 0xFF0D + | 0xFF1A..=0xFF1E + | 0xFF3B + | 0xFF3D + | 0xFF3F + | 0xFF5B..=0xFF60 + | 0xFFE3 + ); + if alt { + return VClass::AlternateOrRotate; + } + // Half-width katakana and Hangul rotate like other half-width text. + if (0xFF61..=0xFFDC).contains(&u) { + return VClass::Rotate; + } + let upright = crate::cjk::classify(c).is_some() + || matches!(u, 0xA7 | 0xA9 | 0xAE | 0xB1 | 0xBC..=0xBE | 0xD7 | 0xF7 | 0x2E80..=0x2EFF | 0xFE10..=0xFE1F | 0xFE30..=0xFE4F | 0x1F000..=0x1FAFF); + if upright { VClass::Upright } else { VClass::Rotate } +} + +/// Placement data of one vertical-type glyph (before mapping to text space). +pub(super) struct VGlyph { + pub(super) upright: bool, + /// Advance along the column (px). + pub(super) advance: f32, + /// Upright: distance from the top of the glyph's cell down to its baseline (px). + pub(super) origin: f32, + /// Rotated: distance from the column centre line to the glyph's baseline (px). + pub(super) centre: f32, +} + +/// Vertical metrics of a font instance: `VORG`, `vhea`/`vmtx`, else the ideographic em box. +pub(super) struct VMetrics<'a> { + font: Option>, + coords: Vec, + /// px per font unit. + scale: f32, + /// Em-box fallback origin (px below the cell top). + em_origin: f32, +} + +impl<'a> VMetrics<'a> { + pub(super) fn new(fd: &'a FontData, coords: &[i16], size: f32) -> Self { + use skrifa::MetadataProvider; + let font = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index).ok(); + let coords: Vec = coords.iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); + let (scale, em_origin) = match &font { + Some(f) => { + let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&coords)); + let upem = f32::from(m.units_per_em).max(1.0); + let (asc, desc) = (m.ascent, -m.descent); + // Ideographic em box: the em centred on the font's ascent/descent span. + let r = if asc + desc > 0.0 && asc.is_finite() && desc.is_finite() { (asc / (asc + desc)).clamp(0.0, 1.0) } else { 0.88 }; + (size / upem, size * r) + } + None => (0.0, size * 0.88), + }; + Self { font, coords, scale, em_origin } + } + + pub(super) fn cmap(&self, c: char) -> Option { + use skrifa::MetadataProvider; + self.font.as_ref()?.charmap().map(c).map(|g| g.to_u32()) + } + + /// Distance from the top of an upright glyph's cell to its baseline (px). + pub(super) fn origin(&self, gid: u32) -> f32 { + self.vertical_origin(gid).filter(|v| v.is_finite()).unwrap_or(self.em_origin) + } + + fn vertical_origin(&self, gid: u32) -> Option { + use skrifa::MetadataProvider; + use skrifa::raw::TableProvider; + let f = self.font.as_ref()?; + let g = skrifa::GlyphId::new(gid); + if let Ok(vorg) = f.vorg() { + return Some(f32::from(vorg.vertical_origin_y(g)) * self.scale); + } + let tsb = f.vmtx().ok()?.side_bearing(g)?; + // Top of the outline (font units), from the outline itself (glyf and CFF alike). + let outline = f.outline_glyphs().get(g)?; + let mut pen = YMax(None); + let settings = skrifa::outline::DrawSettings::unhinted(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&self.coords)); + outline.draw(settings, &mut pen).ok()?; + Some((pen.0? + f32::from(tsb)) * self.scale) + } +} + +/// Outline pen recording the largest y. +struct YMax(Option); + +impl YMax { + fn add(&mut self, y: f32) { + self.0 = Some(self.0.map_or(y, |m| m.max(y))); + } +} + +impl skrifa::outline::OutlinePen for YMax { + fn move_to(&mut self, _x: f32, y: f32) { + self.add(y); + } + fn line_to(&mut self, _x: f32, y: f32) { + self.add(y); + } + fn quad_to(&mut self, _cx0: f32, cy0: f32, _x: f32, y: f32) { + self.add(cy0); + self.add(y); + } + fn curve_to(&mut self, _cx0: f32, cy0: f32, _cx1: f32, cy1: f32, _x: f32, y: f32) { + self.add(cy0); + self.add(cy1); + self.add(y); + } + fn close(&mut self) {} +}