oxedyne/fe2o3/fe2o3_austenite/src/flow/text.rs
64.3 KiB, 94 runs
created by r1870400018:63536, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Original work copyright (c) the Typst project authors (typst-layout `inline/shaping.rs` and typst-library `text/mod.rs`, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | // U6a owns this file: text shaping under resolved `text` styles, and the font store `Engine::fonts` |
| 5 | // holds -- family lookup by name, weight, style and stretch over the embedded faces and every font file |
| 6 | // in the vfs, with Typst's fallback list and a warning on a missing family. |
| 7 | // |
| 8 | // Shaping is a port of Typst 0.15.1's `typst-layout/src/inline/shaping.rs` (Apache-2.0, (c) the Typst |
| 9 | // project authors): a run is shaped with the first family that has a face for the variant, and every |
| 10 | // stretch that face cannot draw is shaped again with the next family, down the list and then Typst's |
| 11 | // fallback list; tracking and spacing are applied per glyph; every glyph carries the stretch and shrink |
| 12 | // justification may give it (`par.justification-limits`). Advances are kept in ems, as Typst keeps them, |
| 13 | // so the line breaker weighs the same widths the oracle weighs. |
| 14 | |
| 15 | use crate::eval::content::ElemKind; |
| 16 | use crate::eval::styles::StyleChain; |
| 17 | use crate::eval::value::{ |
| 18 | Dict, |
| 19 | Length, |
| 20 | Paint, |
| 21 | Relative, |
| 22 | Value, |
| 23 | }; |
| 24 | use crate::eval::Engine; |
| 25 | use crate::font::ShapedText; |
| 26 | use crate::fonts::{ |
| 27 | is_default_ignorable, |
| 28 | stretch_of_ratio, |
| 29 | BookFace, |
| 30 | FaceStyle, |
| 31 | FaceVariant, |
| 32 | FontBook, |
| 33 | }; |
| 34 | use crate::ir::{ |
| 35 | Dims, |
| 36 | Graphic, |
| 37 | DrawOp, |
| 38 | Leaf, |
| 39 | LinkTarget, |
| 40 | Node, |
| 41 | Sp, |
| 42 | }; |
| 43 | |
| 44 | use oxedyne_fe2o3_core::prelude::*; |
| 45 | use oxedyne_fe2o3_font::shape::{ |
| 46 | Dir as ShapeDir, |
| 47 | Feature, |
| 48 | Glyph as RunGlyph, |
| 49 | ShapeSpec, |
| 50 | }; |
| 51 | use oxedyne_fe2o3_graphics::colour::Ink; |
| 52 | use oxedyne_fe2o3_graphics::path::{ |
| 53 | Bounds, |
| 54 | Path, |
| 55 | PathBuilder, |
| 56 | Pt, |
| 57 | }; |
| 58 | use oxedyne_fe2o3_graphics::transform::Transform; |
| 59 | use oxedyne_fe2o3_text::regex::Regex; |
| 60 | use oxedyne_fe2o3_text::unicode::lookup::Partitioned; |
| 61 | use oxedyne_fe2o3_text::unicode::prop::Script; |
| 62 | |
| 63 | use std::path::PathBuf; |
| 64 | use std::sync::Arc; |
| 65 | |
| 66 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 67 | // │ FONT STORE │ |
| 68 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 69 | |
| 70 | /// The faces available to one compilation: Typst's embedded faces the crate carries, then every font |
| 71 | /// file under the directories and byte buffers the caller adds. The book is built on first use and |
| 72 | /// rebuilt after an addition. |
| 73 | #[derive(Clone, Debug, Default)] |
| 74 | pub struct FontStore { |
| 75 | pub families: Vec<String>, // family names known, for diagnostics |
| 76 | book: Option<Arc<FontBook>>, |
| 77 | base: Option<Arc<FontBook>>, // the embedded faces, parsed once by the host, else parsed here |
| 78 | dirs: Vec<PathBuf>, |
| 79 | files: Vec<Arc<Vec<u8>>>, |
| 80 | shape_budget: Option<usize>, // bytes the shaped-run cache may hold, else the default |
| 81 | } |
| 82 | |
| 83 | impl FontStore { |
| 84 | /// A store over a book of the embedded faces the host parsed once. A compile that adds no font of its own |
| 85 | /// shares that book; one that does forks it and adds to the fork, so the base never changes and no |
| 86 | /// project's fonts reach another's. |
| 87 | pub fn with_base(base: Arc<FontBook>) -> Self { |
| 88 | Self { base: Some(base), ..Self::default() } |
| 89 | } |
| 90 | |
| 91 | /// The book of embedded faces the host parsed, if it supplied one. |
| 92 | pub fn base(&self) -> Option<&Arc<FontBook>> { |
| 93 | self.base.as_ref() |
| 94 | } |
| 95 | |
| 96 | /// The same inputs with the book to be built afresh, so that a font file changed on disc is read again. |
| 97 | pub fn renewed(&self) -> Self { |
| 98 | Self { book: None, ..self.clone() } |
| 99 | } |
| 100 | |
| 101 | /// Adds every font file beneath `dir` in the vfs, after the embedded faces. |
| 102 | pub fn add_dir(&mut self, dir: PathBuf) { |
| 103 | self.dirs.push(dir); |
| 104 | self.book = None; |
| 105 | } |
| 106 | |
| 107 | /// The font directories added, and every font file found in them once the book is built: what a watch |
| 108 | /// polls so that a font added, mended or removed is seen. |
| 109 | pub fn scanned(&self) -> Vec<PathBuf> { |
| 110 | let mut out = self.dirs.clone(); |
| 111 | if let Some(book) = &self.book { |
| 112 | out.extend(book.scanned().iter().cloned()); |
| 113 | } |
| 114 | out |
| 115 | } |
| 116 | |
| 117 | /// Adds one font file's bytes, after the embedded faces and any directory. |
| 118 | pub fn add_bytes(&mut self, bytes: Vec<u8>) { |
| 119 | self.files.push(Arc::new(bytes)); |
| 120 | self.book = None; |
| 121 | } |
| 122 | |
| 123 | /// Sets the bytes the shaped-run cache may hold, in the book now and in every book built later. |
| 124 | pub fn set_shape_budget(&mut self, bytes: usize) -> Outcome<()> { |
| 125 | self.shape_budget = Some(bytes); |
| 126 | if let Some(book) = &self.book { |
| 127 | res!(book.set_shape_budget(bytes)); |
| 128 | } |
| 129 | Ok(()) |
| 130 | } |
| 131 | |
| 132 | /// The book, built on first use. |
| 133 | pub fn book(&mut self) -> Outcome<Arc<FontBook>> { |
| 134 | if let Some(b) = &self.book { |
| 135 | return Ok(b.clone()); |
| 136 | } |
| 137 | let mut book = match &self.base { |
| 138 | Some(base) if self.dirs.is_empty() && self.files.is_empty() => { |
| 139 | self.families = base.family_names(); |
| 140 | if let Some(bytes) = self.shape_budget { |
| 141 | res!(base.set_shape_budget(bytes)); |
| 142 | } |
| 143 | self.book = Some(base.clone()); |
| 144 | return Ok(base.clone()); |
| 145 | }, |
| 146 | Some(base) => base.fork(), |
| 147 | None => res!(FontBook::embedded()), |
| 148 | }; |
| 149 | for dir in &self.dirs { |
| 150 | book.add_dir(dir); |
| 151 | } |
| 152 | for bytes in &self.files { |
| 153 | let _ = book.add(bytes.as_ref().clone()); |
| 154 | } |
| 155 | self.families = book.family_names(); |
| 156 | if let Some(bytes) = self.shape_budget { |
| 157 | res!(book.set_shape_budget(bytes)); |
| 158 | } |
| 159 | let book = Arc::new(book); |
| 160 | self.book = Some(book.clone()); |
| 161 | Ok(book) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 166 | // │ RESOLVED TEXT PROPERTIES │ |
| 167 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 168 | |
| 169 | /// One family of a `font` list: the lower-cased name and the characters it is restricted to. |
| 170 | #[derive(Clone, Debug)] |
| 171 | pub struct FamilySpec { |
| 172 | pub name: String, |
| 173 | pub covers: Option<Arc<Regex>>, |
| 174 | } |
| 175 | |
| 176 | /// A top or bottom text edge: a font metric, the glyph bounds, or a fixed length in points. |
| 177 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 178 | pub enum Edge { |
| 179 | Ascender, |
| 180 | CapHeight, |
| 181 | XHeight, |
| 182 | Baseline, |
| 183 | Descender, |
| 184 | Bounds, |
| 185 | Length(f64), |
| 186 | } |
| 187 | |
| 188 | impl Edge { |
| 189 | fn of(v: &Value, size: f64, top: bool) -> Self { |
| 190 | match v { |
| 191 | Value::Str(s) => match s.as_str() { |
| 192 | "ascender" => Edge::Ascender, |
| 193 | "cap-height" => Edge::CapHeight, |
| 194 | "x-height" => Edge::XHeight, |
| 195 | "baseline" => Edge::Baseline, |
| 196 | "descender" => Edge::Descender, |
| 197 | "bounds" => Edge::Bounds, |
| 198 | _ => if top { Edge::CapHeight } else { Edge::Baseline }, |
| 199 | }, |
| 200 | Value::Length(l) => Edge::Length(l.resolve(size)), |
| 201 | _ => if top { Edge::CapHeight } else { Edge::Baseline }, |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /// Typst's `text.costs`, each a ratio of the default cost. |
| 207 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 208 | pub struct Costs { |
| 209 | pub hyphenation: f64, |
| 210 | pub runt: f64, |
| 211 | pub widow: f64, |
| 212 | pub orphan: f64, |
| 213 | } |
| 214 | |
| 215 | impl Default for Costs { |
| 216 | fn default() -> Self { Self { hyphenation: 1.0, runt: 1.0, widow: 1.0, orphan: 1.0 } } |
| 217 | } |
| 218 | |
| 219 | /// Typst's `par.justification-limits`: how far a space may shrink and stretch (as a ratio of its width |
| 220 | /// plus a length in points) and how far tracking may go between other glyphs, in points. |
| 221 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 222 | pub struct Limits { |
| 223 | pub spacing_min: (f64, f64), |
| 224 | pub spacing_max: (f64, f64), |
| 225 | pub tracking_min: f64, |
| 226 | pub tracking_max: f64, |
| 227 | } |
| 228 | |
| 229 | impl Default for Limits { |
| 230 | fn default() -> Self { |
| 231 | Self { spacing_min: (2.0 / 3.0, 0.0), spacing_max: (1.5, 0.0), tracking_min: 0.0, tracking_max: 0.0 } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | /// A sub- or superscript request (`text`'s internal `shift-settings`): whether to prefer the font's own |
| 236 | /// forms, the shift and size in ems of the outer size when given, and which kind. |
| 237 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 238 | pub struct ShiftSettings { |
| 239 | pub typographic: bool, |
| 240 | pub shift: Option<f64>, // ems, positive upwards |
| 241 | pub size: Option<f64>, // ems |
| 242 | pub superscript: bool, |
| 243 | } |
| 244 | |
| 245 | /// What a decoration draws. |
| 246 | #[derive(Clone, Debug)] |
| 247 | pub enum DecoLine { |
| 248 | Underline { stroke: Option<DecoStroke>, offset: Option<f64>, evade: bool, background: bool }, |
| 249 | Overline { stroke: Option<DecoStroke>, offset: Option<f64>, evade: bool, background: bool }, |
| 250 | Strikethrough { stroke: Option<DecoStroke>, offset: Option<f64>, background: bool }, |
| 251 | Highlight { fill: Option<Ink>, top: Edge, bottom: Edge }, |
| 252 | } |
| 253 | |
| 254 | /// A decoration's stroke, resolved: its colour (the text fill when unset) and thickness in points (the |
| 255 | /// font's recommended thickness when unset). |
| 256 | #[derive(Clone, Copy, Debug)] |
| 257 | pub struct DecoStroke { |
| 258 | pub paint: Option<Ink>, |
| 259 | pub thickness: Option<f64>, |
| 260 | } |
| 261 | |
| 262 | /// One decoration and how far it extends past the text on each side, in points. |
| 263 | #[derive(Clone, Debug)] |
| 264 | pub struct Deco { |
| 265 | pub line: DecoLine, |
| 266 | pub extent: f64, |
| 267 | } |
| 268 | |
| 269 | /// The `text` properties shaping and inline layout read, resolved once for a style chain. |
| 270 | #[derive(Clone, Debug)] |
| 271 | pub struct TextProps { |
| 272 | pub size: f64, |
| 273 | pub families: Vec<FamilySpec>, // the `font` list, then the fallback list when `fallback` is on |
| 274 | pub fallback: bool, |
| 275 | pub variant: FaceVariant, |
| 276 | pub features: Vec<Feature>, |
| 277 | pub lang: String, |
| 278 | pub region: Option<String>, |
| 279 | pub script: Option<[u8; 4]>, |
| 280 | pub rtl: bool, |
| 281 | pub tracking: f64, |
| 282 | pub spacing: (f64, f64), // ratio of the space's width, plus points |
| 283 | pub fill: Ink, |
| 284 | pub baseline: f64, |
| 285 | pub overhang: bool, |
| 286 | pub top_edge: Edge, |
| 287 | pub bottom_edge: Edge, |
| 288 | pub hyphenate: Option<bool>, |
| 289 | pub costs: Costs, |
| 290 | pub decos: Vec<Deco>, |
| 291 | pub shift: Option<ShiftSettings>, |
| 292 | pub case: Option<bool>, // Some(true) upper, Some(false) lower |
| 293 | pub hidden: bool, |
| 294 | pub cjk_latin_spacing: bool, |
| 295 | pub limits: Limits, |
| 296 | pub link: Option<LinkTarget>, // where the text links (`link.current`) |
| 297 | pub link_outset: f64, // half the leading, which a link area adds above and below |
| 298 | } |
| 299 | |
| 300 | // Typst's default text fill is `black`, which is `luma(0%)`: a grey, so a writer that keeps the space |
| 301 | // writes the same bytes for a text that set no fill and one that set `black`. |
| 302 | const DEFAULT_FILL: Ink = Ink::Grey { v: 0.0, a: 255 }; |
| 303 | |
| 304 | /// Typst's fallback families, tried after a `font` list when `fallback` is on. |
| 305 | const FALLBACKS: &[&str] = &[ |
| 306 | "libertinus serif", |
| 307 | "twitter color emoji", |
| 308 | "noto color emoji", |
| 309 | "apple color emoji", |
| 310 | "segoe ui emoji", |
| 311 | ]; |
| 312 | |
| 313 | /// A field of `text` in force on the chain, schema default included. |
| 314 | pub fn text_field(styles: &StyleChain, name: &str) -> Outcome<Option<Value>> { |
| 315 | match ElemKind::Text.field_id(name) { |
| 316 | Some(id) => styles.get(ElemKind::Text, id), |
| 317 | None => Ok(None), |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | /// Every value set for a field of `text`, outermost first. |
| 322 | fn text_values(styles: &StyleChain, name: &str) -> Vec<Value> { |
| 323 | match ElemKind::Text.field_id(name) { |
| 324 | Some(id) => styles.values(ElemKind::Text, id).into_iter().rev().cloned().collect(), |
| 325 | None => Vec::new(), |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | /// A field of another element in force on the chain, when that element's schema has it. |
| 330 | pub fn elem_field(styles: &StyleChain, kind: ElemKind, name: &str) -> Outcome<Option<Value>> { |
| 331 | match kind.field_id(name) { |
| 332 | Some(id) => styles.get(kind, id), |
| 333 | None => Ok(None), |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | /// A paint as the one colour the back end draws with: a colour as it is, a gradient by its first stop. |
| 338 | pub fn paint_ink(v: &Value) -> Outcome<Option<Ink>> { |
| 339 | match v { |
| 340 | Value::Color(c) => Ok(Some(c.to_ink())), |
| 341 | Value::Gradient(g) => match g.stops.first() { |
| 342 | Some((c, _)) => Ok(Some(c.to_ink())), |
| 343 | None => Ok(None), |
| 344 | }, |
| 345 | Value::Stroke(s) => match &s.paint { |
| 346 | Some(Paint::Color(c)) => Ok(Some(c.to_ink())), |
| 347 | Some(Paint::Gradient(g)) => match g.stops.first() { |
| 348 | Some((c, _)) => Ok(Some(c.to_ink())), |
| 349 | None => Ok(None), |
| 350 | }, |
| 351 | _ => Ok(None), |
| 352 | }, |
| 353 | _ => Ok(None), |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | fn length_pt(v: &Value, size: f64) -> Option<f64> { |
| 358 | match v { |
| 359 | Value::Length(l) => Some(l.resolve(size)), |
| 360 | _ => None, |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | fn relative_of(v: &Value, size: f64) -> Option<(f64, f64)> { |
| 365 | match v { |
| 366 | Value::Ratio(r) => Some((r.0, 0.0)), |
| 367 | Value::Length(l) => Some((0.0, l.resolve(size))), |
| 368 | Value::Relative(r) => Some((r.rel.0, r.abs.resolve(size))), |
| 369 | _ => None, |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /// The weight a `weight` value names: a number, or one of Typst's names. |
| 374 | pub fn weight_of(v: &Value) -> Option<u16> { |
| 375 | match v { |
| 376 | Value::Int(i) => Some((*i).clamp(0, u16::MAX as i64) as u16), |
| 377 | Value::Str(s) => match s.as_str() { |
| 378 | "thin" => Some(100), |
| 379 | "extralight" => Some(200), |
| 380 | "light" => Some(300), |
| 381 | "regular" => Some(400), |
| 382 | "medium" => Some(500), |
| 383 | "semibold" => Some(600), |
| 384 | "bold" => Some(700), |
| 385 | "extrabold" => Some(800), |
| 386 | "black" => Some(900), |
| 387 | _ => None, |
| 388 | }, |
| 389 | _ => None, |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | /// The font variant the chain asks for: `style`, `weight` and `stretch`, thickened by `strong`'s delta |
| 394 | /// and slanted or straightened by `emph`'s toggle. |
| 395 | pub fn variant(styles: &StyleChain) -> Outcome<FaceVariant> { |
| 396 | let style = match res!(text_field(styles, "style")) { |
| 397 | Some(Value::Str(s)) => match s.as_str() { |
| 398 | "italic" => FaceStyle::Italic, |
| 399 | "oblique" => FaceStyle::Oblique, |
| 400 | _ => FaceStyle::Normal, |
| 401 | }, |
| 402 | _ => FaceStyle::Normal, |
| 403 | }; |
| 404 | let weight = res!(text_field(styles, "weight")).as_ref().and_then(weight_of).unwrap_or(400).clamp(100, 900); |
| 405 | let stretch = match res!(text_field(styles, "stretch")) { |
| 406 | Some(Value::Ratio(r)) => stretch_of_ratio(r.0), |
| 407 | _ => 1000, |
| 408 | }; |
| 409 | let mut v = FaceVariant { style, weight, stretch }; |
| 410 | let delta: i64 = text_values(styles, "delta").iter().map(|d| match d { |
| 411 | Value::Int(i) => *i, |
| 412 | _ => 0, |
| 413 | }).sum(); |
| 414 | v = v.thicken(delta); |
| 415 | let emph = text_values(styles, "emph").iter().fold(false, |acc, e| acc ^ matches!(e, Value::Bool(true))); |
| 416 | if emph { |
| 417 | v.style = match v.style { |
| 418 | FaceStyle::Normal => FaceStyle::Italic, |
| 419 | FaceStyle::Italic => FaceStyle::Normal, |
| 420 | FaceStyle::Oblique => FaceStyle::Normal, |
| 421 | }; |
| 422 | } |
| 423 | Ok(v) |
| 424 | } |
| 425 | |
| 426 | /// The families the chain's `font` names, as Typst resolves them, with the fallback list after when |
| 427 | /// `fallback` is on. |
| 428 | pub fn families(styles: &StyleChain) -> Outcome<(Vec<FamilySpec>, bool)> { |
| 429 | let mut out = Vec::new(); |
| 430 | match res!(text_field(styles, "font")) { |
| 431 | Some(v) => res!(push_families(&v, &mut out)), |
| 432 | None => out.push(FamilySpec { name: "libertinus serif".to_string(), covers: None }), |
| 433 | } |
| 434 | let fallback = !matches!(res!(text_field(styles, "fallback")), Some(Value::Bool(false))); |
| 435 | if fallback { |
| 436 | for f in FALLBACKS { |
| 437 | out.push(FamilySpec { name: f.to_string(), covers: None }); |
| 438 | } |
| 439 | } |
| 440 | Ok((out, fallback)) |
| 441 | } |
| 442 | |
| 443 | fn push_families(v: &Value, out: &mut Vec<FamilySpec>) -> Outcome<()> { |
| 444 | match v { |
| 445 | Value::Str(s) => out.push(FamilySpec { name: s.to_lowercase(), covers: None }), |
| 446 | Value::Dict(d) => { |
| 447 | let name = match d.get("name") { |
| 448 | Some(Value::Str(s)) => s.to_lowercase(), |
| 449 | _ => return Err(err!("a font family dictionary needs a `name`"; Input, Invalid)), |
| 450 | }; |
| 451 | let covers = match d.get("covers") { |
| 452 | Some(Value::Str(s)) if s.as_str() == "latin-in-cjk" => Some(Arc::new(res!(Regex::new( |
| 453 | "[^\u{00B7}\u{2013}\u{2014}\u{2018}\u{2019}\u{201C}\u{201D}\u{2025}-\u{2027}\u{2E3A}]")))), |
| 454 | Some(Value::Regex(r)) => Some(Arc::new(r.re.clone())), |
| 455 | _ => None, |
| 456 | }; |
| 457 | out.push(FamilySpec { name, covers }); |
| 458 | } |
| 459 | Value::Array(a) => { |
| 460 | if a.is_empty() { |
| 461 | return Err(err!("font fallback list must not be empty"; Input, Invalid)); |
| 462 | } |
| 463 | for item in a.iter() { |
| 464 | res!(push_families(item, out)); |
| 465 | } |
| 466 | } |
| 467 | _ => (), |
| 468 | } |
| 469 | Ok(()) |
| 470 | } |
| 471 | |
| 472 | /// The OpenType features the chain asks for, in Typst's order: the switches that are on by default only |
| 473 | /// when turned off, the others only when turned on, then `features` as given. |
| 474 | pub fn features(styles: &StyleChain) -> Outcome<Vec<Feature>> { |
| 475 | let mut tags = Vec::new(); |
| 476 | let field = |name: &str| text_field(styles, name); |
| 477 | if matches!(res!(field("kerning")), Some(Value::Bool(false))) { |
| 478 | tags.push(Feature::set(b"kern", 0)); |
| 479 | } |
| 480 | if let Some(Value::Str(s)) = res!(field("smallcaps")) { |
| 481 | tags.push(Feature::set(b"smcp", 1)); |
| 482 | if s.as_str() == "all" { |
| 483 | tags.push(Feature::set(b"c2sc", 1)); |
| 484 | } |
| 485 | } |
| 486 | match res!(field("alternates")) { |
| 487 | Some(Value::Bool(true)) => tags.push(Feature::set(b"salt", 1)), |
| 488 | Some(Value::Int(i)) if i > 0 => tags.push(Feature::set(b"salt", i as u32)), |
| 489 | _ => (), |
| 490 | } |
| 491 | let sets: Vec<i64> = match res!(field("stylistic-set")) { |
| 492 | Some(Value::Int(i)) => vec![i], |
| 493 | Some(Value::Array(a)) => a.iter().filter_map(|v| match v { Value::Int(i) => Some(*i), _ => None }).collect(), |
| 494 | _ => Vec::new(), |
| 495 | }; |
| 496 | let mut sets: Vec<i64> = sets.into_iter().filter(|i| (1..=20).contains(i)).collect(); |
| 497 | sets.sort(); |
| 498 | sets.dedup(); |
| 499 | for set in sets { |
| 500 | let t = [b's', b's', b'0' + (set / 10) as u8, b'0' + (set % 10) as u8]; |
| 501 | tags.push(Feature::set(&t, 1)); |
| 502 | } |
| 503 | if matches!(res!(field("ligatures")), Some(Value::Bool(false))) { |
| 504 | tags.push(Feature::set(b"liga", 0)); |
| 505 | tags.push(Feature::set(b"clig", 0)); |
| 506 | } |
| 507 | if matches!(res!(field("discretionary-ligatures")), Some(Value::Bool(true))) { |
| 508 | tags.push(Feature::set(b"dlig", 1)); |
| 509 | } |
| 510 | if matches!(res!(field("historical-ligatures")), Some(Value::Bool(true))) { |
| 511 | tags.push(Feature::set(b"hlig", 1)); |
| 512 | } |
| 513 | match res!(field("number-type")) { |
| 514 | Some(Value::Str(s)) if s.as_str() == "lining" => tags.push(Feature::set(b"lnum", 1)), |
| 515 | Some(Value::Str(s)) if s.as_str() == "old-style" => tags.push(Feature::set(b"onum", 1)), |
| 516 | _ => (), |
| 517 | } |
| 518 | match res!(field("number-width")) { |
| 519 | Some(Value::Str(s)) if s.as_str() == "proportional" => tags.push(Feature::set(b"pnum", 1)), |
| 520 | Some(Value::Str(s)) if s.as_str() == "tabular" => tags.push(Feature::set(b"tnum", 1)), |
| 521 | _ => (), |
| 522 | } |
| 523 | if matches!(res!(field("slashed-zero")), Some(Value::Bool(true))) { |
| 524 | tags.push(Feature::set(b"zero", 1)); |
| 525 | } |
| 526 | if matches!(res!(field("fractions")), Some(Value::Bool(true))) { |
| 527 | tags.push(Feature::set(b"frac", 1)); |
| 528 | } |
| 529 | for v in text_values(styles, "features") { |
| 530 | match v { |
| 531 | Value::Array(a) => for t in a.iter() { |
| 532 | if let Value::Str(s) = t { |
| 533 | if let Some(tag) = tag_of(s) { |
| 534 | tags.push(Feature::set(&tag, 1)); |
| 535 | } |
| 536 | } |
| 537 | }, |
| 538 | Value::Dict(d) => for (k, val) in d.iter() { |
| 539 | if let (Some(tag), Value::Int(n)) = (tag_of(k), val) { |
| 540 | tags.push(Feature::set(&tag, (*n).clamp(0, u32::MAX as i64) as u32)); |
| 541 | } |
| 542 | }, |
| 543 | _ => (), |
| 544 | } |
| 545 | } |
| 546 | Ok(tags) |
| 547 | } |
| 548 | |
| 549 | /// A four-byte OpenType tag from a string of one to four printable characters, space padded. |
| 550 | fn tag_of(s: &str) -> Option<[u8; 4]> { |
| 551 | let b = s.as_bytes(); |
| 552 | if b.is_empty() || b.len() > 4 || !b.iter().all(|c| (0x21..=0x7E).contains(c)) { |
| 553 | return None; |
| 554 | } |
| 555 | let mut t = [b' '; 4]; |
| 556 | t[..b.len()].copy_from_slice(b); |
| 557 | Some(t) |
| 558 | } |
| 559 | |
| 560 | /// Is `lang` written right to left? |
| 561 | pub fn lang_is_rtl(lang: &str) -> bool { |
| 562 | matches!(lang, "ar" | "dv" | "fa" | "he" | "ks" | "pa" | "ps" | "sd" | "ug" | "ur" | "yi") |
| 563 | } |
| 564 | |
| 565 | /// The justification limits `par` puts in force, Typst's defaults for whatever is unset. |
| 566 | pub fn limits(styles: &StyleChain, size: f64) -> Outcome<Limits> { |
| 567 | let mut l = Limits::default(); |
| 568 | if let Some(Value::Dict(d)) = res!(elem_field(styles, ElemKind::Par, "justification-limits")) { |
| 569 | if let Some(Value::Dict(s)) = d.get("spacing") { |
| 570 | if let Some(v) = s.get("min").and_then(|v| relative_of(v, size)) { l.spacing_min = v; } |
| 571 | if let Some(v) = s.get("max").and_then(|v| relative_of(v, size)) { l.spacing_max = v; } |
| 572 | } |
| 573 | if let Some(Value::Dict(t)) = d.get("tracking") { |
| 574 | if let Some(v) = t.get("min").and_then(|v| length_pt(v, size)) { l.tracking_min = v; } |
| 575 | if let Some(v) = t.get("max").and_then(|v| length_pt(v, size)) { l.tracking_max = v; } |
| 576 | } |
| 577 | } |
| 578 | Ok(l) |
| 579 | } |
| 580 | |
| 581 | fn costs(styles: &StyleChain) -> Costs { |
| 582 | let mut c = Costs::default(); |
| 583 | for v in text_values(styles, "costs") { |
| 584 | if let Value::Dict(d) = v { |
| 585 | let r = |key: &str| match d.get(key) { |
| 586 | Some(Value::Ratio(r)) => Some(r.0), |
| 587 | _ => None, |
| 588 | }; |
| 589 | if let Some(x) = r("hyphenation") { c.hyphenation = x; } |
| 590 | if let Some(x) = r("runt") { c.runt = x; } |
| 591 | if let Some(x) = r("widow") { c.widow = x; } |
| 592 | if let Some(x) = r("orphan") { c.orphan = x; } |
| 593 | } |
| 594 | } |
| 595 | c |
| 596 | } |
| 597 | |
| 598 | fn deco_stroke(v: Option<&Value>, size: f64) -> Outcome<Option<DecoStroke>> { |
| 599 | let v = match v { |
| 600 | None | Some(Value::Auto) | Some(Value::None) => return Ok(None), |
| 601 | Some(v) => v, |
| 602 | }; |
| 603 | let s = match crate::eval::styles::to_stroke(v) { |
| 604 | Some(s) => s, |
| 605 | None => return Ok(None), |
| 606 | }; |
| 607 | let paint = match &s.paint { |
| 608 | Some(Paint::Color(c)) => Some(c.to_ink()), |
| 609 | Some(Paint::Gradient(g)) => match g.stops.first() { |
| 610 | Some((c, _)) => Some(c.to_ink()), |
| 611 | None => None, |
| 612 | }, |
| 613 | _ => None, |
| 614 | }; |
| 615 | Ok(Some(DecoStroke { paint, thickness: s.thickness.map(|t| t.resolve(size)) })) |
| 616 | } |
| 617 | |
| 618 | fn decos(styles: &StyleChain, size: f64) -> Outcome<Vec<Deco>> { |
| 619 | let mut out = Vec::new(); |
| 620 | for v in text_values(styles, "deco") { |
| 621 | let items: Vec<Value> = match v { |
| 622 | Value::Array(a) => (*a).clone(), |
| 623 | other => vec![other], |
| 624 | }; |
| 625 | for item in items { |
| 626 | let d = match item { |
| 627 | Value::Dict(d) => d, |
| 628 | _ => continue, |
| 629 | }; |
| 630 | let flag = |k: &str, dflt: bool| match d.get(k) { |
| 631 | Some(Value::Bool(b)) => *b, |
| 632 | _ => dflt, |
| 633 | }; |
| 634 | let offset = d.get("offset").and_then(|v| length_pt(v, size)); |
| 635 | let extent = d.get("extent").and_then(|v| length_pt(v, size)).unwrap_or(0.0); |
| 636 | let line = match d.get("line") { |
| 637 | Some(Value::Str(s)) => match s.as_str() { |
| 638 | "underline" => DecoLine::Underline { |
| 639 | stroke: res!(deco_stroke(d.get("stroke"), size)), |
| 640 | offset, |
| 641 | evade: flag("evade", true), |
| 642 | background: flag("background", false), |
| 643 | }, |
| 644 | "overline" => DecoLine::Overline { |
| 645 | stroke: res!(deco_stroke(d.get("stroke"), size)), |
| 646 | offset, |
| 647 | evade: flag("evade", true), |
| 648 | background: flag("background", false), |
| 649 | }, |
| 650 | "strike" => DecoLine::Strikethrough { |
| 651 | stroke: res!(deco_stroke(d.get("stroke"), size)), |
| 652 | offset, |
| 653 | background: flag("background", false), |
| 654 | }, |
| 655 | "highlight" => DecoLine::Highlight { |
| 656 | fill: match d.get("fill") { |
| 657 | Some(v) => res!(paint_ink(v)), |
| 658 | None => None, |
| 659 | }, |
| 660 | top: d.get("top-edge").map(|v| Edge::of(v, size, true)).unwrap_or(Edge::Ascender), |
| 661 | bottom: d.get("bottom-edge").map(|v| Edge::of(v, size, false)).unwrap_or(Edge::Descender), |
| 662 | }, |
| 663 | _ => continue, |
| 664 | }, |
| 665 | _ => continue, |
| 666 | }; |
| 667 | out.push(Deco { line, extent }); |
| 668 | } |
| 669 | } |
| 670 | Ok(out) |
| 671 | } |
| 672 | |
| 673 | fn shift_settings(styles: &StyleChain) -> Outcome<Option<ShiftSettings>> { |
| 674 | let d: Dict = match res!(text_field(styles, "shift-settings")) { |
| 675 | Some(Value::Dict(d)) => (*d).clone(), |
| 676 | _ => return Ok(None), |
| 677 | }; |
| 678 | let em = |k: &str| match d.get(k) { |
| 679 | Some(Value::Float(f)) => Some(*f), |
| 680 | Some(Value::Int(i)) => Some(*i as f64), |
| 681 | _ => None, |
| 682 | }; |
| 683 | Ok(Some(ShiftSettings { |
| 684 | typographic: !matches!(d.get("typographic"), Some(Value::Bool(false))), |
| 685 | shift: em("shift"), |
| 686 | size: em("size"), |
| 687 | superscript: matches!(d.get("kind"), Some(Value::Str(s)) if s.as_str() == "super"), |
| 688 | })) |
| 689 | } |
| 690 | |
| 691 | /// The language and the region the chain sets text in, `en` and none where nothing says otherwise. A |
| 692 | /// document's language is this of the chain its first page is set under, so a `set text(lang: ..)` at the |
| 693 | /// top of the document reaches it. |
| 694 | pub fn locale(styles: &StyleChain) -> Outcome<(String, Option<String>)> { |
| 695 | let lang = match res!(text_field(styles, "lang")) { |
| 696 | Some(Value::Str(s)) => s.to_lowercase(), |
| 697 | _ => "en".to_string(), |
| 698 | }; |
| 699 | let region = match res!(text_field(styles, "region")) { |
| 700 | Some(Value::Str(s)) => Some(s.to_uppercase()), |
| 701 | _ => None, |
| 702 | }; |
| 703 | Ok((lang, region)) |
| 704 | } |
| 705 | |
| 706 | /// Resolves the chain's text properties once, for shaping and inline layout. |
| 707 | pub fn props(styles: &StyleChain) -> Outcome<TextProps> { |
| 708 | let size = styles.font_size(); |
| 709 | let (families, fallback) = res!(families(styles)); |
| 710 | let (lang, region) = res!(locale(styles)); |
| 711 | let script = match res!(text_field(styles, "script")) { |
| 712 | Some(Value::Str(s)) => tag_of(&title_case(&s)), |
| 713 | _ => None, |
| 714 | }; |
| 715 | let rtl = match res!(text_field(styles, "dir")) { |
| 716 | Some(Value::Direction(d)) => matches!(d, crate::eval::value::Direction::Rtl), |
| 717 | _ => lang_is_rtl(&lang), |
| 718 | }; |
| 719 | let fill = match res!(text_field(styles, "fill")) { |
| 720 | Some(v) => res!(paint_ink(&v)).unwrap_or(DEFAULT_FILL), |
| 721 | None => DEFAULT_FILL, |
| 722 | }; |
| 723 | let top_edge = res!(text_field(styles, "top-edge")).map(|v| Edge::of(&v, size, true)).unwrap_or(Edge::CapHeight); |
| 724 | let bottom_edge = res!(text_field(styles, "bottom-edge")).map(|v| Edge::of(&v, size, false)).unwrap_or(Edge::Baseline); |
| 725 | let hyphenate = match res!(text_field(styles, "hyphenate")) { |
| 726 | Some(Value::Bool(b)) => Some(b), |
| 727 | _ => None, |
| 728 | }; |
| 729 | let case = match res!(text_field(styles, "case")) { |
| 730 | Some(Value::Str(s)) if s.as_str() == "upper" => Some(true), |
| 731 | Some(Value::Str(s)) if s.as_str() == "lower" => Some(false), |
| 732 | _ => None, |
| 733 | }; |
| 734 | let link = res!(elem_field(styles, ElemKind::Link, "current")).as_ref().and_then(link_target); |
| 735 | let link_outset = match (&link, res!(elem_field(styles, ElemKind::Par, "leading"))) { |
| 736 | (None, _) => 0.0, |
| 737 | (Some(_), Some(Value::Length(l))) => 0.5 * l.resolve(size), |
| 738 | (Some(_), _) => 0.5 * 0.65 * size, |
| 739 | }; |
| 740 | Ok(TextProps { |
| 741 | size, |
| 742 | families, |
| 743 | fallback, |
| 744 | variant: res!(variant(styles)), |
| 745 | features: res!(features(styles)), |
| 746 | lang, |
| 747 | region, |
| 748 | script, |
| 749 | rtl, |
| 750 | tracking: res!(text_field(styles, "tracking")).and_then(|v| length_pt(&v, size)).unwrap_or(0.0), |
| 751 | spacing: res!(text_field(styles, "spacing")).and_then(|v| relative_of(&v, size)).unwrap_or((1.0, 0.0)), |
| 752 | fill, |
| 753 | baseline: res!(text_field(styles, "baseline")).and_then(|v| length_pt(&v, size)).unwrap_or(0.0), |
| 754 | overhang: !matches!(res!(text_field(styles, "overhang")), Some(Value::Bool(false))), |
| 755 | top_edge, |
| 756 | bottom_edge, |
| 757 | hyphenate, |
| 758 | costs: costs(styles), |
| 759 | decos: res!(decos(styles, size)), |
| 760 | shift: res!(shift_settings(styles)), |
| 761 | case, |
| 762 | hidden: res!(crate::eval::lib::visual::is_hidden(styles)), |
| 763 | cjk_latin_spacing: !matches!(res!(text_field(styles, "cjk-latin-spacing")), Some(Value::None)), |
| 764 | limits: res!(limits(styles, size)), |
| 765 | link, |
| 766 | link_outset, |
| 767 | }) |
| 768 | } |
| 769 | |
| 770 | /// Where `link.current` points, as the IR carries a link: a URL, or a location through its anchor. A page |
| 771 | /// position has no IR form yet, so it gives none; inline layout warns of it. |
| 772 | pub fn link_target(v: &Value) -> Option<LinkTarget> { |
| 773 | match v { |
| 774 | Value::Str(url) => Some(LinkTarget::Uri(url.to_string())), |
| 775 | Value::Location(loc) => Some(LinkTarget::Anchor(loc.anchor())), |
| 776 | _ => None, |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | fn title_case(s: &str) -> String { |
| 781 | let mut out = String::new(); |
| 782 | for (i, c) in s.chars().enumerate() { |
| 783 | if i == 0 { |
| 784 | out.extend(c.to_uppercase()); |
| 785 | } else { |
| 786 | out.extend(c.to_lowercase()); |
| 787 | } |
| 788 | } |
| 789 | out |
| 790 | } |
| 791 | |
| 792 | impl TextProps { |
| 793 | /// The BCP 47 language the shaper is told, the region appended when set. |
| 794 | pub fn bcp47(&self) -> String { |
| 795 | match &self.region { |
| 796 | Some(r) => fmt!("{}-{}", self.lang, r), |
| 797 | None => self.lang.clone(), |
| 798 | } |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 803 | // │ SHAPED TEXT │ |
| 804 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 805 | |
| 806 | /// How a CJK punctuation mark is set, by the standard of the text's region. |
| 807 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 808 | pub enum CjkPunctStyle { |
| 809 | Gb, // mainland China |
| 810 | Cns, // Taiwan and Hong Kong |
| 811 | Jis, // Japan |
| 812 | } |
| 813 | |
| 814 | pub fn cjk_punct_style(lang: &str, region: Option<&str>) -> CjkPunctStyle { |
| 815 | match (lang, region) { |
| 816 | ("zh", Some("TW")) | ("zh", Some("HK")) => CjkPunctStyle::Cns, |
| 817 | ("ja", _) => CjkPunctStyle::Jis, |
| 818 | _ => CjkPunctStyle::Gb, |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | /// One shaped glyph, its metrics in ems of `size`, as Typst's `ShapedGlyph`. |
| 823 | #[derive(Clone, Debug)] |
| 824 | pub struct SGlyph { |
| 825 | pub face: usize, // the font book's face id |
| 826 | pub id: u32, |
| 827 | pub x_advance: f64, |
| 828 | pub x_offset: f64, |
| 829 | pub y_offset: f64, |
| 830 | pub size: f64, // points |
| 831 | pub stretch: (f64, f64), // left and right, ems |
| 832 | pub shrink: (f64, f64), |
| 833 | pub range: (usize, usize), // the cluster's bytes in the paragraph's text |
| 834 | pub c: char, // the cluster's first character |
| 835 | pub justifiable: bool, |
| 836 | pub script: Script, |
| 837 | pub safe_to_break: bool, // the shaper says a line may start here without reshaping |
| 838 | } |
| 839 | |
| 840 | impl SGlyph { |
| 841 | pub fn is_space(&self) -> bool { is_space(self.c) } |
| 842 | |
| 843 | pub fn is_cj_script(&self) -> bool { is_cj_script(self.c, self.script) } |
| 844 | |
| 845 | pub fn is_cjk_left_aligned_punctuation(&self, style: CjkPunctStyle) -> bool { |
| 846 | is_cjk_left_aligned_punctuation(self.c, self.x_advance, self.stretch, style) |
| 847 | } |
| 848 | |
| 849 | pub fn is_cjk_right_aligned_punctuation(&self) -> bool { |
| 850 | is_cjk_right_aligned_punctuation(self.c, self.x_advance, self.stretch) |
| 851 | } |
| 852 | |
| 853 | pub fn is_cjk_center_aligned_punctuation(&self, style: CjkPunctStyle) -> bool { |
| 854 | is_cjk_center_aligned_punctuation(self.c, style) |
| 855 | } |
| 856 | |
| 857 | pub fn is_cjk_punctuation(&self) -> bool { |
| 858 | self.is_cjk_left_aligned_punctuation(CjkPunctStyle::Gb) |
| 859 | || self.is_cjk_right_aligned_punctuation() |
| 860 | || self.is_cjk_center_aligned_punctuation(CjkPunctStyle::Gb) |
| 861 | } |
| 862 | |
| 863 | /// Is it a western letter or number, for CJK-Latin spacing? |
| 864 | pub fn is_letter_or_number(&self) -> bool { |
| 865 | matches!(Script::of(self.c), Script::Latin | Script::Greek | Script::Cyrillic) |
| 866 | || matches!(self.c, '#' | '$' | '%' | '&') |
| 867 | || self.c.is_ascii_digit() |
| 868 | } |
| 869 | |
| 870 | pub fn shrink_left(&mut self, amount: f64) { |
| 871 | self.x_offset -= amount; |
| 872 | self.x_advance -= amount; |
| 873 | self.shrink.0 -= amount; |
| 874 | } |
| 875 | |
| 876 | pub fn shrink_right(&mut self, amount: f64) { |
| 877 | self.x_advance -= amount; |
| 878 | self.shrink.1 -= amount; |
| 879 | } |
| 880 | |
| 881 | /// The stretch and shrink justification may give the glyph (Typst's `base_adjustability`): a space |
| 882 | /// takes the spacing and tracking limits, CJK punctuation may give up half or a quarter of itself, |
| 883 | /// and any other glyph that ends its cluster the tracking limits. |
| 884 | fn base_adjustability(&self, style: CjkPunctStyle, limits: &Limits, font_size: f64, stretchable: bool) |
| 885 | -> ((f64, f64), (f64, f64)) |
| 886 | { |
| 887 | let width = self.x_advance; |
| 888 | let limited = |v: f64| v.min(width * 0.75); |
| 889 | let em = |pt: f64| if font_size > 0.0 { pt / font_size } else { 0.0 }; |
| 890 | if self.is_space() { |
| 891 | let max = (limits.spacing_max.0, limits.spacing_max.1 + limits.tracking_max); |
| 892 | let min = (limits.spacing_min.0, limits.spacing_min.1 + limits.tracking_min); |
| 893 | let stretch = ((max.0 - 1.0) * width + em(max.1)).max(0.0); |
| 894 | let shrink = limited((1.0 - min.0) * width + em(-min.1)); |
| 895 | ((0.0, stretch), (0.0, shrink)) |
| 896 | } else if self.is_cjk_left_aligned_punctuation(style) { |
| 897 | ((0.0, 0.0), (0.0, width / 2.0)) |
| 898 | } else if self.is_cjk_right_aligned_punctuation() { |
| 899 | ((0.0, 0.0), (width / 2.0, 0.0)) |
| 900 | } else if self.is_cjk_center_aligned_punctuation(style) { |
| 901 | ((0.0, 0.0), (width / 4.0, width / 4.0)) |
| 902 | } else if stretchable { |
| 903 | ((0.0, em(limits.tracking_max).max(0.0)), (0.0, limited(em(-limits.tracking_min)))) |
| 904 | } else { |
| 905 | ((0.0, 0.0), (0.0, 0.0)) |
| 906 | } |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | /// A run of shaped text with one style and direction: Typst's `ShapedText`. Glyphs outside `kept` are |
| 911 | /// end-of-line white space trimmed from layout but still drawn, with no advance. |
| 912 | #[derive(Clone, Debug)] |
| 913 | pub struct ShapedRun { |
| 914 | pub base: usize, // where the text starts in the paragraph's text |
| 915 | pub text: Arc<str>, |
| 916 | pub rtl: bool, |
| 917 | pub props: Arc<TextProps>, |
| 918 | pub glyphs: Arc<Vec<SGlyph>>, // shared with the run the line breaker cut this one from |
| 919 | pub span: (usize, usize), // this run's glyphs within `glyphs` |
| 920 | pub kept: (usize, usize), // the glyphs layout sees, within `span` |
| 921 | } |
| 922 | |
| 923 | impl ShapedRun { |
| 924 | /// The glyphs layout sees. |
| 925 | pub fn kept(&self) -> &[SGlyph] { |
| 926 | self.glyphs.get(self.kept.0..self.kept.1).unwrap_or(&[]) |
| 927 | } |
| 928 | |
| 929 | /// The run's glyphs, those trimmed away included. |
| 930 | pub fn all(&self) -> &[SGlyph] { |
| 931 | self.glyphs.get(self.span.0..self.span.1).unwrap_or(&[]) |
| 932 | } |
| 933 | |
| 934 | /// The kept glyphs to change. A run sliced from a longer one first takes its own copy of its span |
| 935 | /// alone, as Typst's `Cow::to_mut` does; `Arc::make_mut` then copies only a list still shared. |
| 936 | pub fn kept_mut(&mut self) -> &mut [SGlyph] { |
| 937 | if self.span != (0, self.glyphs.len()) { |
| 938 | let off = self.span.0; |
| 939 | let own: Vec<SGlyph> = self.all().to_vec(); |
| 940 | self.span = (0, own.len()); |
| 941 | self.kept = (self.kept.0.saturating_sub(off), self.kept.1.saturating_sub(off)); |
| 942 | self.glyphs = Arc::new(own); |
| 943 | } |
| 944 | let (a, b) = self.kept; |
| 945 | match Arc::make_mut(&mut self.glyphs).get_mut(a..b) { |
| 946 | Some(s) => s, |
| 947 | None => &mut [], |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | pub fn end(&self) -> usize { self.base + self.text.len() } |
| 952 | |
| 953 | /// The natural width, in points. |
| 954 | pub fn width(&self) -> f64 { |
| 955 | self.kept().iter().map(|g| g.x_advance * g.size).sum() |
| 956 | } |
| 957 | |
| 958 | pub fn stretchability(&self) -> f64 { |
| 959 | self.kept().iter().map(|g| (g.stretch.0 + g.stretch.1) * g.size).sum() |
| 960 | } |
| 961 | |
| 962 | pub fn shrinkability(&self) -> f64 { |
| 963 | self.kept().iter().map(|g| (g.shrink.0 + g.shrink.1) * g.size).sum() |
| 964 | } |
| 965 | |
| 966 | pub fn justifiables(&self) -> usize { |
| 967 | self.kept().iter().filter(|g| g.justifiable).count() |
| 968 | } |
| 969 | |
| 970 | /// Is the last glyph CJK, which justification leaves alone at a line's end? |
| 971 | pub fn cjk_justifiable_at_last(&self) -> bool { |
| 972 | self.kept().last().map_or(false, |g| g.is_cj_script() || g.is_cjk_punctuation()) |
| 973 | } |
| 974 | |
| 975 | /// Trims glyphs matching `f` from both ends of the kept range. |
| 976 | pub fn trim<F: Fn(&SGlyph) -> bool>(&mut self, f: F) { |
| 977 | let all = self.all(); |
| 978 | let mut a = 0; |
| 979 | while a < all.len() && f(&all[a]) { |
| 980 | a += 1; |
| 981 | } |
| 982 | let mut b = all.len(); |
| 983 | while b > a && f(&all[b - 1]) { |
| 984 | b -= 1; |
| 985 | } |
| 986 | self.kept = (self.span.0 + a, self.span.0 + b); |
| 987 | } |
| 988 | |
| 989 | /// The same properties with no text. |
| 990 | pub fn empty(&self) -> Self { |
| 991 | Self { text: Arc::from(""), glyphs: Arc::new(Vec::new()), span: (0, 0), kept: (0, 0), ..self.clone() } |
| 992 | } |
| 993 | |
| 994 | /// The run's top and bottom extent: the chain's edges measured over each kept glyph's face, or over |
| 995 | /// the first face the families give when the run has no glyphs at all. |
| 996 | pub fn measure(&self, book: &FontBook) -> (f64, f64) { |
| 997 | let size = self.props.size; |
| 998 | let mut top = 0.0f64; |
| 999 | let mut bottom = 0.0f64; |
| 1000 | if self.all().is_empty() { |
| 1001 | let face = self.props.families.iter().find_map(|f| book.select(&f.name, self.props.variant)); |
| 1002 | if let Some(f) = face.and_then(|i| book.face(i)) { |
| 1003 | let (t, b) = edges(f, self.props.top_edge, self.props.bottom_edge, size, None); |
| 1004 | top = top.max(t); |
| 1005 | bottom = bottom.max(b); |
| 1006 | } |
| 1007 | } else { |
| 1008 | for g in self.kept() { |
| 1009 | if let Some(f) = book.face(g.face) { |
| 1010 | let (t, b) = edges(f, self.props.top_edge, self.props.bottom_edge, size, Some(g.id)); |
| 1011 | top = top.max(t); |
| 1012 | bottom = bottom.max(b); |
| 1013 | } |
| 1014 | } |
| 1015 | } |
| 1016 | (top, bottom) |
| 1017 | } |
| 1018 | } |
| 1019 | |
| 1020 | /// A face's top and bottom edges at a size, in points, positive away from the baseline. |
| 1021 | pub fn edges(face: &BookFace, top: Edge, bottom: Edge, size: f64, glyph: Option<u32>) -> (f64, f64) { |
| 1022 | let m = &face.metrics; |
| 1023 | let em = |u: f32| face.to_em(u) * size; |
| 1024 | let bbox = || glyph.and_then(|g| glyph_bounds(face, g)); |
| 1025 | let t = match top { |
| 1026 | Edge::Ascender => em(m.ascender), |
| 1027 | Edge::CapHeight => em(m.cap_height.unwrap_or(m.ascender)), |
| 1028 | Edge::XHeight => em(m.x_height.unwrap_or(m.ascender)), |
| 1029 | Edge::Baseline => 0.0, |
| 1030 | Edge::Descender => em(m.descender), |
| 1031 | Edge::Bounds => bbox().map(|b| em(b.y1)).unwrap_or(0.0), |
| 1032 | Edge::Length(l) => l, |
| 1033 | }; |
| 1034 | let b = match bottom { |
| 1035 | Edge::Ascender => -em(m.ascender), |
| 1036 | Edge::CapHeight => -em(m.cap_height.unwrap_or(m.ascender)), |
| 1037 | Edge::XHeight => -em(m.x_height.unwrap_or(m.ascender)), |
| 1038 | Edge::Baseline => 0.0, |
| 1039 | Edge::Descender => -em(m.descender), |
| 1040 | Edge::Bounds => bbox().map(|b| -em(b.y0)).unwrap_or(0.0), |
| 1041 | Edge::Length(l) => -l, |
| 1042 | }; |
| 1043 | (t, b) |
| 1044 | } |
| 1045 | |
| 1046 | /// A glyph's outline bounds in font units, y up. |
| 1047 | pub fn glyph_bounds(face: &BookFace, id: u32) -> Option<Bounds> { |
| 1048 | let upem = face.metrics.units_per_em; |
| 1049 | let path = face.font.outline(0, id, upem).ok()?; |
| 1050 | path.bounds(&Transform::IDENTITY) |
| 1051 | } |
| 1052 | |
| 1053 | /// Is it a space for justification: an ordinary, a no-break or an ideographic space? |
| 1054 | pub fn is_space(c: char) -> bool { |
| 1055 | matches!(c, ' ' | '\u{00A0}' | '\u{3000}') |
| 1056 | } |
| 1057 | |
| 1058 | /// Is the character Chinese or Japanese script (not Korean), which sets without spaces? |
| 1059 | pub fn is_cj_script(c: char, script: Script) -> bool { |
| 1060 | matches!(script, Script::Hiragana | Script::Katakana | Script::Han) || c == '\u{30FC}' |
| 1061 | } |
| 1062 | |
| 1063 | pub fn is_of_cj_script(c: char) -> bool { |
| 1064 | is_cj_script(c, Script::of(c)) |
| 1065 | } |
| 1066 | |
| 1067 | fn is_cjk_left_aligned_punctuation(c: char, x_advance: f64, stretch: (f64, f64), style: CjkPunctStyle) -> bool { |
| 1068 | if matches!(c, '\u{201D}' | '\u{2019}') && x_advance + stretch.1 == 1.0 { |
| 1069 | return true; |
| 1070 | } |
| 1071 | if matches!(style, CjkPunctStyle::Gb | CjkPunctStyle::Jis) |
| 1072 | && matches!(c, '\u{FF0C}' | '\u{3002}' | '\u{FF0E}' | '\u{3001}' | '\u{FF1A}' | '\u{FF1B}') |
| 1073 | { |
| 1074 | return true; |
| 1075 | } |
| 1076 | if matches!(style, CjkPunctStyle::Gb) && matches!(c, '\u{FF1F}' | '\u{FF01}') { |
| 1077 | return true; |
| 1078 | } |
| 1079 | matches!(c, '\u{300B}' | '\u{FF09}' | '\u{300F}' | '\u{300D}' | '\u{3011}' | '\u{3017}' | '\u{3015}' |
| 1080 | | '\u{3009}' | '\u{FF3D}' | '\u{FF5D}') |
| 1081 | } |
| 1082 | |
| 1083 | fn is_cjk_right_aligned_punctuation(c: char, x_advance: f64, stretch: (f64, f64)) -> bool { |
| 1084 | if matches!(c, '\u{201C}' | '\u{2018}') && x_advance + stretch.0 == 1.0 { |
| 1085 | return true; |
| 1086 | } |
| 1087 | matches!(c, '\u{300A}' | '\u{FF08}' | '\u{300E}' | '\u{300C}' | '\u{3010}' | '\u{3016}' | '\u{3014}' |
| 1088 | | '\u{3008}' | '\u{FF3B}' | '\u{FF5B}') |
| 1089 | } |
| 1090 | |
| 1091 | fn is_cjk_center_aligned_punctuation(c: char, style: CjkPunctStyle) -> bool { |
| 1092 | if matches!(style, CjkPunctStyle::Cns) |
| 1093 | && matches!(c, '\u{FF0C}' | '\u{3002}' | '\u{FF0E}' | '\u{3001}' | '\u{FF1A}' | '\u{FF1B}') |
| 1094 | { |
| 1095 | return true; |
| 1096 | } |
| 1097 | matches!(c, '\u{30FB}' | '\u{00B7}') |
| 1098 | } |
| 1099 | |
| 1100 | fn is_justifiable(c: char, script: Script, x_advance: f64, stretch: (f64, f64)) -> bool { |
| 1101 | let style = CjkPunctStyle::Gb; |
| 1102 | is_space(c) |
| 1103 | || is_cj_script(c, script) |
| 1104 | || is_cjk_left_aligned_punctuation(c, x_advance, stretch, style) |
| 1105 | || is_cjk_right_aligned_punctuation(c, x_advance, stretch) |
| 1106 | || is_cjk_center_aligned_punctuation(c, style) |
| 1107 | } |
| 1108 | |
| 1109 | /// The CJK punctuation a line may begin with. |
| 1110 | pub const BEGIN_PUNCT: &[char] = &['\u{201C}', '\u{2018}', '\u{300A}', '\u{3008}', '\u{FF08}', '\u{300E}', |
| 1111 | '\u{300C}', '\u{3010}', '\u{3016}', '\u{3014}', '\u{FF3B}', '\u{FF5B}']; |
| 1112 | |
| 1113 | /// The CJK punctuation a line may end with. |
| 1114 | pub const END_PUNCT: &[char] = &['\u{201D}', '\u{2019}', '\u{FF0C}', '\u{FF0E}', '\u{3002}', '\u{3001}', |
| 1115 | '\u{FF1A}', '\u{FF1B}', '\u{300B}', '\u{3009}', '\u{FF09}', '\u{300F}', '\u{300D}', '\u{3011}', |
| 1116 | '\u{3017}', '\u{3015}', '\u{FF3D}', '\u{FF5D}', '\u{FF1F}', '\u{FF01}']; |
| 1117 | |
| 1118 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 1119 | // │ SHAPING │ |
| 1120 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 1121 | |
| 1122 | struct Ctx<'a> { |
| 1123 | book: &'a FontBook, |
| 1124 | props: &'a TextProps, |
| 1125 | glyphs: Vec<SGlyph>, |
| 1126 | used: Vec<usize>, // faces exhausted, which fallback may not choose again |
| 1127 | rtl: bool, |
| 1128 | lang: String, |
| 1129 | } |
| 1130 | |
| 1131 | /// Shapes `text`, which starts at byte `base` of the paragraph's text, under `props`. |
| 1132 | pub fn shape_run(book: &FontBook, base: usize, text: &str, props: &Arc<TextProps>, rtl: bool) -> Outcome<ShapedRun> { |
| 1133 | let mut ctx = Ctx { |
| 1134 | book, |
| 1135 | props: props.as_ref(), |
| 1136 | glyphs: Vec::new(), |
| 1137 | used: Vec::new(), |
| 1138 | rtl, |
| 1139 | lang: props.bcp47(), |
| 1140 | }; |
| 1141 | if !text.is_empty() { |
| 1142 | res!(shape_segment(&mut ctx, base, text, 0)); |
| 1143 | } |
| 1144 | track_and_space(&mut ctx); |
| 1145 | calculate_adjustability(&mut ctx); |
| 1146 | let n = ctx.glyphs.len(); |
| 1147 | Ok(ShapedRun { |
| 1148 | base, |
| 1149 | text: Arc::from(text), |
| 1150 | rtl, |
| 1151 | props: props.clone(), |
| 1152 | glyphs: Arc::new(ctx.glyphs), |
| 1153 | span: (0, n), |
| 1154 | kept: (0, n), |
| 1155 | }) |
| 1156 | } |
| 1157 | |
| 1158 | /// Asks the host for the font-pack family a list reaches before any family the book holds -- the face the |
| 1159 | /// text would have been set in -- as an error naming `font:<family>` in `needs`, once a compile. A build |
| 1160 | /// with the embedded faces holds every pack family, so this is silent there; a family outside the pack is |
| 1161 | /// left to Typst's `unknown font family` warning and the fallback. |
| 1162 | pub fn ask_for_face<'f, I: IntoIterator<Item = &'f str>>(engine: &mut Engine, book: &FontBook, families: I) { |
| 1163 | for fam in families { |
| 1164 | if book.has_family(&fam.to_lowercase()) { |
| 1165 | return; |
| 1166 | } |
| 1167 | if let Some(need) = crate::fonts::need(fam) { |
| 1168 | if !engine.diags.iter().any(|d| d.need.as_deref() == Some(need.as_str())) { |
| 1169 | let family = need.trim_start_matches("font:").to_string(); |
| 1170 | let d = crate::diag::Diagnostic::error(crate::diag::DiagnosticKind::MissingFont, |
| 1171 | crate::syntax::Span::detached(), fmt!("the font family {} is not loaded", family)) |
| 1172 | .with_hint("this build embeds no fonts, so the host supplies the family from the font pack") |
| 1173 | .needing(need); |
| 1174 | engine.diags.push(d); |
| 1175 | } |
| 1176 | return; |
| 1177 | } |
| 1178 | } |
| 1179 | } |
| 1180 | |
| 1181 | /// The first family from `from` with a face for the variant that is not yet exhausted, then Typst's |
| 1182 | /// fallback search; the face, its coverage and the index of the family after it. |
| 1183 | fn font_and_covers(ctx: &mut Ctx, text: &str, from: usize) |
| 1184 | -> (Option<(usize, Option<Arc<Regex>>)>, usize) |
| 1185 | { |
| 1186 | let mut next = from; |
| 1187 | let mut selection = None; |
| 1188 | while next < ctx.props.families.len() { |
| 1189 | let fam = &ctx.props.families[next]; |
| 1190 | next += 1; |
| 1191 | if let Some(id) = ctx.book.select(&fam.name, ctx.props.variant) { |
| 1192 | if !ctx.used.contains(&id) { |
| 1193 | selection = Some((id, fam.covers.clone())); |
| 1194 | break; |
| 1195 | } |
| 1196 | } |
| 1197 | } |
| 1198 | if selection.is_none() && ctx.props.fallback { |
| 1199 | let first = ctx.used.first().copied(); |
| 1200 | if let Some(id) = ctx.book.select_fallback(first, ctx.props.variant, text) { |
| 1201 | if !ctx.used.contains(&id) { |
| 1202 | selection = Some((id, None)); |
| 1203 | } |
| 1204 | } |
| 1205 | } |
| 1206 | (selection, next) |
| 1207 | } |
| 1208 | |
| 1209 | /// Shapes a segment with the next family that has a face, re-shaping whatever that face cannot draw |
| 1210 | /// with the families after it; with no face left, the first face used draws not-defined glyphs. |
| 1211 | fn shape_segment(ctx: &mut Ctx, base: usize, text: &str, from: usize) -> Outcome<()> { |
| 1212 | if text.chars().all(|c| c == '\n' || c == '\t' || is_default_ignorable(c)) { |
| 1213 | return Ok(()); |
| 1214 | } |
| 1215 | let (sel, next) = font_and_covers(ctx, text, from); |
| 1216 | let (fid, covers) = match sel { |
| 1217 | Some(s) => s, |
| 1218 | None => { |
| 1219 | if let Some(&first) = ctx.used.first() { |
| 1220 | res!(shape_tofus(ctx, base, text, first)); |
| 1221 | } |
| 1222 | return Ok(()); |
| 1223 | }, |
| 1224 | }; |
| 1225 | if covers.is_none() { |
| 1226 | ctx.used.push(fid); |
| 1227 | } |
| 1228 | let bf = match ctx.book.face(fid) { |
| 1229 | Some(f) => f, |
| 1230 | None => return Err(err!("Face {} is not in the font book.", fid; Bug)), |
| 1231 | }; |
| 1232 | let upem = bf.metrics.units_per_em; |
| 1233 | |
| 1234 | // Scripts: the font's own sub- and superscript forms when asked for and present, else a synthesised |
| 1235 | // shift, compensation and scale from the face's metrics. |
| 1236 | let mut features = ctx.props.features.clone(); |
| 1237 | let (script_shift, script_comp, scale) = match ctx.props.shift { |
| 1238 | Some(s) => { |
| 1239 | let (shift, comp, scale, feat) = res!(determine_shift(bf, text, s, &ctx.props.features, ctx.rtl)); |
| 1240 | if let Some(f) = feat { |
| 1241 | features.push(f); |
| 1242 | } |
| 1243 | (shift, comp, scale) |
| 1244 | }, |
| 1245 | None => (0.0, 0.0, 1.0), |
| 1246 | }; |
| 1247 | |
| 1248 | let spec = ShapeSpec { |
| 1249 | features: &features, |
| 1250 | language: Some(&ctx.lang), |
| 1251 | script: ctx.props.script, |
| 1252 | remove_ignorables: true, |
| 1253 | }; |
| 1254 | let dir = if ctx.rtl { ShapeDir::Rtl } else { ShapeDir::Ltr }; |
| 1255 | // Shaped at one pixel per font unit, so advances and offsets come back in font units exactly, and |
| 1256 | // from the book's cache when the same call has been made before. |
| 1257 | let shaped = res!(ctx.book.shape(fid, text, dir, &spec)); |
| 1258 | let glyphs = shaped.as_slice(); |
| 1259 | let to_em = |u: f32| u as f64 / upem as f64; |
| 1260 | |
| 1261 | let is_covered = |offset: usize| -> bool { |
| 1262 | match &covers { |
| 1263 | None => true, |
| 1264 | Some(re) => { |
| 1265 | let end = text.get(offset..).and_then(|t| t.char_indices().nth(1).map(|(i, _)| offset + i)) |
| 1266 | .unwrap_or(text.len()); |
| 1267 | text.get(offset..end).map_or(false, |s| matches!(re.is_match(s), Ok(true))) |
| 1268 | }, |
| 1269 | } |
| 1270 | }; |
| 1271 | |
| 1272 | let mut pens = Vec::with_capacity(glyphs.len()); |
| 1273 | let mut pen = 0.0f32; |
| 1274 | for g in glyphs.iter() { |
| 1275 | pens.push(pen); |
| 1276 | pen += g.adv; |
| 1277 | } |
| 1278 | |
| 1279 | let mut i = 0; |
| 1280 | while i < glyphs.len() { |
| 1281 | let g: RunGlyph = glyphs[i]; |
| 1282 | let cluster = g.cluster; |
| 1283 | if g.id != 0 && is_covered(cluster) { |
| 1284 | let start = base + cluster; |
| 1285 | // The cluster's end: the next glyph in logical order with another cluster, else the text's end. |
| 1286 | let mut k = i; |
| 1287 | let end = loop { |
| 1288 | let nk = if ctx.rtl { k.checked_sub(1) } else { Some(k + 1) }; |
| 1289 | match nk.and_then(|n| glyphs.get(n).map(|gi| (n, gi))) { |
| 1290 | None => break base + text.len(), |
| 1291 | Some((n, gi)) => { |
| 1292 | if gi.cluster != cluster { |
| 1293 | break base + gi.cluster; |
| 1294 | } |
| 1295 | k = n; |
| 1296 | } |
| 1297 | } |
| 1298 | }; |
| 1299 | let c = text.get(cluster..).and_then(|t| t.chars().next()).unwrap_or(' '); |
| 1300 | let script = Script::of(c); |
| 1301 | let x_advance = to_em(g.adv); |
| 1302 | ctx.glyphs.push(SGlyph { |
| 1303 | face: fid, |
| 1304 | id: g.id, |
| 1305 | x_advance, |
| 1306 | x_offset: to_em(g.x - pens[i]) + script_comp, |
| 1307 | y_offset: to_em(g.y) + script_shift, |
| 1308 | size: scale * ctx.props.size, |
| 1309 | stretch: (0.0, 0.0), |
| 1310 | shrink: (0.0, 0.0), |
| 1311 | range: (start, end), |
| 1312 | c, |
| 1313 | justifiable: is_justifiable(c, script, x_advance, (0.0, 0.0)), |
| 1314 | script, |
| 1315 | safe_to_break: g.safe_to_break, |
| 1316 | }); |
| 1317 | } else { |
| 1318 | // The end of the not-drawn stretch, then its text range. |
| 1319 | let k = i; |
| 1320 | while glyphs.get(i + 1).map_or(false, |gi| gi.id == 0 || !is_covered(gi.cluster)) { |
| 1321 | i += 1; |
| 1322 | } |
| 1323 | let start = glyphs[if ctx.rtl { i } else { k }].cluster; |
| 1324 | let end_idx = if ctx.rtl { k.checked_sub(1) } else { Some(i + 1) }; |
| 1325 | let end = end_idx.and_then(|e| glyphs.get(e)).map_or(text.len(), |gi| gi.cluster); |
| 1326 | let (lo, hi) = (base + start, base + end); |
| 1327 | while ctx.glyphs.last().map_or(false, |gl| gl.range.0 >= lo && gl.range.0 < hi) { |
| 1328 | ctx.glyphs.pop(); |
| 1329 | } |
| 1330 | if let Some(sub) = text.get(start..end) { |
| 1331 | res!(shape_segment(ctx, base + start, sub, next)); |
| 1332 | } |
| 1333 | } |
| 1334 | i += 1; |
| 1335 | } |
| 1336 | ctx.used.pop(); |
| 1337 | Ok(()) |
| 1338 | } |
| 1339 | |
| 1340 | /// The shift, compensation and scale (ems) that make a sub- or superscript, and the feature that gives |
| 1341 | /// the font's own forms when it has them for every character. |
| 1342 | fn determine_shift(face: &BookFace, text: &str, s: ShiftSettings, base: &[Feature], rtl: bool) |
| 1343 | -> Outcome<(f64, f64, f64, Option<Feature>)> |
| 1344 | { |
| 1345 | let tag = if s.superscript { *b"sups" } else { *b"subs" }; |
| 1346 | if s.typographic { |
| 1347 | // The font's forms serve when the feature substitutes every character: shaped with and without |
| 1348 | // it, each glyph changes and none is missing. |
| 1349 | let f = res!(face.face()); |
| 1350 | let upem = face.metrics.units_per_em; |
| 1351 | let dir = if rtl { ShapeDir::Rtl } else { ShapeDir::Ltr }; |
| 1352 | let plain = res!(f.shape_spec(text, upem, dir, 0, 0, &ShapeSpec { features: base, ..ShapeSpec::default() })); |
| 1353 | let mut with: Vec<Feature> = base.to_vec(); |
| 1354 | with.push(Feature::set(&tag, 1)); |
| 1355 | let feat = res!(f.shape_spec(text, upem, dir, 0, 0, &ShapeSpec { features: &with, ..ShapeSpec::default() })); |
| 1356 | let all = !text.is_empty() |
| 1357 | && text.chars().all(|c| f.glyph_index(c).is_some()) |
| 1358 | && plain.glyphs.len() == feat.glyphs.len() |
| 1359 | && plain.glyphs.iter().zip(feat.glyphs.iter()).all(|(a, b)| a.id != b.id); |
| 1360 | if all { |
| 1361 | return Ok((0.0, 0.0, 1.0, Some(Feature::set(&tag, 1)))); |
| 1362 | } |
| 1363 | } |
| 1364 | let (height, hoff, voff) = script_metrics(Some(face), s.superscript); |
| 1365 | Ok((s.shift.unwrap_or(voff), hoff, s.size.unwrap_or(height), None)) |
| 1366 | } |
| 1367 | |
| 1368 | /// A face's advice for a synthesised script, in ems: its height, and its offsets right and up; Typst's |
| 1369 | /// defaults where the face gives none. |
| 1370 | fn script_metrics(face: Option<&BookFace>, superscript: bool) -> (f64, f64, f64) { |
| 1371 | let m = face.map(|f| (f, if superscript { f.metrics.superscript } else { f.metrics.subscript })); |
| 1372 | match (superscript, m) { |
| 1373 | (true, Some((f, Some(sm)))) => (f.to_em(sm.y_size), f.to_em(sm.x_offset), f.to_em(sm.y_offset)), |
| 1374 | (false, Some((f, Some(sm)))) => (f.to_em(sm.y_size), f.to_em(sm.x_offset), -f.to_em(sm.y_offset)), |
| 1375 | (true, _) => (0.6, 0.0, 0.5), |
| 1376 | (false, _) => (0.6, 0.0, -0.2), |
| 1377 | } |
| 1378 | } |
| 1379 | |
| 1380 | /// How far an inline frame's contents move under the text's baseline shift, right and down, in points: |
| 1381 | /// Typst's `apply_shift`, `text.baseline` and a script's offset from the first face of the families. |
| 1382 | pub fn frame_shift(book: &FontBook, props: &TextProps) -> (f64, f64) { |
| 1383 | let mut right = 0.0; |
| 1384 | let mut down = props.baseline; |
| 1385 | if let Some(s) = props.shift { |
| 1386 | let face = props.families.iter().find_map(|f| book.select(&f.name, props.variant)).and_then(|i| book.face(i)); |
| 1387 | let (_, hoff, voff) = script_metrics(face, s.superscript); |
| 1388 | down -= s.shift.unwrap_or(voff) * props.size; |
| 1389 | right += hoff * props.size; |
| 1390 | } |
| 1391 | (right, down) |
| 1392 | } |
| 1393 | |
| 1394 | /// Not-defined glyphs from face `fid`, one per character. |
| 1395 | fn shape_tofus(ctx: &mut Ctx, base: usize, text: &str, fid: usize) -> Outcome<()> { |
| 1396 | let bf = match ctx.book.face(fid) { |
| 1397 | Some(f) => f, |
| 1398 | None => return Ok(()), |
| 1399 | }; |
| 1400 | let adv = res!(bf.face()).advance_units(0).map(|u| bf.to_em(u)).unwrap_or(0.0); |
| 1401 | let mut push = |cluster: usize, c: char| { |
| 1402 | let script = Script::of(c); |
| 1403 | ctx.glyphs.push(SGlyph { |
| 1404 | face: fid, |
| 1405 | id: 0, |
| 1406 | x_advance: adv, |
| 1407 | x_offset: 0.0, |
| 1408 | y_offset: 0.0, |
| 1409 | size: ctx.props.size, |
| 1410 | stretch: (0.0, 0.0), |
| 1411 | shrink: (0.0, 0.0), |
| 1412 | range: (base + cluster, base + cluster + c.len_utf8()), |
| 1413 | c, |
| 1414 | justifiable: is_justifiable(c, script, adv, (0.0, 0.0)), |
| 1415 | script, |
| 1416 | safe_to_break: true, |
| 1417 | }); |
| 1418 | }; |
| 1419 | if ctx.rtl { |
| 1420 | for (i, c) in text.char_indices().rev() { |
| 1421 | push(i, c); |
| 1422 | } |
| 1423 | } else { |
| 1424 | for (i, c) in text.char_indices() { |
| 1425 | push(i, c); |
| 1426 | } |
| 1427 | } |
| 1428 | Ok(()) |
| 1429 | } |
| 1430 | |
| 1431 | /// Applies `tracking` between clusters and `spacing` to spaces; a no-break space takes the width of an |
| 1432 | /// ordinary one. |
| 1433 | fn track_and_space(ctx: &mut Ctx) { |
| 1434 | let size = ctx.props.size; |
| 1435 | let tracking = if size > 0.0 { ctx.props.tracking / size } else { 0.0 }; |
| 1436 | let (ratio, abs) = ctx.props.spacing; |
| 1437 | let abs_em = if size > 0.0 { abs / size } else { 0.0 }; |
| 1438 | let n = ctx.glyphs.len(); |
| 1439 | for i in 0..n { |
| 1440 | if ctx.glyphs[i].c == '\u{00A0}' { |
| 1441 | let delta = nbsp_delta(ctx.book, ctx.glyphs[i].face).unwrap_or(0.0); |
| 1442 | ctx.glyphs[i].x_advance -= delta; |
| 1443 | } |
| 1444 | if ctx.glyphs[i].is_space() { |
| 1445 | ctx.glyphs[i].x_advance = ratio * ctx.glyphs[i].x_advance + abs_em; |
| 1446 | } |
| 1447 | if i + 1 < n && ctx.glyphs[i].range.0 != ctx.glyphs[i + 1].range.0 { |
| 1448 | ctx.glyphs[i].x_advance += tracking; |
| 1449 | } |
| 1450 | } |
| 1451 | } |
| 1452 | |
| 1453 | /// A face's no-break space advance less its space advance, in ems. |
| 1454 | fn nbsp_delta(book: &FontBook, fid: usize) -> Option<f64> { |
| 1455 | let bf = book.face(fid)?; |
| 1456 | let f = bf.face().ok()?; |
| 1457 | let space = f.glyph_index(' ')?; |
| 1458 | let nbsp = f.glyph_index('\u{00A0}')?; |
| 1459 | Some(bf.to_em(f.advance_units(nbsp)?) - bf.to_em(f.advance_units(space)?)) |
| 1460 | } |
| 1461 | |
| 1462 | /// Gives each glyph its stretch and shrink, then compresses consecutive CJK punctuation. |
| 1463 | fn calculate_adjustability(ctx: &mut Ctx) { |
| 1464 | let style = cjk_punct_style(&ctx.props.lang, ctx.props.region.as_deref()); |
| 1465 | let limits = ctx.props.limits; |
| 1466 | let size = ctx.props.size; |
| 1467 | let n = ctx.glyphs.len(); |
| 1468 | for i in 0..n { |
| 1469 | let stretchable = i + 1 >= n || ctx.glyphs[i].range.0 != ctx.glyphs[i + 1].range.0; |
| 1470 | let (st, sh) = ctx.glyphs[i].base_adjustability(style, &limits, size, stretchable); |
| 1471 | ctx.glyphs[i].stretch = st; |
| 1472 | ctx.glyphs[i].shrink = sh; |
| 1473 | } |
| 1474 | for i in 0..n { |
| 1475 | if ctx.glyphs[i].is_cjk_punctuation() && style == CjkPunctStyle::Cns { |
| 1476 | continue; |
| 1477 | } |
| 1478 | if i + 1 >= n { |
| 1479 | continue; |
| 1480 | } |
| 1481 | let width = ctx.glyphs[i].x_advance; |
| 1482 | let delta = width / 2.0; |
| 1483 | if ctx.glyphs[i].is_cjk_punctuation() |
| 1484 | && ctx.glyphs[i + 1].is_cjk_punctuation() |
| 1485 | && ctx.glyphs[i].shrink.1 + ctx.glyphs[i + 1].shrink.0 >= delta |
| 1486 | { |
| 1487 | let left = ctx.glyphs[i].shrink.1.min(delta); |
| 1488 | ctx.glyphs[i].shrink_right(left); |
| 1489 | ctx.glyphs[i + 1].shrink_left(delta - left); |
| 1490 | } |
| 1491 | } |
| 1492 | } |
| 1493 | |
| 1494 | impl ShapedRun { |
| 1495 | /// The slice `start..end` of the run, as Typst's `reshape`: the run's own glyphs, shared, when the |
| 1496 | /// shaper marked both ends safe to break, else the slice shaped afresh, since a line boundary there |
| 1497 | /// may change kerning or a ligature. |
| 1498 | pub fn reshape(&self, book: &FontBook, start: usize, end: usize) -> Outcome<ShapedRun> { |
| 1499 | let text = match self.text.get(start.saturating_sub(self.base)..end.saturating_sub(self.base)) { |
| 1500 | Some(t) if start >= self.base => t, |
| 1501 | _ => return Err(err!( |
| 1502 | "A line cuts a text run off a character boundary at {}..{}.", start, end; Bug)), |
| 1503 | }; |
| 1504 | if let Some((a, b)) = self.slice_safe_to_break(start, end) { |
| 1505 | return Ok(ShapedRun { |
| 1506 | base: start, |
| 1507 | text: Arc::from(text), |
| 1508 | rtl: self.rtl, |
| 1509 | props: self.props.clone(), |
| 1510 | glyphs: self.glyphs.clone(), |
| 1511 | span: (a, b), |
| 1512 | kept: (a, b), |
| 1513 | }); |
| 1514 | } |
| 1515 | shape_run(book, start, text, &self.props, self.rtl) |
| 1516 | } |
| 1517 | |
| 1518 | /// The glyphs, as a range within `glyphs`, that draw `start..end` when both ends are safe to break. |
| 1519 | fn slice_safe_to_break(&self, start: usize, end: usize) -> Option<(usize, usize)> { |
| 1520 | let (l, r) = if self.rtl { (end, start) } else { (start, end) }; |
| 1521 | let a = self.find_safe_to_break(l)?; |
| 1522 | let b = self.find_safe_to_break(r)?; |
| 1523 | if a <= b { Some((self.span.0 + a, self.span.0 + b)) } else { None } |
| 1524 | } |
| 1525 | |
| 1526 | /// The index, within the run, of the glyph that starts text index `at` furthest towards the run's |
| 1527 | /// start, when the shaper marked it safe to break; Typst's `find_safe_to_break`. |
| 1528 | fn find_safe_to_break(&self, at: usize) -> Option<usize> { |
| 1529 | let all = self.all(); |
| 1530 | let ltr = !self.rtl; |
| 1531 | let len = all.len(); |
| 1532 | if at == self.base { |
| 1533 | return Some(if ltr { 0 } else { len }); |
| 1534 | } else if at == self.base + self.text.len() { |
| 1535 | return Some(if ltr { len } else { 0 }); |
| 1536 | } |
| 1537 | let found = all.binary_search_by(|g| { |
| 1538 | let o = g.range.0.cmp(&at); |
| 1539 | if ltr { o } else { o.reverse() } |
| 1540 | }); |
| 1541 | let mut idx = match found { |
| 1542 | Ok(i) => i, |
| 1543 | Err(i) => { |
| 1544 | // A break before a newline, which draws no glyph: safe when the glyph before ends there. |
| 1545 | let nl = i > 0 |
| 1546 | && all.get(i - 1).map_or(false, |g| g.range.1 == at) |
| 1547 | && self.text.get(at - self.base..).map_or(false, |t| t.starts_with('\n')); |
| 1548 | return if nl { Some(i) } else { None }; |
| 1549 | }, |
| 1550 | }; |
| 1551 | // The start-most glyph at `at`: empty clusters there go with this line's start, those at the end |
| 1552 | // with the next line. |
| 1553 | loop { |
| 1554 | let next = if ltr { idx.checked_sub(1) } else { idx.checked_add(1) }; |
| 1555 | match next { |
| 1556 | Some(n) if all.get(n).map_or(false, |g| g.range.0 == at) => idx = n, |
| 1557 | _ => break, |
| 1558 | } |
| 1559 | } |
| 1560 | // Right to left, the range's left side is exclusive and its right inclusive. |
| 1561 | match all.get(idx) { |
| 1562 | Some(g) if g.safe_to_break => Some(idx + usize::from(!ltr)), |
| 1563 | _ => None, |
| 1564 | } |
| 1565 | } |
| 1566 | |
| 1567 | /// A hyphen in the run's style, from the first family whose face has one: a soft hyphen's glyph when |
| 1568 | /// `soft` (it copies as the soft hyphen it stands for), else an ordinary hyphen. |
| 1569 | pub fn hyphen(&self, book: &FontBook, pos: usize, soft: bool) -> Option<ShapedRun> { |
| 1570 | let props = &self.props; |
| 1571 | let mut ids: Vec<usize> = props.families.iter() |
| 1572 | .filter(|f| f.covers.as_ref().map_or(true, |c| matches!(c.is_match("-"), Ok(true)))) |
| 1573 | .filter_map(|f| book.select(&f.name, props.variant)) |
| 1574 | .collect(); |
| 1575 | if props.fallback { |
| 1576 | if let Some(id) = book.select_fallback(None, props.variant, "-") { |
| 1577 | ids.push(id); |
| 1578 | } |
| 1579 | } |
| 1580 | for id in ids { |
| 1581 | let bf = book.face(id)?; |
| 1582 | let f = bf.face().ok()?; |
| 1583 | let gid = match f.glyph_index('-') { |
| 1584 | Some(g) => g, |
| 1585 | None => continue, |
| 1586 | }; |
| 1587 | let adv = match f.advance_units(gid) { |
| 1588 | Some(a) => bf.to_em(a), |
| 1589 | None => continue, |
| 1590 | }; |
| 1591 | let text: &str = if soft { "\u{00AD}" } else { "-" }; |
| 1592 | let g = SGlyph { |
| 1593 | face: id, |
| 1594 | id: gid, |
| 1595 | x_advance: adv, |
| 1596 | x_offset: 0.0, |
| 1597 | y_offset: 0.0, |
| 1598 | size: props.size, |
| 1599 | stretch: (0.0, 0.0), |
| 1600 | shrink: (0.0, 0.0), |
| 1601 | range: (pos, pos + text.len()), |
| 1602 | c: if soft { '\u{00AD}' } else { '-' }, |
| 1603 | justifiable: false, |
| 1604 | script: Script::Common, |
| 1605 | safe_to_break: true, |
| 1606 | }; |
| 1607 | return Some(ShapedRun { |
| 1608 | base: pos, |
| 1609 | text: Arc::from(text), |
| 1610 | rtl: self.rtl, |
| 1611 | props: props.clone(), |
| 1612 | glyphs: Arc::new(vec![g]), |
| 1613 | span: (0, 1), |
| 1614 | kept: (0, 1), |
| 1615 | }); |
| 1616 | } |
| 1617 | None |
| 1618 | } |
| 1619 | |
| 1620 | /// The run as drawn nodes for a line, each seated on its baseline: a text leaf per group of glyphs |
| 1621 | /// sharing a face, offset and size, justified by `ratio` (of each glyph's stretch or shrink) and |
| 1622 | /// `extra` points on each justifiable glyph, decorated as the style asks. Returns the nodes and the |
| 1623 | /// advance they take, in points. |
| 1624 | pub fn build(&self, book: &FontBook, ratio: f64, extra: f64) -> Outcome<(Vec<Node>, f64)> { |
| 1625 | let props = &self.props; |
| 1626 | let size = props.size; |
| 1627 | let (top, bottom) = self.measure(book); |
| 1628 | let mut out: Vec<Node> = Vec::new(); |
| 1629 | let mut offset = 0.0f64; |
| 1630 | let all = self.all(); |
| 1631 | let at = self.span.0; |
| 1632 | let mut i = 0; |
| 1633 | while i < all.len() { |
| 1634 | let key = (all[i].face, all[i].y_offset, all[i].size); |
| 1635 | let mut j = i; |
| 1636 | while j < all.len() && (all[j].face, all[j].y_offset, all[j].size) == key { |
| 1637 | j += 1; |
| 1638 | } |
| 1639 | let group = &all[i..j]; |
| 1640 | let lo = group.iter().map(|g| g.range.0).min().unwrap_or(self.base); |
| 1641 | let hi = group.iter().map(|g| g.range.1).max().unwrap_or(self.base); |
| 1642 | let gsize = key.2; |
| 1643 | let mut run_glyphs: Vec<RunGlyph> = Vec::with_capacity(group.len()); |
| 1644 | let mut pen = 0.0f64; |
| 1645 | for (gi, g) in group.iter().enumerate() { |
| 1646 | let k = at + i + gi; |
| 1647 | let kept = k >= self.kept.0 && k < self.kept.1; |
| 1648 | let (adv, xoff) = if kept { |
| 1649 | let left = if ratio < 0.0 { g.shrink.0 } else { g.stretch.0 }; |
| 1650 | let right = if ratio < 0.0 { g.shrink.1 } else { g.stretch.1 }; |
| 1651 | let jl = left * ratio; |
| 1652 | let mut jr = right * ratio; |
| 1653 | if g.justifiable && gsize > 0.0 { |
| 1654 | jr += extra / gsize; |
| 1655 | } |
| 1656 | (g.x_advance + jl + jr, g.x_offset + jl) |
| 1657 | } else { |
| 1658 | (0.0, 0.0) |
| 1659 | }; |
| 1660 | run_glyphs.push(RunGlyph { |
| 1661 | id: g.id, |
| 1662 | face: 0, |
| 1663 | x: ((pen + xoff) * gsize) as f32, |
| 1664 | y: 0.0, |
| 1665 | adv: (adv * gsize) as f32, |
| 1666 | cluster: g.range.0.saturating_sub(lo), |
| 1667 | safe_to_break: g.safe_to_break, |
| 1668 | }); |
| 1669 | pen += adv; |
| 1670 | } |
| 1671 | let width = pen * gsize; |
| 1672 | let bf = match book.face(key.0) { |
| 1673 | Some(f) => f, |
| 1674 | None => return Err(err!("Face {} is not in the font book.", key.0; Bug)), |
| 1675 | }; |
| 1676 | let text = self.text.get(lo.saturating_sub(self.base)..hi.saturating_sub(self.base)).unwrap_or(""); |
| 1677 | // The group's baseline: `baseline` lowers (a positive `text.baseline` moves text down), the |
| 1678 | // glyph offset raises. |
| 1679 | let shift = props.baseline - key.1 * size; |
| 1680 | if props.hidden { |
| 1681 | out.push(Node::Glue(crate::ir::Glue::fixed(Sp::from_pt(width)))); |
| 1682 | } else { |
| 1683 | let shaped = ShapedText::from_glyphs( |
| 1684 | bf.font.clone(), gsize as f32, run_glyphs, text.to_string(), props.fill, |
| 1685 | Dims::new(Sp::from_pt(width), Sp::from_pt(top), Sp::from_pt(bottom)), |
| 1686 | ); |
| 1687 | // Decorations are zero-size graphics at the group's start on the baseline, those under the |
| 1688 | // text first. |
| 1689 | let mut front: Vec<Node> = Vec::new(); |
| 1690 | for d in &props.decos { |
| 1691 | let (nodes, background) = res!(decorate(d, bf, group, props, width, shift)); |
| 1692 | if background { out.extend(nodes); } else { front.extend(nodes); } |
| 1693 | } |
| 1694 | out.extend(front); |
| 1695 | let dims = shaped.dims(); |
| 1696 | out.push(Node::Leaf(Leaf::text_dims(shaped, dims).with_shift(Sp::from_pt(shift)))); |
| 1697 | } |
| 1698 | offset += width; |
| 1699 | i = j; |
| 1700 | } |
| 1701 | Ok((out, offset)) |
| 1702 | } |
| 1703 | } |
| 1704 | |
| 1705 | /// A decoration for one group of glyphs `width` points wide whose baseline is lowered by `shift`: |
| 1706 | /// zero-size graphics at the group's start whose origin is the line's baseline, drawn under the text |
| 1707 | /// when `background`. |
| 1708 | fn decorate( |
| 1709 | deco: &Deco, |
| 1710 | face: &BookFace, |
| 1711 | group: &[SGlyph], |
| 1712 | props: &TextProps, |
| 1713 | width: f64, |
| 1714 | shift: f64, |
| 1715 | ) |
| 1716 | -> Outcome<(Vec<Node>, bool)> |
| 1717 | { |
| 1718 | let size = group.first().map_or(props.size, |g| g.size); |
| 1719 | let m = &face.metrics; |
| 1720 | let em = |u: f32| face.to_em(u) * size; |
| 1721 | let mut ops: Vec<DrawOp> = Vec::new(); |
| 1722 | let x0 = -deco.extent; |
| 1723 | let background; |
| 1724 | match &deco.line { |
| 1725 | DecoLine::Highlight { fill, top: te, bottom: be } => { |
| 1726 | let mut t = 0.0f64; |
| 1727 | let mut b = 0.0f64; |
| 1728 | for g in group { |
| 1729 | let (tt, bb) = edges(face, *te, *be, size, Some(g.id)); |
| 1730 | t = t.max(tt); |
| 1731 | b = b.max(bb); |
| 1732 | } |
| 1733 | if let Some(fill) = fill { |
| 1734 | let r = Bounds::new(x0 as f32, (shift - t) as f32, (width + deco.extent) as f32, (shift + b) as f32); |
| 1735 | ops.push(DrawOp::Fill { path: res!(Path::rect(r)), colour: *fill }); |
| 1736 | } |
| 1737 | background = true; |
| 1738 | } |
| 1739 | line => { |
| 1740 | let (stroke, pos_thick, off, evade, bg) = match line { |
| 1741 | DecoLine::Strikethrough { stroke, offset, background } => ( |
| 1742 | stroke, m.strikeout.map(|(p, t)| (em(p), em(t))).unwrap_or((0.25 * size, 0.06 * size)), offset, false, *background), |
| 1743 | DecoLine::Overline { stroke, offset, evade, background } => { |
| 1744 | let und = m.underline.or(m.strikeout).map(|(_, t)| em(t)).unwrap_or(0.06 * size); |
| 1745 | (stroke, (em(m.cap_height.unwrap_or(m.ascender)) + 0.1 * size, und), offset, *evade, *background) |
| 1746 | } |
| 1747 | DecoLine::Underline { stroke, offset, evade, background } => ( |
| 1748 | stroke, m.underline.map(|(p, t)| (em(p), em(t))).unwrap_or((-0.2 * size, 0.06 * size)), offset, *evade, *background), |
| 1749 | DecoLine::Highlight { .. } => return Ok((Vec::new(), false)), |
| 1750 | }; |
| 1751 | background = bg; |
| 1752 | let y = off.unwrap_or(-pos_thick.0) + shift; |
| 1753 | let colour = stroke.and_then(|s| s.paint).unwrap_or(props.fill); |
| 1754 | let thick = stroke.and_then(|s| s.thickness).unwrap_or(pos_thick.1); |
| 1755 | let gap = 0.08 * size; |
| 1756 | let min_width = 0.162 * size; |
| 1757 | let start = x0; |
| 1758 | let end = width + deco.extent; |
| 1759 | let mut cuts: Vec<f64> = Vec::new(); |
| 1760 | if evade { |
| 1761 | let mut x = 0.0f64; |
| 1762 | for g in group { |
| 1763 | let dx = g.x_offset * size + x; |
| 1764 | x += g.x_advance * size; |
| 1765 | if let Ok(path) = face.font.outline(0, g.id, size as f32) { |
| 1766 | let band = y - shift; // the line's height against the glyph's baseline, down |
| 1767 | if let Some(bb) = path.bounds(&Transform::IDENTITY) { |
| 1768 | if !(-band >= bb.y0 as f64 && -band <= bb.y1 as f64) { |
| 1769 | continue; |
| 1770 | } |
| 1771 | } |
| 1772 | for poly in path.flatten(&Transform::IDENTITY, 0.01) { |
| 1773 | for w in poly.windows(2) { |
| 1774 | let (p, q) = (w[0], w[1]); |
| 1775 | let (py, qy) = (-(p.y as f64), -(q.y as f64)); |
| 1776 | if (py - band) * (qy - band) <= 0.0 && py != qy { |
| 1777 | let t = (band - py) / (qy - py); |
| 1778 | cuts.push(dx + p.x as f64 + t * (q.x as f64 - p.x as f64)); |
| 1779 | } |
| 1780 | } |
| 1781 | } |
| 1782 | } |
| 1783 | } |
| 1784 | } |
| 1785 | let mut segs: Vec<(f64, f64)> = Vec::new(); |
| 1786 | if !evade { |
| 1787 | segs.push((start, end)); |
| 1788 | } else { |
| 1789 | cuts.push(start - gap); |
| 1790 | cuts.push(end + gap); |
| 1791 | cuts.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 1792 | for w in cuts.windows(2) { |
| 1793 | let (l, r) = (w[0], w[1]); |
| 1794 | if r - l < gap { |
| 1795 | continue; |
| 1796 | } |
| 1797 | let (a, b) = (l + gap, r - gap); |
| 1798 | if b - a >= min_width { |
| 1799 | segs.push((a, b)); |
| 1800 | } |
| 1801 | } |
| 1802 | } |
| 1803 | for (a, b) in segs { |
| 1804 | let mut pb = PathBuilder::new(); |
| 1805 | pb.move_to(Pt::new(a as f32, y as f32)); |
| 1806 | pb.line_to(Pt::new(b as f32, y as f32)); |
| 1807 | let path = res!(pb.finish()); |
| 1808 | ops.push(DrawOp::Stroke { path, colour, width: thick as f32 }); |
| 1809 | } |
| 1810 | } |
| 1811 | } |
| 1812 | if ops.is_empty() { |
| 1813 | return Ok((Vec::new(), background)); |
| 1814 | } |
| 1815 | let graphic = Graphic::new(ops, Dims::new(Sp::ZERO, Sp::ZERO, Sp::ZERO)); |
| 1816 | Ok((vec![Node::Leaf(Leaf::graphic(graphic))], background)) |
| 1817 | } |
| 1818 | |
| 1819 | /// Shapes one run of text under the chain's `text` properties, as one drawable run: the contract entry |
| 1820 | /// for callers outside inline layout (an SVG's text, a label). Faces are chosen with Typst's fallback; |
| 1821 | /// the run's glyphs may come from several faces. |
| 1822 | pub fn shape(engine: &mut Engine, text: &str, styles: &StyleChain) -> Outcome<ShapedText> { |
| 1823 | let book = res!(engine.fonts.book()); |
| 1824 | let props = Arc::new(res!(props(styles))); |
| 1825 | ask_for_face(engine, &book, props.families.iter().map(|f| f.name.as_str())); |
| 1826 | let run = res!(shape_run(&book, 0, text, &props, props.rtl)); |
| 1827 | let size = props.size; |
| 1828 | let mut fonts: Vec<Arc<oxedyne_fe2o3_font::font::Font>> = Vec::new(); |
| 1829 | let mut glyphs = Vec::with_capacity(run.glyphs.len()); |
| 1830 | let mut pen = 0.0f64; // points |
| 1831 | for g in run.glyphs.iter() { |
| 1832 | let bf = match book.face(g.face) { |
| 1833 | Some(f) => f, |
| 1834 | None => continue, |
| 1835 | }; |
| 1836 | let fi = match fonts.iter().position(|f| Arc::ptr_eq(f, &bf.font)) { |
| 1837 | Some(i) => i, |
| 1838 | None => { |
| 1839 | fonts.push(bf.font.clone()); |
| 1840 | fonts.len() - 1 |
| 1841 | } |
| 1842 | }; |
| 1843 | glyphs.push(RunGlyph { |
| 1844 | id: g.id, |
| 1845 | face: fi as u8, |
| 1846 | x: (pen + g.x_offset * g.size) as f32, |
| 1847 | y: (g.y_offset * size) as f32, |
| 1848 | adv: (g.x_advance * g.size) as f32, |
| 1849 | cluster: g.range.0, |
| 1850 | safe_to_break: g.safe_to_break, |
| 1851 | }); |
| 1852 | pen += g.x_advance * g.size; |
| 1853 | } |
| 1854 | let (top, bottom) = run.measure(&book); |
| 1855 | let width = run.width(); |
| 1856 | ShapedText::from_faces( |
| 1857 | fonts, size as f32, glyphs, text.to_string(), props.fill, |
| 1858 | Dims::new(Sp::from_pt(width), Sp::from_pt(top), Sp::from_pt(bottom)), |
| 1859 | ) |
| 1860 | } |
| 1861 | |
| 1862 | /// The absolute length of a relative one at a whole of `whole` points under the chain's font size. |
| 1863 | pub fn resolve_rel(r: &Relative, whole: f64, styles: &StyleChain) -> f64 { |
| 1864 | r.rel.0 * whole + styles.resolve_length(r.abs) |
| 1865 | } |
| 1866 | |
| 1867 | /// A length in points under the chain's font size. |
| 1868 | pub fn resolve_len(l: &Length, styles: &StyleChain) -> f64 { |
| 1869 | styles.resolve_length(*l) |
| 1870 | } |