1#![deny(missing_docs)]
12
13#[cfg(doctest)]
15#[doc = include_str!("../README.md")]
16pub struct ReadmeDoctests;
17
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::sync::{Mutex, OnceLock, RwLock};
20
21use cosmic_text::{Attrs, Buffer, FontSystem, Metrics, Shaping, Style, Weight};
22use frus_core::{fits, FontWeight, Point, Rect, ResolvedTextStyle, Size, TextRun, TextStyle};
23
24use frus_core::DEFAULT_LINE_HEIGHT as LINE_HEIGHT_FACTOR;
30
31#[cfg(feature = "bundled-sans")]
53const DEJAVU_SANS: &[u8] = include_bytes!("../assets/DejaVuSans.ttf");
54#[cfg(feature = "bundled-sans")]
55const DEJAVU_SANS_BOLD: &[u8] = include_bytes!("../assets/DejaVuSans-Bold.ttf");
56#[cfg(feature = "bundled-italic")]
62const DEJAVU_SANS_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-Oblique.ttf");
63#[cfg(feature = "bundled-italic")]
64const DEJAVU_SANS_BOLD_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-BoldOblique.ttf");
65#[cfg(feature = "bundled-mono")]
67const DEJAVU_MONO: &[u8] = include_bytes!("../assets/DejaVuSansMono.ttf");
68#[cfg(feature = "bundled-arabic")]
71const NOTO_ARABIC: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Regular.ttf");
72#[cfg(feature = "bundled-arabic")]
73const NOTO_ARABIC_BOLD: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Bold.ttf");
74
75#[cfg(feature = "bundled-sans")]
77const SANS_FAMILY: &str = "DejaVu Sans";
78#[cfg(feature = "bundled-mono")]
79const MONO_FAMILY: &str = "DejaVu Sans Mono";
80#[cfg(feature = "bundled-arabic")]
82const ARABIC_FAMILY: &str = "Noto Naskh Arabic";
83
84#[cfg(feature = "bundled-sans")]
98static SANS: RwLock<Option<&'static str>> = RwLock::new(Some(SANS_FAMILY));
99#[cfg(not(feature = "bundled-sans"))]
100static SANS: RwLock<Option<&'static str>> = RwLock::new(None);
101#[cfg(feature = "bundled-mono")]
102static MONO: RwLock<Option<&'static str>> = RwLock::new(Some(MONO_FAMILY));
103#[cfg(not(feature = "bundled-mono"))]
104static MONO: RwLock<Option<&'static str>> = RwLock::new(None);
105#[cfg(feature = "bundled-arabic")]
106static ARABIC: RwLock<Option<&'static str>> = RwLock::new(Some(ARABIC_FAMILY));
107#[cfg(not(feature = "bundled-arabic"))]
108static ARABIC: RwLock<Option<&'static str>> = RwLock::new(None);
109static ITALIC: AtomicBool = AtomicBool::new(cfg!(feature = "bundled-italic"));
112
113static EXTRA_FONTS: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
117
118static APP_FAMILIES: Mutex<Vec<String>> = Mutex::new(Vec::new());
121
122pub fn add_font(data: Vec<u8>) {
135 let families = families_in(&data);
136 if families.is_empty() {
137 log::warn!(
138 "frus: add_font was given {} bytes that hold no font face; nothing was registered",
139 data.len()
140 );
141 return;
142 }
143 {
144 let mut known = APP_FAMILIES.lock().expect("font registry");
145 for family in families {
146 if !known.contains(&family) {
147 known.push(family);
148 }
149 }
150 }
151 EXTRA_FONTS
152 .lock()
153 .expect("font registry")
154 .push(data.clone());
155 if let Some(system) = FONT_SYSTEM.get() {
158 if let Ok(mut system) = system.lock() {
159 let db = system.db_mut();
160 db.load_font_data(data);
161 take_stock(db);
162 }
163 }
164 forget_measurements();
165}
166
167pub fn set_default_family(name: &'static str) {
178 *SANS.write().expect("family registry") = Some(name);
179 forget_measurements();
180}
181
182pub fn set_monospace_family(name: &'static str) {
186 *MONO.write().expect("family registry") = Some(name);
187 forget_measurements();
188}
189
190fn families_in(data: &[u8]) -> Vec<String> {
193 let mut db = cosmic_text::fontdb::Database::new();
194 db.load_font_data(data.to_vec());
195 let mut names: Vec<String> = Vec::new();
196 for face in db.faces() {
197 for (name, _) in &face.families {
198 if !names.contains(name) {
199 names.push(name.clone());
200 }
201 }
202 }
203 names
204}
205
206fn squashed(name: &str) -> String {
209 name.chars()
210 .filter(|c| !matches!(c, ' ' | '-' | '_'))
211 .flat_map(char::to_lowercase)
212 .collect()
213}
214
215fn match_family<'a>(
227 requested: &str,
228 loaded: &'a [String],
229 preferred: &[String],
230) -> Option<&'a str> {
231 if let Some(exact) = loaded.iter().find(|family| *family == requested) {
232 return Some(exact);
233 }
234 let wanted = squashed(requested);
235 if let Some(same) = loaded.iter().find(|family| squashed(family) == wanted) {
236 return Some(same);
237 }
238 let prefix = format!("{} ", requested.trim().to_lowercase());
239 loaded
240 .iter()
241 .filter(|family| family.to_lowercase().starts_with(&prefix))
242 .min_by_key(|family| (!preferred.contains(family), family.len()))
243 .map(String::as_str)
244}
245
246fn weight_range(
249 db: &cosmic_text::fontdb::Database,
250 face: &cosmic_text::fontdb::FaceInfo,
251) -> (u16, u16) {
252 use cosmic_text::skrifa::MetadataProvider;
253 let axis = db.with_face_data(face.id, |data, index| {
254 let font = cosmic_text::skrifa::FontRef::from_index(data, index).ok()?;
255 let axis = font
256 .axes()
257 .get_by_tag(cosmic_text::skrifa::Tag::new(b"wght"))?;
258 Some((axis.min_value() as u16, axis.max_value() as u16))
259 });
260 match axis {
261 Some(Some((low, high))) if low <= high => (low, high),
262 _ => (face.weight.0, face.weight.0),
263 }
264}
265
266struct Loaded {
269 families: Vec<String>,
271 text: Vec<String>,
273 app: Vec<String>,
275 slanted: Vec<String>,
277 generic_sans: bool,
280 generic_mono: bool,
281 answers: Mutex<std::collections::HashMap<&'static str, Option<&'static str>>>,
284}
285
286impl Loaded {
287 fn of(db: &cosmic_text::fontdb::Database) -> Self {
288 use cosmic_text::fontdb::{Family, Query, Style};
289 let mut families: Vec<String> = Vec::new();
290 let mut text: Vec<String> = Vec::new();
291 let mut slanted: Vec<String> = Vec::new();
292 for face in db.faces() {
293 let emoji = face.post_script_name.contains("Emoji");
294 for (name, _) in &face.families {
295 if !families.contains(name) {
296 families.push(name.clone());
297 }
298 if !emoji && !text.contains(name) {
299 text.push(name.clone());
300 }
301 if face.style != Style::Normal && !slanted.contains(name) {
302 slanted.push(name.clone());
303 }
304 }
305 }
306 let resolves = |family| {
307 db.query(&Query {
308 families: &[family],
309 ..Query::default()
310 })
311 .is_some()
312 };
313 Loaded {
314 families,
315 text,
316 app: APP_FAMILIES.lock().expect("font registry").clone(),
317 slanted,
318 generic_sans: resolves(Family::SansSerif),
319 generic_mono: resolves(Family::Monospace),
320 answers: Mutex::new(std::collections::HashMap::new()),
321 }
322 }
323
324 fn fallback(&self) -> Option<&str> {
328 self.app
329 .iter()
330 .find(|family| self.text.contains(family))
331 .or_else(|| self.text.iter().find(|family| *family == PLATFORM_SANS))
332 .or_else(|| self.text.first())
333 .map(String::as_str)
334 }
335
336 #[cfg(any(target_os = "android", test))]
341 fn wants_platform_sans(&self, requested: Option<&str>) -> bool {
342 let named = requested.is_some_and(|name| {
343 match_family(name, &self.families, &self.app)
344 .is_some_and(|family| self.text.iter().any(|text| text == family))
345 });
346 let own = self.app.iter().any(|family| self.text.contains(family));
347 !(named || own || (requested.is_none() && self.generic_sans))
348 }
349}
350
351static WEIGHTS: RwLock<Vec<(u16, u16)>> = RwLock::new(Vec::new());
355
356fn weights_of(db: &cosmic_text::fontdb::Database, family: &str) -> Vec<(u16, u16)> {
359 let faces: Vec<_> = db
360 .faces()
361 .filter(|face| face.families.iter().any(|(name, _)| name == family))
362 .collect();
363 let upright: Vec<_> = faces
364 .iter()
365 .filter(|face| face.style == cosmic_text::fontdb::Style::Normal)
366 .collect();
367 let chosen = if upright.is_empty() {
368 faces.iter().collect()
369 } else {
370 upright
371 };
372 let mut ranges: Vec<(u16, u16)> = chosen.iter().map(|face| weight_range(db, face)).collect();
373 ranges.sort_unstable();
374 ranges.dedup();
375 ranges
376}
377
378fn nearest_weight(wanted: u16, have: &[(u16, u16)]) -> u16 {
383 if have
384 .iter()
385 .any(|&(low, high)| (low..=high).contains(&wanted))
386 {
387 return wanted;
388 }
389 let mut ends: Vec<u16> = have.iter().flat_map(|&(low, high)| [low, high]).collect();
391 ends.sort_unstable();
392 ends.dedup();
393 let lighter = ends.iter().rev().find(|&&w| w < wanted).copied();
394 let heavier = ends.iter().find(|&&w| w > wanted).copied();
395 let pick = if (400..=500).contains(&wanted) {
396 ends.iter()
397 .find(|&&w| w > wanted && w <= 500)
398 .copied()
399 .or(lighter)
400 .or(heavier)
401 } else if wanted < 400 {
402 lighter.or(heavier)
403 } else {
404 heavier.or(lighter)
405 };
406 pick.unwrap_or(wanted)
407}
408
409const PLATFORM_SANS: &str = "Roboto";
412
413static LOADED: RwLock<Option<Loaded>> = RwLock::new(None);
416
417static INTERNED: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
420
421fn interned(name: &str) -> &'static str {
422 let mut interned = INTERNED.lock().expect("family registry");
423 if let Some(found) = interned.iter().find(|known| **known == name) {
424 return found;
425 }
426 let leaked: &'static str = Box::leak(name.to_string().into_boxed_str());
427 interned.push(leaked);
428 leaked
429}
430
431static WARNED: Mutex<Vec<String>> = Mutex::new(Vec::new());
434
435fn warn_once(message: String) {
436 let mut warned = WARNED.lock().expect("family registry");
437 if !warned.contains(&message) {
438 log::warn!("{message}");
439 warned.push(message);
440 }
441}
442
443fn take_stock(db: &mut cosmic_text::fontdb::Database) {
447 *LOADED.write().expect("family registry") = Some(Loaded::of(db));
448 let sans = default_family();
452 if let Some(sans) = sans {
453 db.set_sans_serif_family(sans);
454 db.set_serif_family(sans);
455 db.set_cursive_family(sans);
456 db.set_fantasy_family(sans);
457 }
458 if let cosmic_text::Family::Name(mono) = monospace_family() {
459 db.set_monospace_family(mono);
460 }
461 *WEIGHTS.write().expect("family registry") = match sans {
462 Some(name) => weights_of(db, name),
463 None => Vec::new(),
464 };
465 let italic = match LOADED.read().expect("family registry").as_ref() {
468 Some(loaded) => match sans {
469 Some(name) => loaded.slanted.iter().any(|family| family == name),
470 None => !loaded.slanted.is_empty(),
471 },
472 None => false,
473 };
474 ITALIC.store(italic, Ordering::Relaxed);
475}
476
477fn loaded_family(name: &'static str) -> Option<&'static str> {
482 let guard = LOADED.read().expect("family registry");
483 let Some(loaded) = guard.as_ref() else {
484 return Some(name);
485 };
486 let mut answers = loaded.answers.lock().expect("family registry");
487 if let Some(answer) = answers.get(name) {
488 return *answer;
489 }
490 let answer = match_family(name, &loaded.families, &loaded.app).map(interned);
491 if let Some(actual) = answer {
492 if actual != name {
493 warn_once(format!(
494 "frus: no font family is called \"{name}\"; drawing \"{actual}\", the name \
495 inside the font files. Write \"{actual}\" to say so."
496 ));
497 }
498 }
499 answers.insert(name, answer);
500 answer
501}
502
503fn fallback_for(role: &str, name: &str) -> Option<&'static str> {
506 let guard = LOADED.read().expect("family registry");
507 let loaded = guard.as_ref()?;
508 let fallback = loaded.fallback().map(interned);
509 let registered = if loaded.app.is_empty() {
510 "add_font registered none".to_string()
511 } else {
512 format!("add_font registered {:?}", loaded.app)
513 };
514 let drawn = match fallback {
515 Some(family) => format!("drawing \"{family}\" instead"),
516 None => "and no other face can draw text".to_string(),
517 };
518 warn_once(format!(
519 "frus: the {role} font family \"{name}\" is not loaded; {drawn}. The name must be \
520 the one inside the font file ({registered})."
521 ));
522 fallback
523}
524
525fn default_family() -> Option<&'static str> {
529 let requested = *SANS.read().expect("family registry");
530 match requested {
531 Some(name) => loaded_family(name).or_else(|| fallback_for("default", name)),
532 None => {
533 let generic = LOADED
534 .read()
535 .expect("family registry")
536 .as_ref()
537 .is_none_or(|loaded| loaded.generic_sans);
538 if generic {
539 None
540 } else {
541 LOADED
542 .read()
543 .expect("family registry")
544 .as_ref()
545 .and_then(Loaded::fallback)
546 .map(interned)
547 }
548 }
549 }
550}
551
552fn sans_family() -> cosmic_text::Family<'static> {
554 match default_family() {
555 Some(name) => cosmic_text::Family::Name(name),
556 None => cosmic_text::Family::SansSerif,
557 }
558}
559
560fn contains_arabic(text: &str) -> bool {
563 text.chars().any(|c| {
564 matches!(c as u32,
565 0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF)
566 })
567}
568
569pub fn family_for(text: &str) -> cosmic_text::Family<'static> {
577 if contains_arabic(text) {
578 let arabic = *ARABIC.read().expect("family registry");
581 match arabic.and_then(loaded_family) {
582 Some(name) => cosmic_text::Family::Name(name),
583 None => sans_family(),
584 }
585 } else {
586 sans_family()
587 }
588}
589
590pub fn family_for_style(
609 text: &str,
610 family: Option<frus_core::FontFamily>,
611) -> cosmic_text::Family<'static> {
612 use frus_core::FontFamily;
613 match family {
614 None => family_for(text),
616 Some(_) if contains_arabic(text) => family_for(text),
618 Some(FontFamily::SansSerif) => sans_family(),
619 Some(FontFamily::Serif) => cosmic_text::Family::Serif,
620 Some(FontFamily::Monospace) => monospace_family(),
621 Some(FontFamily::Named(name)) => match loaded_family(name) {
622 Some(found) => cosmic_text::Family::Name(found),
623 None => {
624 fallback_for("named", name);
625 sans_family()
626 }
627 },
628 }
629}
630
631pub fn monospace_family() -> cosmic_text::Family<'static> {
635 let requested = *MONO.read().expect("family registry");
636 match requested {
637 Some(name) => match loaded_family(name) {
638 Some(found) => cosmic_text::Family::Name(found),
639 None => {
640 fallback_for("monospace", name);
641 sans_family()
642 }
643 },
644 None => {
645 let generic = LOADED
646 .read()
647 .expect("family registry")
648 .as_ref()
649 .is_none_or(|loaded| loaded.generic_mono);
650 if generic {
651 cosmic_text::Family::Monospace
652 } else {
653 sans_family()
654 }
655 }
656 }
657}
658
659pub fn available_style(italic: bool) -> Style {
665 if italic && ITALIC.load(Ordering::Relaxed) {
666 Style::Italic
667 } else {
668 Style::Normal
669 }
670}
671
672#[cfg(target_os = "android")]
674const ANDROID_FONT_DIR: &str = "/system/fonts";
675
676#[cfg(any(target_os = "android", test))]
679fn load_platform_faces(
680 db: &mut cosmic_text::fontdb::Database,
681 dir: &std::path::Path,
682 keep: impl Fn(&str) -> bool,
683) -> usize {
684 let Ok(entries) = std::fs::read_dir(dir) else {
685 return 0;
686 };
687 let mut taken = 0;
688 for path in entries.flatten().map(|entry| entry.path()) {
689 let name = path
690 .file_name()
691 .and_then(|name| name.to_str())
692 .map(str::to_ascii_lowercase)
693 .unwrap_or_default();
694 let font = [".ttf", ".otf", ".ttc"]
695 .iter()
696 .any(|extension| name.ends_with(extension));
697 if font && keep(&name) && db.load_font_file(&path).is_ok() {
698 taken += 1;
699 }
700 }
701 taken
702}
703
704#[cfg(any(target_os = "android", test))]
713fn load_emoji_faces(db: &mut cosmic_text::fontdb::Database, dir: &std::path::Path) -> usize {
714 load_platform_faces(db, dir, |name| name.contains("emoji"))
715}
716
717#[cfg(any(target_os = "android", test))]
725fn load_platform_sans(db: &mut cosmic_text::fontdb::Database, dir: &std::path::Path) -> usize {
726 load_platform_faces(db, dir, |name| name.starts_with("roboto-"))
727}
728
729pub fn new_font_system() -> FontSystem {
740 let started = web_time::Instant::now();
741 let font_system = build_font_system();
742 if let Ok(mut loading) = FONT_LOADING.lock() {
743 loading.0 += started.elapsed();
744 loading.1 += 1;
745 }
746 font_system
747}
748
749pub fn font_loading() -> (std::time::Duration, u32) {
753 FONT_LOADING
754 .lock()
755 .map(|loading| *loading)
756 .unwrap_or_default()
757}
758
759static FONT_LOADING: Mutex<(std::time::Duration, u32)> = Mutex::new((std::time::Duration::ZERO, 0));
760
761fn build_font_system() -> FontSystem {
762 let mut font_system = FontSystem::new();
763 let db = font_system.db_mut();
764 #[cfg(target_os = "android")]
765 load_emoji_faces(db, std::path::Path::new(ANDROID_FONT_DIR));
766 #[cfg(feature = "bundled-sans")]
767 {
768 db.load_font_data(DEJAVU_SANS.to_vec());
769 db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
770 }
771 #[cfg(feature = "bundled-italic")]
772 {
773 db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
774 db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
775 }
776 #[cfg(feature = "bundled-mono")]
777 db.load_font_data(DEJAVU_MONO.to_vec());
778 #[cfg(feature = "bundled-arabic")]
779 {
780 db.load_font_data(NOTO_ARABIC.to_vec());
781 db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
782 }
783 for face in EXTRA_FONTS.lock().expect("font registry").iter() {
785 db.load_font_data(face.clone());
786 }
787 #[cfg(target_os = "android")]
790 {
791 let requested = *SANS.read().expect("family registry");
792 if Loaded::of(db).wants_platform_sans(requested)
793 && load_platform_sans(db, std::path::Path::new(ANDROID_FONT_DIR)) > 0
794 {
795 log::info!(
796 "frus: no bundled or registered face draws text; using the platform's Roboto"
797 );
798 }
799 }
800 take_stock(db);
801 font_system
802}
803
804static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();
805
806fn font_system() -> &'static Mutex<FontSystem> {
807 FONT_SYSTEM.get_or_init(|| Mutex::new(new_font_system()))
808}
809
810#[derive(PartialEq, Eq, Hash)]
817struct MeasureKey {
818 text: String,
819 size: u32,
820 weight: u16,
821 italic: bool,
822 max_width: Option<u32>,
823 line_h: u32,
826 family: Option<frus_core::FontFamily>,
829 letter_spacing: u32,
831}
832
833const CACHE_CAP: usize = 2048;
838
839#[derive(Default)]
844struct MeasureCache {
845 current: std::collections::HashMap<MeasureKey, Size>,
846 previous: std::collections::HashMap<MeasureKey, Size>,
847}
848
849static MEASURE_CACHE: Mutex<Option<MeasureCache>> = Mutex::new(None);
850
851fn forget_measurements() {
855 if let Ok(mut cache) = MEASURE_CACHE.lock() {
856 *cache = None;
857 }
858}
859
860pub fn available_weight(weight: FontWeight) -> u16 {
873 let wanted = weight.to_u16();
874 let have = WEIGHTS.read().expect("family registry");
875 if have.is_empty() {
876 return if wanted < 550 { 400 } else { 700 };
877 }
878 nearest_weight(wanted, &have)
879}
880
881#[derive(Clone, Copy, PartialEq, Eq, Hash)]
885struct BaselineKey {
886 size: u32,
887 weight: u16,
888 italic: bool,
889}
890
891static BASELINES: std::sync::LazyLock<
892 std::sync::Mutex<std::collections::HashMap<BaselineKey, f32>>,
893> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
894
895pub fn spaced(attrs: Attrs<'static>, letter_spacing: f32, size_px: f32) -> Attrs<'static> {
899 if letter_spacing == 0.0 || size_px <= 0.0 {
900 attrs
901 } else {
902 attrs.letter_spacing(letter_spacing / size_px)
903 }
904}
905
906pub fn line_height(size_px: f32) -> f32 {
914 size_px * LINE_HEIGHT_FACTOR
915}
916
917pub fn baseline(size_px: f32, weight: FontWeight, italic: bool) -> f32 {
930 let _ = font_system();
933 let key = BaselineKey {
934 size: size_px.to_bits(),
935 weight: available_weight(weight),
936 italic: available_style(italic) == Style::Italic,
937 };
938 if let Some(cached) = BASELINES.lock().expect("baseline cache").get(&key) {
939 return *cached;
940 }
941
942 let line_h = line_height(size_px);
943 let mut font_system = font_system().lock().expect("FontSystem lock");
944 let metrics = Metrics::new(size_px, line_h);
945 let mut buffer = Buffer::new(&mut font_system, metrics);
946 let probe = "Hg";
949 let attrs = Attrs::new()
950 .family(family_for(probe))
951 .weight(Weight(available_weight(weight)))
952 .style(available_style(italic));
953 buffer.set_text(probe, &attrs, Shaping::Advanced, None);
954 buffer.shape_until_scroll(&mut font_system, false);
955 let baseline = buffer
958 .layout_runs()
959 .next()
960 .map(|run| run.line_y)
961 .unwrap_or(size_px);
962 drop(font_system);
963 BASELINES
964 .lock()
965 .expect("baseline cache")
966 .insert(key, baseline);
967 baseline
968}
969
970pub fn baseline_of_runs(runs: &[TextRun]) -> Option<f32> {
973 runs.iter()
974 .map(|run| baseline(run.size, run.weight, run.italic))
975 .fold(None, |acc: Option<f32>, b| {
976 Some(acc.map_or(b, |a| a.max(b)))
977 })
978}
979
980pub fn measure(text: &str, size_px: f32) -> Size {
983 measure_styled(text, size_px, FontWeight::Regular, false)
984}
985
986pub fn measure_style(text: &str, style: TextStyle) -> Size {
993 measure_resolved(text, &style.resolved())
994}
995
996pub fn measure_resolved(text: &str, style: &ResolvedTextStyle) -> Size {
1000 measure_wrapped_resolved(text, style, None)
1001}
1002
1003pub fn line_box(min: f32, style: &ResolvedTextStyle, padding: f32) -> f32 {
1011 min.max(fits(style.line_height() + padding))
1014}
1015
1016pub fn measure_wrapped_resolved(
1020 text: &str,
1021 style: &ResolvedTextStyle,
1022 max_width: Option<f32>,
1023) -> Size {
1024 measure_at(text, style, max_width)
1028}
1029
1030pub fn measure_styled(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Size {
1033 measure_wrapped(text, size_px, weight, italic, None)
1034}
1035
1036pub fn measure_wrapped(
1040 text: &str,
1041 size_px: f32,
1042 weight: FontWeight,
1043 italic: bool,
1044 max_width: Option<f32>,
1045) -> Size {
1046 let style = ResolvedTextStyle {
1047 weight,
1048 italic,
1049 ..ResolvedTextStyle::exact(size_px)
1050 };
1051 measure_at(text, &style, max_width)
1052}
1053
1054fn measure_at(text: &str, style: &ResolvedTextStyle, max_width: Option<f32>) -> Size {
1061 let (size_px, weight, italic) = (style.size, style.weight, style.italic);
1062 let (line_h, family, letter_spacing) =
1063 (style.line_height(), style.family, style.letter_spacing);
1064 if text.is_empty() {
1065 return Size::new(0.0, fits(line_h));
1069 }
1070
1071 let _ = font_system();
1076
1077 let key = MeasureKey {
1081 text: text.to_string(),
1082 size: size_px.to_bits(),
1083 weight: available_weight(weight),
1084 italic: available_style(italic) == Style::Italic,
1085 max_width: max_width.map(f32::to_bits),
1086 line_h: line_h.to_bits(),
1089 family,
1090 letter_spacing: letter_spacing.to_bits(),
1091 };
1092 if let Some(size) = cached_measurement(&key) {
1093 return size;
1094 }
1095
1096 let mut font_system = font_system().lock().expect("FontSystem lock");
1097 let metrics = Metrics::new(size_px, line_h);
1098 let mut buffer = Buffer::new(&mut font_system, metrics);
1099 buffer.set_size(max_width, None);
1101 let attrs = spaced(
1102 Attrs::new()
1103 .family(family_for_style(text, family))
1106 .weight(Weight(available_weight(weight)))
1107 .style(available_style(italic)),
1108 letter_spacing,
1109 size_px,
1110 );
1111 buffer.set_text(text, &attrs, Shaping::Advanced, None);
1112 buffer.shape_until_scroll(&mut font_system, false);
1113
1114 let mut width = 0.0_f32;
1115 let mut lines = 0.0_f32;
1116 for run in buffer.layout_runs() {
1117 width = width.max(run.line_w);
1118 lines += 1.0;
1119 }
1120
1121 let width = match max_width {
1131 Some(max) => fits(width).min(max),
1132 None => fits(width),
1133 };
1134 let measured = Size::new(width, fits(lines.max(1.0) * line_h));
1140 remember_measurement(key, measured);
1141 measured
1142}
1143
1144fn cached_measurement(key: &MeasureKey) -> Option<Size> {
1147 let mut guard = MEASURE_CACHE.lock().ok()?;
1148 let cache = guard.as_mut()?;
1149 if let Some(size) = cache.current.get(key) {
1150 return Some(*size);
1151 }
1152 let size = *cache.previous.get(key)?;
1153 cache.current.insert(
1155 MeasureKey {
1156 text: key.text.clone(),
1157 ..*key
1158 },
1159 size,
1160 );
1161 Some(size)
1162}
1163
1164fn remember_measurement(key: MeasureKey, size: Size) {
1165 let Ok(mut guard) = MEASURE_CACHE.lock() else {
1166 return;
1167 };
1168 let cache = guard.get_or_insert_with(MeasureCache::default);
1169 if cache.current.len() >= CACHE_CAP {
1170 cache.previous = std::mem::take(&mut cache.current);
1171 }
1172 cache.current.insert(key, size);
1173}
1174
1175pub fn line_spans(
1190 text: &str,
1191 size_px: f32,
1192 weight: FontWeight,
1193 italic: bool,
1194 max_width: Option<f32>,
1195 soft_wrap: bool,
1196) -> Vec<std::ops::Range<usize>> {
1197 let style = ResolvedTextStyle {
1198 weight,
1199 italic,
1200 ..ResolvedTextStyle::exact(size_px)
1201 };
1202 line_spans_resolved(text, &style, max_width, soft_wrap)
1203}
1204
1205pub fn line_spans_resolved(
1208 text: &str,
1209 style: &ResolvedTextStyle,
1210 max_width: Option<f32>,
1211 soft_wrap: bool,
1212) -> Vec<std::ops::Range<usize>> {
1213 let size_px = style.size;
1214 let mut font_system = font_system().lock().expect("FontSystem lock");
1215 let metrics = Metrics::new(size_px, style.line_height());
1216 let mut buffer = Buffer::new(&mut font_system, metrics);
1217 if !soft_wrap {
1218 buffer.set_wrap(cosmic_text::Wrap::None);
1219 }
1220 buffer.set_size(max_width, None);
1221 let attrs = spaced(
1222 Attrs::new()
1223 .family(family_for_style(text, style.family))
1224 .weight(Weight(available_weight(style.weight)))
1225 .style(available_style(style.italic)),
1226 style.letter_spacing,
1227 size_px,
1228 );
1229 buffer.set_text(text, &attrs, Shaping::Advanced, None);
1230 buffer.shape_until_scroll(&mut font_system, false);
1231
1232 let mut line_start = Vec::new();
1236 let mut at = 0usize;
1237 for line in &buffer.lines {
1238 line_start.push(at);
1239 at += line.text().len() + 1;
1240 }
1241
1242 let mut spans = Vec::new();
1243 for run in buffer.layout_runs() {
1244 let base = line_start.get(run.line_i).copied().unwrap_or(0);
1245 let start = run.glyphs.iter().map(|g| g.start).min();
1248 let end = run.glyphs.iter().map(|g| g.end).max();
1249 match (start, end) {
1250 (Some(start), Some(end)) => spans.push(base + start..base + end),
1251 _ => spans.push(base..base),
1253 }
1254 }
1255 if spans.is_empty() {
1258 spans.push(0..0);
1259 }
1260 spans
1261}
1262
1263pub fn measure_runs(runs: &[TextRun]) -> Size {
1266 measure_runs_wrapped(runs, None)
1267}
1268
1269pub fn measure_runs_wrapped(runs: &[TextRun], max_width: Option<f32>) -> Size {
1272 if runs.iter().all(|r| r.text.is_empty()) {
1273 return Size::new(0.0, 0.0);
1274 }
1275 let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);
1276
1277 let mut font_system = font_system().lock().expect("FontSystem lock");
1278 let metrics = Metrics::new(base, line_height(base));
1279 let mut buffer = Buffer::new(&mut font_system, metrics);
1280 buffer.set_size(max_width, None);
1281 let spans = runs.iter().map(|run| {
1282 (
1283 run.text.as_str(),
1284 spaced(
1285 Attrs::new()
1286 .family(family_for(&run.text))
1287 .weight(Weight(available_weight(run.weight)))
1288 .style(available_style(run.italic))
1289 .metrics(Metrics::new(run.size, line_height(run.size))),
1290 run.letter_spacing,
1291 run.size,
1292 ),
1293 )
1294 });
1295 buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
1296 buffer.shape_until_scroll(&mut font_system, false);
1297
1298 let mut width = 0.0_f32;
1299 let mut height = 0.0_f32;
1300 for run in buffer.layout_runs() {
1301 width = width.max(run.line_w);
1302 height = height.max(run.line_top + run.line_height);
1303 }
1304 let width = match max_width {
1308 Some(max) => fits(width).min(max),
1309 None => fits(width),
1310 };
1311 Size::new(width, fits(height))
1314}
1315
1316pub fn runs_cut_at(
1327 runs: &[TextRun],
1328 max_width: Option<f32>,
1329 soft_wrap: bool,
1330 max_lines: usize,
1331) -> Option<usize> {
1332 if runs.iter().all(|r| r.text.is_empty()) {
1333 return None;
1334 }
1335 let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);
1336 let mut font_system = font_system().lock().expect("FontSystem lock");
1337 let metrics = Metrics::new(base, line_height(base));
1338 let mut buffer = Buffer::new(&mut font_system, metrics);
1339 if !soft_wrap {
1340 buffer.set_wrap(cosmic_text::Wrap::None);
1341 }
1342 buffer.set_size(max_width, None);
1343 let spans = runs.iter().map(|run| {
1344 (
1345 run.text.as_str(),
1346 spaced(
1347 Attrs::new()
1348 .family(family_for(&run.text))
1349 .weight(Weight(available_weight(run.weight)))
1350 .style(available_style(run.italic))
1351 .metrics(Metrics::new(run.size, line_height(run.size))),
1352 run.letter_spacing,
1353 run.size,
1354 ),
1355 )
1356 });
1357 buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
1358 buffer.shape_until_scroll(&mut font_system, false);
1359
1360 let mut line_start = Vec::new();
1364 let mut at = 0usize;
1365 for line in &buffer.lines {
1366 line_start.push(at);
1367 at += line.text().len() + 1;
1368 }
1369 for (index, run) in buffer.layout_runs().enumerate() {
1370 if index < max_lines {
1371 continue;
1372 }
1373 let start = run.glyphs.iter().map(|g| g.start).min().unwrap_or(0);
1374 return Some(line_start.get(run.line_i).copied().unwrap_or(0) + start);
1375 }
1376 None
1377}
1378
1379struct LayoutLine {
1382 start_char: usize,
1384 offsets: Vec<f32>,
1386 top: f32,
1388 height: f32,
1390}
1391
1392pub struct TextLayout {
1402 lines: Vec<LayoutLine>,
1403 size: Size,
1404 chars: usize,
1406}
1407
1408impl TextLayout {
1409 pub fn new(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Self {
1412 Self::wrapped(text, size_px, weight, italic, None)
1413 }
1414
1415 pub fn wrapped(
1424 text: &str,
1425 size_px: f32,
1426 weight: FontWeight,
1427 italic: bool,
1428 max_width: Option<f32>,
1429 ) -> Self {
1430 Self::shaped(
1431 text,
1432 size_px,
1433 weight,
1434 italic,
1435 max_width,
1436 line_height(size_px),
1437 None,
1438 0.0,
1439 )
1440 }
1441
1442 pub fn resolved(text: &str, style: &ResolvedTextStyle, max_width: Option<f32>) -> Self {
1450 Self::shaped(
1451 text,
1452 style.size,
1453 style.weight,
1454 style.italic,
1455 max_width,
1456 style.line_height(),
1457 style.family,
1458 style.letter_spacing,
1459 )
1460 }
1461
1462 #[allow(clippy::too_many_arguments)]
1464 fn shaped(
1465 text: &str,
1466 size_px: f32,
1467 weight: FontWeight,
1468 italic: bool,
1469 max_width: Option<f32>,
1470 fallback_h: f32,
1471 family: Option<frus_core::FontFamily>,
1472 letter_spacing: f32,
1473 ) -> Self {
1474 let mut lines: Vec<LayoutLine> = Vec::new();
1475 let mut width = 0.0_f32;
1476 let mut height = 0.0_f32;
1477
1478 if !text.is_empty() {
1479 let hard: Vec<&str> = text.split('\n').collect();
1481 let mut line_byte_start = Vec::with_capacity(hard.len());
1482 {
1483 let mut b = 0usize;
1484 for l in &hard {
1485 line_byte_start.push(b);
1486 b += l.len() + 1; }
1488 }
1489
1490 let mut font_system = font_system().lock().expect("FontSystem lock");
1491 let metrics = Metrics::new(size_px, fallback_h);
1492 let mut buffer = Buffer::new(&mut font_system, metrics);
1493 buffer.set_size(max_width, None);
1494 let attrs = spaced(
1495 Attrs::new()
1496 .family(family_for_style(text, family))
1497 .weight(Weight(available_weight(weight)))
1498 .style(available_style(italic)),
1499 letter_spacing,
1500 size_px,
1501 );
1502 buffer.set_text(text, &attrs, Shaping::Advanced, None);
1503 buffer.shape_until_scroll(&mut font_system, false);
1504
1505 let runs: Vec<_> = buffer.layout_runs().collect();
1507 for (idx, run) in runs.iter().enumerate() {
1508 let line_text = hard[run.line_i];
1509 let first_of_line = idx == 0 || runs[idx - 1].line_i != run.line_i;
1510 let lo = if first_of_line {
1515 0
1516 } else {
1517 run.glyphs.iter().map(|g| g.start).min().unwrap_or(0)
1518 };
1519 let hi = runs
1520 .get(idx + 1)
1521 .filter(|r| r.line_i == run.line_i)
1522 .and_then(|r| r.glyphs.iter().map(|g| g.start).min())
1523 .unwrap_or(line_text.len());
1524
1525 let span = &line_text[lo..hi];
1527 let char_bytes: Vec<usize> = span.char_indices().map(|(b, _)| lo + b).collect();
1528 let n = char_bytes.len();
1529 let mut offsets = vec![f32::NAN; n + 1];
1530 offsets[0] = 0.0;
1531
1532 for glyph in run.glyphs.iter() {
1535 let covered: Vec<usize> = (0..n)
1536 .filter(|&i| char_bytes[i] >= glyph.start && char_bytes[i] < glyph.end)
1537 .collect();
1538 let k = covered.len().max(1) as f32;
1539 for (j, &i) in covered.iter().enumerate() {
1540 offsets[i] = glyph.x + glyph.w * (j as f32 / k);
1541 }
1542 if let Some(next) = (0..=n).find(|&i| {
1543 let b = if i == n {
1544 lo + span.len()
1545 } else {
1546 char_bytes[i]
1547 };
1548 b == glyph.end
1549 }) {
1550 offsets[next] = glyph.x + glyph.w;
1551 }
1552 }
1553 for i in 1..=n {
1555 if offsets[i].is_nan() {
1556 offsets[i] = offsets[i - 1];
1557 }
1558 }
1559
1560 let start_char = text[..line_byte_start[run.line_i] + lo].chars().count();
1561 width = width.max(run.line_w);
1562 height = height.max(run.line_top + run.line_height);
1563 lines.push(LayoutLine {
1564 start_char,
1565 offsets,
1566 top: run.line_top,
1567 height: run.line_height,
1568 });
1569 }
1570 }
1571
1572 if lines.is_empty() {
1575 lines.push(LayoutLine {
1576 start_char: 0,
1577 offsets: vec![0.0],
1578 top: 0.0,
1579 height: fallback_h,
1580 });
1581 height = fallback_h;
1582 }
1583
1584 let chars = text.chars().count();
1585 Self {
1586 lines,
1587 size: Size::new(width, height),
1588 chars,
1589 }
1590 }
1591
1592 pub fn size(&self) -> Size {
1594 self.size
1595 }
1596
1597 fn line_of(&self, index: usize) -> &LayoutLine {
1599 self.lines
1600 .iter()
1601 .rev()
1602 .find(|line| index >= line.start_char)
1603 .unwrap_or(&self.lines[0])
1604 }
1605
1606 pub fn caret_rect(&self, index: usize) -> Rect {
1609 let index = index.min(self.chars);
1610 let line = self.line_of(index);
1611 let local = (index - line.start_char).min(line.offsets.len() - 1);
1612 Rect::new(line.offsets[local], line.top, 0.0, line.height)
1613 }
1614
1615 pub fn hit_test(&self, point: Point) -> usize {
1618 let line = self
1619 .lines
1620 .iter()
1621 .find(|line| point.y < line.top + line.height)
1622 .unwrap_or(self.lines.last().expect("at least one line"));
1623
1624 let mut best = 0;
1625 let mut best_dist = f32::MAX;
1626 for (i, x) in line.offsets.iter().enumerate() {
1627 let dist = (x - point.x).abs();
1628 if dist < best_dist {
1629 best_dist = dist;
1630 best = i;
1631 }
1632 }
1633 (line.start_char + best).min(self.chars)
1634 }
1635
1636 pub fn selection_rects(&self, start: usize, end: usize) -> Vec<Rect> {
1639 let (start, end) = (start.min(self.chars), end.min(self.chars));
1640 if start >= end {
1641 return Vec::new();
1642 }
1643 let mut rects = Vec::new();
1644 for line in &self.lines {
1645 let line_len = line.offsets.len() - 1;
1646 let lo = start.max(line.start_char);
1647 let hi = end.min(line.start_char + line_len);
1648 if lo >= hi {
1649 continue;
1650 }
1651 let x0 = line.offsets[lo - line.start_char];
1652 let x1 = line.offsets[hi - line.start_char];
1653 if x1 > x0 {
1654 rects.push(Rect::new(x0, line.top, x1 - x0, line.height));
1655 }
1656 }
1657 rects
1658 }
1659}
1660
1661#[cfg(test)]
1662mod tests {
1663
1664 #[test]
1669 fn letter_spacing_widens_a_word_by_its_spacing() {
1670 let word = "Spacious";
1671 let plain = ResolvedTextStyle::exact(16.0);
1672 let spaced = ResolvedTextStyle {
1673 letter_spacing: 2.0,
1674 ..plain
1675 };
1676 let tight = ResolvedTextStyle {
1677 letter_spacing: -0.5,
1678 ..plain
1679 };
1680 let w0 = measure_resolved(word, &plain).width;
1681 let w2 = measure_resolved(word, &spaced).width;
1682 let wt = measure_resolved(word, &tight).width;
1683 let added = w2 - w0;
1684 assert!(
1685 (added - 16.0).abs() <= 2.5,
1686 "eight letters, two pixels each: {added} added"
1687 );
1688 assert!(wt < w0, "negative spacing tightens: {wt} vs {w0}");
1689 let layout = TextLayout::resolved(word, &spaced, None);
1691 let laid = layout.size().width;
1692 assert!((laid - w2).abs() <= 1.0, "{laid} vs {w2}");
1693 let end = layout.caret_rect(word.chars().count()).x;
1695 assert!(end > w0 + 8.0, "the caret ends past the spacing: {end}");
1696 }
1697
1698 #[test]
1701 fn letter_spacing_moves_the_line_breaks() {
1702 let text = "one two three";
1703 let plain = ResolvedTextStyle::exact(14.0);
1704 let width = measure_resolved(text, &plain).width + 2.0;
1705 assert_eq!(
1706 line_spans_resolved(text, &plain, Some(width), true).len(),
1707 1
1708 );
1709 let spaced = ResolvedTextStyle {
1710 letter_spacing: 3.0,
1711 ..plain
1712 };
1713 assert!(line_spans_resolved(text, &spaced, Some(width), true).len() >= 2);
1714 }
1715
1716 #[test]
1721 fn a_resolved_layout_takes_the_styles_leading() {
1722 let text = "one two three four five six seven eight";
1723 let open = ResolvedTextStyle {
1724 height: Some(2.0),
1725 ..ResolvedTextStyle::exact(16.0)
1726 };
1727 let styled = TextLayout::resolved(text, &open, Some(90.0));
1728 let plain = TextLayout::wrapped(text, 16.0, FontWeight::Regular, false, Some(90.0));
1729 let spans = line_spans(text, 16.0, FontWeight::Regular, false, Some(90.0), true);
1730 assert!(spans.len() >= 3, "the fixture wraps: {spans:?}");
1731 let second = spans[1].start;
1732 assert_eq!(styled.caret_rect(second).y, 32.0, "two lines of 32 px");
1733 assert_eq!(plain.caret_rect(second).y, line_height(16.0));
1734 assert!(styled.size().height > plain.size().height * 1.5);
1735 let closed = TextLayout::resolved(text, &ResolvedTextStyle::exact(16.0), Some(90.0));
1737 assert_eq!(closed.caret_rect(second), plain.caret_rect(second));
1738 assert_eq!(closed.size(), plain.size());
1739 }
1740
1741 #[test]
1745 fn line_spans_break_where_the_shaper_breaks() {
1746 let text = "one two three four five six seven eight";
1747 let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
1748 assert!(spans.len() > 1, "it wrapped: {spans:?}");
1749 let words: Vec<&str> = spans
1750 .iter()
1751 .flat_map(|s| text[s.clone()].split_whitespace())
1752 .collect();
1753 assert_eq!(words, text.split_whitespace().collect::<Vec<_>>());
1754 for span in &spans {
1755 let w = measure_styled(&text[span.clone()], 14.0, FontWeight::Regular, false).width;
1756 assert!(
1757 w <= 80.5,
1758 "each line fits: {:?} at {w}",
1759 &text[span.clone()]
1760 );
1761 }
1762 }
1763
1764 #[test]
1767 fn the_spans_run_forwards() {
1768 let text = "one two three four five six seven eight";
1769 let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
1770 for pair in spans.windows(2) {
1771 assert!(pair[0].end <= pair[1].start, "{pair:?}");
1772 }
1773 }
1774
1775 #[test]
1778 fn without_wrapping_there_is_one_line() {
1779 let text = "one two three four five six seven eight";
1780 let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(40.0), false);
1781 assert_eq!(spans.len(), 1);
1782 assert_eq!(&text[spans[0].clone()], text);
1783 }
1784 use super::*;
1785
1786 #[test]
1787 fn empty_text_has_zero_width() {
1788 let size = measure("", 16.0);
1789 assert_eq!(size.width, 0.0);
1790 assert!(size.height > 0.0);
1791 }
1792
1793 #[test]
1794 fn non_empty_text_has_positive_size() {
1795 let size = measure("Bonjour", 24.0);
1796 assert!(size.width > 0.0, "width = {}", size.width);
1797 assert!(size.height > 0.0, "height = {}", size.height);
1798 }
1799
1800 #[test]
1801 fn rich_runs_measure_mixed_styles() {
1802 use frus_core::Color;
1803 let run = |text: &str, size: f32, weight: FontWeight| TextRun {
1804 text: text.to_string(),
1805 size,
1806 weight,
1807 italic: false,
1808 color: Color::WHITE,
1809 decoration: frus_core::TextDecoration::NONE,
1810 decoration_color: None,
1811 letter_spacing: 0.0,
1812 };
1813 let plain = measure_runs(&[run("normal", 16.0, FontWeight::Regular)]);
1816 let mixed = measure_runs(&[
1817 run("normal", 16.0, FontWeight::Regular),
1818 run(" BOLD", 24.0, FontWeight::Bold),
1819 ]);
1820 assert!(mixed.width > plain.width);
1821 assert!(
1822 mixed.height >= line_height(24.0) - 1.0,
1823 "height driven by the 24px run: {}",
1824 mixed.height
1825 );
1826 assert_eq!(measure_runs(&[]), Size::new(0.0, 0.0));
1828 }
1829
1830 #[test]
1831 fn wrapped_text_grows_taller_within_the_width() {
1832 let text = "a text that is long enough to wrap onto several lines";
1833 let free = measure_wrapped(text, 16.0, FontWeight::Regular, false, None);
1834 let narrow = measure_wrapped(text, 16.0, FontWeight::Regular, false, Some(120.0));
1835 assert!(
1836 narrow.width <= 120.0,
1837 "wrapped within the width: {}",
1838 narrow.width
1839 );
1840 assert!(narrow.height > free.height, "wrapping grows the height");
1841 }
1842
1843 #[test]
1844 fn layout_offsets_are_monotonic_and_match_size() {
1845 let layout = TextLayout::new("Bonjour le monde", 18.0, FontWeight::Regular, false);
1846 let mut prev = -1.0;
1847 for i in 0..=16 {
1848 let x = layout.caret_rect(i).x;
1849 assert!(x >= prev, "offset decreasing at boundary {i}");
1850 prev = x;
1851 }
1852 assert!((layout.caret_rect(16).x - layout.size().width).abs() < 0.5);
1854 assert_eq!(layout.caret_rect(99).x, layout.caret_rect(16).x);
1856 }
1857
1858 #[test]
1859 fn hit_test_roundtrips_caret_positions() {
1860 let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
1861 for i in 0..=7 {
1862 let caret = layout.caret_rect(i);
1863 let hit = layout.hit_test(Point::new(caret.x, caret.y + 1.0));
1864 assert_eq!(hit, i, "caret->hit round trip at boundary {i}");
1865 }
1866 assert_eq!(layout.hit_test(Point::new(-100.0, 0.0)), 0);
1868 assert_eq!(layout.hit_test(Point::new(10_000.0, 0.0)), 7);
1869 }
1870
1871 #[test]
1872 fn selection_rects_cover_the_range() {
1873 let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
1874 let rects = layout.selection_rects(2, 5);
1875 assert_eq!(rects.len(), 1);
1876 let r = rects[0];
1877 assert!((r.x - layout.caret_rect(2).x).abs() < 0.01);
1878 assert!((r.x + r.width - layout.caret_rect(5).x).abs() < 0.01);
1879 assert!(r.height > 0.0);
1880 assert!(layout.selection_rects(3, 3).is_empty());
1882 assert!(layout.selection_rects(5, 2).is_empty());
1883 }
1884
1885 #[test]
1886 fn multiline_layout_maps_lines_and_indices() {
1887 let layout = TextLayout::new("ab\ncd", 18.0, FontWeight::Regular, false);
1889 let first = layout.caret_rect(0);
1890 let second = layout.caret_rect(3);
1891 assert!(second.y > first.y, "the 2nd line sits lower");
1892 assert_eq!(second.x, 0.0, "second line starts at x = 0");
1893 let hit = layout.hit_test(Point::new(0.0, second.y + 1.0));
1895 assert_eq!(hit, 3);
1896 }
1897
1898 #[test]
1899 fn soft_wrap_indexes_chars_correctly_across_lines() {
1900 let text = "aaaa bbbb cccc dddd"; let layout = TextLayout::wrapped(text, 18.0, FontWeight::Regular, false, Some(60.0));
1905 assert!(
1906 layout.size().height > line_height(18.0) * 2.0,
1907 "several visual lines"
1908 );
1909
1910 let mut prev_y = -1.0;
1913 for &start in &[0usize, 5, 10, 15] {
1914 let c = layout.caret_rect(start);
1915 assert!(c.x < 1.0, "word start {start} at x about 0 (x={})", c.x);
1916 assert!(c.y > prev_y, "lines of increasing y at {start}");
1917 prev_y = c.y;
1918 }
1919 let c = layout.caret_rect(11);
1922 assert_eq!(layout.hit_test(Point::new(c.x, c.y + 1.0)), 11);
1923 assert_eq!(layout.caret_rect(19).x, layout.caret_rect(99).x);
1925 assert_eq!(layout.caret_rect(19).y, layout.caret_rect(99).y);
1926 }
1927
1928 #[test]
1929 fn empty_layout_keeps_caret_at_origin() {
1930 let layout = TextLayout::new("", 18.0, FontWeight::Regular, false);
1931 let caret = layout.caret_rect(0);
1932 assert_eq!(caret.x, 0.0);
1933 assert!(caret.height > 0.0, "wrapped line height");
1934 assert_eq!(layout.hit_test(Point::new(50.0, 0.0)), 0);
1935 }
1936
1937 #[test]
1943 #[cfg(all(
1944 feature = "bundled-sans",
1945 feature = "bundled-italic",
1946 feature = "bundled-mono"
1947 ))]
1948 fn embedded_only_font_system_shapes_every_style() {
1949 let mut db = cosmic_text::fontdb::Database::new();
1950 db.load_font_data(DEJAVU_SANS.to_vec());
1951 db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
1952 db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
1953 db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
1954 db.load_font_data(DEJAVU_MONO.to_vec());
1955 db.set_sans_serif_family(SANS_FAMILY);
1956 db.set_serif_family(SANS_FAMILY);
1957 db.set_cursive_family(SANS_FAMILY);
1958 db.set_fantasy_family(SANS_FAMILY);
1959 db.set_monospace_family(MONO_FAMILY);
1960 let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
1961
1962 for weight in [
1963 FontWeight::Regular,
1964 FontWeight::Medium,
1965 FontWeight::SemiBold,
1966 FontWeight::Bold,
1967 ] {
1968 for italic in [false, true] {
1969 let attrs = Attrs::new()
1970 .weight(Weight(available_weight(weight)))
1971 .style(if italic { Style::Italic } else { Style::Normal });
1972 let mut buffer = Buffer::new(&mut fs, Metrics::new(20.0, 24.0));
1973 buffer.set_size(None, None);
1974 buffer.set_text("Nothing to show", &attrs, Shaping::Advanced, None);
1975 buffer.shape_until_scroll(&mut fs, false); let w: f32 = buffer.layout_runs().map(|r| r.line_w).fold(0.0, f32::max);
1977 assert!(w > 0.0, "weight {weight:?} italic {italic}: nothing shaped");
1978 }
1979 }
1980 }
1981
1982 struct FontDir(std::path::PathBuf);
1984
1985 impl FontDir {
1986 fn new(tag: &str) -> Self {
1987 let dir = std::env::temp_dir().join(format!("frus-fonts-{tag}-{}", std::process::id()));
1988 let _ = std::fs::remove_dir_all(&dir);
1989 std::fs::create_dir_all(&dir).expect("a scratch font directory");
1990 Self(dir)
1991 }
1992
1993 fn put(&self, name: &str, bytes: &[u8]) {
1994 std::fs::write(self.0.join(name), bytes).expect("a scratch font file");
1995 }
1996 }
1997
1998 impl Drop for FontDir {
1999 fn drop(&mut self) {
2000 let _ = std::fs::remove_dir_all(&self.0);
2001 }
2002 }
2003
2004 #[test]
2011 #[cfg(feature = "bundled-sans")]
2012 fn only_the_emoji_faces_are_taken_from_a_font_directory() {
2013 let dir = FontDir::new("filter");
2014 dir.put("NotoColorEmoji.ttf", DEJAVU_SANS);
2015 dir.put("Roboto-Regular.ttf", DEJAVU_SANS);
2016 dir.put("emoji-notes.txt", DEJAVU_SANS);
2017 let mut db = cosmic_text::fontdb::Database::new();
2018 assert_eq!(load_emoji_faces(&mut db, &dir.0), 1, "one file taken");
2019 assert_eq!(db.faces().count(), 1, "and one face in the database");
2020 assert_eq!(load_emoji_faces(&mut db, &dir.0.join("absent")), 0);
2022 }
2023
2024 #[test]
2027 #[cfg(feature = "bundled-sans")]
2028 fn the_platform_sans_is_robotos_files_and_nothing_else() {
2029 let dir = FontDir::new("platform-sans");
2030 dir.put("Roboto-Regular.ttf", DEJAVU_SANS);
2031 dir.put("Roboto-Bold.ttf", DEJAVU_SANS_BOLD);
2032 dir.put("RobotoCondensed-Regular.ttf", DEJAVU_SANS);
2033 dir.put("NotoColorEmoji.ttf", DEJAVU_SANS);
2034 dir.put("roboto-notes.txt", DEJAVU_SANS);
2035 let mut db = cosmic_text::fontdb::Database::new();
2036 assert_eq!(load_platform_sans(&mut db, &dir.0), 2, "two files taken");
2037 assert_eq!(db.faces().count(), 2);
2038 assert_eq!(load_platform_sans(&mut db, &dir.0.join("absent")), 0);
2039 }
2040
2041 #[test]
2046 fn a_family_name_finds_the_one_inside_the_file() {
2047 let loaded: Vec<String> = ["DejaVu Sans", "DejaVu Sans Mono", "Inter 24pt", "Open Sans"]
2048 .map(String::from)
2049 .to_vec();
2050 let none: Vec<String> = Vec::new();
2051 assert_eq!(
2053 match_family("DejaVu Sans", &loaded, &none),
2054 Some("DejaVu Sans")
2055 );
2056 assert_eq!(match_family("open-sans", &loaded, &none), Some("Open Sans"));
2058 assert_eq!(match_family("OPENSANS", &loaded, &none), Some("Open Sans"));
2059 assert_eq!(match_family("Inter", &loaded, &none), Some("Inter 24pt"));
2061 assert_eq!(match_family("inter", &loaded, &none), Some("Inter 24pt"));
2062 assert_eq!(match_family("DejaVu", &loaded, &none), Some("DejaVu Sans"));
2064 let mono = vec!["DejaVu Sans Mono".to_string()];
2065 assert_eq!(
2066 match_family("DejaVu", &loaded, &mono),
2067 Some("DejaVu Sans Mono")
2068 );
2069 assert_eq!(match_family("Inter Tight", &loaded, &none), None);
2071 assert_eq!(match_family("Int", &loaded, &none), None);
2072 assert_eq!(match_family("Roboto", &loaded, &none), None);
2073 }
2074
2075 #[test]
2077 fn a_weight_snaps_to_the_nearest_loaded_by_the_webs_rule() {
2078 let bundled = [(400, 400), (700, 700)];
2079 assert_eq!(nearest_weight(400, &bundled), 400);
2081 assert_eq!(nearest_weight(500, &bundled), 400);
2082 assert_eq!(nearest_weight(600, &bundled), 700);
2083 assert_eq!(nearest_weight(300, &bundled), 400);
2084 assert_eq!(nearest_weight(900, &bundled), 700);
2085 let four = [(400, 400), (500, 500), (600, 600), (700, 700)];
2087 for weight in [400, 500, 600, 700] {
2088 assert_eq!(nearest_weight(weight, &four), weight);
2089 }
2090 assert_eq!(nearest_weight(400, &[(300, 300), (500, 500)]), 500);
2092 assert_eq!(nearest_weight(450, &[(300, 300), (600, 600)]), 300);
2093 assert_eq!(nearest_weight(350, &[(300, 300), (400, 400)]), 300);
2095 assert_eq!(nearest_weight(550, &[(500, 500), (600, 600)]), 600);
2096 assert_eq!(nearest_weight(650, &[(100, 900)]), 650);
2098 assert_eq!(nearest_weight(950, &[(100, 900)]), 900);
2099 assert_eq!(nearest_weight(500, &[]), 500);
2101 }
2102
2103 #[test]
2106 #[cfg(all(feature = "bundled-sans", feature = "bundled-italic"))]
2107 fn the_inventory_reads_the_faces_loaded() {
2108 assert_eq!(families_in(DEJAVU_SANS), vec!["DejaVu Sans".to_string()]);
2109 assert!(families_in(b"not a font").is_empty());
2110
2111 let mut db = cosmic_text::fontdb::Database::new();
2112 db.load_font_data(DEJAVU_SANS.to_vec());
2113 db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
2114 db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
2115 let mut loaded = Loaded::of(&db);
2116 loaded.app.clear();
2117 assert_eq!(loaded.text, vec!["DejaVu Sans".to_string()]);
2118 assert_eq!(loaded.slanted, vec!["DejaVu Sans".to_string()]);
2119 assert_eq!(weights_of(&db, "DejaVu Sans"), vec![(400, 400), (700, 700)]);
2120 assert!(weights_of(&db, "Inter").is_empty());
2121
2122 assert!(!loaded.generic_sans);
2124 assert!(
2125 !loaded.wants_platform_sans(Some("DejaVu")),
2126 "a name it plainly means"
2127 );
2128 assert!(
2129 loaded.wants_platform_sans(Some("Inter")),
2130 "a name nothing answers to"
2131 );
2132 assert!(
2133 loaded.wants_platform_sans(None),
2134 "no name, and no generic either"
2135 );
2136 loaded.app = vec!["DejaVu Sans".to_string()];
2139 assert!(!loaded.wants_platform_sans(Some("Inter")));
2140 assert_eq!(loaded.fallback(), Some("DejaVu Sans"));
2141 }
2142
2143 #[test]
2147 #[cfg(feature = "bundled-sans")]
2148 fn a_family_found_by_its_plain_name_draws_real_glyphs() {
2149 let mut db = cosmic_text::fontdb::Database::new();
2150 db.load_font_data(DEJAVU_SANS.to_vec());
2151 let face = db.faces().next().map(|face| face.id).expect("the face");
2152 let loaded = Loaded::of(&db);
2153 let family = match_family("dejavu", &loaded.families, &[]).expect("found");
2154 let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2155 let mut buffer = Buffer::new(&mut fs, Metrics::new(20.0, 24.0));
2156 buffer.set_size(None, None);
2157 let attrs = Attrs::new().family(cosmic_text::Family::Name(family));
2158 buffer.set_text("Hello", &attrs, Shaping::Advanced, None);
2159 buffer.shape_until_scroll(&mut fs, false);
2160 let glyphs: Vec<_> = buffer
2161 .layout_runs()
2162 .flat_map(|run| run.glyphs.iter())
2163 .map(|glyph| (glyph.font_id, glyph.glyph_id))
2164 .collect();
2165 assert_eq!(glyphs.len(), 5);
2166 assert!(glyphs
2167 .iter()
2168 .all(|&(font, glyph)| font == face && glyph != 0));
2169 }
2170
2171 #[test]
2179 #[cfg(feature = "bundled-sans")]
2180 fn an_emoji_is_drawn_from_the_emoji_face_the_runs_font_lacks() {
2181 let emoji = std::path::Path::new("C:\\Windows\\Fonts\\seguiemj.ttf");
2182 if !emoji.exists() {
2183 eprintln!("no colour emoji font at {}; skipped", emoji.display());
2184 return;
2185 }
2186 let mut db = cosmic_text::fontdb::Database::new();
2187 db.load_font_data(DEJAVU_SANS.to_vec());
2188 db.load_font_file(emoji).expect("the emoji font");
2189 db.set_sans_serif_family(SANS_FAMILY);
2190 let emoji_face = db
2191 .faces()
2192 .find(|face| face.post_script_name.contains("Emoji"))
2193 .map(|face| face.id)
2194 .expect("an emoji face");
2195 let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2196
2197 let text = "Hi \u{1F44B}";
2198 let at = text.find('\u{1F44B}').expect("the wave");
2199 let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
2200 buffer.set_size(None, None);
2201 buffer.set_text(
2202 text,
2203 &Attrs::new().family(family_for(text)),
2204 Shaping::Advanced,
2205 None,
2206 );
2207 buffer.shape_until_scroll(&mut fs, false);
2208 let (font, glyph) = buffer
2209 .layout_runs()
2210 .flat_map(|run| run.glyphs.iter())
2211 .find(|glyph| glyph.start == at)
2212 .map(|glyph| (glyph.font_id, glyph.glyph_id))
2213 .expect("a glyph for the emoji");
2214 assert_eq!(font, emoji_face, "the emoji comes from the emoji face");
2215 assert_ne!(glyph, 0, "and is a real glyph, not the empty box");
2216 }
2217
2218 #[test]
2225 #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
2226 fn arabic_shapes_with_embedded_only_font_system() {
2227 let mut db = cosmic_text::fontdb::Database::new();
2228 db.load_font_data(DEJAVU_SANS.to_vec());
2229 db.load_font_data(NOTO_ARABIC.to_vec());
2230 db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
2231 db.set_sans_serif_family(SANS_FAMILY);
2232 let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2233
2234 let text = "مهامي";
2235 let attrs = Attrs::new().family(family_for(text));
2236 let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
2237 buffer.set_size(None, None);
2238 buffer.set_text(text, &attrs, Shaping::Advanced, None);
2239 buffer.shape_until_scroll(&mut fs, false);
2240
2241 let mut glyphs = 0usize;
2242 let mut real = 0usize; for run in buffer.layout_runs() {
2244 for g in run.glyphs.iter() {
2245 glyphs += 1;
2246 if g.glyph_id != 0 {
2247 real += 1;
2248 }
2249 }
2250 }
2251 assert!(glyphs > 0, "no glyph shaped for Arabic");
2252 assert!(
2253 real > 0,
2254 "only .notdef ({glyphs} glyphs, 0 real): Family::Name(\"{ARABIC_FAMILY}\") did not resolve the Naskh face"
2255 );
2256 }
2257
2258 #[test]
2264 #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
2265 fn rtl_right_aligns_to_buffer_width() {
2266 let mut db = cosmic_text::fontdb::Database::new();
2267 db.load_font_data(DEJAVU_SANS.to_vec());
2268 db.load_font_data(NOTO_ARABIC.to_vec());
2269 db.set_sans_serif_family(SANS_FAMILY);
2270 let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
2271 let text = "العربية";
2272 let attrs = Attrs::new().family(family_for(text));
2273
2274 let mut first_glyph_x = |width: Option<f32>| {
2275 let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
2276 buffer.set_size(width, Some(200.0));
2277 buffer.set_text(text, &attrs, Shaping::Advanced, None);
2278 buffer.shape_until_scroll(&mut fs, false);
2279 buffer
2280 .layout_runs()
2281 .flat_map(|r| r.glyphs.iter().map(|g| g.x))
2282 .fold(f32::MAX, f32::min)
2283 };
2284
2285 let wide = first_glyph_x(Some(1080.0));
2286 let free = first_glyph_x(None);
2287 assert!(wide > 500.0, "a wide RTL run should push right (x={wide})");
2288 assert!(
2289 free < 50.0,
2290 "an unconstrained RTL run should start left (x={free})"
2291 );
2292 }
2293
2294 #[test]
2295 #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
2296 fn arabic_falls_back_to_the_embedded_naskh_face() {
2297 let hello = "مرحبا بالعالم"; let m = measure(hello, 24.0);
2302 assert!(m.width > 60.0, "Arabic must shape (width {})", m.width);
2303 assert!(m.height > 0.0);
2304
2305 let latin = measure("Hello", 24.0);
2307 assert!(latin.width > 0.0);
2308
2309 let mixed = measure("قيمة 42 نقطة", 24.0);
2312 assert!(mixed.width > 0.0, "mixed bidi text was not shaped");
2313 }
2314
2315 #[test]
2316 fn weights_snap_to_embedded_faces() {
2317 assert_eq!(available_weight(FontWeight::Regular), 400);
2321 assert_eq!(available_weight(FontWeight::Medium), 400);
2322 assert_eq!(available_weight(FontWeight::SemiBold), 700);
2323 assert_eq!(available_weight(FontWeight::Bold), 700);
2324 let text = "Titre de section";
2327 let regular = measure_styled(text, 20.0, FontWeight::Regular, false);
2328 let medium = measure_styled(text, 20.0, FontWeight::Medium, false);
2329 assert_eq!(medium.width, regular.width);
2330 let semibold = measure_styled(text, 20.0, FontWeight::SemiBold, false);
2331 let bold = measure_styled(text, 20.0, FontWeight::Bold, false);
2332 assert_eq!(semibold.width, bold.width);
2333 assert!(bold.width > regular.width);
2334 }
2335
2336 #[test]
2341 fn the_natural_width_is_never_rounded_down_below_the_text() {
2342 for text in ["Write code", "Bonjour le monde", "A", "iiiii"] {
2343 for size in [12.0_f32, 15.0, 20.0, 24.0] {
2344 let natural = measure_styled(text, size, FontWeight::Bold, false);
2345 assert_eq!(
2346 natural.width,
2347 natural.width.ceil(),
2348 "a whole number for {text:?} at {size}: {}",
2349 natural.width
2350 );
2351 let at_its_width =
2353 measure_wrapped(text, size, FontWeight::Bold, false, Some(natural.width));
2354 assert_eq!(
2355 at_its_width.height, natural.height,
2356 "{text:?} at {size} wrapped inside its own width"
2357 );
2358 }
2359 }
2360 }
2361
2362 #[test]
2371 fn the_natural_height_is_a_whole_number_too() {
2372 for text in ["Write code", "one two three four five six seven eight", "A"] {
2373 for size in [12.0_f32, 15.0, 20.0, 24.0] {
2374 for width in [None, Some(60.0), Some(120.0)] {
2375 let measured = measure_wrapped(text, size, FontWeight::Bold, false, width);
2376 assert_eq!(
2377 measured.height,
2378 measured.height.ceil(),
2379 "a whole number for {text:?} at {size} in {width:?}: {}",
2380 measured.height
2381 );
2382 }
2383 }
2384 }
2385 let empty = measure_styled("", 16.0, FontWeight::Regular, false);
2388 assert_eq!(empty.height, empty.height.ceil(), "{}", empty.height);
2389 assert!(empty.height >= line_height(16.0));
2390 }
2391
2392 #[test]
2395 fn a_constrained_measurement_never_exceeds_its_constraint() {
2396 let measured = measure_wrapped(
2397 "A rather long sentence that has to wrap somewhere",
2398 18.0,
2399 FontWeight::Regular,
2400 false,
2401 Some(120.0),
2402 );
2403 assert!(measured.width <= 120.0, "{}", measured.width);
2404 }
2405
2406 #[test]
2411 fn italic_measures_whether_or_not_an_oblique_face_is_bundled() {
2412 let measured = measure_styled("Slanted", 16.0, FontWeight::Regular, true);
2413 assert!(measured.width > 0.0, "nothing shaped");
2414 }
2415
2416 #[test]
2419 fn italic_is_only_asked_for_when_a_face_can_answer() {
2420 let _ = measure("x", 12.0);
2422 assert_eq!(
2423 available_style(false),
2424 Style::Normal,
2425 "upright asked for italic"
2426 );
2427 assert_eq!(
2428 available_style(true) == Style::Italic,
2429 ITALIC.load(Ordering::Relaxed),
2430 "italic asked for without a face to answer it"
2431 );
2432 }
2433
2434 #[test]
2435 fn bold_measures_wider_than_regular() {
2436 let regular = measure_styled("Bonjour le monde", 24.0, FontWeight::Regular, false);
2439 let bold = measure_styled("Bonjour le monde", 24.0, FontWeight::Bold, false);
2440 assert!(
2441 bold.width > regular.width,
2442 "gras {} <= normal {}",
2443 bold.width,
2444 regular.width
2445 );
2446 }
2447
2448 #[test]
2451 fn a_cached_measurement_is_the_measurement() {
2452 for (text, size) in [("Open", 15.0_f32), ("Task number 42 — due Friday", 13.0)] {
2453 let first = measure(text, size);
2454 let second = measure(text, size);
2455 assert_eq!(
2456 first, second,
2457 "{text:?} measured differently the second time"
2458 );
2459
2460 let styled = measure_styled(text, size, FontWeight::Bold, false);
2461 assert_eq!(
2462 styled,
2463 measure_styled(text, size, FontWeight::Bold, false),
2464 "{text:?} bold measured differently the second time"
2465 );
2466
2467 let wrapped = measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0));
2468 assert_eq!(
2469 wrapped,
2470 measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0)),
2471 "{text:?} wrapped measured differently the second time"
2472 );
2473 assert!(
2476 wrapped.height >= first.height,
2477 "wrapping to 60 px should not make {text:?} shorter"
2478 );
2479 }
2480 }
2481
2482 #[test]
2486 fn a_string_still_in_use_survives_the_rotation() {
2487 let kept = measure("still here", 14.0);
2488 for i in 0..(CACHE_CAP * 2 + 64) {
2489 measure(&format!("filler {i}"), 14.0);
2490 if i % 512 == 0 {
2491 assert_eq!(kept, measure("still here", 14.0), "lost at {i}");
2492 }
2493 }
2494 assert_eq!(kept, measure("still here", 14.0));
2495 }
2496
2497 #[test]
2500 fn registering_a_font_forgets_what_was_measured() {
2501 let before = measure("forget me", 15.0);
2502 forget_measurements();
2503 let after = measure("forget me", 15.0);
2504 assert_eq!(before, after, "the same faces must measure the same");
2505 }
2506 #[test]
2509 fn a_baseline_sits_where_a_line_of_text_does() {
2510 let size = 20.0;
2511 let b = baseline(size, FontWeight::Regular, false);
2512 let line = line_height(size);
2513 assert!(b > 0.0 && b < line, "inside the line box: {b} of {line}");
2514 assert!(b > line * 0.5, "and below its middle: {b} of {line}");
2515 }
2516
2517 #[test]
2520 fn a_bigger_face_has_a_lower_baseline() {
2521 let small = baseline(12.0, FontWeight::Regular, false);
2522 let large = baseline(24.0, FontWeight::Regular, false);
2523 assert!(large > small * 1.5, "{small} then {large}");
2524 }
2525
2526 #[test]
2529 fn mixed_runs_take_the_tallest_baseline() {
2530 let run = |text: &str, size: f32| TextRun {
2531 text: text.into(),
2532 size,
2533 weight: FontWeight::Regular,
2534 italic: false,
2535 color: frus_core::Color::WHITE,
2536 decoration: frus_core::TextDecoration::default(),
2537 decoration_color: None,
2538 letter_spacing: 0.0,
2539 };
2540 let runs = vec![run("small", 12.0), run("large", 24.0)];
2541 let mixed = baseline_of_runs(&runs).expect("two runs");
2542 assert!((mixed - baseline(24.0, FontWeight::Regular, false)).abs() < 0.01);
2543 }
2544
2545 #[test]
2551 fn a_named_line_height_reaches_the_measurement() {
2552 let words = "one two three four five six seven eight nine ten";
2553 let plain = ResolvedTextStyle::exact(16.0);
2554 let open = ResolvedTextStyle {
2555 height: Some(2.4),
2556 ..plain
2557 };
2558 let a = measure_wrapped_resolved(words, &plain, Some(80.0));
2560 let b = measure_wrapped_resolved(words, &open, Some(80.0));
2561 assert!(a.height > 0.0 && b.height > 0.0);
2562 assert_eq!(
2563 a.width, b.width,
2564 "the line height changes the stacking, never the letters"
2565 );
2566 let ratio = b.height / a.height;
2567 assert!(
2568 (ratio - 2.0).abs() < 0.01,
2569 "doubling the line height doubles the block: {ratio}"
2570 );
2571 }
2572
2573 #[test]
2576 fn two_line_heights_do_not_share_a_cached_answer() {
2577 let words = "cached words that wrap across a couple of lines here";
2578 let packed = ResolvedTextStyle {
2579 height: Some(1.0),
2580 ..ResolvedTextStyle::exact(14.0)
2581 };
2582 let open = ResolvedTextStyle {
2583 height: Some(2.0),
2584 ..ResolvedTextStyle::exact(14.0)
2585 };
2586 let first = measure_wrapped_resolved(words, &packed, Some(90.0));
2587 let second = measure_wrapped_resolved(words, &open, Some(90.0));
2588 assert_eq!(measure_wrapped_resolved(words, &open, Some(90.0)), second);
2591 assert_eq!(measure_wrapped_resolved(words, &packed, Some(90.0)), first);
2592 assert!(second.height > first.height);
2593 }
2594
2595 #[test]
2597 fn a_line_box_follows_the_height_it_was_given() {
2598 let open = ResolvedTextStyle {
2599 height: Some(3.0),
2600 ..ResolvedTextStyle::exact(16.0)
2601 };
2602 assert_eq!(line_box(32.0, &ResolvedTextStyle::exact(16.0), 0.0), 32.0);
2603 assert_eq!(
2604 line_box(32.0, &open, 0.0),
2605 48.0,
2606 "the content wins over the floor"
2607 );
2608 }
2609
2610 #[test]
2613 fn a_named_family_reaches_the_measurement() {
2614 let words = "The quick brown fox";
2615 let plain = ResolvedTextStyle::exact(16.0);
2616 let mono = ResolvedTextStyle {
2617 family: Some(frus_core::FontFamily::Monospace),
2618 ..plain
2619 };
2620 let a = measure_wrapped_resolved(words, &plain, None);
2621 let b = measure_wrapped_resolved(words, &mono, None);
2622 assert!(a.width > 0.0 && b.width > 0.0);
2623 assert_ne!(
2624 a.width, b.width,
2625 "a monospaced face sets these words to a different width"
2626 );
2627 }
2628
2629 #[test]
2637 fn arabic_keeps_its_face_whatever_was_named() {
2638 let arabic = "\u{0645}\u{0631}\u{062d}\u{0628}\u{0627}";
2639 let named = family_for_style(arabic, Some(frus_core::FontFamily::Monospace));
2640 assert_eq!(
2641 format!("{named:?}"),
2642 format!("{:?}", family_for(arabic)),
2643 "the script wins over the name"
2644 );
2645 let latin = family_for_style("hello", Some(frus_core::FontFamily::Monospace));
2647 assert_eq!(format!("{latin:?}"), format!("{:?}", monospace_family()));
2648 }
2649
2650 #[test]
2653 fn two_families_do_not_share_a_cached_answer() {
2654 let words = "shared words in two faces";
2655 let plain = ResolvedTextStyle::exact(15.0);
2656 let mono = ResolvedTextStyle {
2657 family: Some(frus_core::FontFamily::Monospace),
2658 ..plain
2659 };
2660 let first = measure_wrapped_resolved(words, &plain, None);
2661 let second = measure_wrapped_resolved(words, &mono, None);
2662 assert_eq!(measure_wrapped_resolved(words, &mono, None), second);
2665 assert_eq!(measure_wrapped_resolved(words, &plain, None), first);
2666 assert_ne!(first.width, second.width);
2667 }
2668}