gpui-base 0.11.0

Behavior, interaction, and infrastructure foundations for GPUI applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use gpui::{
    App, Div, Entity, EntityId, InteractiveElement as _, IntoElement, Pixels, ShapedLine,
    SharedString, Stateful, TextRun, TextStyle, View, ViewElement, Window, px,
};

use super::{EditorMode, InputBaseState, InputModeKind, element::LINE_NUMBER_RIGHT_MARGIN};

/// Supplies computed line-number geometry and glyphs for a single rendered frame.
///
/// The element owns this renderer, never the editing state: application styling
/// must not become retained Base data. Measurement runs before wrapping; shaping
/// runs only for visible buffer lines after wrapping and folding are resolved.
#[doc(hidden)]
pub trait EditorLineNumberRenderer: 'static {
    /// Returns the number lane width (excluding the gap) and resolved gap.
    /// A zero digit count requests only the gap when line numbers are hidden.
    fn measure_line_numbers(
        &self,
        digit_count: usize,
        body_style: &TextStyle,
        window: &Window,
    ) -> (Pixels, Pixels);

    /// Resolves a shared vertical offset from the configured fonts before shaping rows.
    /// Renderers using body typography need no vertical correction.
    fn resolve_line_number_baseline_offset(
        &self,
        _body_style: &TextStyle,
        _window: &Window,
    ) -> Pixels {
        px(0.)
    }

    /// Shapes one supported, one-based line number, without padding characters.
    fn shape_line_number(
        &self,
        number: usize,
        is_active: bool,
        body_style: &TextStyle,
        window: &Window,
        cx: &App,
    ) -> ShapedLine;
}

impl EditorLineNumberRenderer for () {
    fn measure_line_numbers(
        &self,
        digit_count: usize,
        body_style: &TextStyle,
        window: &Window,
    ) -> (Pixels, Pixels) {
        if digit_count == 0 {
            return (px(0.), LINE_NUMBER_RIGHT_MARGIN);
        }
        let font_size = body_style.font_size.to_pixels(window.rem_size());
        let font_id = window.text_system().resolve_font(&body_style.font());
        // Proportional digits can differ in width; every supported digit must fit.
        let width = "0123456789"
            .chars()
            .map(|digit| window.text_system().layout_width(font_id, font_size, digit))
            .fold(px(0.), Pixels::max)
            * digit_count;
        (width, LINE_NUMBER_RIGHT_MARGIN)
    }

    fn resolve_line_number_baseline_offset(&self, _: &TextStyle, _: &Window) -> Pixels {
        // The default renderer uses the body's own font and size.
        px(0.)
    }

    fn shape_line_number(
        &self,
        number: usize,
        _: bool,
        body_style: &TextStyle,
        window: &Window,
        _: &App,
    ) -> ShapedLine {
        let label: SharedString = number.to_string().into();
        // Right alignment uses the shaped advance, so padding characters would
        // change the label's measured width rather than provide layout spacing.
        let run = TextRun {
            len: label.len(),
            font: body_style.font(),
            color: body_style.color,
            background_color: None,
            underline: None,
            strikethrough: None,
        };
        window.text_system().shape_line(
            label,
            body_style.font_size.to_pixels(window.rem_size()),
            &[run],
            None,
        )
    }
}

/// State for source-code editing.
///
/// This is the shared editing engine in its code-editor kind. Languages, line
/// numbers, folding, indent guides, diagnostics, decorations, and the LSP
/// providers exist on this kind only, so an ordinary input or textarea never
/// exposes them.
pub type EditorState = InputBaseState<EditorMode>;

impl InputModeKind for EditorMode {
    const MULTI_LINE: bool = true;
    const CODE_EDITOR: bool = true;

    type Extras = super::EditorExtras;

    fn hover_definition_style(
        state: &InputBaseState<Self>,
        _cx: &App,
    ) -> Option<(std::ops::Range<usize>, gpui::HighlightStyle)> {
        state.hover_definition_style()
    }

    fn hover_definition_hitbox(
        state: &InputBaseState<Self>,
        window: &mut Window,
        _cx: &App,
    ) -> Option<gpui::Hitbox> {
        state.hover_definition_hitbox(window)
    }

    fn reset_language_features(state: &mut InputBaseState<Self>) {
        state.extras.lsp.reset();
    }

    fn reset_annotations(state: &mut InputBaseState<Self>) {
        state.extras.hover_popover = None;
        state.extras.decorations.clear();
        state.extras.range_decorations.clear();
        state.extras.gutter_decorations.clear();
        state.extras.overview_ruler_decorations.clear();
    }

    fn editing_syntax_context(state: &InputBaseState<Self>, offset: usize) -> super::SyntaxContext {
        state.syntax_context_at(offset)
    }

    fn adjust_annotations(
        state: &mut InputBaseState<Self>,
        range: &std::ops::Range<usize>,
        new_len: usize,
    ) {
        state.extras.decorations.adjust_for_edit(range, new_len);
        state
            .extras
            .range_decorations
            .adjust_for_edit(range, new_len);
        state
            .extras
            .gutter_decorations
            .adjust_for_edit(range, new_len);
        state
            .extras
            .overview_ruler_decorations
            .adjust_for_edit(range, new_len);
    }

    fn refresh_language_features(
        state: &mut InputBaseState<Self>,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        let text = state.text().clone();
        state.extras.lsp.update(&text, window, cx);
    }

    fn accept_inline_completion(
        state: &mut InputBaseState<Self>,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) -> bool {
        state.accept_inline_completion(window, cx)
    }

    fn has_inline_completion(state: &InputBaseState<Self>) -> bool {
        state.has_inline_completion()
    }

    fn on_click(
        state: &mut InputBaseState<Self>,
        event: &gpui::MouseDownEvent,
        offset: usize,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) -> bool {
        state.handle_click_hover_definition(event, offset, window, cx)
    }

    fn clear_hover_state(
        state: &mut InputBaseState<Self>,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        state.clear_hover_state(cx);
    }

    fn on_text_typed(
        state: &mut InputBaseState<Self>,
        range: &std::ops::Range<usize>,
        text: &str,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        state.handle_completion_trigger(range, text, window, cx);
    }

    fn clear_inline_completion(
        state: &mut InputBaseState<Self>,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        state.clear_inline_completion(cx);
    }

    fn hide_context_menu(
        state: &mut InputBaseState<Self>,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        state.hide_context_menu(cx);
    }

    fn is_context_menu_open(state: &InputBaseState<Self>, cx: &App) -> bool {
        state.is_context_menu_open(cx)
    }

    fn handle_context_menu_action(
        state: &mut InputBaseState<Self>,
        action: Box<dyn gpui::Action>,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) -> bool {
        state.handle_action_for_context_menu(action, window, cx)
    }

    fn on_hover_definition(
        state: &mut InputBaseState<Self>,
        offset: usize,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        state.handle_hover_definition(offset, window, cx);
    }

    fn on_mouse_move(
        state: &mut InputBaseState<Self>,
        offset: usize,
        event: &gpui::MouseMoveEvent,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        state.handle_mouse_move(offset, event, window, cx);
    }

    fn drive_highlighter(
        highlighter: &std::rc::Rc<std::cell::RefCell<Option<Box<dyn super::InputHighlighter>>>>,
        edit: super::InputEdit,
        text: &ropey::Rope,
        folding: bool,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        let mut highlighter = highlighter.borrow_mut();
        let Some(highlighter) = highlighter.as_mut() else {
            return;
        };
        highlighter.update(Some(edit), text, folding, window, cx);
    }

    fn drive_highlighter_batch(
        highlighter: &std::rc::Rc<std::cell::RefCell<Option<Box<dyn super::InputHighlighter>>>>,
        edits: &[(super::InputEdit, ropey::Rope)],
        folding: bool,
        window: &mut Window,
        cx: &mut gpui::Context<InputBaseState<Self>>,
    ) {
        let mut highlighter = highlighter.borrow_mut();
        let Some(highlighter) = highlighter.as_mut() else {
            return;
        };
        highlighter.update_batch(edits, folding, window, cx);
    }

    fn register_actions(
        element: Stateful<Div>,
        entity: &Entity<InputBaseState<Self>>,
        window: &mut Window,
    ) -> Stateful<Div> {
        element
            .key_context("Input mode=editor")
            .on_action(window.listener_for(entity, InputBaseState::on_action_toggle_code_actions))
            .on_action(window.listener_for(entity, InputBaseState::on_action_show_completions))
            .on_action(window.listener_for(entity, InputBaseState::on_action_go_to_definition))
    }
}

impl EditorState {
    /// The LSP providers and their cached results.
    ///
    /// This exists on the editor alone: an ordinary input or textarea has no
    /// language server, and no field to reach one through.
    pub fn lsp(&self) -> &super::Lsp {
        &self.extras.lsp
    }

    /// The LSP providers, mutably. Configure the providers through this.
    pub fn lsp_mut(&mut self) -> &mut super::Lsp {
        &mut self.extras.lsp
    }

    /// Syntax context at `offset`, or `Code` when the language has no provider.
    pub(crate) fn syntax_context_at(&self, offset: usize) -> super::SyntaxContext {
        self.mode.syntax_context_at(&self.text, offset)
    }
}

/// An unstyled source-code editor.
pub struct Editor<R = ()> {
    state: Entity<EditorState>,
    line_number_renderer: R,
}

impl Editor {
    pub fn new(state: &Entity<EditorState>) -> Self {
        Self {
            state: state.clone(),
            line_number_renderer: (),
        }
    }
}

impl<R: EditorLineNumberRenderer> Editor<R> {
    /// Supplies presentation for this element's frame without changing editor state.
    #[doc(hidden)]
    pub fn with_line_number_renderer<T: EditorLineNumberRenderer>(self, renderer: T) -> Editor<T> {
        Editor {
            state: self.state,
            line_number_renderer: renderer,
        }
    }
}

impl<R: EditorLineNumberRenderer> IntoElement for Editor<R> {
    type Element = ViewElement<Self>;

    fn into_element(self) -> Self::Element {
        ViewElement::new(self)
    }
}

impl<R: EditorLineNumberRenderer> View for Editor<R> {
    fn entity_id(&self) -> Option<EntityId> {
        Some(self.state.entity_id())
    }

    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        // Preserve the entity's identity for invalidation and element-state scoping.
        self.state.update(cx, |state, cx| {
            state
                .render_with_line_numbers(self.line_number_renderer, window, cx)
                .into_any_element()
        })
    }
}

/// What a code editor exposes to the renderer. See [`crate::input::InputExtras`].
impl crate::input::InputExtras for super::EditorExtras {
    fn decoration_layers(&self) -> Vec<&[super::TextDecoration]> {
        self.decorations.iter().collect()
    }

    fn range_decorations(&self, ranges: &[std::ops::Range<usize>]) -> Vec<&super::RangeDecoration> {
        self.range_decorations.intersecting(ranges)
    }

    fn gutter_decorations_width(&self) -> Option<gpui::Pixels> {
        self.gutter_decorations
            .has_collections()
            .then_some(self.gutter_decorations_width)
    }

    fn gutter_decorations(&self, range: std::ops::Range<usize>) -> Vec<&super::GutterDecoration> {
        self.gutter_decorations.intersecting(&[range])
    }

    fn overview_ruler_decorations(&self) -> Vec<&super::OverviewRulerDecoration> {
        self.overview_ruler_decorations.iter().flatten().collect()
    }

    fn overview_ruler_revision(&self) -> u64 {
        self.overview_ruler_decorations.revision()
    }

    fn semantic_token_styles(
        &self,
        text: &ropey::Rope,
        range: &std::ops::Range<usize>,
        resolver: &dyn crate::input::HighlightStyleResolver,
    ) -> Vec<(std::ops::Range<usize>, gpui::HighlightStyle)> {
        self.lsp.semantic_tokens_for_range(text, range, resolver)
    }

    fn document_color_swatches(
        &self,
        text: &ropey::Rope,
        range: &std::ops::Range<usize>,
    ) -> Vec<(std::ops::Range<usize>, gpui::Hsla)> {
        self.lsp.document_colors_for_range(text, range)
    }

    fn hover_symbol_range(&self) -> Option<std::ops::Range<usize>> {
        self.hover_popover
            .as_ref()
            .map(|session| session.symbol_range.clone())
    }

    fn inline_completion_item(&self) -> Option<&lsp_types::InlineCompletionItem> {
        self.inline_completion.item.as_ref()
    }

    fn context_menu_capabilities(&self) -> (bool, bool) {
        (
            self.lsp.definition_provider.is_some(),
            !self.lsp.code_action_providers.is_empty(),
        )
    }
}