Skip to main content

u0ui/
typography.rs

1//! IBM Plex fonts and Carbon type styles.
2//!
3//! [`crate::init`] registers the bundled IBM Plex Sans (Light 300, Regular 400,
4//! SemiBold 600, Italic 400), IBM Plex Mono (Regular 400, Italic 400 for
5//! `.g-syn-comment`, SemiBold 600) and IBM
6//! Plex Serif (Light 300, Regular 400; `.cu-typeset blockquote`), so nothing
7//! depends on what the machine has installed. Chinese/Japanese text falls back
8//! through `tokens.json`'s stack: PingFang SC → Hiragino Sans GB → Noto Sans CJK
9//! SC (mono: PingFang SC → Noto Sans Mono CJK SC).
10//!
11//! Apply a type style to any styled element:
12//!
13//! ```ignore
14//! use u0ui::prelude::*;
15//! div().type_style(TypeStyle::BodyCompact01).child("Create project")
16//! ```
17//!
18//! This sets family (with fallbacks), size (rems, so zoom reflows), line height
19//! (a multiplier of the size) and weight. **Letter spacing** (`0.16px` on
20//! body-compact-01, `0.32px` on label-01) is not applied: GPUI's text system has
21//! no tracking control. The value is kept in [`crate::tokens::TypeSpec`] for when
22//! it does; at these sizes the difference is under half a pixel per glyph.
23//!
24//! **Inline code.** GPUI text runs cannot change size, so the 13px inline
25//! code of 14px prose uses a derived face, [`INLINE_CODE_FAMILY`] (see
26//! [`inline_code_font`] and `inline_face.rs`).
27use crate::tokens::{FontFamilyKey, TypeStyle};
28use gpui_kit::{App, Div, Font, FontFallbacks, FontFeatures, FontStyle, FontWeight, Styled, div};
29use std::borrow::Cow;
30
31/// The bundled font files (IBM Plex, SIL OFL 1.1; see `assets/fonts/OFL.txt`).
32pub const FONT_FILES: &[(&str, &[u8])] = &[
33    (
34        "IBMPlexSans-Light.ttf",
35        include_bytes!("../assets/fonts/IBMPlexSans-Light.ttf"),
36    ),
37    (
38        "IBMPlexSans-Regular.ttf",
39        include_bytes!("../assets/fonts/IBMPlexSans-Regular.ttf"),
40    ),
41    (
42        "IBMPlexSans-Italic.ttf",
43        include_bytes!("../assets/fonts/IBMPlexSans-Italic.ttf"),
44    ),
45    (
46        "IBMPlexSans-SemiBold.ttf",
47        include_bytes!("../assets/fonts/IBMPlexSans-SemiBold.ttf"),
48    ),
49    (
50        "IBMPlexMono-Regular.ttf",
51        include_bytes!("../assets/fonts/IBMPlexMono-Regular.ttf"),
52    ),
53    (
54        // IBM/plex v6.4.0 `IBM-Plex-Mono/fonts/complete/ttf`, the release the
55        // other Plex files come from.
56        "IBMPlexMono-Italic.ttf",
57        include_bytes!("../assets/fonts/IBMPlexMono-Italic.ttf"),
58    ),
59    (
60        "IBMPlexMono-SemiBold.ttf",
61        include_bytes!("../assets/fonts/IBMPlexMono-SemiBold.ttf"),
62    ),
63    (
64        "IBMPlexSerif-Light.ttf",
65        include_bytes!("../assets/fonts/IBMPlexSerif-Light.ttf"),
66    ),
67    (
68        "IBMPlexSerif-Regular.ttf",
69        include_bytes!("../assets/fonts/IBMPlexSerif-Regular.ttf"),
70    ),
71];
72
73mod inline_face;
74
75/// The family of the inline-code face: IBM Plex Mono Regular whose glyphs
76/// draw at 13/14 of the run's size, so a run of it in a 14px paragraph is
77/// 13px code (`.g-prose code, .t3-amsg-body code { font-size: 0.8125rem }`).
78pub const INLINE_CODE_FAMILY: &str = "u0 Inline Mono";
79
80/// The prose size the inline-code face is scaled for (`.g-prose,
81/// .t3-amsg-body { font-size: 0.875rem }`) and the code size it draws at.
82pub const INLINE_CODE_SIZES: (f32, f32) = (14., 13.);
83
84/// The face's em in font units: Plex Mono's 1000 × 14 / 13.
85const INLINE_CODE_EM: u16 = 1077;
86
87/// The face's U+202F advance in font units: the code's 4px inline padding
88/// (`padding: 1px 4px`) at 14px.
89const INLINE_CODE_PAD: u16 = 308;
90
91/// The inline-code face's bytes, derived from the bundled Plex Mono.
92pub fn inline_code_face() -> Option<Vec<u8>> {
93    let (_, mono) = FONT_FILES
94        .iter()
95        .find(|(name, _)| *name == "IBMPlexMono-Regular.ttf")?;
96    inline_face::derive(mono, INLINE_CODE_EM, INLINE_CODE_FAMILY, INLINE_CODE_PAD)
97}
98
99/// The inline-code face with the mono CJK fallbacks. In a paragraph at
100/// `INLINE_CODE_SIZES.0` it draws `INLINE_CODE_SIZES.1`; elsewhere it scales
101/// with the paragraph (GPUI has no per-run size).
102pub fn inline_code_font() -> Font {
103    let mut f = font(FontFamilyKey::Mono, 400);
104    f.family = INLINE_CODE_FAMILY.into();
105    f
106}
107
108/// Register the bundled fonts with GPUI's text system (called by [`crate::init`]).
109pub fn register_fonts(cx: &mut App) {
110    let mut fonts: Vec<Cow<'static, [u8]>> = FONT_FILES
111        .iter()
112        .map(|(_, bytes)| Cow::Borrowed(*bytes))
113        .collect();
114    fonts.extend(inline_code_face().map(Cow::Owned));
115    if let Err(error) = cx.text_system().add_fonts(fonts) {
116        eprintln!("u0ui: failed to register IBM Plex fonts: {error}");
117    }
118}
119
120/// A GPUI font for a Carbon family at a CSS weight, with the CJK fallback stack.
121pub fn font(family: FontFamilyKey, weight: u16) -> Font {
122    let stack = family.stack();
123    Font {
124        family: stack[0].into(),
125        features: FontFeatures::default(),
126        fallbacks: Some(FontFallbacks::from_fonts(
127            stack[1..].iter().map(|s| s.to_string()).collect(),
128        )),
129        weight: FontWeight(weight as f32),
130        style: FontStyle::Normal,
131    }
132}
133
134/// The width of the longest word of `text` at `size_px` in `family` /
135/// `weight`: the min-content width CSS gives wrapping text. GPUI wraps text
136/// only at its box's width and breaks a word that does not fit, so a box
137/// that may shrink holds this as its least width to wrap between words only.
138pub fn longest_word_width(
139    text: &str,
140    size_px: f32,
141    family: FontFamilyKey,
142    weight: u16,
143    window: &gpui_kit::Window,
144) -> gpui_kit::Pixels {
145    let size = gpui_kit::rems(size_px / crate::tokens::REM_PX).to_pixels(window.rem_size());
146    text.split_whitespace()
147        .map(|word| {
148            // With the space after it: GPUI's line wrapper keeps the space
149            // on the word's line, and one that does not fit becomes a line
150            // of its own.
151            let word = format!("{word} ");
152            let run = gpui_kit::TextRun {
153                len: word.len(),
154                font: font(family, weight),
155                color: gpui_kit::black(),
156                background_color: None,
157                underline: None,
158                strikethrough: None,
159            };
160            window
161                .text_system()
162                .shape_line(gpui_kit::SharedString::from(word), size, &[run], None)
163                .width
164        })
165        .fold(gpui_kit::px(0.), |a, b| a.max(b))
166        // Whole pixels and one to spare: the line wrapper breaks a word
167        // that only just fits its measured width.
168        .ceil()
169        + gpui_kit::px(1.)
170}
171
172/// Apply Carbon type styles to any [`Styled`] element.
173pub trait TypeStyled: Styled + Sized {
174    /// Set family (with CJK fallbacks), size, line height and weight from a
175    /// Carbon type style. See the module docs about letter spacing.
176    fn type_style(self, style: TypeStyle) -> Self {
177        let spec = style.spec();
178        self.font(font(spec.family, spec.weight))
179            .text_size(spec.font_size())
180            .line_height(spec.line_height())
181    }
182}
183
184impl<T: Styled> TypeStyled for T {}
185
186/// The type style of a bare `<p>`: Carbon's global rule
187/// (`bundle.css`: `p { font-size: var(--body-02-font-size); line-height:
188/// var(--body-02-line-height); letter-spacing: 0 }`), 16px/24px. It wins over
189/// an inherited `font-size`, so a `<p>` inside 14px text is still 16px unless
190/// a rule of its own (`.cu-pempty p`, …) sets the size.
191pub const PARAGRAPH: TypeStyle = TypeStyle::Body02;
192
193/// A block for a reference's bare `<p>` (one without a size rule of its
194/// own): [`PARAGRAPH`], 16px/24px. Callers set the color.
195pub fn paragraph() -> Div {
196    div().type_style(PARAGRAPH)
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn bare_paragraph_is_body_02_16_on_24() {
205        let spec = PARAGRAPH.spec();
206        assert_eq!(spec.font_size_rem * 16., 16.);
207        assert_eq!(spec.weight, 400);
208        assert_eq!(spec.letter_spacing_px, 0.);
209        assert!(
210            matches!(spec.line_height, crate::tokens::LineHeight::Multiplier(m) if (m * 16. - 24.).abs() < 0.01)
211        );
212    }
213
214    #[test]
215    fn fonts_are_bundled_and_stacks_fall_back_to_cjk() {
216        assert_eq!(FONT_FILES.len(), 9);
217        for (name, bytes) in FONT_FILES {
218            assert!(bytes.len() > 100_000, "{name}");
219        }
220        let sans = font(FontFamilyKey::Sans, 600);
221        assert_eq!(sans.family.as_ref(), "IBM Plex Sans");
222        assert_eq!(sans.weight, FontWeight(600.));
223        assert!(sans.fallbacks.is_some());
224        // `.cu-typeset blockquote { font-family: var(--font-serif); font-weight: 300 }`.
225        let serif = font(FontFamilyKey::Serif, 300);
226        assert_eq!(serif.family.as_ref(), "IBM Plex Serif");
227        assert!(
228            FONT_FILES
229                .iter()
230                .any(|(n, _)| *n == "IBMPlexSerif-Light.ttf")
231        );
232        // `.g-syn-comment { font-style: italic }` in Plex Mono, and italic
233        // prose in Plex Sans, each resolve to a real italic face: the `head`
234        // table's macStyle has the italic bit.
235        for name in ["IBMPlexMono-Italic.ttf", "IBMPlexSans-Italic.ttf"] {
236            let (_, bytes) = FONT_FILES.iter().find(|(n, _)| *n == name).unwrap();
237            assert!(mac_style(bytes) & 0b10 != 0, "{name} is italic");
238        }
239        let (_, regular) = FONT_FILES
240            .iter()
241            .find(|(n, _)| *n == "IBMPlexMono-Regular.ttf")
242            .unwrap();
243        assert_eq!(mac_style(regular) & 0b10, 0);
244    }
245
246    /// `head.macStyle` (offset 44) of a TrueType font.
247    fn mac_style(font: &[u8]) -> u16 {
248        let be16 = |o: usize| u16::from_be_bytes([font[o], font[o + 1]]);
249        let be32 = |o: usize| u32::from_be_bytes([font[o], font[o + 1], font[o + 2], font[o + 3]]);
250        let tables = be16(4) as usize;
251        let head = (0..tables)
252            .map(|i| 12 + 16 * i)
253            .find(|&rec| &font[rec..rec + 4] == b"head")
254            .map(|rec| be32(rec + 8) as usize)
255            .expect("head table");
256        be16(head + 44)
257    }
258
259    #[test]
260    fn inline_code_face_draws_13px_in_14px_prose() {
261        let (body, code) = INLINE_CODE_SIZES;
262        assert!((1000. * body / code - INLINE_CODE_EM as f32).abs() < 0.5);
263        // 4px of padding at the 14px run size.
264        assert!((INLINE_CODE_PAD as f32 / INLINE_CODE_EM as f32 * body - 4.).abs() < 0.01);
265        assert!(inline_code_face().is_some_and(|f| f.len() > 100_000));
266        let f = inline_code_font();
267        assert_eq!(f.family.as_ref(), INLINE_CODE_FAMILY);
268        assert_eq!(f.weight, FontWeight(400.));
269    }
270}