| 1 | use onestore::page::text::Paragraph; |
| 2 | use parley::{ |
| 3 | Affinity, Alignment, AlignmentOptions, BoundingBox, FontContext, FontFamily, FontFamilyName, |
| 4 | FontStyle, FontWeight, GenericFamily, Layout, LayoutContext, OverflowWrap, |
| 5 | PositionedLayoutItem, StyleProperty, |
| 6 | editing::{Cursor, Selection}, |
| 7 | fontique::{Blob, FontInfo, SourceCache}, |
| 8 | }; |
| 9 | use skrifa::{FontRef, MetadataProvider, raw::TableProvider, string::StringId}; |
| 10 | use std::{ |
| 11 | collections::{BTreeMap, BTreeSet}, |
| 12 | fmt, |
| 13 | ops::Range, |
| 14 | sync::{ |
| 15 | Arc, OnceLock, |
| 16 | atomic::{AtomicU64, Ordering}, |
| 17 | }, |
| 18 | }; |
| 19 | |
| 20 | pub struct TextEngine { |
| 21 | pub fonts: FontContext, |
| 22 | context: LayoutContext<TextBrush>, |
| 23 | arial_substitutes: BTreeSet<u64>, |
| 24 | /// The substitute each family lays out in, by family. |
| 25 | substitutes: BTreeMap<&'static str, Substitute>, |
| 26 | } |
| 27 | |
| 28 | /// A font laid out in place of a family. |
| 29 | #[derive(Clone)] |
| 30 | pub struct Substitute { |
| 31 | pub name: &'static str, |
| 32 | /// Its faces as registered for the family. |
| 33 | pub faces: Vec<(Blob<u8>, FontInfo)>, |
| 34 | bundled: bool, |
| 35 | } |
| 36 | |
| 37 | /// Superscripts and subscripts draw at this fraction of their run's size. |
| 38 | const SCRIPT_SCALE: f32 = 2.0 / 3.0; |
| 39 | const SUPERSCRIPT_RISE: f32 = 1.0 / 3.0; |
| 40 | const SUBSCRIPT_DROP: f32 = 0.08; |
| 41 | |
| 42 | #[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 43 | pub struct TextBrush { |
| 44 | /// COLORREF, or `None` for OneNote's automatic colour, which follows the paper. |
| 45 | pub(crate) color: Option<u32>, |
| 46 | pub(crate) highlight: Option<u32>, |
| 47 | /// Points the run draws above the line's baseline: positive for a superscript, |
| 48 | /// negative for a subscript. Line metrics and hit-testing keep the baseline. |
| 49 | pub(crate) rise: f32, |
| 50 | } |
| 51 | |
| 52 | #[derive(Clone, Debug)] |
| 53 | pub struct LineBox { |
| 54 | pub source: Range<usize>, |
| 55 | pub top: f32, |
| 56 | pub baseline: f32, |
| 57 | pub height: f32, |
| 58 | } |
| 59 | |
| 60 | #[derive(Clone)] |
| 61 | pub struct TextLayout { |
| 62 | id: u64, |
| 63 | pub(crate) shaped: Arc<Layout<TextBrush>>, |
| 64 | /// The paragraph text laid out, which a PDF's text layer maps glyphs back to. |
| 65 | #[cfg(feature = "gpu")] |
| 66 | pub(crate) text: Arc<str>, |
| 67 | lines: Vec<LineBox>, |
| 68 | /// Where each inline space lies: its index in the spaces laid out, its x, and its line. |
| 69 | spaces: Vec<(usize, f32, usize)>, |
| 70 | } |
| 71 | |
| 72 | /// Room kept in a line for something drawn inline, such as an equation, before the text at |
| 73 | /// byte `index`; the line grows to its ascent and descent. |
| 74 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 75 | pub(crate) struct InlineSpace { |
| 76 | pub(crate) index: usize, |
| 77 | pub(crate) width: f32, |
| 78 | pub(crate) ascent: f32, |
| 79 | pub(crate) descent: f32, |
| 80 | } |
| 81 | |
| 82 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 83 | pub enum LayoutError { |
| 84 | InvalidWidth, |
| 85 | InvalidFontSize, |
| 86 | InvalidSourceRange, |
| 87 | InvalidFontMetrics, |
| 88 | InvalidIndentation, |
| 89 | InvalidSpacing, |
| 90 | InvalidList, |
| 91 | UnsupportedContent, |
| 92 | UnsupportedSubstituteFont, |
| 93 | } |
| 94 | |
| 95 | impl fmt::Display for LayoutError { |
| 96 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 97 | match self { |
| 98 | Self::UnsupportedSubstituteFont => { |
| 99 | write!( |
| 100 | f, |
| 101 | "Choose an Arimo, Carlito, Caladea, Tinos or Cousine font file." |
| 102 | ) |
| 103 | } |
| 104 | _ => write!(f, "Text layout failed: {self:?}"), |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | impl std::error::Error for LayoutError {} |
| 110 | |
| 111 | /// What a run without a font or size of its own is laid out in. |
| 112 | pub(crate) const DEFAULT_FONT: &str = "Arial"; |
| 113 | pub(crate) const DEFAULT_FONT_SIZE: f32 = 11.0; |
| 114 | |
| 115 | /// Metric-compatible faces for the fonts OneNote pages use most, under the SIL Open Font |
| 116 | /// Licence files beside them, deflated, by the family each stands in for. The build script |
| 117 | /// leaves out each whose family the system ships, and every one from the browser's module, |
| 118 | /// which fetches them beside it instead (`register_substitute`). |
| 119 | const BUNDLED: &[(&str, &[&[u8]])] = include!(concat!(env!("OUT_DIR"), "/bundled.rs")); |
| 120 | |
| 121 | /// Each bundled family's faces, inflated the first time they are asked for. |
| 122 | static INFLATED: [OnceLock<Vec<Blob<u8>>>; BUNDLED.len()] = |
| 123 | [const { OnceLock::new() }; BUNDLED.len()]; |
| 124 | |
| 125 | /// The bundled faces standing in for `family`, inflated the first time they are asked for; |
| 126 | /// none where the build left the family out. |
| 127 | pub(crate) fn bundled(family: &str) -> Option<&'static [Blob<u8>]> { |
| 128 | let at = BUNDLED.iter().position(|(bundled, _)| *bundled == family)?; |
| 129 | let faces = INFLATED[at].get_or_init(|| { |
| 130 | BUNDLED[at] |
| 131 | .1 |
| 132 | .iter() |
| 133 | .map(|face| { |
| 134 | let face = miniz_oxide::inflate::decompress_to_vec(face); |
| 135 | Blob::new(Arc::new(face.expect("bundled substitutes inflate"))) |
| 136 | }) |
| 137 | .collect() |
| 138 | }); |
| 139 | Some(faces) |
| 140 | } |
| 141 | |
| 142 | impl Default for TextEngine { |
| 143 | /// An engine that lays out each bundled family in its substitute where it is missing. |
| 144 | fn default() -> Self { |
| 145 | let mut engine = Self { |
| 146 | // Clones share loaded font files, so glyphs one lays out draw from the same cache. |
| 147 | fonts: FontContext { |
| 148 | source_cache: SourceCache::new_shared(), |
| 149 | ..FontContext::default() |
| 150 | }, |
| 151 | context: LayoutContext::default(), |
| 152 | arial_substitutes: BTreeSet::new(), |
| 153 | substitutes: BTreeMap::new(), |
| 154 | }; |
| 155 | for (family, _) in BUNDLED { |
| 156 | if engine.fonts.collection.family_id(family).is_some() { |
| 157 | continue; |
| 158 | } |
| 159 | for face in bundled(family).into_iter().flatten() { |
| 160 | engine |
| 161 | .register(face.clone(), true) |
| 162 | .expect("bundled substitutes register"); |
| 163 | } |
| 164 | } |
| 165 | engine |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /// Another engine with the same fonts and substitutes, to lay out on another thread. |
| 170 | impl Clone for TextEngine { |
| 171 | fn clone(&self) -> Self { |
| 172 | Self { |
| 173 | fonts: self.fonts.clone(), |
| 174 | context: LayoutContext::default(), |
| 175 | arial_substitutes: self.arial_substitutes.clone(), |
| 176 | substitutes: self.substitutes.clone(), |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | impl TextEngine { |
| 182 | /// Register Arimo as Arial, Carlito as Calibri, Caladea as Cambria, Tinos as Times New |
| 183 | /// Roman or Cousine as Courier New before creating layouts, in place of the bundled |
| 184 | /// substitute. |
| 185 | pub fn register_substitute(&mut self, data: Blob<u8>) -> Result<&'static str, LayoutError> { |
| 186 | self.register(data, false) |
| 187 | } |
| 188 | |
| 189 | fn register(&mut self, data: Blob<u8>, bundled: bool) -> Result<&'static str, LayoutError> { |
| 190 | let font = |
| 191 | FontRef::new(data.as_ref()).map_err(|_| LayoutError::UnsupportedSubstituteFont)?; |
| 192 | let family = font |
| 193 | .localized_strings(StringId::TYPOGRAPHIC_FAMILY_NAME) |
| 194 | .english_or_first() |
| 195 | .or_else(|| { |
| 196 | font.localized_strings(StringId::FAMILY_NAME) |
| 197 | .english_or_first() |
| 198 | }) |
| 199 | .map(|name| name.to_string()) |
| 200 | .ok_or(LayoutError::UnsupportedSubstituteFont)?; |
| 201 | let (substitute, target) = match family.as_str() { |
| 202 | "Arimo" => ("Arimo", "Arial"), |
| 203 | "Carlito" => ("Carlito", "Calibri"), |
| 204 | "Caladea" => ("Caladea", "Cambria"), |
| 205 | "Tinos" => ("Tinos", "Times New Roman"), |
| 206 | "Cousine" => ("Cousine", "Courier New"), |
| 207 | _ => return Err(LayoutError::UnsupportedSubstituteFont), |
| 208 | }; |
| 209 | let id = data.id(); |
| 210 | if target == "Arial" { |
| 211 | let head = font.head().map_err(|_| LayoutError::InvalidFontMetrics)?; |
| 212 | let hhea = font.hhea().map_err(|_| LayoutError::InvalidFontMetrics)?; |
| 213 | if head.units_per_em() == 0 |
| 214 | || hhea.ascender().to_i16() <= 0 |
| 215 | || hhea.descender().to_i16() > 0 |
| 216 | { |
| 217 | return Err(LayoutError::InvalidFontMetrics); |
| 218 | } |
| 219 | } |
| 220 | let collection = &mut self.fonts.collection; |
| 221 | // A substitute of the caller's replaces the bundled one outright. |
| 222 | if !bundled |
| 223 | && self |
| 224 | .substitutes |
| 225 | .get(target) |
| 226 | .is_some_and(|known| known.bundled) |
| 227 | && let Some(replaced) = self.substitutes.remove(target) |
| 228 | && let Some(family) = collection.family_id(target) |
| 229 | { |
| 230 | for (face, info) in replaced.faces { |
| 231 | collection.unregister_font(family, info.width(), info.style(), info.weight()); |
| 232 | self.arial_substitutes.remove(&face.id()); |
| 233 | } |
| 234 | } |
| 235 | let registered = collection.register_fonts( |
| 236 | data.clone(), |
| 237 | Some(parley::fontique::FontInfoOverride { |
| 238 | family_name: Some(target), |
| 239 | ..Default::default() |
| 240 | }), |
| 241 | ); |
| 242 | if registered.is_empty() { |
| 243 | return Err(LayoutError::UnsupportedSubstituteFont); |
| 244 | } |
| 245 | if target == "Arial" { |
| 246 | self.arial_substitutes.insert(id); |
| 247 | } |
| 248 | let entry = self.substitutes.entry(target).or_insert(Substitute { |
| 249 | name: substitute, |
| 250 | faces: Vec::new(), |
| 251 | bundled, |
| 252 | }); |
| 253 | entry.faces.extend( |
| 254 | registered |
| 255 | .into_iter() |
| 256 | .flat_map(|(_, infos)| infos) |
| 257 | .map(|info| (data.clone(), info)), |
| 258 | ); |
| 259 | Ok(target) |
| 260 | } |
| 261 | |
| 262 | /// The font `family` lays out in when a substitute stands in for it. |
| 263 | pub fn substitute(&self, family: &str) -> Option<&Substitute> { |
| 264 | self.substitutes.get(family) |
| 265 | } |
| 266 | |
| 267 | fn shape( |
| 268 | &mut self, |
| 269 | paragraph: &Paragraph, |
| 270 | width: f32, |
| 271 | spaces: &[InlineSpace], |
| 272 | ) -> Result<Layout<TextBrush>, LayoutError> { |
| 273 | if !width.is_finite() || width <= 0.0 { |
| 274 | return Err(LayoutError::InvalidWidth); |
| 275 | } |
| 276 | let text = paragraph.text(); |
| 277 | let mut builder = self |
| 278 | .context |
| 279 | .ranged_builder(&mut self.fonts, text, 1.0, false); |
| 280 | builder.push_default(StyleProperty::OverflowWrap(OverflowWrap::BreakWord)); |
| 281 | // OneNote 2010 uses unkerned advances for text and table widths. |
| 282 | builder.push_default(StyleProperty::FontFeatures(r#""kern" 0"#.into())); |
| 283 | let mut start = 0; |
| 284 | for (index, span) in paragraph.spans().iter().enumerate() { |
| 285 | let format = &span.format; |
| 286 | let link = format.hyperlink == Some(true); |
| 287 | let size = format.font_size.unwrap_or(DEFAULT_FONT_SIZE); |
| 288 | if !size.is_finite() || size <= 0.0 { |
| 289 | return Err(LayoutError::InvalidFontSize); |
| 290 | } |
| 291 | let rise = if format.superscript == Some(true) { |
| 292 | SUPERSCRIPT_RISE * size |
| 293 | } else if format.subscript == Some(true) { |
| 294 | -SUBSCRIPT_DROP * size |
| 295 | } else { |
| 296 | 0.0 |
| 297 | }; |
| 298 | let size = if rise == 0.0 { |
| 299 | size |
| 300 | } else { |
| 301 | size * SCRIPT_SCALE |
| 302 | }; |
| 303 | let properties = [ |
| 304 | StyleProperty::FontFamily(FontFamily::List( |
| 305 | [ |
| 306 | Some(FontFamilyName::named( |
| 307 | format.font.as_deref().unwrap_or(DEFAULT_FONT), |
| 308 | )), |
| 309 | // macOS ships STIX Two Math where Windows has Cambria Math. |
| 310 | (format.font.as_deref() == Some("Cambria Math")) |
| 311 | .then_some(FontFamilyName::named("STIX Two Math")), |
| 312 | // A missing family otherwise falls back per script and can put digits in an emoji font. |
| 313 | Some(GenericFamily::SansSerif.into()), |
| 314 | ] |
| 315 | .into_iter() |
| 316 | .flatten() |
| 317 | .collect::<Vec<_>>() |
| 318 | .into(), |
| 319 | )), |
| 320 | StyleProperty::FontSize(size), |
| 321 | StyleProperty::FontWeight(if format.bold == Some(true) { |
| 322 | FontWeight::BOLD |
| 323 | } else { |
| 324 | FontWeight::NORMAL |
| 325 | }), |
| 326 | StyleProperty::FontStyle(if format.italic == Some(true) { |
| 327 | FontStyle::Italic |
| 328 | } else { |
| 329 | FontStyle::Normal |
| 330 | }), |
| 331 | StyleProperty::Brush(TextBrush { |
| 332 | // Links take OneNote's blue unless given a colour of their own. |
| 333 | color: match format.color { |
| 334 | Some(color) if color != 0xff000000 => Some(color), |
| 335 | _ if link => Some(0x00ff0000), |
| 336 | _ => None, |
| 337 | }, |
| 338 | highlight: format.highlight.filter(|color| *color != 0xff000000), |
| 339 | rise, |
| 340 | }), |
| 341 | StyleProperty::Underline(format.underline.unwrap_or(false) || link), |
| 342 | StyleProperty::Strikethrough(format.strike.unwrap_or(false)), |
| 343 | ]; |
| 344 | for property in properties { |
| 345 | if index == 0 { |
| 346 | builder.push_default(property.clone()); |
| 347 | } |
| 348 | builder.push(property, start..span.end); |
| 349 | } |
| 350 | start = span.end; |
| 351 | } |
| 352 | for (id, space) in spaces.iter().enumerate() { |
| 353 | builder.push_inline_box(parley::InlineBox { |
| 354 | id: id as u64, |
| 355 | kind: parley::InlineBoxKind::InFlow, |
| 356 | index: space.index, |
| 357 | width: space.width, |
| 358 | height: space.ascent + space.descent, |
| 359 | baseline: Some(space.ascent), |
| 360 | }); |
| 361 | } |
| 362 | let mut shaped = builder.build(text); |
| 363 | shaped.break_all_lines(Some(width)); |
| 364 | let alignment = match paragraph.spans()[0].format.alignment { |
| 365 | Some(1) => Alignment::Center, |
| 366 | Some(2) => Alignment::End, |
| 367 | _ => Alignment::Start, |
| 368 | }; |
| 369 | shaped.align(alignment, AlignmentOptions::default()); |
| 370 | Ok(shaped) |
| 371 | } |
| 372 | |
| 373 | fn font_extents( |
| 374 | &self, |
| 375 | run: parley::layout::Run<'_, TextBrush>, |
| 376 | ) -> Result<(f32, f32), LayoutError> { |
| 377 | let data = &run.font().font; |
| 378 | let font = FontRef::from_index(data.data.as_ref(), data.index) |
| 379 | .map_err(|_| LayoutError::InvalidFontMetrics)?; |
| 380 | Ok(if self.arial_substitutes.contains(&data.data.id()) { |
| 381 | // Arimo's hhea extents match Arial's Windows extents; omit hhea line gap. |
| 382 | let head = font.head().map_err(|_| LayoutError::InvalidFontMetrics)?; |
| 383 | let hhea = font.hhea().map_err(|_| LayoutError::InvalidFontMetrics)?; |
| 384 | let scale = run.font_size() / f32::from(head.units_per_em()); |
| 385 | ( |
| 386 | f32::from(hhea.ascender().to_i16()) * scale, |
| 387 | -f32::from(hhea.descender().to_i16()) * scale, |
| 388 | ) |
| 389 | } else if let (Ok(head), Ok(os2)) = (font.head(), font.os2()) |
| 390 | && head.units_per_em() != 0 |
| 391 | && font |
| 392 | .table_data(skrifa::raw::types::Tag::new(b"MATH")) |
| 393 | .is_some() |
| 394 | { |
| 395 | // A math font's Windows extents reach its tallest operators; OneNote sets linear |
| 396 | // math in lines of text height. |
| 397 | let scale = run.font_size() / f32::from(head.units_per_em()); |
| 398 | ( |
| 399 | f32::from(os2.s_typo_ascender()) * scale, |
| 400 | -f32::from(os2.s_typo_descender()) * scale, |
| 401 | ) |
| 402 | } else if let (Ok(head), Ok(os2)) = (font.head(), font.os2()) |
| 403 | && head.units_per_em() != 0 |
| 404 | && (os2.us_win_ascent() != 0 || os2.us_win_descent() != 0) |
| 405 | { |
| 406 | let scale = run.font_size() / f32::from(head.units_per_em()); |
| 407 | ( |
| 408 | f32::from(os2.us_win_ascent()) * scale, |
| 409 | f32::from(os2.us_win_descent()) * scale, |
| 410 | ) |
| 411 | } else { |
| 412 | let metrics = run.font_metrics(); |
| 413 | (metrics.ascent, metrics.descent) |
| 414 | }) |
| 415 | } |
| 416 | |
| 417 | pub fn layout(&mut self, paragraph: &Paragraph, width: f32) -> Result<TextLayout, LayoutError> { |
| 418 | self.layout_with(paragraph, width, &[]) |
| 419 | } |
| 420 | |
| 421 | /// Lays out `paragraph` keeping `spaces` inline, for what draws in them. |
| 422 | pub(crate) fn layout_with( |
| 423 | &mut self, |
| 424 | paragraph: &Paragraph, |
| 425 | width: f32, |
| 426 | spaces: &[InlineSpace], |
| 427 | ) -> Result<TextLayout, LayoutError> { |
| 428 | let shaped = self.shape(paragraph, width, spaces)?; |
| 429 | let mut placed = Vec::new(); |
| 430 | let text = paragraph.text(); |
| 431 | let mut lines = Vec::with_capacity(shaped.len()); |
| 432 | let mut top = 0.0_f64; |
| 433 | let mut source_end = 0; |
| 434 | for line in shaped.lines() { |
| 435 | if !line.metrics().advance.is_finite() |
| 436 | || !line.metrics().trailing_whitespace.is_finite() |
| 437 | { |
| 438 | return Err(LayoutError::InvalidFontMetrics); |
| 439 | } |
| 440 | // Parley gives its synthetic empty line a 0..1 range. |
| 441 | let range = if text.is_empty() { |
| 442 | 0..0 |
| 443 | } else { |
| 444 | line.text_range() |
| 445 | }; |
| 446 | if range.start != source_end |
| 447 | || range.end < range.start |
| 448 | || !text.is_char_boundary(range.end) |
| 449 | { |
| 450 | return Err(LayoutError::InvalidSourceRange); |
| 451 | } |
| 452 | source_end = range.end; |
| 453 | let mut ascent = 0.0_f32; |
| 454 | let mut descent = 0.0_f32; |
| 455 | for run in line.runs() { |
| 456 | let data = &run.font().font; |
| 457 | let font = FontRef::from_index(data.data.as_ref(), data.index) |
| 458 | .map_err(|_| LayoutError::InvalidFontMetrics)?; |
| 459 | // Color glyphs fit the source font's line box instead of shifting annotation rows. |
| 460 | let (a, d) = if font.colr().is_ok() || font.sbix().is_ok() || font.cbdt().is_ok() { |
| 461 | let format = &paragraph |
| 462 | .spans() |
| 463 | .iter() |
| 464 | .find(|span| span.end > run.text_range().start) |
| 465 | .unwrap_or_else(|| paragraph.spans().last().unwrap()) |
| 466 | .format; |
| 467 | let sample = |
| 468 | self.shape(&Paragraph::new("Mg".into(), format.clone()), f32::MAX, &[])?; |
| 469 | sample.lines().flat_map(|line| line.runs()).try_fold( |
| 470 | (0.0_f32, 0.0_f32), |
| 471 | |(a, d), run| { |
| 472 | let (next_a, next_d) = self.font_extents(run)?; |
| 473 | Ok::<_, LayoutError>((a.max(next_a), d.max(next_d))) |
| 474 | }, |
| 475 | )? |
| 476 | } else { |
| 477 | self.font_extents(run)? |
| 478 | }; |
| 479 | if !a.is_finite() || !d.is_finite() || a < 0.0 || d < 0.0 { |
| 480 | return Err(LayoutError::InvalidFontMetrics); |
| 481 | } |
| 482 | ascent = ascent.max(a); |
| 483 | descent = descent.max(d); |
| 484 | } |
| 485 | for item in line.items() { |
| 486 | if let PositionedLayoutItem::InlineBox(inline) = item { |
| 487 | let space = &spaces[inline.id as usize]; |
| 488 | ascent = ascent.max(space.ascent); |
| 489 | descent = descent.max(space.descent); |
| 490 | placed.push((inline.id as usize, inline.x, lines.len())); |
| 491 | } |
| 492 | } |
| 493 | let height = ascent + descent; |
| 494 | if height <= 0.0 || !height.is_finite() { |
| 495 | return Err(LayoutError::InvalidFontMetrics); |
| 496 | } |
| 497 | lines.push(LineBox { |
| 498 | source: range, |
| 499 | top: top as f32, |
| 500 | baseline: (top + f64::from(ascent)) as f32, |
| 501 | height, |
| 502 | }); |
| 503 | top += f64::from(height); |
| 504 | if !(top as f32).is_finite() { |
| 505 | return Err(LayoutError::InvalidFontMetrics); |
| 506 | } |
| 507 | } |
| 508 | if source_end != text.len() || lines.is_empty() { |
| 509 | return Err(LayoutError::InvalidSourceRange); |
| 510 | } |
| 511 | static NEXT_ID: AtomicU64 = AtomicU64::new(0); |
| 512 | let id = NEXT_ID |
| 513 | .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) |
| 514 | .expect("Text layout identities exhausted"); |
| 515 | Ok(TextLayout { |
| 516 | id, |
| 517 | shaped: Arc::new(shaped), |
| 518 | #[cfg(feature = "gpu")] |
| 519 | text: text.into(), |
| 520 | lines, |
| 521 | spaces: placed, |
| 522 | }) |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | impl TextLayout { |
| 527 | /// Process-unique identity for caches of an externally immutable layout. |
| 528 | pub(crate) fn id(&self) -> u64 { |
| 529 | self.id |
| 530 | } |
| 531 | |
| 532 | pub(crate) fn minimum_line_height(&mut self, minimum: f32) -> Result<(), LayoutError> { |
| 533 | if !minimum.is_finite() || minimum < 0.0 { |
| 534 | return Err(LayoutError::InvalidSpacing); |
| 535 | } |
| 536 | if minimum == 0.0 { |
| 537 | return Ok(()); |
| 538 | } |
| 539 | let mut top = 0.0_f64; |
| 540 | for line in &mut self.lines { |
| 541 | let ascent = line.baseline - line.top; |
| 542 | line.height = line.height.max(minimum); |
| 543 | line.top = top as f32; |
| 544 | line.baseline = (top + f64::from(ascent)) as f32; |
| 545 | top += f64::from(line.height); |
| 546 | if !(top as f32).is_finite() { |
| 547 | return Err(LayoutError::InvalidSpacing); |
| 548 | } |
| 549 | } |
| 550 | Ok(()) |
| 551 | } |
| 552 | |
| 553 | /// Each inline space laid out, by its index, with its x and its line's baseline. |
| 554 | pub fn spaces(&self) -> impl Iterator<Item = (usize, [f32; 2])> + '_ { |
| 555 | self.spaces |
| 556 | .iter() |
| 557 | .map(|&(id, x, line)| (id, [x, self.lines[line].baseline])) |
| 558 | } |
| 559 | |
| 560 | pub fn lines(&self) -> impl Iterator<Item = (parley::Line<'_, TextBrush>, &LineBox)> { |
| 561 | self.shaped.lines().zip(&self.lines) |
| 562 | } |
| 563 | |
| 564 | pub fn backgrounds(&self) -> impl Iterator<Item = (BoundingBox, u32)> { |
| 565 | self.lines().flat_map(|(line, bounds)| { |
| 566 | line.items().filter_map(move |item| { |
| 567 | let PositionedLayoutItem::GlyphRun(run) = item else { |
| 568 | return None; |
| 569 | }; |
| 570 | let color = run.style().brush.highlight?; |
| 571 | Some(( |
| 572 | BoundingBox { |
| 573 | x0: f64::from(run.offset()), |
| 574 | y0: f64::from(bounds.top), |
| 575 | x1: f64::from(run.offset() + run.advance()), |
| 576 | y1: f64::from(bounds.top + bounds.height), |
| 577 | }, |
| 578 | color, |
| 579 | )) |
| 580 | }) |
| 581 | }) |
| 582 | } |
| 583 | |
| 584 | pub fn height(&self) -> f32 { |
| 585 | let last = self.lines.last().unwrap(); |
| 586 | last.top + last.height |
| 587 | } |
| 588 | |
| 589 | pub(crate) fn cursor(&self, byte: usize, affinity: Affinity) -> Cursor { |
| 590 | Cursor::from_byte_index(&self.shaped, byte, affinity) |
| 591 | } |
| 592 | |
| 593 | pub(crate) fn hit_test(&self, x: f32, y: f32) -> Cursor { |
| 594 | let index = self |
| 595 | .lines |
| 596 | .partition_point(|line| line.top + line.height <= y) |
| 597 | .min(self.lines.len() - 1); |
| 598 | let metrics = *self.shaped.get(index).unwrap().metrics(); |
| 599 | Cursor::from_point( |
| 600 | &self.shaped, |
| 601 | x, |
| 602 | (metrics.block_min_coord + metrics.block_max_coord) * 0.5, |
| 603 | ) |
| 604 | } |
| 605 | |
| 606 | pub fn caret(&self, cursor: Cursor, width: f32) -> BoundingBox { |
| 607 | let mut rect = cursor.geometry(&self.shaped, width); |
| 608 | // parley pairs the logical end of an RTL cluster leading its line with the previous |
| 609 | // line's last cluster, placing the caret at that line's end. |
| 610 | if cursor.affinity() == Affinity::Upstream |
| 611 | && let Some(cluster) = cursor |
| 612 | .index() |
| 613 | .checked_sub(1) |
| 614 | .and_then(|index| parley::Cluster::from_byte_index(&self.shaped, index)) |
| 615 | && cluster.is_rtl() |
| 616 | && cluster |
| 617 | .previous_visual() |
| 618 | .is_some_and(|previous| previous.path().line_index() != cluster.path().line_index()) |
| 619 | { |
| 620 | let x = f64::from(cluster.visual_offset().unwrap_or_default()); |
| 621 | let metrics = *cluster.line().metrics(); |
| 622 | rect = BoundingBox::new( |
| 623 | x, |
| 624 | f64::from(metrics.block_min_coord), |
| 625 | x + f64::from(width), |
| 626 | f64::from(metrics.block_max_coord), |
| 627 | ); |
| 628 | } |
| 629 | let index = self |
| 630 | .shaped |
| 631 | .lines() |
| 632 | .position(|line| rect.y0 < f64::from(line.metrics().block_max_coord)) |
| 633 | .unwrap_or(self.lines.len() - 1); |
| 634 | let line = &self.lines[index]; |
| 635 | rect.y0 = f64::from(line.top); |
| 636 | rect.y1 = f64::from(line.top + line.height); |
| 637 | rect |
| 638 | } |
| 639 | |
| 640 | /// Each line's part of `selection` as a mark under the text runs: its left, its right |
| 641 | /// and the line's baseline. |
| 642 | pub(crate) fn underlines(&self, selection: Selection) -> Vec<[f32; 3]> { |
| 643 | selection |
| 644 | .geometry(&self.shaped) |
| 645 | .into_iter() |
| 646 | .map(|(rect, index)| [rect.x0 as f32, rect.x1 as f32, self.lines[index].baseline]) |
| 647 | .collect() |
| 648 | } |
| 649 | |
| 650 | pub fn selection(&self, selection: Selection) -> Vec<BoundingBox> { |
| 651 | selection |
| 652 | .geometry(&self.shaped) |
| 653 | .into_iter() |
| 654 | .map(|(mut rect, index)| { |
| 655 | let line = &self.lines[index]; |
| 656 | rect.y0 = f64::from(line.top); |
| 657 | rect.y1 = f64::from(line.top + line.height); |
| 658 | rect |
| 659 | }) |
| 660 | .collect() |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | #[cfg(test)] |
| 665 | mod tests { |
| 666 | use super::*; |
| 667 | use onestore::document::Format; |
| 668 | |
| 669 | #[test] |
| 670 | #[ignore = "requires Arial"] |
| 671 | fn native_unkerned_advances() { |
| 672 | let mut engine = TextEngine::default(); |
| 673 | for (font, expected) in [("Calibri", 149.63843), ("Arial", 184.58305)] { |
| 674 | let paragraph = Paragraph::new( |
| 675 | "AVATAR AVATAR SECOND OFFICE".into(), |
| 676 | onestore::document::Format { |
| 677 | font: Some(font.into()), |
| 678 | font_size: Some(11.0), |
| 679 | ..Default::default() |
| 680 | }, |
| 681 | ); |
| 682 | let layout = engine.layout(&paragraph, 400.0).unwrap(); |
| 683 | assert_eq!(layout.lines().count(), 1); |
| 684 | assert!((layout.lines().next().unwrap().0.metrics().advance - expected).abs() < 0.001); |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | #[test] |
| 689 | fn a_registered_substitute_replaces_the_bundled_one() { |
| 690 | let mut engine = TextEngine::default(); |
| 691 | if engine.substitute("Calibri").is_none() { |
| 692 | return; |
| 693 | } |
| 694 | let explicit = Blob::new(Arc::new( |
| 695 | include_bytes!("../assets/fonts/Carlito-Regular.ttf").to_vec(), |
| 696 | )); |
| 697 | assert_eq!(engine.register_substitute(explicit.clone()), Ok("Calibri")); |
| 698 | let substitute = engine.substitute("Calibri").unwrap(); |
| 699 | assert_eq!(substitute.faces.len(), 1); |
| 700 | let paragraph = Paragraph::new( |
| 701 | "Calibri".into(), |
| 702 | Format { |
| 703 | font: Some("Calibri".into()), |
| 704 | bold: Some(true), |
| 705 | ..Format::default() |
| 706 | }, |
| 707 | ); |
| 708 | let layout = engine.layout(&paragraph, 400.0).unwrap(); |
| 709 | let (line, _) = layout.lines().next().unwrap(); |
| 710 | for item in line.items() { |
| 711 | let PositionedLayoutItem::GlyphRun(run) = item else { |
| 712 | continue; |
| 713 | }; |
| 714 | assert_eq!(run.run().font().font.data.id(), explicit.id()); |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn rejected_substitute_leaves_font_selection_unchanged() { |
| 720 | let mut engine = TextEngine::default(); |
| 721 | let paragraph = Paragraph::new("first words wrap here".into(), Format::default()); |
| 722 | let before = engine.layout(&paragraph, 72.0).unwrap(); |
| 723 | for data in [Vec::new(), vec![0; 512], b"not a font".to_vec()] { |
| 724 | let result = |
| 725 | engine.register_substitute(parley::fontique::Blob::new(std::sync::Arc::new(data))); |
| 726 | assert_eq!(result.unwrap_err(), LayoutError::UnsupportedSubstituteFont); |
| 727 | } |
| 728 | assert!(engine.arial_substitutes.is_empty()); |
| 729 | let after = engine.layout(&paragraph, 72.0).unwrap(); |
| 730 | assert_eq!(before.height(), after.height()); |
| 731 | let lines = |layout: &TextLayout| { |
| 732 | layout |
| 733 | .lines() |
| 734 | .map(|(_, line)| (line.source.clone(), line.baseline)) |
| 735 | .collect::<Vec<_>>() |
| 736 | }; |
| 737 | assert_eq!(lines(&before), lines(&after)); |
| 738 | assert_eq!( |
| 739 | before |
| 740 | .lines() |
| 741 | .next() |
| 742 | .unwrap() |
| 743 | .0 |
| 744 | .runs() |
| 745 | .next() |
| 746 | .unwrap() |
| 747 | .font() |
| 748 | .font |
| 749 | .data |
| 750 | .id(), |
| 751 | after |
| 752 | .lines() |
| 753 | .next() |
| 754 | .unwrap() |
| 755 | .0 |
| 756 | .runs() |
| 757 | .next() |
| 758 | .unwrap() |
| 759 | .font() |
| 760 | .font |
| 761 | .data |
| 762 | .id() |
| 763 | ); |
| 764 | } |
| 765 | |
| 766 | #[test] |
| 767 | fn missing_family_keeps_digits_in_the_letters_face() { |
| 768 | let paragraph = Paragraph::new( |
| 769 | "Monday, August 10, 2026".into(), |
| 770 | Format { |
| 771 | font: Some("Snowbound Missing Family".into()), |
| 772 | ..Format::default() |
| 773 | }, |
| 774 | ); |
| 775 | let layout = TextEngine::default().layout(&paragraph, 468.0).unwrap(); |
| 776 | let fonts = layout |
| 777 | .lines() |
| 778 | .flat_map(|(line, _)| { |
| 779 | line.runs() |
| 780 | .map(|run| run.font().font.data.id()) |
| 781 | .collect::<Vec<_>>() |
| 782 | }) |
| 783 | .collect::<BTreeSet<_>>(); |
| 784 | assert_eq!(fonts.len(), 1); |
| 785 | } |
| 786 | |
| 787 | #[test] |
| 788 | fn scripts_shrink_and_shift_without_moving_the_baseline() { |
| 789 | let mut engine = TextEngine::default(); |
| 790 | let script = |superscript, subscript| Format { |
| 791 | superscript, |
| 792 | subscript, |
| 793 | ..Format::default() |
| 794 | }; |
| 795 | let layout = engine |
| 796 | .layout( |
| 797 | &Paragraph::from_runs([ |
| 798 | ("x".into(), Format::default()), |
| 799 | ("2".into(), script(Some(true), None)), |
| 800 | ("i".into(), script(None, Some(true))), |
| 801 | ]), |
| 802 | 300.0, |
| 803 | ) |
| 804 | .unwrap(); |
| 805 | let runs: Vec<_> = layout |
| 806 | .lines() |
| 807 | .flat_map(|(line, _)| line.items().collect::<Vec<_>>()) |
| 808 | .filter_map(|item| match item { |
| 809 | PositionedLayoutItem::GlyphRun(run) => { |
| 810 | Some((run.run().font_size(), run.style().brush.rise)) |
| 811 | } |
| 812 | _ => None, |
| 813 | }) |
| 814 | .collect(); |
| 815 | let third = 11.0 / 3.0; |
| 816 | assert_eq!(runs[0], (11.0, 0.0)); |
| 817 | assert!((runs[1].0 - 2.0 * third).abs() < 0.001 && (runs[1].1 - third).abs() < 0.001); |
| 818 | assert!(runs[2].1 < 0.0); |
| 819 | let plain = engine |
| 820 | .layout(&Paragraph::new("x2i".into(), Format::default()), 300.0) |
| 821 | .unwrap(); |
| 822 | assert_eq!( |
| 823 | layout.lines().next().unwrap().1.baseline, |
| 824 | plain.lines().next().unwrap().1.baseline |
| 825 | ); |
| 826 | } |
| 827 | |
| 828 | #[test] |
| 829 | fn links_draw_blue_and_underlined_unless_coloured() { |
| 830 | let mut engine = TextEngine::default(); |
| 831 | let link = Format { |
| 832 | hyperlink: Some(true), |
| 833 | ..Format::default() |
| 834 | }; |
| 835 | let layout = engine |
| 836 | .layout( |
| 837 | &Paragraph::from_runs([ |
| 838 | ("plain ".into(), Format::default()), |
| 839 | ("link".into(), link.clone()), |
| 840 | ( |
| 841 | " red".into(), |
| 842 | Format { |
| 843 | color: Some(0x0000_00ff), |
| 844 | ..link |
| 845 | }, |
| 846 | ), |
| 847 | ]), |
| 848 | 300.0, |
| 849 | ) |
| 850 | .unwrap(); |
| 851 | let runs: Vec<_> = layout |
| 852 | .lines() |
| 853 | .flat_map(|(line, _)| line.items().collect::<Vec<_>>()) |
| 854 | .filter_map(|item| match item { |
| 855 | PositionedLayoutItem::GlyphRun(run) => { |
| 856 | let style = run.style(); |
| 857 | Some((style.brush.color, style.underline.is_some())) |
| 858 | } |
| 859 | _ => None, |
| 860 | }) |
| 861 | .collect(); |
| 862 | assert_eq!( |
| 863 | runs, |
| 864 | [ |
| 865 | (None, false), |
| 866 | (Some(0x00ff_0000), true), |
| 867 | (Some(0x0000_00ff), true) |
| 868 | ] |
| 869 | ); |
| 870 | } |
| 871 | |
| 872 | #[test] |
| 873 | fn paragraph_alignment_offsets_lines_within_the_wrap_width() { |
| 874 | let mut engine = TextEngine::default(); |
| 875 | let mut offset = |alignment| { |
| 876 | let layout = engine |
| 877 | .layout( |
| 878 | &Paragraph::new( |
| 879 | "Short".into(), |
| 880 | Format { |
| 881 | alignment, |
| 882 | ..Format::default() |
| 883 | }, |
| 884 | ), |
| 885 | 200.0, |
| 886 | ) |
| 887 | .unwrap(); |
| 888 | let (line, _) = layout.lines().next().unwrap(); |
| 889 | let advance = line.metrics().advance; |
| 890 | let x = line |
| 891 | .items() |
| 892 | .find_map(|item| match item { |
| 893 | PositionedLayoutItem::GlyphRun(run) => Some(run.offset()), |
| 894 | _ => None, |
| 895 | }) |
| 896 | .unwrap(); |
| 897 | (x, advance) |
| 898 | }; |
| 899 | let (left, advance) = offset(None); |
| 900 | assert_eq!(left, 0.0); |
| 901 | assert!(((offset(Some(1)).0) - (200.0 - advance) / 2.0).abs() < 0.01); |
| 902 | assert!(((offset(Some(2)).0) - (200.0 - advance)).abs() < 0.01); |
| 903 | } |
| 904 | |
| 905 | #[test] |
| 906 | fn highlights_share_line_geometry_without_changing_wraps() { |
| 907 | let paragraph = Paragraph::from_runs([ |
| 908 | ( |
| 909 | "A highlighted ".into(), |
| 910 | Format { |
| 911 | highlight: Some(0x0000ffff), |
| 912 | ..Format::default() |
| 913 | }, |
| 914 | ), |
| 915 | ( |
| 916 | "phrase and ".into(), |
| 917 | Format { |
| 918 | highlight: Some(0), |
| 919 | ..Format::default() |
| 920 | }, |
| 921 | ), |
| 922 | ( |
| 923 | "automatic background".into(), |
| 924 | Format { |
| 925 | highlight: Some(0xff000000), |
| 926 | ..Format::default() |
| 927 | }, |
| 928 | ), |
| 929 | ]); |
| 930 | let mut engine = TextEngine::default(); |
| 931 | let layout = engine.layout(&paragraph, 80.0).unwrap(); |
| 932 | let plain = engine |
| 933 | .layout( |
| 934 | &Paragraph::new(paragraph.text().into(), Format::default()), |
| 935 | 80.0, |
| 936 | ) |
| 937 | .unwrap(); |
| 938 | assert_eq!( |
| 939 | layout |
| 940 | .lines() |
| 941 | .map(|(_, l)| l.source.clone()) |
| 942 | .collect::<Vec<_>>(), |
| 943 | plain |
| 944 | .lines() |
| 945 | .map(|(_, l)| l.source.clone()) |
| 946 | .collect::<Vec<_>>() |
| 947 | ); |
| 948 | let backgrounds = layout.backgrounds().collect::<Vec<_>>(); |
| 949 | assert!(backgrounds.iter().any(|(_, color)| *color == 0)); |
| 950 | assert!(backgrounds.iter().any(|(_, color)| *color == 0x0000ffff)); |
| 951 | assert!(!backgrounds.iter().any(|(_, color)| *color == 0xff000000)); |
| 952 | for (rect, _) in backgrounds { |
| 953 | assert!(rect.width() > 0.0); |
| 954 | assert!( |
| 955 | layout |
| 956 | .lines() |
| 957 | .any(|(_, line)| rect.y0 == f64::from(line.top) |
| 958 | && rect.y1 == f64::from(line.top + line.height)) |
| 959 | ); |
| 960 | } |
| 961 | } |
| 962 | |
| 963 | #[test] |
| 964 | fn color_boundaries_preserve_contextual_shaping_and_wrapping() { |
| 965 | let mut engine = TextEngine::default(); |
| 966 | for text in ["office affinity", "العربية سلام", "ae\u{301}👩🏽💻z"] { |
| 967 | let plain = Paragraph::new(text.into(), Format::default()); |
| 968 | let colored = Paragraph::from_runs(text.chars().enumerate().map(|(index, ch)| { |
| 969 | ( |
| 970 | ch.to_string(), |
| 971 | Format { |
| 972 | color: Some(if index % 2 == 0 { 0xff } else { 0xff0000 }), |
| 973 | ..Format::default() |
| 974 | }, |
| 975 | ) |
| 976 | })); |
| 977 | for width in [1.0, 40.0, 110.0, 1000.0] { |
| 978 | let plain = engine.layout(&plain, width).unwrap(); |
| 979 | let colored = engine.layout(&colored, width).unwrap(); |
| 980 | assert_eq!(plain.lines.len(), colored.lines.len()); |
| 981 | for ((plain_line, plain_box), (colored_line, colored_box)) in |
| 982 | plain.lines().zip(colored.lines()) |
| 983 | { |
| 984 | assert_eq!(plain_box.source, colored_box.source); |
| 985 | assert_eq!(plain_box.baseline, colored_box.baseline); |
| 986 | assert_eq!(plain_box.height, colored_box.height); |
| 987 | let glyphs = |line: parley::Line<'_, TextBrush>| { |
| 988 | line.items() |
| 989 | .flat_map(|item| match item { |
| 990 | PositionedLayoutItem::GlyphRun(run) => run |
| 991 | .positioned_glyphs() |
| 992 | .map(|glyph| { |
| 993 | ( |
| 994 | run.run().font().font.data.id(), |
| 995 | glyph.id, |
| 996 | glyph.x, |
| 997 | glyph.y, |
| 998 | ) |
| 999 | }) |
| 1000 | .collect::<Vec<_>>(), |
| 1001 | PositionedLayoutItem::InlineBox(_) => unreachable!(), |
| 1002 | }) |
| 1003 | .collect::<Vec<_>>() |
| 1004 | }; |
| 1005 | let plain_glyphs = glyphs(plain_line); |
| 1006 | let colored_glyphs = glyphs(colored_line); |
| 1007 | assert_eq!(plain_glyphs.len(), colored_glyphs.len()); |
| 1008 | for (a, b) in plain_glyphs.into_iter().zip(colored_glyphs) { |
| 1009 | assert_eq!((a.0, a.1), (b.0, b.1), "{text}, width {width}"); |
| 1010 | assert!((a.2 - b.2).abs() < 0.001 && (a.3 - b.3).abs() < 0.001); |
| 1011 | } |
| 1012 | } |
| 1013 | } |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | #[test] |
| 1018 | fn empty_paragraph_has_source_position_and_caret() { |
| 1019 | let paragraph = Paragraph::new(String::new(), Format::default()); |
| 1020 | let layout = TextEngine::default().layout(&paragraph, 100.0).unwrap(); |
| 1021 | assert_eq!(layout.lines().next().unwrap().1.source, 0..0); |
| 1022 | assert!(layout.height() > 0.0); |
| 1023 | let cursor = layout.hit_test(50.0, 50.0); |
| 1024 | assert_eq!(cursor.index(), 0); |
| 1025 | let caret = layout.caret(cursor, 1.0); |
| 1026 | assert_eq!(caret.y0, 0.0); |
| 1027 | assert_eq!(caret.y1, f64::from(layout.height())); |
| 1028 | } |
| 1029 | |
| 1030 | #[test] |
| 1031 | fn long_words_wrap_with_complete_source_and_usable_carets() { |
| 1032 | let paragraph = Paragraph::new( |
| 1033 | "Wrapped HAMBURGEFONTS abcdefghijklmnopqrstuvwxyz 0123456789".into(), |
| 1034 | Format::default(), |
| 1035 | ); |
| 1036 | let width = 110.0; |
| 1037 | let layout = TextEngine::default().layout(&paragraph, width).unwrap(); |
| 1038 | let mut end = 0; |
| 1039 | for (line, bounds) in layout.lines() { |
| 1040 | assert!(line.metrics().advance - line.metrics().trailing_whitespace <= width); |
| 1041 | assert_eq!(bounds.source.start, end); |
| 1042 | end = bounds.source.end; |
| 1043 | } |
| 1044 | assert_eq!(end, paragraph.text().len()); |
| 1045 | for byte in 0..=end { |
| 1046 | for affinity in [Affinity::Upstream, Affinity::Downstream] { |
| 1047 | let rect = layout.caret(layout.cursor(byte, affinity), 0.0); |
| 1048 | let hit = layout.hit_test(rect.x0 as f32, ((rect.y0 + rect.y1) * 0.5) as f32); |
| 1049 | assert_eq!(hit.index(), byte, "byte {byte}, {affinity:?}, {rect:?}"); |
| 1050 | } |
| 1051 | } |
| 1052 | } |
| 1053 | |
| 1054 | #[test] |
| 1055 | fn wrapped_carets_hit_the_same_source_position() { |
| 1056 | let paragraph = Paragraph::new( |
| 1057 | "A quiet evening under the trees, with notes beside every line.".into(), |
| 1058 | Format::default(), |
| 1059 | ); |
| 1060 | let layout = TextEngine::default().layout(&paragraph, 110.0).unwrap(); |
| 1061 | assert!(layout.lines.len() > 1); |
| 1062 | for byte in 0..=paragraph.text().len() { |
| 1063 | for affinity in [Affinity::Upstream, Affinity::Downstream] { |
| 1064 | let cursor = layout.cursor(byte, affinity); |
| 1065 | let rect = layout.caret(cursor, 0.0); |
| 1066 | let hit = layout.hit_test(rect.x0 as f32, ((rect.y0 + rect.y1) * 0.5) as f32); |
| 1067 | assert_eq!(hit.index(), byte, "byte {byte}, {affinity:?}, {rect:?}"); |
| 1068 | } |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | #[test] |
| 1073 | fn visual_navigation_keeps_combining_and_emoji_sequences_intact() { |
| 1074 | let graphemes = ["a", "e\u{301}", "👩🏽💻", "🇨🇦", "👩👩👧👦", "z"]; |
| 1075 | let text = graphemes.concat(); |
| 1076 | let paragraph = Paragraph::new(text, Format::default()); |
| 1077 | let layout = TextEngine::default().layout(&paragraph, 1000.0).unwrap(); |
| 1078 | let mut byte = 0; |
| 1079 | let mut cursor = layout.cursor(0, Affinity::Downstream); |
| 1080 | for grapheme in graphemes { |
| 1081 | byte += grapheme.len(); |
| 1082 | cursor = cursor.next_visual(&layout.shaped); |
| 1083 | assert_eq!(cursor.index(), byte); |
| 1084 | } |
| 1085 | for grapheme in graphemes.into_iter().rev() { |
| 1086 | byte -= grapheme.len(); |
| 1087 | cursor = cursor.previous_visual(&layout.shaped); |
| 1088 | assert_eq!(cursor.index(), byte); |
| 1089 | } |
| 1090 | } |
| 1091 | |
| 1092 | #[test] |
| 1093 | fn emoji_only_lines_have_nonzero_metrics() { |
| 1094 | let paragraph = Paragraph::new("👩👩👧👦".into(), Format::default()); |
| 1095 | let layout = TextEngine::default().layout(&paragraph, 100.0).unwrap(); |
| 1096 | assert!(layout.height() > 0.0); |
| 1097 | let caret = layout.caret(layout.cursor(0, Affinity::Downstream), 1.0); |
| 1098 | assert!(caret.height() > 0.0); |
| 1099 | } |
| 1100 | |
| 1101 | #[cfg(target_os = "macos")] |
| 1102 | #[test] |
| 1103 | fn color_emoji_preserve_text_baselines_and_respect_explicit_font_size() { |
| 1104 | let mut engine = TextEngine::default(); |
| 1105 | for size in [11.0, 22.0] { |
| 1106 | let format = Format { |
| 1107 | font_size: Some(size), |
| 1108 | ..Default::default() |
| 1109 | }; |
| 1110 | let base = engine |
| 1111 | .layout(&Paragraph::new("Mg".into(), format.clone()), 1000.0) |
| 1112 | .unwrap(); |
| 1113 | for text in ["🌳", "👩👩👧👦", "before 🌳 after", "Mg\n🌳\nMg"] { |
| 1114 | let layout = engine |
| 1115 | .layout(&Paragraph::new(text.into(), format.clone()), 1000.0) |
| 1116 | .unwrap(); |
| 1117 | for (_, line) in layout.lines() { |
| 1118 | assert_eq!(line.height, base.lines[0].height, "{text}"); |
| 1119 | assert!( |
| 1120 | (line.baseline - line.top - base.lines[0].baseline).abs() < 0.0001, |
| 1121 | "{text}" |
| 1122 | ); |
| 1123 | } |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | #[test] |
| 1129 | fn bidi_hit_testing_stays_on_grapheme_boundaries() { |
| 1130 | let graphemes = [ |
| 1131 | "a", |
| 1132 | " ", |
| 1133 | "ש", |
| 1134 | "ל", |
| 1135 | "ו", |
| 1136 | "ם", |
| 1137 | " ", |
| 1138 | "1", |
| 1139 | "2", |
| 1140 | "3", |
| 1141 | " ", |
| 1142 | "👩🏽💻", |
| 1143 | " ", |
| 1144 | "e\u{301}", |
| 1145 | ]; |
| 1146 | let mut boundaries = vec![0]; |
| 1147 | for grapheme in graphemes { |
| 1148 | boundaries.push(boundaries.last().unwrap() + grapheme.len()); |
| 1149 | } |
| 1150 | let paragraph = Paragraph::new(graphemes.concat(), Format::default()); |
| 1151 | let mut engine = TextEngine::default(); |
| 1152 | for width in [1.0, 10.0, 40.0, 80.0, 1000.0] { |
| 1153 | let layout = engine.layout(&paragraph, width).unwrap(); |
| 1154 | for (_, line) in layout.lines() { |
| 1155 | assert!(boundaries.contains(&line.source.start)); |
| 1156 | assert!(boundaries.contains(&line.source.end)); |
| 1157 | } |
| 1158 | for y in (-10..layout.height() as i32 + 10).step_by(3) { |
| 1159 | for x in (-10..width as i32 + 10).step_by(3) { |
| 1160 | let cursor = layout.hit_test(x as f32, y as f32); |
| 1161 | assert!( |
| 1162 | boundaries.contains(&cursor.index()), |
| 1163 | "{width}: {x}, {y} -> {cursor:?}" |
| 1164 | ); |
| 1165 | let caret = layout.caret(cursor, 1.0); |
| 1166 | assert!(caret.x0.is_finite() && caret.y0.is_finite() && caret.height() > 0.0); |
| 1167 | } |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | |
| 1172 | #[test] |
| 1173 | fn selection_uses_the_same_line_boxes_as_hit_testing() { |
| 1174 | let paragraph = Paragraph::new( |
| 1175 | "one two three four five six seven".into(), |
| 1176 | Format::default(), |
| 1177 | ); |
| 1178 | let layout = TextEngine::default().layout(&paragraph, 60.0).unwrap(); |
| 1179 | let selection = Selection::from(layout.cursor(0, Affinity::Downstream)) |
| 1180 | .extend(layout.cursor(paragraph.text().len(), Affinity::Upstream)); |
| 1181 | let rects = layout.selection(selection); |
| 1182 | assert_eq!(rects.len(), layout.lines.len()); |
| 1183 | for (rect, line) in rects.iter().zip(&layout.lines) { |
| 1184 | assert_eq!(rect.y0, f64::from(line.top)); |
| 1185 | assert_eq!(rect.y1, f64::from(line.top + line.height)); |
| 1186 | let cursor = layout.hit_test(rect.x0 as f32 + 0.01, ((rect.y0 + rect.y1) * 0.5) as f32); |
| 1187 | assert_eq!(cursor.index(), line.source.start); |
| 1188 | } |
| 1189 | } |
| 1190 | } |