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 core::fmt;
21use derive_more::{Add, Deref, FromStr, Sub};
22use itertools::Itertools;
23use open_gpui_collections::FxHashMap;
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 ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
241 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
242 }
243
244 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
248 Ok(self.advance(font_id, font_size, '0')?.width)
249 }
250
251 pub fn units_per_em(&self, font_id: FontId) -> u32 {
255 self.read_metrics(font_id, |metrics| metrics.units_per_em)
256 }
257
258 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
260 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
261 }
262
263 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
265 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
266 }
267
268 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
270 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
271 }
272
273 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
276 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
277 }
278
279 pub fn baseline_offset(
281 &self,
282 font_id: FontId,
283 font_size: Pixels,
284 line_height: Pixels,
285 ) -> Pixels {
286 let ascent = self.ascent(font_id, font_size);
287 let descent = self.descent(font_id, font_size);
288 let padding_top = (line_height - ascent - descent) / 2.;
289 padding_top + ascent
290 }
291
292 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
293 let lock = self.font_metrics.upgradable_read();
294
295 if let Some(metrics) = lock.get(&font_id) {
296 read(metrics)
297 } else {
298 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
299 let metrics = lock
300 .entry(font_id)
301 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
302 read(metrics)
303 }
304 }
305
306 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
308 let lock = &mut self.wrapper_pool.lock();
309 let font_id = self.resolve_font(&font);
310 let wrappers = lock
311 .entry(FontIdWithSize { font_id, font_size })
312 .or_default();
313 let wrapper = wrappers
314 .pop()
315 .unwrap_or_else(|| LineWrapper::new(font_id, font_size, self.clone()));
316
317 LineWrapperHandle {
318 wrapper: Some(wrapper),
319 text_system: self.clone(),
320 }
321 }
322
323 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
325 let raster_bounds = self.raster_bounds.upgradable_read();
326 if let Some(bounds) = raster_bounds.get(params) {
327 Ok(*bounds)
328 } else {
329 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
330 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
331 raster_bounds.insert(params.clone(), bounds);
332 Ok(bounds)
333 }
334 }
335
336 pub(crate) fn rasterize_glyph(
337 &self,
338 params: &RenderGlyphParams,
339 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
340 let raster_bounds = self.raster_bounds(params)?;
341 self.platform_text_system
342 .rasterize_glyph(params, raster_bounds)
343 }
344
345 pub(crate) fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
347 self.platform_text_system.glyph_dilation_for_color(color)
348 }
349
350 pub(crate) fn recommended_rendering_mode(
353 &self,
354 font_id: FontId,
355 font_size: Pixels,
356 ) -> TextRenderingMode {
357 self.platform_text_system
358 .recommended_rendering_mode(font_id, font_size)
359 }
360}
361
362#[derive(Deref)]
364pub struct WindowTextSystem {
365 line_layout_cache: LineLayoutCache,
366 #[deref]
367 text_system: Arc<TextSystem>,
368}
369
370impl WindowTextSystem {
371 pub fn new(text_system: Arc<TextSystem>) -> Self {
373 Self {
374 line_layout_cache: LineLayoutCache::new(text_system.platform_text_system.clone()),
375 text_system,
376 }
377 }
378
379 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
380 self.line_layout_cache.layout_index()
381 }
382
383 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
384 self.line_layout_cache.reuse_layouts(index)
385 }
386
387 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
388 self.line_layout_cache.truncate_layouts(index)
389 }
390
391 pub fn shape_line(
398 &self,
399 text: SharedString,
400 font_size: Pixels,
401 runs: &[TextRun],
402 force_width: Option<Pixels>,
403 ) -> ShapedLine {
404 debug_assert!(
405 text.find('\n').is_none(),
406 "text argument should not contain newlines"
407 );
408
409 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
410 for run in runs {
411 if let Some(last_run) = decoration_runs.last_mut()
412 && last_run.color == run.color
413 && last_run.underline == run.underline
414 && last_run.strikethrough == run.strikethrough
415 && last_run.background_color == run.background_color
416 {
417 last_run.len += run.len as u32;
418 continue;
419 }
420 decoration_runs.push(DecorationRun {
421 len: run.len as u32,
422 color: run.color,
423 background_color: run.background_color,
424 underline: run.underline,
425 strikethrough: run.strikethrough,
426 });
427 }
428
429 let layout = self.layout_line(&text, font_size, runs, force_width);
430
431 ShapedLine {
432 layout,
433 text,
434 decoration_runs,
435 }
436 }
437
438 pub fn shape_line_by_hash(
449 &self,
450 text_hash: u64,
451 text_len: usize,
452 font_size: Pixels,
453 runs: &[TextRun],
454 force_width: Option<Pixels>,
455 materialize_text: impl FnOnce() -> SharedString,
456 ) -> ShapedLine {
457 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
458 for run in runs {
459 if let Some(last_run) = decoration_runs.last_mut()
460 && last_run.color == run.color
461 && last_run.underline == run.underline
462 && last_run.strikethrough == run.strikethrough
463 && last_run.background_color == run.background_color
464 {
465 last_run.len += run.len as u32;
466 continue;
467 }
468 decoration_runs.push(DecorationRun {
469 len: run.len as u32,
470 color: run.color,
471 background_color: run.background_color,
472 underline: run.underline,
473 strikethrough: run.strikethrough,
474 });
475 }
476
477 let mut used_force_width = force_width;
478 let layout = self.layout_line_by_hash(
479 text_hash,
480 text_len,
481 font_size,
482 runs,
483 used_force_width,
484 || {
485 let text = materialize_text();
486 debug_assert!(
487 text.find('\n').is_none(),
488 "text argument should not contain newlines"
489 );
490 text
491 },
492 );
493
494 let text: SharedString = SharedString::new_static("");
498
499 ShapedLine {
500 layout,
501 text,
502 decoration_runs,
503 }
504 }
505
506 pub fn shape_text(
510 &self,
511 text: SharedString,
512 font_size: Pixels,
513 runs: &[TextRun],
514 wrap_width: Option<Pixels>,
515 line_clamp: Option<usize>,
516 ) -> Result<SmallVec<[WrappedLine; 1]>> {
517 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
518 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
519
520 let mut lines = SmallVec::new();
521 let mut max_wrap_lines = line_clamp;
522 let mut wrapped_lines = 0;
523
524 let mut process_line = |line_text: SharedString, line_start, line_end| {
525 font_runs.clear();
526
527 let mut decoration_runs = <Vec<DecorationRun>>::with_capacity(32);
528 let mut run_start = line_start;
529 while run_start < line_end {
530 let Some(run) = runs.peek_mut() else {
531 log::warn!("`TextRun`s do not cover the entire to be shaped text");
532 break;
533 };
534
535 let run_len_within_line = cmp::min(line_end - run_start, run.len);
536
537 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
538 && last_run.color == run.color
539 && last_run.underline == run.underline
540 && last_run.strikethrough == run.strikethrough
541 && last_run.background_color == run.background_color
542 {
543 last_run.len += run_len_within_line as u32;
544 false
545 } else {
546 decoration_runs.push(DecorationRun {
547 len: run_len_within_line as u32,
548 color: run.color,
549 background_color: run.background_color,
550 underline: run.underline,
551 strikethrough: run.strikethrough,
552 });
553 true
554 };
555
556 let font_id = self.resolve_font(&run.font);
557 if let Some(font_run) = font_runs.last_mut()
558 && font_id == font_run.font_id
559 && !decoration_changed
560 {
561 font_run.len += run_len_within_line;
562 } else {
563 font_runs.push(FontRun {
564 len: run_len_within_line,
565 font_id,
566 });
567 }
568
569 run.len -= run_len_within_line;
571 if run.len == 0 {
572 runs.next();
573 }
574 run_start += run_len_within_line;
575 }
576
577 let layout = self.line_layout_cache.layout_wrapped_line(
578 &line_text,
579 font_size,
580 &font_runs,
581 wrap_width,
582 max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
583 );
584 wrapped_lines += layout.wrap_boundaries.len();
585
586 lines.push(WrappedLine {
587 layout,
588 decoration_runs,
589 text: line_text,
590 });
591
592 if let Some(run) = runs.peek_mut() {
594 run.len -= 1;
595 if run.len == 0 {
596 runs.next();
597 }
598 }
599 };
600
601 let mut split_lines = text.split('\n');
602
603 if let Some(first_line) = split_lines.next()
605 && let Some(second_line) = split_lines.next()
606 {
607 let mut line_start = 0;
608 process_line(
609 SharedString::new(first_line),
610 line_start,
611 line_start + first_line.len(),
612 );
613 line_start += first_line.len() + '\n'.len_utf8();
614 process_line(
615 SharedString::new(second_line),
616 line_start,
617 line_start + second_line.len(),
618 );
619 for line_text in split_lines {
620 line_start += line_text.len() + '\n'.len_utf8();
621 process_line(
622 SharedString::new(line_text),
623 line_start,
624 line_start + line_text.len(),
625 );
626 }
627 } else {
628 let end = text.len();
629 process_line(text, 0, end);
630 }
631
632 self.font_runs_pool.lock().push(font_runs);
633
634 Ok(lines)
635 }
636
637 pub(crate) fn finish_frame(&self) {
638 self.line_layout_cache.finish_frame()
639 }
640
641 pub fn layout_line(
646 &self,
647 text: &str,
648 font_size: Pixels,
649 runs: &[TextRun],
650 force_width: Option<Pixels>,
651 ) -> Arc<LineLayout> {
652 let mut last_run = None::<&TextRun>;
653 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
654 font_runs.clear();
655
656 for run in runs.iter() {
657 let decoration_changed = if let Some(last_run) = last_run
658 && last_run.color == run.color
659 && last_run.underline == run.underline
660 && last_run.strikethrough == run.strikethrough
661 {
664 false
665 } else {
666 last_run = Some(run);
667 true
668 };
669
670 let font_id = self.resolve_font(&run.font);
671 if let Some(font_run) = font_runs.last_mut()
672 && font_id == font_run.font_id
673 && !decoration_changed
674 {
675 font_run.len += run.len;
676 } else {
677 font_runs.push(FontRun {
678 len: run.len,
679 font_id,
680 });
681 }
682 }
683
684 let layout = self.line_layout_cache.layout_line(
685 &SharedString::new(text),
686 font_size,
687 &font_runs,
688 force_width,
689 );
690
691 self.font_runs_pool.lock().push(font_runs);
692
693 layout
694 }
695
696 pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
698 let mut buffer = [0; 4];
699 let buffer: &_ = ch.encode_utf8(&mut buffer);
700 self.line_layout_cache
701 .layout_line(
702 buffer,
703 font_size,
704 &[FontRun {
705 len: buffer.len(),
706 font_id,
707 }],
708 None,
709 )
710 .width
711 }
712
713 pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
715 self.layout_width(font_id, font_size, 'm')
716 }
717
718 pub fn try_layout_line_by_hash(
727 &self,
728 text_hash: u64,
729 text_len: usize,
730 font_size: Pixels,
731 runs: &[TextRun],
732 force_width: Option<Pixels>,
733 ) -> Option<Arc<LineLayout>> {
734 let mut last_run = None::<&TextRun>;
735 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
736 font_runs.clear();
737
738 for run in runs.iter() {
739 let decoration_changed = if let Some(last_run) = last_run
740 && last_run.color == run.color
741 && last_run.underline == run.underline
742 && last_run.strikethrough == run.strikethrough
743 {
746 false
747 } else {
748 last_run = Some(run);
749 true
750 };
751
752 let font_id = self.resolve_font(&run.font);
753 if let Some(font_run) = font_runs.last_mut()
754 && font_id == font_run.font_id
755 && !decoration_changed
756 {
757 font_run.len += run.len;
758 } else {
759 font_runs.push(FontRun {
760 len: run.len,
761 font_id,
762 });
763 }
764 }
765
766 let layout = self.line_layout_cache.try_layout_line_by_hash(
767 text_hash,
768 text_len,
769 font_size,
770 &font_runs,
771 force_width,
772 );
773
774 self.font_runs_pool.lock().push(font_runs);
775
776 layout
777 }
778
779 pub fn layout_line_by_hash(
788 &self,
789 text_hash: u64,
790 text_len: usize,
791 font_size: Pixels,
792 runs: &[TextRun],
793 force_width: Option<Pixels>,
794 materialize_text: impl FnOnce() -> SharedString,
795 ) -> Arc<LineLayout> {
796 let mut last_run = None::<&TextRun>;
797 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
798 font_runs.clear();
799
800 for run in runs.iter() {
801 let decoration_changed = if let Some(last_run) = last_run
802 && last_run.color == run.color
803 && last_run.underline == run.underline
804 && last_run.strikethrough == run.strikethrough
805 {
808 false
809 } else {
810 last_run = Some(run);
811 true
812 };
813
814 let font_id = self.resolve_font(&run.font);
815 if let Some(font_run) = font_runs.last_mut()
816 && font_id == font_run.font_id
817 && !decoration_changed
818 {
819 font_run.len += run.len;
820 } else {
821 font_runs.push(FontRun {
822 len: run.len,
823 font_id,
824 });
825 }
826 }
827
828 let layout = self.line_layout_cache.layout_line_by_hash(
829 text_hash,
830 text_len,
831 font_size,
832 &font_runs,
833 force_width,
834 materialize_text,
835 );
836
837 self.font_runs_pool.lock().push(font_runs);
838
839 layout
840 }
841}
842
843#[derive(Hash, Eq, PartialEq)]
844struct FontIdWithSize {
845 font_id: FontId,
846 font_size: Pixels,
847}
848
849pub struct LineWrapperHandle {
851 wrapper: Option<LineWrapper>,
852 text_system: Arc<TextSystem>,
853}
854
855impl Drop for LineWrapperHandle {
856 fn drop(&mut self) {
857 let mut state = self.text_system.wrapper_pool.lock();
858 let wrapper = self.wrapper.take().unwrap();
859 state
860 .get_mut(&FontIdWithSize {
861 font_id: wrapper.font_id,
862 font_size: wrapper.font_size,
863 })
864 .unwrap()
865 .push(wrapper);
866 }
867}
868
869impl Deref for LineWrapperHandle {
870 type Target = LineWrapper;
871
872 fn deref(&self) -> &Self::Target {
873 self.wrapper.as_ref().unwrap()
874 }
875}
876
877impl DerefMut for LineWrapperHandle {
878 fn deref_mut(&mut self) -> &mut Self::Target {
879 self.wrapper.as_mut().unwrap()
880 }
881}
882
883#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
886#[serde(transparent)]
887pub struct FontWeight(pub f32);
888
889impl Display for FontWeight {
890 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891 write!(f, "{}", self.0)
892 }
893}
894
895impl From<f32> for FontWeight {
896 fn from(weight: f32) -> Self {
897 FontWeight(weight)
898 }
899}
900
901impl Default for FontWeight {
902 #[inline]
903 fn default() -> FontWeight {
904 FontWeight::NORMAL
905 }
906}
907
908impl Hash for FontWeight {
909 fn hash<H: Hasher>(&self, state: &mut H) {
910 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
911 }
912}
913
914impl Eq for FontWeight {}
915
916impl FontWeight {
917 pub const THIN: FontWeight = FontWeight(100.0);
919 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
921 pub const LIGHT: FontWeight = FontWeight(300.0);
923 pub const NORMAL: FontWeight = FontWeight(400.0);
925 pub const MEDIUM: FontWeight = FontWeight(500.0);
927 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
929 pub const BOLD: FontWeight = FontWeight(700.0);
931 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
933 pub const BLACK: FontWeight = FontWeight(900.0);
935
936 pub const ALL: [FontWeight; 9] = [
938 Self::THIN,
939 Self::EXTRA_LIGHT,
940 Self::LIGHT,
941 Self::NORMAL,
942 Self::MEDIUM,
943 Self::SEMIBOLD,
944 Self::BOLD,
945 Self::EXTRA_BOLD,
946 Self::BLACK,
947 ];
948}
949
950impl schemars::JsonSchema for FontWeight {
951 fn schema_name() -> std::borrow::Cow<'static, str> {
952 "FontWeight".into()
953 }
954
955 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
956 use schemars::json_schema;
957 json_schema!({
958 "type": "number",
959 "minimum": Self::THIN,
960 "maximum": Self::BLACK,
961 "default": Self::default(),
962 "description": "Font weight value between 100 (thin) and 900 (black)"
963 })
964 }
965}
966
967#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
969pub enum FontStyle {
970 #[default]
972 Normal,
973 Italic,
975 Oblique,
977}
978
979impl Display for FontStyle {
980 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
981 Debug::fmt(self, f)
982 }
983}
984
985#[derive(Clone, Debug, PartialEq, Eq, Default)]
987pub struct TextRun {
988 pub len: usize,
990 pub font: Font,
992 pub color: Hsla,
994 pub background_color: Option<Hsla>,
996 pub underline: Option<UnderlineStyle>,
998 pub strikethrough: Option<StrikethroughStyle>,
1000}
1001
1002#[cfg(all(target_os = "macos", test))]
1003impl TextRun {
1004 fn with_len(&self, len: usize) -> Self {
1005 let mut this = self.clone();
1006 this.len = len;
1007 this
1008 }
1009}
1010
1011#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1013#[repr(C)]
1014pub struct GlyphId(pub u32);
1015
1016#[derive(Clone, Debug, PartialEq)]
1022#[expect(missing_docs)]
1023pub struct RenderGlyphParams {
1024 pub font_id: FontId,
1025 pub glyph_id: GlyphId,
1026 pub font_size: Pixels,
1027 pub subpixel_variant: Point<u8>,
1028 pub scale_factor: f32,
1029 pub is_emoji: bool,
1030 pub subpixel_rendering: bool,
1031 pub dilation: u8,
1032}
1033
1034impl Eq for RenderGlyphParams {}
1035
1036impl Hash for RenderGlyphParams {
1037 fn hash<H: Hasher>(&self, state: &mut H) {
1038 self.font_id.0.hash(state);
1039 self.glyph_id.0.hash(state);
1040 self.font_size.0.to_bits().hash(state);
1041 self.subpixel_variant.hash(state);
1042 self.scale_factor.to_bits().hash(state);
1043 self.is_emoji.hash(state);
1044 self.subpixel_rendering.hash(state);
1045 self.dilation.hash(state);
1046 }
1047}
1048
1049#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1051pub struct Font {
1052 pub family: SharedString,
1056
1057 pub features: FontFeatures,
1059
1060 pub fallbacks: Option<FontFallbacks>,
1062
1063 pub weight: FontWeight,
1065
1066 pub style: FontStyle,
1068}
1069
1070impl Default for Font {
1071 fn default() -> Self {
1072 font(".SystemUIFont")
1073 }
1074}
1075
1076pub fn font(family: impl Into<SharedString>) -> Font {
1078 Font {
1079 family: family.into(),
1080 features: FontFeatures::default(),
1081 weight: FontWeight::default(),
1082 style: FontStyle::default(),
1083 fallbacks: None,
1084 }
1085}
1086
1087impl Font {
1088 pub fn bold(mut self) -> Self {
1090 self.weight = FontWeight::BOLD;
1091 self
1092 }
1093
1094 pub fn italic(mut self) -> Self {
1096 self.style = FontStyle::Italic;
1097 self
1098 }
1099}
1100
1101#[derive(Clone, Copy, Debug)]
1104pub struct FontMetrics {
1105 pub units_per_em: u32,
1108
1109 pub ascent: f32,
1111
1112 pub descent: f32,
1114
1115 pub line_gap: f32,
1117
1118 pub underline_position: f32,
1120
1121 pub underline_thickness: f32,
1123
1124 pub cap_height: f32,
1126
1127 pub x_height: f32,
1129
1130 pub bounding_box: Bounds<f32>,
1133}
1134
1135impl FontMetrics {
1136 pub fn ascent(&self, font_size: Pixels) -> Pixels {
1138 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1139 }
1140
1141 pub fn descent(&self, font_size: Pixels) -> Pixels {
1143 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1144 }
1145
1146 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1148 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1149 }
1150
1151 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1153 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1154 }
1155
1156 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1158 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1159 }
1160
1161 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1163 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1164 }
1165
1166 pub fn x_height(&self, font_size: Pixels) -> Pixels {
1168 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1169 }
1170
1171 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1173 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1174 }
1175}
1176
1177#[allow(unused)]
1179pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1180 match name {
1184 ".SystemUIFont" => system,
1185 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1186 ".ZedMono" | "Zed Plex Mono" => "Lilex",
1187 _ => name,
1188 }
1189}
1190
1191#[allow(unused)]
1193pub fn font_name_with_fallbacks_shared<'a>(
1194 name: &'a SharedString,
1195 system: &'a SharedString,
1196) -> &'a SharedString {
1197 match name.as_str() {
1201 ".SystemUIFont" => system,
1202 ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1203 ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1204 _ => name,
1205 }
1206}