1mod font_fallbacks;
2mod font_features;
3mod line;
4mod line_layout;
5mod line_wrapper;
6
7pub use font_fallbacks::*;
8pub use font_features::*;
9pub use line::*;
10pub use line_layout::*;
11pub use line_wrapper::*;
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
17 StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,
18};
19use anyhow::{Context as _, anyhow};
20use collections::FxHashMap;
21use core::fmt;
22use derive_more::{Add, Deref, FromStr, Sub};
23use itertools::Itertools;
24use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
25use smallvec::{SmallVec, smallvec};
26use std::{
27 borrow::Cow,
28 cmp,
29 fmt::{Debug, Display, Formatter},
30 hash::{Hash, Hasher},
31 ops::{Deref, DerefMut, Range},
32 sync::Arc,
33};
34
35#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
37#[repr(C)]
38pub struct FontId(pub usize);
39
40#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
42pub struct FontFamilyId(pub usize);
43
44pub const SUBPIXEL_VARIANTS_X: u8 = 4;
46
47pub const SUBPIXEL_VARIANTS_Y: u8 = 1;
49
50pub struct TextSystem {
52 platform_text_system: Arc<dyn PlatformTextSystem>,
53 font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
54 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
55 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
56 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
57 font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
58 fallback_font_stack: SmallVec<[Font; 2]>,
59}
60
61impl TextSystem {
62 pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
64 TextSystem {
65 platform_text_system,
66 font_metrics: RwLock::default(),
67 raster_bounds: RwLock::default(),
68 font_ids_by_font: RwLock::default(),
69 wrapper_pool: Mutex::default(),
70 font_runs_pool: Mutex::default(),
71 fallback_font_stack: smallvec![
72 font(".ZedMono"),
74 font(".ZedSans"),
75 font("Helvetica"),
76 font("Segoe UI"), font("Ubuntu"), font("Adwaita Sans"), font("Cantarell"), font("Noto Sans"), font("DejaVu Sans"),
82 font("Arial"), ],
84 }
85 }
86
87 pub fn all_font_names(&self) -> Vec<String> {
89 let mut names = self.platform_text_system.all_font_names();
90 names.extend(
91 self.fallback_font_stack
92 .iter()
93 .map(|font| font.family.to_string()),
94 );
95 names.push(".SystemUIFont".to_string());
96 names.sort();
97 names.dedup();
98 names
99 }
100
101 pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
103 self.platform_text_system.add_fonts(fonts)
104 }
105
106 fn font_id(&self, font: &Font) -> Result<FontId> {
108 fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {
109 match font_id {
110 Ok(font_id) => Ok(*font_id),
111 Err(err) => Err(anyhow!("{err}")),
112 }
113 }
114
115 let font_id = self
116 .font_ids_by_font
117 .read()
118 .get(font)
119 .map(clone_font_id_result);
120 if let Some(font_id) = font_id {
121 font_id
122 } else {
123 let font_id = self.platform_text_system.font_id(font);
124 self.font_ids_by_font
125 .write()
126 .insert(font.clone(), clone_font_id_result(&font_id));
127 font_id
128 }
129 }
130
131 pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
133 let lock = self.font_ids_by_font.read();
134 lock.iter()
135 .filter_map(|(font, result)| match result {
136 Ok(font_id) if *font_id == id => Some(font.clone()),
137 _ => None,
138 })
139 .next()
140 }
141
142 pub fn resolve_font(&self, font: &Font) -> FontId {
149 if let Ok(font_id) = self.font_id(font) {
150 return font_id;
151 }
152 for fallback in &self.fallback_font_stack {
153 if let Ok(font_id) = self.font_id(fallback) {
154 return font_id;
155 }
156 }
157
158 panic!(
159 "failed to resolve font '{}' or any of the fallbacks: {}",
160 font.family,
161 self.fallback_font_stack
162 .iter()
163 .map(|fallback| &fallback.family)
164 .join(", ")
165 );
166 }
167
168 pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
172 self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
173 }
174
175 pub fn typographic_bounds(
177 &self,
178 font_id: FontId,
179 font_size: Pixels,
180 character: char,
181 ) -> Result<Bounds<Pixels>> {
182 let glyph_id = self
183 .platform_text_system
184 .glyph_for_char(font_id, character)
185 .with_context(|| format!("glyph not found for character '{character}'"))?;
186 let bounds = self
187 .platform_text_system
188 .typographic_bounds(font_id, glyph_id)?;
189 Ok(self.read_metrics(font_id, |metrics| {
190 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
191 }))
192 }
193
194 pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
196 let glyph_id = self
197 .platform_text_system
198 .glyph_for_char(font_id, ch)
199 .with_context(|| format!("glyph not found for character '{ch}'"))?;
200 let result = self.platform_text_system.advance(font_id, glyph_id)?
201 / self.units_per_em(font_id) as f32;
202
203 Ok(result * font_size)
204 }
205
206 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
209 let mut buffer = [0; 4];
210 let buffer = ch.encode_utf8(&mut buffer);
211 self.platform_text_system
212 .layout_line(
213 buffer,
214 font_size,
215 &[FontRun {
216 len: buffer.len(),
217 font_id,
218 }],
219 )
220 .width
221 }
222
223 pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
227 Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
228 }
229
230 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
234 Ok(self.advance(font_id, font_size, 'm')?.width)
235 }
236
237 pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
240 self.layout_width(font_id, font_size, 'm')
241 }
242
243 pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
247 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
248 }
249
250 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
254 Ok(self.advance(font_id, font_size, '0')?.width)
255 }
256
257 pub fn units_per_em(&self, font_id: FontId) -> u32 {
261 self.read_metrics(font_id, |metrics| metrics.units_per_em)
262 }
263
264 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
266 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
267 }
268
269 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
271 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
272 }
273
274 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
276 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
277 }
278
279 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
282 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
283 }
284
285 pub fn baseline_offset(
287 &self,
288 font_id: FontId,
289 font_size: Pixels,
290 line_height: Pixels,
291 ) -> Pixels {
292 let ascent = self.ascent(font_id, font_size);
293 let descent = self.descent(font_id, font_size);
294 let padding_top = (line_height - ascent - descent) / 2.;
295 padding_top + ascent
296 }
297
298 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
299 let lock = self.font_metrics.upgradable_read();
300
301 if let Some(metrics) = lock.get(&font_id) {
302 read(metrics)
303 } else {
304 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
305 let metrics = lock
306 .entry(font_id)
307 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
308 read(metrics)
309 }
310 }
311
312 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
314 let lock = &mut self.wrapper_pool.lock();
315 let font_id = self.resolve_font(&font);
316 let wrappers = lock
317 .entry(FontIdWithSize { font_id, font_size })
318 .or_default();
319 let wrapper = wrappers
320 .pop()
321 .unwrap_or_else(|| LineWrapper::new(font_id, font_size, self.clone()));
322
323 LineWrapperHandle {
324 wrapper: Some(wrapper),
325 text_system: self.clone(),
326 }
327 }
328
329 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
331 let raster_bounds = self.raster_bounds.upgradable_read();
332 if let Some(bounds) = raster_bounds.get(params) {
333 Ok(*bounds)
334 } else {
335 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
336 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
337 raster_bounds.insert(params.clone(), bounds);
338 Ok(bounds)
339 }
340 }
341
342 pub(crate) fn rasterize_glyph(
343 &self,
344 params: &RenderGlyphParams,
345 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
346 let raster_bounds = self.raster_bounds(params)?;
347 self.platform_text_system
348 .rasterize_glyph(params, raster_bounds)
349 }
350
351 pub(crate) fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
353 self.platform_text_system.glyph_dilation_for_color(color)
354 }
355
356 pub(crate) fn recommended_rendering_mode(
359 &self,
360 font_id: FontId,
361 font_size: Pixels,
362 ) -> TextRenderingMode {
363 self.platform_text_system
364 .recommended_rendering_mode(font_id, font_size)
365 }
366}
367
368#[derive(Deref)]
370pub struct WindowTextSystem {
371 line_layout_cache: LineLayoutCache,
372 #[deref]
373 text_system: Arc<TextSystem>,
374}
375
376impl WindowTextSystem {
377 pub fn new(text_system: Arc<TextSystem>) -> Self {
379 Self {
380 line_layout_cache: LineLayoutCache::new(text_system.platform_text_system.clone()),
381 text_system,
382 }
383 }
384
385 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
386 self.line_layout_cache.layout_index()
387 }
388
389 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
390 self.line_layout_cache.reuse_layouts(index)
391 }
392
393 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
394 self.line_layout_cache.truncate_layouts(index)
395 }
396
397 pub fn shape_line(
404 &self,
405 text: SharedString,
406 font_size: Pixels,
407 runs: &[TextRun],
408 force_width: Option<Pixels>,
409 ) -> ShapedLine {
410 debug_assert!(
411 text.find('\n').is_none(),
412 "text argument should not contain newlines"
413 );
414
415 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
416 for run in runs {
417 if let Some(last_run) = decoration_runs.last_mut()
418 && last_run.color == run.color
419 && last_run.underline == run.underline
420 && last_run.strikethrough == run.strikethrough
421 && last_run.background_color == run.background_color
422 {
423 last_run.len += run.len as u32;
424 continue;
425 }
426 decoration_runs.push(DecorationRun {
427 len: run.len as u32,
428 color: run.color,
429 background_color: run.background_color,
430 underline: run.underline,
431 strikethrough: run.strikethrough,
432 });
433 }
434
435 let layout = self.layout_line(&text, font_size, runs, force_width);
436
437 ShapedLine {
438 layout,
439 text,
440 decoration_runs,
441 }
442 }
443
444 pub fn shape_line_by_hash(
455 &self,
456 text_hash: u64,
457 text_len: usize,
458 font_size: Pixels,
459 runs: &[TextRun],
460 force_width: Option<Pixels>,
461 materialize_text: impl FnOnce() -> SharedString,
462 ) -> ShapedLine {
463 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
464 for run in runs {
465 if let Some(last_run) = decoration_runs.last_mut()
466 && last_run.color == run.color
467 && last_run.underline == run.underline
468 && last_run.strikethrough == run.strikethrough
469 && last_run.background_color == run.background_color
470 {
471 last_run.len += run.len as u32;
472 continue;
473 }
474 decoration_runs.push(DecorationRun {
475 len: run.len as u32,
476 color: run.color,
477 background_color: run.background_color,
478 underline: run.underline,
479 strikethrough: run.strikethrough,
480 });
481 }
482
483 let mut used_force_width = force_width;
484 let layout = self.layout_line_by_hash(
485 text_hash,
486 text_len,
487 font_size,
488 runs,
489 used_force_width,
490 || {
491 let text = materialize_text();
492 debug_assert!(
493 text.find('\n').is_none(),
494 "text argument should not contain newlines"
495 );
496 text
497 },
498 );
499
500 let text: SharedString = SharedString::new_static("");
504
505 ShapedLine {
506 layout,
507 text,
508 decoration_runs,
509 }
510 }
511
512 pub fn shape_text(
516 &self,
517 text: SharedString,
518 font_size: Pixels,
519 runs: &[TextRun],
520 wrap_width: Option<Pixels>,
521 line_clamp: Option<usize>,
522 ) -> Result<SmallVec<[WrappedLine; 1]>> {
523 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
524 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
525
526 let mut lines = SmallVec::new();
527 let mut max_wrap_lines = line_clamp;
528 let mut wrapped_lines = 0;
529
530 let mut process_line = |line_text: SharedString, line_start, line_end| {
531 font_runs.clear();
532
533 let mut decoration_runs = <Vec<DecorationRun>>::with_capacity(32);
534 let mut run_start = line_start;
535 while run_start < line_end {
536 let Some(run) = runs.peek_mut() else {
537 log::warn!("`TextRun`s do not cover the entire to be shaped text");
538 break;
539 };
540
541 let run_len_within_line = cmp::min(line_end - run_start, run.len);
542
543 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
544 && last_run.color == run.color
545 && last_run.underline == run.underline
546 && last_run.strikethrough == run.strikethrough
547 && last_run.background_color == run.background_color
548 {
549 last_run.len += run_len_within_line as u32;
550 false
551 } else {
552 decoration_runs.push(DecorationRun {
553 len: run_len_within_line as u32,
554 color: run.color,
555 background_color: run.background_color,
556 underline: run.underline,
557 strikethrough: run.strikethrough,
558 });
559 true
560 };
561
562 let font_id = self.resolve_font(&run.font);
563 if let Some(font_run) = font_runs.last_mut()
564 && font_id == font_run.font_id
565 && !decoration_changed
566 {
567 font_run.len += run_len_within_line;
568 } else {
569 font_runs.push(FontRun {
570 len: run_len_within_line,
571 font_id,
572 });
573 }
574
575 run.len -= run_len_within_line;
577 if run.len == 0 {
578 runs.next();
579 }
580 run_start += run_len_within_line;
581 }
582
583 let layout = self.line_layout_cache.layout_wrapped_line(
584 &line_text,
585 font_size,
586 &font_runs,
587 wrap_width,
588 max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
589 );
590 wrapped_lines += layout.wrap_boundaries.len();
591
592 lines.push(WrappedLine {
593 layout,
594 decoration_runs,
595 text: line_text,
596 });
597
598 if let Some(run) = runs.peek_mut() {
600 run.len -= 1;
601 if run.len == 0 {
602 runs.next();
603 }
604 }
605 };
606
607 let mut split_lines = text.split('\n');
608
609 if let Some(first_line) = split_lines.next()
611 && let Some(second_line) = split_lines.next()
612 {
613 let mut line_start = 0;
614 process_line(
615 SharedString::new(first_line),
616 line_start,
617 line_start + first_line.len(),
618 );
619 line_start += first_line.len() + '\n'.len_utf8();
620 process_line(
621 SharedString::new(second_line),
622 line_start,
623 line_start + second_line.len(),
624 );
625 for line_text in split_lines {
626 line_start += line_text.len() + '\n'.len_utf8();
627 process_line(
628 SharedString::new(line_text),
629 line_start,
630 line_start + line_text.len(),
631 );
632 }
633 } else {
634 let end = text.len();
635 process_line(text, 0, end);
636 }
637
638 self.font_runs_pool.lock().push(font_runs);
639
640 Ok(lines)
641 }
642
643 pub(crate) fn finish_frame(&self) {
644 self.line_layout_cache.finish_frame()
645 }
646
647 pub fn layout_line(
652 &self,
653 text: &str,
654 font_size: Pixels,
655 runs: &[TextRun],
656 force_width: Option<Pixels>,
657 ) -> Arc<LineLayout> {
658 let mut last_run = None::<&TextRun>;
659 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
660 font_runs.clear();
661
662 for run in runs.iter() {
663 let decoration_changed = if let Some(last_run) = last_run
664 && last_run.color == run.color
665 && last_run.underline == run.underline
666 && last_run.strikethrough == run.strikethrough
667 {
670 false
671 } else {
672 last_run = Some(run);
673 true
674 };
675
676 let font_id = self.resolve_font(&run.font);
677 if let Some(font_run) = font_runs.last_mut()
678 && font_id == font_run.font_id
679 && !decoration_changed
680 {
681 font_run.len += run.len;
682 } else {
683 font_runs.push(FontRun {
684 len: run.len,
685 font_id,
686 });
687 }
688 }
689
690 let layout = self.line_layout_cache.layout_line(
691 &SharedString::new(text),
692 font_size,
693 &font_runs,
694 force_width,
695 );
696
697 self.font_runs_pool.lock().push(font_runs);
698
699 layout
700 }
701
702 pub fn try_layout_line_by_hash(
711 &self,
712 text_hash: u64,
713 text_len: usize,
714 font_size: Pixels,
715 runs: &[TextRun],
716 force_width: Option<Pixels>,
717 ) -> Option<Arc<LineLayout>> {
718 let mut last_run = None::<&TextRun>;
719 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
720 font_runs.clear();
721
722 for run in runs.iter() {
723 let decoration_changed = if let Some(last_run) = last_run
724 && last_run.color == run.color
725 && last_run.underline == run.underline
726 && last_run.strikethrough == run.strikethrough
727 {
730 false
731 } else {
732 last_run = Some(run);
733 true
734 };
735
736 let font_id = self.resolve_font(&run.font);
737 if let Some(font_run) = font_runs.last_mut()
738 && font_id == font_run.font_id
739 && !decoration_changed
740 {
741 font_run.len += run.len;
742 } else {
743 font_runs.push(FontRun {
744 len: run.len,
745 font_id,
746 });
747 }
748 }
749
750 let layout = self.line_layout_cache.try_layout_line_by_hash(
751 text_hash,
752 text_len,
753 font_size,
754 &font_runs,
755 force_width,
756 );
757
758 self.font_runs_pool.lock().push(font_runs);
759
760 layout
761 }
762
763 pub fn layout_line_by_hash(
772 &self,
773 text_hash: u64,
774 text_len: usize,
775 font_size: Pixels,
776 runs: &[TextRun],
777 force_width: Option<Pixels>,
778 materialize_text: impl FnOnce() -> SharedString,
779 ) -> Arc<LineLayout> {
780 let mut last_run = None::<&TextRun>;
781 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
782 font_runs.clear();
783
784 for run in runs.iter() {
785 let decoration_changed = if let Some(last_run) = last_run
786 && last_run.color == run.color
787 && last_run.underline == run.underline
788 && last_run.strikethrough == run.strikethrough
789 {
792 false
793 } else {
794 last_run = Some(run);
795 true
796 };
797
798 let font_id = self.resolve_font(&run.font);
799 if let Some(font_run) = font_runs.last_mut()
800 && font_id == font_run.font_id
801 && !decoration_changed
802 {
803 font_run.len += run.len;
804 } else {
805 font_runs.push(FontRun {
806 len: run.len,
807 font_id,
808 });
809 }
810 }
811
812 let layout = self.line_layout_cache.layout_line_by_hash(
813 text_hash,
814 text_len,
815 font_size,
816 &font_runs,
817 force_width,
818 materialize_text,
819 );
820
821 self.font_runs_pool.lock().push(font_runs);
822
823 layout
824 }
825}
826
827#[derive(Hash, Eq, PartialEq)]
828struct FontIdWithSize {
829 font_id: FontId,
830 font_size: Pixels,
831}
832
833pub struct LineWrapperHandle {
835 wrapper: Option<LineWrapper>,
836 text_system: Arc<TextSystem>,
837}
838
839impl Drop for LineWrapperHandle {
840 fn drop(&mut self) {
841 let mut state = self.text_system.wrapper_pool.lock();
842 let wrapper = self.wrapper.take().unwrap();
843 state
844 .get_mut(&FontIdWithSize {
845 font_id: wrapper.font_id,
846 font_size: wrapper.font_size,
847 })
848 .unwrap()
849 .push(wrapper);
850 }
851}
852
853impl Deref for LineWrapperHandle {
854 type Target = LineWrapper;
855
856 fn deref(&self) -> &Self::Target {
857 self.wrapper.as_ref().unwrap()
858 }
859}
860
861impl DerefMut for LineWrapperHandle {
862 fn deref_mut(&mut self) -> &mut Self::Target {
863 self.wrapper.as_mut().unwrap()
864 }
865}
866
867#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
870#[serde(transparent)]
871pub struct FontWeight(pub f32);
872
873impl Display for FontWeight {
874 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
875 write!(f, "{}", self.0)
876 }
877}
878
879impl From<f32> for FontWeight {
880 fn from(weight: f32) -> Self {
881 FontWeight(weight)
882 }
883}
884
885impl Default for FontWeight {
886 #[inline]
887 fn default() -> FontWeight {
888 FontWeight::NORMAL
889 }
890}
891
892impl Hash for FontWeight {
893 fn hash<H: Hasher>(&self, state: &mut H) {
894 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
895 }
896}
897
898impl Eq for FontWeight {}
899
900impl FontWeight {
901 pub const THIN: FontWeight = FontWeight(100.0);
903 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
905 pub const LIGHT: FontWeight = FontWeight(300.0);
907 pub const NORMAL: FontWeight = FontWeight(400.0);
909 pub const MEDIUM: FontWeight = FontWeight(500.0);
911 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
913 pub const BOLD: FontWeight = FontWeight(700.0);
915 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
917 pub const BLACK: FontWeight = FontWeight(900.0);
919
920 pub const ALL: [FontWeight; 9] = [
922 Self::THIN,
923 Self::EXTRA_LIGHT,
924 Self::LIGHT,
925 Self::NORMAL,
926 Self::MEDIUM,
927 Self::SEMIBOLD,
928 Self::BOLD,
929 Self::EXTRA_BOLD,
930 Self::BLACK,
931 ];
932}
933
934impl schemars::JsonSchema for FontWeight {
935 fn schema_name() -> std::borrow::Cow<'static, str> {
936 "FontWeight".into()
937 }
938
939 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
940 use schemars::json_schema;
941 json_schema!({
942 "type": "number",
943 "minimum": Self::THIN,
944 "maximum": Self::BLACK,
945 "default": Self::default(),
946 "description": "Font weight value between 100 (thin) and 900 (black)"
947 })
948 }
949}
950
951#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
953pub enum FontStyle {
954 #[default]
956 Normal,
957 Italic,
959 Oblique,
961}
962
963impl Display for FontStyle {
964 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
965 Debug::fmt(self, f)
966 }
967}
968
969#[derive(Clone, Debug, PartialEq, Eq, Default)]
971pub struct TextRun {
972 pub len: usize,
974 pub font: Font,
976 pub color: Hsla,
978 pub background_color: Option<Hsla>,
980 pub underline: Option<UnderlineStyle>,
982 pub strikethrough: Option<StrikethroughStyle>,
984}
985
986#[cfg(all(target_os = "macos", test))]
987impl TextRun {
988 fn with_len(&self, len: usize) -> Self {
989 let mut this = self.clone();
990 this.len = len;
991 this
992 }
993}
994
995#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
997#[repr(C)]
998pub struct GlyphId(pub u32);
999
1000#[derive(Clone, Debug, PartialEq)]
1006#[expect(missing_docs)]
1007pub struct RenderGlyphParams {
1008 pub font_id: FontId,
1009 pub glyph_id: GlyphId,
1010 pub font_size: Pixels,
1011 pub subpixel_variant: Point<u8>,
1012 pub scale_factor: f32,
1013 pub is_emoji: bool,
1014 pub subpixel_rendering: bool,
1015 pub dilation: u8,
1016}
1017
1018impl Eq for RenderGlyphParams {}
1019
1020impl Hash for RenderGlyphParams {
1021 fn hash<H: Hasher>(&self, state: &mut H) {
1022 self.font_id.0.hash(state);
1023 self.glyph_id.0.hash(state);
1024 self.font_size.0.to_bits().hash(state);
1025 self.subpixel_variant.hash(state);
1026 self.scale_factor.to_bits().hash(state);
1027 self.is_emoji.hash(state);
1028 self.subpixel_rendering.hash(state);
1029 self.dilation.hash(state);
1030 }
1031}
1032
1033#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1035pub struct Font {
1036 pub family: SharedString,
1040
1041 pub features: FontFeatures,
1043
1044 pub fallbacks: Option<FontFallbacks>,
1046
1047 pub weight: FontWeight,
1049
1050 pub style: FontStyle,
1052}
1053
1054impl Default for Font {
1055 fn default() -> Self {
1056 font(".SystemUIFont")
1057 }
1058}
1059
1060pub fn font(family: impl Into<SharedString>) -> Font {
1062 Font {
1063 family: family.into(),
1064 features: FontFeatures::default(),
1065 weight: FontWeight::default(),
1066 style: FontStyle::default(),
1067 fallbacks: None,
1068 }
1069}
1070
1071impl Font {
1072 pub fn bold(mut self) -> Self {
1074 self.weight = FontWeight::BOLD;
1075 self
1076 }
1077
1078 pub fn italic(mut self) -> Self {
1080 self.style = FontStyle::Italic;
1081 self
1082 }
1083}
1084
1085#[derive(Clone, Copy, Debug)]
1088pub struct FontMetrics {
1089 pub units_per_em: u32,
1092
1093 pub ascent: f32,
1095
1096 pub descent: f32,
1098
1099 pub line_gap: f32,
1101
1102 pub underline_position: f32,
1104
1105 pub underline_thickness: f32,
1107
1108 pub cap_height: f32,
1110
1111 pub x_height: f32,
1113
1114 pub bounding_box: Bounds<f32>,
1117}
1118
1119impl FontMetrics {
1120 pub fn ascent(&self, font_size: Pixels) -> Pixels {
1122 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1123 }
1124
1125 pub fn descent(&self, font_size: Pixels) -> Pixels {
1127 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1128 }
1129
1130 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1132 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1133 }
1134
1135 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1137 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1138 }
1139
1140 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1142 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1143 }
1144
1145 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1147 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1148 }
1149
1150 pub fn x_height(&self, font_size: Pixels) -> Pixels {
1152 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1153 }
1154
1155 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1157 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1158 }
1159}
1160
1161#[allow(unused)]
1163pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1164 match name {
1168 ".SystemUIFont" => system,
1169 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1170 ".ZedMono" | "Zed Plex Mono" => "Lilex",
1171 _ => name,
1172 }
1173}
1174
1175#[allow(unused)]
1177pub fn font_name_with_fallbacks_shared<'a>(
1178 name: &'a SharedString,
1179 system: &'a SharedString,
1180) -> &'a SharedString {
1181 match name.as_str() {
1185 ".SystemUIFont" => system,
1186 ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1187 ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1188 _ => name,
1189 }
1190}