Skip to main content

gpui_base/input/base/
layout.rs

1use std::{ops::Range, rc::Rc};
2
3use gpui::{Bounds, Pixels, ShapedLine, TextAlign, px};
4
5use crate::Side;
6
7use super::{WrappingIndent, display_map::LineLayout};
8
9#[derive(Clone, Default)]
10pub(crate) struct WhitespaceIndicators {
11    pub(crate) space: ShapedLine,
12    pub(crate) tab: ShapedLine,
13}
14
15/// A column of the editor's gutter, ordered from the text outward with
16/// `gutter_order`.
17///
18/// The order is the same on either [`Side`], so a gutter on the right is the
19/// mirror of one on the left.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum GutterColumn {
23    /// The fold icons.
24    FoldIcons,
25    /// The line numbers.
26    LineNumbers,
27    /// The column of the line decorations' gutter icons.
28    Icons,
29    /// The strip of the gutter decorations.
30    Decorations,
31}
32
33impl GutterColumn {
34    /// The columns in their default order, from the text outward.
35    pub(crate) const DEFAULT_ORDER: [Self; 4] = [
36        Self::FoldIcons,
37        Self::LineNumbers,
38        Self::Icons,
39        Self::Decorations,
40    ];
41
42    /// Return every column once, those listed first and the rest in their
43    /// default order.
44    pub(super) fn order(columns: impl IntoIterator<Item = Self>) -> [Self; 4] {
45        let mut order = Self::DEFAULT_ORDER;
46        let mut len = 0;
47        for column in columns.into_iter().chain(Self::DEFAULT_ORDER) {
48            if len == order.len() {
49                break;
50            }
51            if !order[..len].contains(&column) {
52                order[len] = column;
53                len += 1;
54            }
55        }
56        order
57    }
58}
59
60/// What a point of an input is over, as it was last painted.
61///
62/// Returned by [`hit_test`](super::InputBaseState::hit_test).
63#[non_exhaustive]
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub struct InputHit {
66    /// The part of the input the point is over.
67    pub area: InputHitArea,
68    /// The zero-based buffer row the point is beside.
69    ///
70    /// Over the text it is the row of the offset. In the gutter it is `None`
71    /// above the first laid-out row, below the last and beside the ghost lines
72    /// of an inline completion.
73    pub row: Option<usize>,
74    /// Whether the point is on a spacer row beside [`Self::row`] rather than on
75    /// the row itself.
76    pub spacer: bool,
77}
78
79/// The part of an input a point is over.
80#[non_exhaustive]
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum InputHitArea {
83    /// The text, at the byte offset a click there places the caret at.
84    #[non_exhaustive]
85    Text { offset: usize },
86    /// The gutter, in one of its columns, or `None` in its margin or padding.
87    #[non_exhaustive]
88    Gutter { column: Option<GutterColumn> },
89}
90
91#[derive(Clone)]
92pub(super) struct LastLayout {
93    pub(super) visible_range: Range<usize>,
94    pub(super) visible_buffer_lines: Vec<usize>,
95    pub(super) visible_line_byte_offsets: Vec<usize>,
96    pub(super) visible_top: Pixels,
97    pub(super) anchor_display_row: usize,
98    pub(super) visible_range_offset: Range<usize>,
99    pub(super) lines: Rc<Vec<LineLayout>>,
100    pub(super) line_height: Pixels,
101    pub(super) wrap_width: Option<Pixels>,
102    pub(super) wrapping_indent: WrappingIndent,
103    pub(super) line_number_width: Pixels,
104    /// Resolved gap between the text and the gutter columns for this frame.
105    pub(super) gutter_gap: Pixels,
106    /// Width reserved for the column of the line decorations' gutter icons and
107    /// its gap toward the line numbers, zero while no provider has gutter icons.
108    /// Part of `line_number_width`.
109    pub(super) gutter_icon_width: Pixels,
110    /// Width reserved for the gutter decoration strip and its gap toward the
111    /// line numbers, zero without a gutter decoration collection. Part of
112    /// `line_number_width`.
113    pub(super) gutter_decorations_width: Pixels,
114    /// The buffer row that inline completion ghost lines follow, and their height.
115    pub(super) ghost_lines: Option<(usize, Pixels)>,
116    /// How many spacer rows stand above and below each laid-out row, in
117    /// `visible_buffer_lines` order; empty when the editor has no spacers.
118    pub(super) spacer_rows: Vec<(usize, usize)>,
119    pub(super) gutter_side: Side,
120    pub(super) gutter_order: [GutterColumn; 4],
121    /// The x of the text, relative to the input bounds.
122    pub(super) text_origin_x: Pixels,
123    /// The x of the gutter, relative to the input bounds.
124    pub(super) gutter_origin_x: Pixels,
125    /// The width of the text, without the gutter and the margin kept from a
126    /// scrollbar on the left.
127    pub(super) text_width: Pixels,
128    /// Width of one space in the editor font.
129    ///
130    /// Past the end of a line there are no glyphs to hit-test against, so this is the
131    /// step used to measure how far past the end a pointer sits.
132    pub(super) space_width: Pixels,
133    pub(super) cursor_bounds: Option<Bounds<Pixels>>,
134    pub(super) text_align: TextAlign,
135    pub(super) content_width: Pixels,
136}
137
138impl LastLayout {
139    pub(crate) fn line(&self, row: usize) -> Option<&LineLayout> {
140        let pos = self.visible_buffer_lines.binary_search(&row).ok()?;
141        self.lines.get(pos)
142    }
143
144    /// The heights of the spacer rows above and below the `ix`th laid-out row.
145    pub(super) fn spacers(&self, ix: usize) -> (Pixels, Pixels) {
146        self.spacer_rows
147            .get(ix)
148            .map_or((px(0.), px(0.)), |&(above, below)| {
149                (self.line_height * above, self.line_height * below)
150            })
151    }
152
153    /// The top and height of each laid-out row, in `visible_buffer_lines` order.
154    ///
155    /// Tops are relative to the content origin and, as painted, rows after the
156    /// ghost lines are shifted down by their height. A row's spacers are not
157    /// part of its height; ghost lines stand between its text and the spacers
158    /// below it.
159    pub(super) fn row_extents(&self) -> impl Iterator<Item = (Pixels, Pixels)> + '_ {
160        let mut top = self.visible_top;
161        self.lines
162            .iter()
163            .zip(&self.visible_buffer_lines)
164            .enumerate()
165            .map(move |(ix, (line, &row))| {
166                let (above, below) = self.spacers(ix);
167                top += above;
168                let height = line.size(self.line_height).height;
169                let extent = (top, height);
170                top += height;
171                if let Some((ghost_row, ghost_height)) = self.ghost_lines
172                    && ghost_row == row
173                {
174                    top += ghost_height;
175                }
176                top += below;
177                extent
178            })
179    }
180
181    /// The buffer row at `y`, relative to the content origin, and whether `y`
182    /// is on one of its spacer rows. `None` above the first row, below the
183    /// last and on ghost lines.
184    pub(super) fn row_at(&self, y: Pixels) -> Option<(usize, bool)> {
185        self.row_extents()
186            .zip(&self.visible_buffer_lines)
187            .enumerate()
188            .find_map(|(ix, ((top, height), &row))| {
189                let (above, below) = self.spacers(ix);
190                let bottom = top + height;
191                let below_top = match self.ghost_lines {
192                    Some((ghost_row, ghost_height)) if ghost_row == row => bottom + ghost_height,
193                    _ => bottom,
194                };
195                let spacer =
196                    (y >= top - above && y < top) || (y >= below_top && y < below_top + below);
197                (spacer || (y >= top && y < bottom)).then_some((row, spacer))
198            })
199    }
200
201    #[cfg(test)]
202    pub(super) fn local_row_y(&self, row_offset: isize) -> Pixels {
203        self.visible_top + self.line_height * (row_offset as f32)
204    }
205
206    pub(super) fn display_row_y(&self, display_row: usize) -> Pixels {
207        let delta = display_row as f64 - self.anchor_display_row as f64;
208        self.visible_top + px((f64::from(f32::from(self.line_height)) * delta) as f32)
209    }
210}