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, 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/// An opaque identifier for a specific font.
36#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
37#[repr(C)]
38pub struct FontId(pub usize);
39
40/// An opaque identifier for a specific font family.
41#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
42pub struct FontFamilyId(pub usize);
43
44pub(crate) const SUBPIXEL_VARIANTS_X: u8 = 4;
45
46pub(crate) const SUBPIXEL_VARIANTS_Y: u8 =
47 if cfg!(target_os = "windows") || cfg!(target_os = "linux") {
48 1
49 } else {
50 SUBPIXEL_VARIANTS_X
51 };
52
53/// The GPUI text rendering sub system.
54pub struct TextSystem {
55 platform_text_system: Arc<dyn PlatformTextSystem>,
56 font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
57 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
58 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
59 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
60 font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
61 fallback_font_stack: SmallVec<[Font; 2]>,
62}
63
64impl TextSystem {
65 pub(crate) fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
66 TextSystem {
67 platform_text_system,
68 font_metrics: RwLock::default(),
69 raster_bounds: RwLock::default(),
70 font_ids_by_font: RwLock::default(),
71 wrapper_pool: Mutex::default(),
72 font_runs_pool: Mutex::default(),
73 fallback_font_stack: smallvec![
74 // TODO: Remove this when Linux have implemented setting fallbacks.
75 font(".ZedMono"),
76 font(".ZedSans"),
77 font("Helvetica"),
78 font("Segoe UI"), // Windows
79 font("Cantarell"), // Gnome
80 font("Ubuntu"), // Gnome (Ubuntu)
81 font("Noto Sans"), // KDE
82 font("DejaVu Sans")
83 ],
84 }
85 }
86
87 /// Get a list of all available font names from the operating system.
88 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 /// Add a font's data to the text system.
102 pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
103 self.platform_text_system.add_fonts(fonts)
104 }
105
106 /// Get the FontId for the configure font family and style.
107 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 /// Get the Font for the Font Id.
132 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 /// Resolves the specified font, falling back to the default font stack if
143 /// the font fails to load.
144 ///
145 /// # Panics
146 ///
147 /// Panics if the font and none of the fallbacks can be resolved.
148 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 /// Get the bounding box for the given font and font size.
169 /// A font's bounding box is the smallest rectangle that could enclose all glyphs
170 /// in the font. superimposed over one another.
171 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 /// Get the typographic bounds for the given character, in the given font and size.
176 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 /// Get the advance width for the given character, in the given font and size.
195 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 /// Returns the width of an `em`.
207 ///
208 /// Uses the width of the `m` character in the given font and size.
209 pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
210 Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
211 }
212
213 /// Returns the advance width of an `em`.
214 ///
215 /// Uses the advance width of the `m` character in the given font and size.
216 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
217 Ok(self.advance(font_id, font_size, 'm')?.width)
218 }
219
220 /// Returns the width of an `ch`.
221 ///
222 /// Uses the width of the `0` character in the given font and size.
223 pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
224 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
225 }
226
227 /// Returns the advance width of an `ch`.
228 ///
229 /// Uses the advance width of the `0` character in the given font and size.
230 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
231 Ok(self.advance(font_id, font_size, '0')?.width)
232 }
233
234 /// Get the number of font size units per 'em square',
235 /// Per MDN: "an abstract square whose height is the intended distance between
236 /// lines of type in the same type size"
237 pub fn units_per_em(&self, font_id: FontId) -> u32 {
238 self.read_metrics(font_id, |metrics| metrics.units_per_em)
239 }
240
241 /// Get the height of a capital letter in the given font and size.
242 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
243 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
244 }
245
246 /// Get the height of the x character in the given font and size.
247 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
248 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
249 }
250
251 /// Get the recommended distance from the baseline for the given font
252 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
253 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
254 }
255
256 /// Get the recommended distance below the baseline for the given font,
257 /// in single spaced text.
258 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
259 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
260 }
261
262 /// Get the recommended baseline offset for the given font and line height.
263 pub fn baseline_offset(
264 &self,
265 font_id: FontId,
266 font_size: Pixels,
267 line_height: Pixels,
268 ) -> Pixels {
269 let ascent = self.ascent(font_id, font_size);
270 let descent = self.descent(font_id, font_size);
271 let padding_top = (line_height - ascent - descent) / 2.;
272 padding_top + ascent
273 }
274
275 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
276 let lock = self.font_metrics.upgradable_read();
277
278 if let Some(metrics) = lock.get(&font_id) {
279 read(metrics)
280 } else {
281 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
282 let metrics = lock
283 .entry(font_id)
284 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
285 read(metrics)
286 }
287 }
288
289 /// Returns a handle to a line wrapper, for the given font and font size.
290 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
291 let lock = &mut self.wrapper_pool.lock();
292 let font_id = self.resolve_font(&font);
293 let wrappers = lock
294 .entry(FontIdWithSize { font_id, font_size })
295 .or_default();
296 let wrapper = wrappers.pop().unwrap_or_else(|| {
297 LineWrapper::new(font_id, font_size, self.platform_text_system.clone())
298 });
299
300 LineWrapperHandle {
301 wrapper: Some(wrapper),
302 text_system: self.clone(),
303 }
304 }
305
306 /// Get the rasterized size and location of a specific, rendered glyph.
307 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
308 let raster_bounds = self.raster_bounds.upgradable_read();
309 if let Some(bounds) = raster_bounds.get(params) {
310 Ok(*bounds)
311 } else {
312 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
313 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
314 raster_bounds.insert(params.clone(), bounds);
315 Ok(bounds)
316 }
317 }
318
319 pub(crate) fn rasterize_glyph(
320 &self,
321 params: &RenderGlyphParams,
322 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
323 let raster_bounds = self.raster_bounds(params)?;
324 self.platform_text_system
325 .rasterize_glyph(params, raster_bounds)
326 }
327}
328
329/// The GPUI text layout subsystem.
330#[derive(Deref)]
331pub struct WindowTextSystem {
332 line_layout_cache: LineLayoutCache,
333 #[deref]
334 text_system: Arc<TextSystem>,
335}
336
337impl WindowTextSystem {
338 pub(crate) fn new(text_system: Arc<TextSystem>) -> Self {
339 Self {
340 line_layout_cache: LineLayoutCache::new(text_system.platform_text_system.clone()),
341 text_system,
342 }
343 }
344
345 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
346 self.line_layout_cache.layout_index()
347 }
348
349 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
350 self.line_layout_cache.reuse_layouts(index)
351 }
352
353 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
354 self.line_layout_cache.truncate_layouts(index)
355 }
356
357 /// Shape the given line, at the given font_size, for painting to the screen.
358 /// Subsets of the line can be styled independently with the `runs` parameter.
359 ///
360 /// Note that this method can only shape a single line of text. It will panic
361 /// if the text contains newlines. If you need to shape multiple lines of text,
362 /// use [`Self::shape_text`] instead.
363 pub fn shape_line(
364 &self,
365 text: SharedString,
366 font_size: Pixels,
367 runs: &[TextRun],
368 force_width: Option<Pixels>,
369 ) -> ShapedLine {
370 debug_assert!(
371 text.find('\n').is_none(),
372 "text argument should not contain newlines"
373 );
374
375 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
376 for run in runs {
377 if let Some(last_run) = decoration_runs.last_mut()
378 && last_run.color == run.color
379 && last_run.underline == run.underline
380 && last_run.strikethrough == run.strikethrough
381 && last_run.background_color == run.background_color
382 {
383 last_run.len += run.len as u32;
384 continue;
385 }
386 decoration_runs.push(DecorationRun {
387 len: run.len as u32,
388 color: run.color,
389 background_color: run.background_color,
390 underline: run.underline,
391 strikethrough: run.strikethrough,
392 });
393 }
394
395 let layout = self.layout_line(&text, font_size, runs, force_width);
396
397 ShapedLine {
398 layout,
399 text,
400 decoration_runs,
401 }
402 }
403
404 /// Shape a multi line string of text, at the given font_size, for painting to the screen.
405 /// Subsets of the text can be styled independently with the `runs` parameter.
406 /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
407 pub fn shape_text(
408 &self,
409 text: SharedString,
410 font_size: Pixels,
411 runs: &[TextRun],
412 wrap_width: Option<Pixels>,
413 line_clamp: Option<usize>,
414 ) -> Result<SmallVec<[WrappedLine; 1]>> {
415 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
416 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
417
418 let mut lines = SmallVec::new();
419 let mut line_start = 0;
420 let mut max_wrap_lines = line_clamp.unwrap_or(usize::MAX);
421 let mut wrapped_lines = 0;
422
423 let mut process_line = |line_text: SharedString| {
424 font_runs.clear();
425 let line_end = line_start + line_text.len();
426
427 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
428 let mut run_start = line_start;
429 while run_start < line_end {
430 let Some(run) = runs.peek_mut() else {
431 break;
432 };
433
434 let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
435
436 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
437 && last_run.color == run.color
438 && last_run.underline == run.underline
439 && last_run.strikethrough == run.strikethrough
440 && last_run.background_color == run.background_color
441 {
442 last_run.len += run_len_within_line as u32;
443 false
444 } else {
445 decoration_runs.push(DecorationRun {
446 len: run_len_within_line as u32,
447 color: run.color,
448 background_color: run.background_color,
449 underline: run.underline,
450 strikethrough: run.strikethrough,
451 });
452 true
453 };
454
455 let font_id = self.resolve_font(&run.font);
456 if let Some(font_run) = font_runs.last_mut()
457 && font_id == font_run.font_id
458 && !decoration_changed
459 {
460 font_run.len += run_len_within_line;
461 } else {
462 font_runs.push(FontRun {
463 len: run_len_within_line,
464 font_id,
465 });
466 }
467
468 if run_len_within_line == run.len {
469 runs.next();
470 } else {
471 // Preserve the remainder of the run for the next line
472 run.len -= run_len_within_line;
473 }
474 run_start += run_len_within_line;
475 }
476
477 let layout = self.line_layout_cache.layout_wrapped_line(
478 &line_text,
479 font_size,
480 &font_runs,
481 wrap_width,
482 Some(max_wrap_lines - wrapped_lines),
483 );
484 wrapped_lines += layout.wrap_boundaries.len();
485
486 lines.push(WrappedLine {
487 layout,
488 decoration_runs,
489 text: line_text,
490 });
491
492 // Skip `\n` character.
493 line_start = line_end + 1;
494 if let Some(run) = runs.peek_mut() {
495 run.len -= 1;
496 if run.len == 0 {
497 runs.next();
498 }
499 }
500 };
501
502 let mut split_lines = text.split('\n');
503 let mut processed = false;
504
505 if let Some(first_line) = split_lines.next()
506 && let Some(second_line) = split_lines.next()
507 {
508 processed = true;
509 process_line(first_line.to_string().into());
510 process_line(second_line.to_string().into());
511 for line_text in split_lines {
512 process_line(line_text.to_string().into());
513 }
514 }
515
516 if !processed {
517 process_line(text);
518 }
519
520 self.font_runs_pool.lock().push(font_runs);
521
522 Ok(lines)
523 }
524
525 pub(crate) fn finish_frame(&self) {
526 self.line_layout_cache.finish_frame()
527 }
528
529 /// Layout the given line of text, at the given font_size.
530 /// Subsets of the line can be styled independently with the `runs` parameter.
531 /// Generally, you should prefer to use [`Self::shape_line`] instead, which
532 /// can be painted directly.
533 pub fn layout_line(
534 &self,
535 text: &str,
536 font_size: Pixels,
537 runs: &[TextRun],
538 force_width: Option<Pixels>,
539 ) -> Arc<LineLayout> {
540 let mut last_run = None::<&TextRun>;
541 let mut last_font: Option<FontId> = None;
542 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
543 font_runs.clear();
544
545 for run in runs.iter() {
546 let decoration_changed = if let Some(last_run) = last_run
547 && last_run.color == run.color
548 && last_run.underline == run.underline
549 && last_run.strikethrough == run.strikethrough
550 // we do not consider differing background color relevant, as it does not affect glyphs
551 // && last_run.background_color == run.background_color
552 {
553 false
554 } else {
555 last_run = Some(run);
556 true
557 };
558
559 if let Some(font_run) = font_runs.last_mut()
560 && Some(font_run.font_id) == last_font
561 && !decoration_changed
562 {
563 font_run.len += run.len;
564 } else {
565 let font_id = self.resolve_font(&run.font);
566 last_font = Some(font_id);
567 font_runs.push(FontRun {
568 len: run.len,
569 font_id,
570 });
571 }
572 }
573
574 let layout = self.line_layout_cache.layout_line(
575 &SharedString::new(text),
576 font_size,
577 &font_runs,
578 force_width,
579 );
580
581 self.font_runs_pool.lock().push(font_runs);
582
583 layout
584 }
585}
586
587#[derive(Hash, Eq, PartialEq)]
588struct FontIdWithSize {
589 font_id: FontId,
590 font_size: Pixels,
591}
592
593/// A handle into the text system, which can be used to compute the wrapped layout of text
594pub struct LineWrapperHandle {
595 wrapper: Option<LineWrapper>,
596 text_system: Arc<TextSystem>,
597}
598
599impl Drop for LineWrapperHandle {
600 fn drop(&mut self) {
601 let mut state = self.text_system.wrapper_pool.lock();
602 let wrapper = self.wrapper.take().unwrap();
603 state
604 .get_mut(&FontIdWithSize {
605 font_id: wrapper.font_id,
606 font_size: wrapper.font_size,
607 })
608 .unwrap()
609 .push(wrapper);
610 }
611}
612
613impl Deref for LineWrapperHandle {
614 type Target = LineWrapper;
615
616 fn deref(&self) -> &Self::Target {
617 self.wrapper.as_ref().unwrap()
618 }
619}
620
621impl DerefMut for LineWrapperHandle {
622 fn deref_mut(&mut self) -> &mut Self::Target {
623 self.wrapper.as_mut().unwrap()
624 }
625}
626
627/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
628/// with 400.0 as normal.
629#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
630#[serde(transparent)]
631pub struct FontWeight(pub f32);
632
633impl Display for FontWeight {
634 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635 write!(f, "{}", self.0)
636 }
637}
638
639impl From<f32> for FontWeight {
640 fn from(weight: f32) -> Self {
641 FontWeight(weight)
642 }
643}
644
645impl Default for FontWeight {
646 #[inline]
647 fn default() -> FontWeight {
648 FontWeight::NORMAL
649 }
650}
651
652impl Hash for FontWeight {
653 fn hash<H: Hasher>(&self, state: &mut H) {
654 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
655 }
656}
657
658impl Eq for FontWeight {}
659
660impl FontWeight {
661 /// Thin weight (100), the thinnest value.
662 pub const THIN: FontWeight = FontWeight(100.0);
663 /// Extra light weight (200).
664 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
665 /// Light weight (300).
666 pub const LIGHT: FontWeight = FontWeight(300.0);
667 /// Normal (400).
668 pub const NORMAL: FontWeight = FontWeight(400.0);
669 /// Medium weight (500, higher than normal).
670 pub const MEDIUM: FontWeight = FontWeight(500.0);
671 /// Semibold weight (600).
672 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
673 /// Bold weight (700).
674 pub const BOLD: FontWeight = FontWeight(700.0);
675 /// Extra-bold weight (800).
676 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
677 /// Black weight (900), the thickest value.
678 pub const BLACK: FontWeight = FontWeight(900.0);
679
680 /// All of the font weights, in order from thinnest to thickest.
681 pub const ALL: [FontWeight; 9] = [
682 Self::THIN,
683 Self::EXTRA_LIGHT,
684 Self::LIGHT,
685 Self::NORMAL,
686 Self::MEDIUM,
687 Self::SEMIBOLD,
688 Self::BOLD,
689 Self::EXTRA_BOLD,
690 Self::BLACK,
691 ];
692}
693
694impl schemars::JsonSchema for FontWeight {
695 fn schema_name() -> std::borrow::Cow<'static, str> {
696 "FontWeight".into()
697 }
698
699 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
700 use schemars::json_schema;
701 json_schema!({
702 "type": "number",
703 "minimum": Self::THIN,
704 "maximum": Self::BLACK,
705 "default": Self::default(),
706 "description": "Font weight value between 100 (thin) and 900 (black)"
707 })
708 }
709}
710
711/// Allows italic or oblique faces to be selected.
712#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
713pub enum FontStyle {
714 /// A face that is neither italic not obliqued.
715 #[default]
716 Normal,
717 /// A form that is generally cursive in nature.
718 Italic,
719 /// A typically-sloped version of the regular face.
720 Oblique,
721}
722
723impl Display for FontStyle {
724 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
725 Debug::fmt(self, f)
726 }
727}
728
729/// A styled run of text, for use in [`crate::TextLayout`].
730#[derive(Clone, Debug, PartialEq, Eq)]
731pub struct TextRun {
732 /// A number of utf8 bytes
733 pub len: usize,
734 /// The font to use for this run.
735 pub font: Font,
736 /// The color
737 pub color: Hsla,
738 /// The background color (if any)
739 pub background_color: Option<Hsla>,
740 /// The underline style (if any)
741 pub underline: Option<UnderlineStyle>,
742 /// The strikethrough style (if any)
743 pub strikethrough: Option<StrikethroughStyle>,
744}
745
746#[cfg(all(target_os = "macos", test))]
747impl TextRun {
748 fn with_len(&self, len: usize) -> Self {
749 let mut this = self.clone();
750 this.len = len;
751 this
752 }
753}
754
755/// An identifier for a specific glyph, as returned by [`WindowTextSystem::layout_line`].
756#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
757#[repr(C)]
758pub struct GlyphId(pub(crate) u32);
759
760#[derive(Clone, Debug, PartialEq)]
761pub(crate) struct RenderGlyphParams {
762 pub(crate) font_id: FontId,
763 pub(crate) glyph_id: GlyphId,
764 pub(crate) font_size: Pixels,
765 pub(crate) subpixel_variant: Point<u8>,
766 pub(crate) scale_factor: f32,
767 pub(crate) is_emoji: bool,
768}
769
770impl Eq for RenderGlyphParams {}
771
772impl Hash for RenderGlyphParams {
773 fn hash<H: Hasher>(&self, state: &mut H) {
774 self.font_id.0.hash(state);
775 self.glyph_id.0.hash(state);
776 self.font_size.0.to_bits().hash(state);
777 self.subpixel_variant.hash(state);
778 self.scale_factor.to_bits().hash(state);
779 self.is_emoji.hash(state);
780 }
781}
782
783/// The configuration details for identifying a specific font.
784#[derive(Clone, Debug, Eq, PartialEq, Hash)]
785pub struct Font {
786 /// The font family name.
787 ///
788 /// The special name ".SystemUIFont" is used to identify the system UI font, which varies based on platform.
789 pub family: SharedString,
790
791 /// The font features to use.
792 pub features: FontFeatures,
793
794 /// The fallbacks fonts to use.
795 pub fallbacks: Option<FontFallbacks>,
796
797 /// The font weight.
798 pub weight: FontWeight,
799
800 /// The font style.
801 pub style: FontStyle,
802}
803
804/// Get a [`Font`] for a given name.
805pub fn font(family: impl Into<SharedString>) -> Font {
806 Font {
807 family: family.into(),
808 features: FontFeatures::default(),
809 weight: FontWeight::default(),
810 style: FontStyle::default(),
811 fallbacks: None,
812 }
813}
814
815impl Font {
816 /// Set this Font to be bold
817 pub fn bold(mut self) -> Self {
818 self.weight = FontWeight::BOLD;
819 self
820 }
821
822 /// Set this Font to be italic
823 pub fn italic(mut self) -> Self {
824 self.style = FontStyle::Italic;
825 self
826 }
827}
828
829/// A struct for storing font metrics.
830/// It is used to define the measurements of a typeface.
831#[derive(Clone, Copy, Debug)]
832pub struct FontMetrics {
833 /// The number of font units that make up the "em square",
834 /// a scalable grid for determining the size of a typeface.
835 pub(crate) units_per_em: u32,
836
837 /// The vertical distance from the baseline of the font to the top of the glyph covers.
838 pub(crate) ascent: f32,
839
840 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
841 pub(crate) descent: f32,
842
843 /// The recommended additional space to add between lines of type.
844 pub(crate) line_gap: f32,
845
846 /// The suggested position of the underline.
847 pub(crate) underline_position: f32,
848
849 /// The suggested thickness of the underline.
850 pub(crate) underline_thickness: f32,
851
852 /// The height of a capital letter measured from the baseline of the font.
853 pub(crate) cap_height: f32,
854
855 /// The height of a lowercase x.
856 pub(crate) x_height: f32,
857
858 /// The outer limits of the area that the font covers.
859 /// Corresponds to the xMin / xMax / yMin / yMax values in the OpenType `head` table
860 pub(crate) bounding_box: Bounds<f32>,
861}
862
863impl FontMetrics {
864 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
865 pub fn ascent(&self, font_size: Pixels) -> Pixels {
866 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
867 }
868
869 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
870 pub fn descent(&self, font_size: Pixels) -> Pixels {
871 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
872 }
873
874 /// Returns the recommended additional space to add between lines of type in pixels.
875 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
876 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
877 }
878
879 /// Returns the suggested position of the underline in pixels.
880 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
881 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
882 }
883
884 /// Returns the suggested thickness of the underline in pixels.
885 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
886 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
887 }
888
889 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
890 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
891 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
892 }
893
894 /// Returns the height of a lowercase x in pixels.
895 pub fn x_height(&self, font_size: Pixels) -> Pixels {
896 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
897 }
898
899 /// Returns the outer limits of the area that the font covers in pixels.
900 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
901 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
902 }
903}
904
905#[allow(unused)]
906pub(crate) fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
907 // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
908 // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
909 // and so retained here for backward compatibility.
910 match name {
911 ".SystemUIFont" => system,
912 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
913 ".ZedMono" | "Zed Plex Mono" => "Lilex",
914 _ => name,
915 }
916}