Skip to main content

gpui_component/input/
gutter_style.rs

1use gpui::{
2    AbsoluteLength, App, Font, Hsla, Pixels, ShapedLine, SharedString, TextRun, TextStyle, Window,
3    px,
4};
5use gpui_base::input::EditorLineNumberRenderer;
6
7use crate::ActiveTheme as _;
8
9/// Optional line-number presentation supplied by the application or UI layer.
10///
11/// Unspecified properties inherit the editor's defaults. Keeping them optional
12/// lets a per-editor override follow later theme changes for every other property.
13#[derive(Clone, Debug, Default, PartialEq)]
14pub struct GutterStyle {
15    gap: Option<AbsoluteLength>,
16    line_number_color: Option<Hsla>,
17    active_line_number_color: Option<Hsla>,
18    line_number_font_family: Option<SharedString>,
19    line_number_font_size: Option<AbsoluteLength>,
20}
21
22impl EditorLineNumberRenderer for GutterStyle {
23    fn measure_line_numbers(
24        &self,
25        digit_count: usize,
26        body_style: &TextStyle,
27        window: &Window,
28    ) -> (Pixels, Pixels) {
29        let gap = self.resolve_gap(window.rem_size());
30        // Hidden line numbers need spacing but no font resolution or glyph metrics.
31        if digit_count == 0 {
32            return (px(0.), gap);
33        }
34        let style = self.resolve_text_style(body_style);
35        let font_size = style.font_size.to_pixels(window.rem_size());
36        let font_id = window.text_system().resolve_font(&style.font());
37        // A font's punctuation does not bound its digits, and proportional
38        // digits can differ from each other. Every supported digit must fit.
39        let width = "0123456789"
40            .chars()
41            .map(|digit| window.text_system().layout_width(font_id, font_size, digit))
42            .fold(px(0.), Pixels::max)
43            * digit_count;
44        (width, gap)
45    }
46
47    fn resolve_line_number_baseline_offset(
48        &self,
49        body_style: &TextStyle,
50        window: &Window,
51    ) -> Pixels {
52        let number_style = self.resolve_text_style(body_style);
53        let text_system = window.text_system();
54        let line_height = window.line_height();
55        // Empty rows have no glyph metrics. Use the configured fonts so edits
56        // and syntax highlighting cannot move the line-number baseline.
57        let baseline = |style: &TextStyle| {
58            let size = style.font_size.to_pixels(window.rem_size());
59            let font_id = text_system.resolve_font(&style.font());
60            let ascent = text_system.ascent(font_id, size);
61            // GPUI's shaped layouts use a positive descent for centered painting.
62            let descent = text_system.descent(font_id, size).abs();
63            (line_height - ascent - descent) / 2. + ascent
64        };
65        baseline(body_style) - baseline(&number_style)
66    }
67
68    fn shape_line_number(
69        &self,
70        number: usize,
71        is_active: bool,
72        body_style: &TextStyle,
73        window: &Window,
74        cx: &App,
75    ) -> ShapedLine {
76        let color = if is_active {
77            self.active_line_number_color
78                .unwrap_or(cx.theme().foreground)
79        } else {
80            self.line_number_color
81                .unwrap_or(cx.theme().muted_foreground)
82        };
83        // Base aligns shaped advances, so padding would distort the label width.
84        let label: SharedString = number.to_string().into();
85        // Build only the shaping inputs; cloning TextStyle for every visible
86        // line would also copy unrelated layout settings and shared handles.
87        let run = TextRun {
88            len: label.len(),
89            font: Font {
90                family: self
91                    .line_number_font_family
92                    .as_ref()
93                    .unwrap_or(&body_style.font_family)
94                    .clone(),
95                features: body_style.font_features.clone(),
96                fallbacks: body_style.font_fallbacks.clone(),
97                weight: body_style.font_weight,
98                style: body_style.font_style,
99            },
100            color,
101            // Body annotations describe editable text, not the gutter labels.
102            background_color: None,
103            underline: None,
104            strikethrough: None,
105        };
106        window.text_system().shape_line(
107            label,
108            self.line_number_font_size
109                .unwrap_or(body_style.font_size)
110                .to_pixels(window.rem_size()),
111            &[run],
112            None,
113        )
114    }
115}
116
117impl GutterStyle {
118    /// Sets the gap before the body text, after any folding controls.
119    ///
120    /// Accepts rems that follow window zoom or pixels for a fixed gap.
121    pub fn with_gap(mut self, gap: impl Into<AbsoluteLength>) -> Self {
122        self.gap = Some(gap.into());
123        self
124    }
125
126    /// Sets the color of line numbers outside the current line.
127    pub fn with_line_number_color(mut self, color: Hsla) -> Self {
128        self.line_number_color = Some(color);
129        self
130    }
131
132    /// Sets the color of the current line number.
133    pub fn with_active_line_number_color(mut self, color: Hsla) -> Self {
134        self.active_line_number_color = Some(color);
135        self
136    }
137
138    /// Sets the line-number font independently of the body font.
139    pub fn with_line_number_font_family(mut self, family: impl Into<SharedString>) -> Self {
140        self.line_number_font_family = Some(family.into());
141        self
142    }
143
144    /// Sets the line-number font size without changing the body row height.
145    ///
146    /// Accepts rems that follow window zoom or pixels for a fixed font size.
147    pub fn with_line_number_font_size(mut self, size: impl Into<AbsoluteLength>) -> Self {
148        self.line_number_font_size = Some(size.into());
149        self
150    }
151
152    /// Returns the explicitly specified gap.
153    pub fn gap(&self) -> Option<AbsoluteLength> {
154        self.gap
155    }
156
157    /// Returns the explicitly specified normal line-number color.
158    pub fn line_number_color(&self) -> Option<Hsla> {
159        self.line_number_color
160    }
161
162    /// Returns the explicitly specified current-line number color.
163    pub fn active_line_number_color(&self) -> Option<Hsla> {
164        self.active_line_number_color
165    }
166
167    /// Returns the explicitly specified line-number font family.
168    pub fn line_number_font_family(&self) -> Option<&SharedString> {
169        self.line_number_font_family.as_ref()
170    }
171
172    /// Returns the explicitly specified line-number font size.
173    pub fn line_number_font_size(&self) -> Option<AbsoluteLength> {
174        self.line_number_font_size
175    }
176
177    /// Applies only explicitly specified properties, including transparent colors.
178    pub(crate) fn apply_overrides(&mut self, overrides: Self) {
179        self.gap = overrides.gap.or(self.gap);
180        self.line_number_color = overrides.line_number_color.or(self.line_number_color);
181        self.active_line_number_color = overrides
182            .active_line_number_color
183            .or(self.active_line_number_color);
184        if let Some(family) = overrides.line_number_font_family {
185            self.line_number_font_family = Some(family);
186        }
187        self.line_number_font_size = overrides
188            .line_number_font_size
189            .or(self.line_number_font_size);
190    }
191
192    pub(crate) fn resolve_gap(&self, rem_size: Pixels) -> Pixels {
193        // Preserve each length's unit so GPUI controls pixel and rem behavior.
194        self.gap.unwrap_or(px(6.).into()).to_pixels(rem_size)
195    }
196
197    pub(crate) fn resolve_text_style(&self, body: &TextStyle) -> TextStyle {
198        let mut style = body.clone();
199        if let Some(family) = &self.line_number_font_family {
200            style.font_family = family.clone();
201        }
202        if let Some(size) = self.line_number_font_size {
203            style.font_size = size;
204        }
205        style
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use gpui::{Styled as _, div, px, rems, rgb};
213
214    #[test]
215    fn test_gutter_style_builder_and_partial_overrides() {
216        let normal = rgb(0x808080).into();
217        let active = rgb(0xeeeeee).into();
218        let mut style = GutterStyle::default()
219            .with_gap(px(12.))
220            .with_line_number_color(normal)
221            .with_active_line_number_color(active)
222            .with_line_number_font_family("Number Font")
223            .with_line_number_font_size(px(12.));
224        let defaults = style.clone();
225
226        style.apply_overrides(GutterStyle::default());
227        assert_eq!(style, defaults);
228
229        // Zero spacing and transparent ink are explicit values, so treating
230        // either as an unset sentinel would lose an application's override.
231        style.apply_overrides(
232            GutterStyle::default()
233                .with_gap(px(0.))
234                .with_line_number_color(Hsla::transparent_black())
235                .with_line_number_font_size(px(10.)),
236        );
237        assert_eq!(style.gap(), Some(px(0.).into()));
238        assert_eq!(style.line_number_color(), Some(Hsla::transparent_black()));
239        assert_eq!(style.active_line_number_color(), Some(active));
240        assert_eq!(
241            style.line_number_font_family().unwrap().as_ref(),
242            "Number Font"
243        );
244        assert_eq!(style.line_number_font_size(), Some(px(10.).into()));
245
246        style.apply_overrides(GutterStyle::default().with_active_line_number_color(normal));
247        assert_eq!(style.active_line_number_color(), Some(normal));
248        assert_eq!(style.line_number_color(), Some(Hsla::transparent_black()));
249    }
250
251    #[test]
252    fn gutter_typography_inherits_unspecified_properties_without_changing_the_body() {
253        let mut body = TextStyle::default();
254        body.font_family = "Body Font".into();
255        body.font_size = px(16.).into();
256        let original = body.clone();
257
258        assert_eq!(GutterStyle::default().resolve_text_style(&body), original);
259        assert_eq!(GutterStyle::default().resolve_gap(px(16.)), px(6.));
260
261        let family_only = GutterStyle::default()
262            .with_line_number_font_family("Number Font")
263            .resolve_text_style(&body);
264        assert_eq!(family_only.font_family.as_ref(), "Number Font");
265        assert_eq!(family_only.font_size, body.font_size);
266        assert_eq!(family_only.line_height, body.line_height);
267
268        let size_only = GutterStyle::default()
269            .with_line_number_font_size(px(12.))
270            .resolve_text_style(&body);
271        assert_eq!(size_only.font_family, body.font_family);
272        assert_eq!(size_only.font_size.to_pixels(px(16.)), px(12.));
273        assert_eq!(size_only.line_height, body.line_height);
274        assert_eq!(body, original);
275    }
276
277    #[test]
278    fn gutter_dimensions_follow_zoom_without_changing_configured_values() {
279        let style = GutterStyle::default()
280            .with_gap(rems(0.75))
281            .with_line_number_font_size(rems(0.75));
282        let fixed_style = GutterStyle::default()
283            .with_gap(px(12.))
284            .with_line_number_font_size(px(12.));
285        let mut body = TextStyle::default();
286        body.font_size = rems(1.).into();
287        let resolved = style.resolve_text_style(&body);
288        let reference_gap = div().gap_3().style().gap.width.unwrap();
289
290        for (rem_size, expected_size) in [(12., 9.), (16., 12.), (24., 18.), (32., 24.), (16., 12.)]
291        {
292            assert_eq!(style.resolve_gap(px(rem_size)), px(expected_size));
293            assert_eq!(fixed_style.resolve_gap(px(rem_size)), px(12.));
294            assert_eq!(
295                fixed_style
296                    .resolve_text_style(&body)
297                    .font_size
298                    .to_pixels(px(rem_size)),
299                px(12.)
300            );
301            assert_eq!(
302                style.resolve_gap(px(rem_size)),
303                reference_gap.to_pixels(px(0.).into(), px(rem_size))
304            );
305            assert_eq!(
306                resolved.font_size.to_pixels(px(rem_size)),
307                px(expected_size)
308            );
309            assert_eq!(GutterStyle::default().resolve_gap(px(rem_size)), px(6.));
310            assert_eq!(
311                style.clone().with_gap(px(0.)).resolve_gap(px(rem_size)),
312                px(0.)
313            );
314            assert_eq!(GutterStyle::default().resolve_text_style(&body), body);
315        }
316        assert_eq!(style.gap(), Some(rems(0.75).into()));
317        assert_eq!(style.line_number_font_size(), Some(rems(0.75).into()));
318    }
319}