gpui_base/input/base/kind.rs
1//! Compile-time input modes.
2//!
3//! The three input states are one engine seen through a mode marker, one per
4//! state:
5//!
6//! ```ignore
7//! pub type InputState = InputBaseState<InputMode>;
8//! pub type TextareaState = InputBaseState<TextareaMode>;
9//! pub type EditorState = InputBaseState<EditorMode>;
10//! ```
11//!
12//! A method that only makes sense for one mode lives in that mode's `impl`
13//! block, so it does not exist on the others: `InputState` has no `auto_grow`
14//! or `soft_wrap`, `TextareaState` has no `masked` or `line_number`, and only
15//! `EditorState` performs code actions. Methods shared by the two multi-line
16//! modes go on [`MultiLineMode`]. Reaching for the wrong one is a compile
17//! error rather than a debug assertion.
18//!
19//! [`super::LayoutMode`] carries the same distinction at runtime, since the
20//! engine branches on it while editing. The marker only decides which API is
21//! reachable.
22
23use std::cell::RefCell;
24use std::rc::Rc;
25
26use gpui::{Div, Entity, Stateful, Window};
27use ropey::Rope;
28
29use super::decorations::DecorationCollections;
30use super::line_decorations::LineDecorationProviders;
31use super::lsp::{ContextMenuContent, HoverDefinition, InlineCompletion};
32use super::spacers::SpacerProvider;
33use crate::input::{
34 GutterDecoration, HighlightStyleResolver, InputEdit, InputHighlighter, LineDecoration,
35 OverviewRulerDecoration, RangeDecoration, SyntaxContext, TextDecoration,
36};
37use crate::input::{HoverPopoverState, Lsp};
38use gpui::Task;
39
40use super::InputBaseState;
41
42/// A single-line text field: the mode of [`crate::input::InputState`].
43pub struct InputMode;
44
45/// Ordinary multi-line text: the mode of [`crate::input::TextareaState`].
46pub struct TextareaMode;
47
48/// Source code, with language features: the mode of [`crate::input::EditorState`].
49pub struct EditorMode;
50
51mod sealed {
52 pub trait Sealed {}
53}
54
55impl sealed::Sealed for InputMode {}
56impl sealed::Sealed for TextareaMode {}
57impl sealed::Sealed for EditorMode {}
58
59/// The modes whose layout spans more than one line: [`TextareaMode`] and
60/// [`EditorMode`].
61///
62/// Soft wrap, wrapping indent and the search session are meaningless in a
63/// single-line field, but shared by the two multi-line modes. Bounding an
64/// `impl` block on this trait puts those methods on both without writing them
65/// twice, and keeps them off [`InputMode`].
66pub trait MultiLineMode: InputModeKind {}
67
68impl MultiLineMode for TextareaMode {}
69impl MultiLineMode for EditorMode {}
70
71/// What the renderer may read out of a mode's extra state.
72///
73/// Kept apart from [`InputModeKind`] on purpose. This trait is *data*: the
74/// renderer is generic over the mode, so it cannot name `EditorExtras` and
75/// reach its fields directly, and these are the accessors it goes through
76/// instead. Every one of them has an empty answer, which is what a plain input
77/// gives; a textarea answers only [`Self::decoration_layers`].
78///
79/// [`InputModeKind`] is *behavior*: points where the engine hands control back
80/// during an edit. Adding a field an editor renders belongs here and leaves
81/// the engine's callbacks alone.
82pub trait InputExtras: Default + 'static {
83 /// Decoration ranges to paint, innermost collection first.
84 fn decoration_layers(&self) -> Vec<&[TextDecoration]> {
85 Vec::new()
86 }
87
88 /// Changes whenever [`Self::decoration_layers`] are set again. Edits that only move
89 /// their ranges leave it as it is.
90 fn decorations_revision(&self) -> u64 {
91 0
92 }
93
94 /// Geometric decorations intersecting visible, non-folded buffer spans.
95 fn range_decorations(&self, _ranges: &[std::ops::Range<usize>]) -> Vec<&RangeDecoration> {
96 Vec::new()
97 }
98
99 /// Return the gutter decoration strip width, or `None` when no gutter
100 /// collection exists.
101 fn gutter_decorations_width(&self) -> Option<gpui::Pixels> {
102 None
103 }
104
105 /// Return the gutter decorations that touch a UTF-8 byte range, in paint
106 /// order. An empty decoration touches the range when it lies inside it.
107 fn gutter_decorations(&self, _range: std::ops::Range<usize>) -> Vec<&GutterDecoration> {
108 Vec::new()
109 }
110
111 /// Return all overview ruler decorations in paint order.
112 fn overview_ruler_decorations(&self) -> Vec<&OverviewRulerDecoration> {
113 Vec::new()
114 }
115
116 /// A number that changes whenever an overview ruler collection is created,
117 /// replaced, extended, cleared or released.
118 fn overview_ruler_revision(&self) -> u64 {
119 0
120 }
121
122 /// Line decorations for the visible buffer rows, in collection order.
123 fn line_decorations(
124 &self,
125 _rows: std::ops::Range<usize>,
126 _cx: &gpui::App,
127 ) -> Vec<LineDecoration> {
128 Vec::new()
129 }
130
131 /// Whether any line decoration collection has a provider.
132 fn has_line_decorations(&self) -> bool {
133 false
134 }
135
136 /// Whether any line decoration collection's provider has gutter icons.
137 fn has_gutter_icons(&self) -> bool {
138 false
139 }
140
141 /// The provider of the spacers, if one is set.
142 fn spacer_provider(&self) -> Option<Rc<dyn SpacerProvider>> {
143 None
144 }
145
146 /// Semantic-token styles for a visible range, when an LSP supplies them.
147 fn semantic_token_styles(
148 &self,
149 _text: &Rope,
150 _range: &std::ops::Range<usize>,
151 _resolver: &dyn HighlightStyleResolver,
152 ) -> Vec<(std::ops::Range<usize>, gpui::HighlightStyle)> {
153 Vec::new()
154 }
155
156 /// Document colours to paint as swatches, when an LSP supplies them.
157 fn document_color_swatches(
158 &self,
159 _text: &Rope,
160 _range: &std::ops::Range<usize>,
161 ) -> Vec<(std::ops::Range<usize>, gpui::Hsla)> {
162 Vec::new()
163 }
164
165 /// The symbol range the hover popover is anchored to.
166 fn hover_symbol_range(&self) -> Option<std::ops::Range<usize>> {
167 None
168 }
169
170 /// The inline completion to paint as ghost text.
171 fn inline_completion_item(&self) -> Option<&lsp_types::InlineCompletionItem> {
172 None
173 }
174
175 /// What this mode can offer its context menu: go-to-definition, code actions.
176 fn context_menu_capabilities(&self) -> (bool, bool) {
177 (false, false)
178 }
179}
180
181/// A mode with nothing extra to render.
182impl InputExtras for () {}
183
184/// Hooks the shared engine calls back into for mode-specific work.
185///
186/// The engine's render path is generic over the mode, so it cannot name a
187/// specific state type. This hook is the seam: each implementation is written
188/// for one concrete mode, so inside it `Entity<InputBaseState<Self>>` is that
189/// mode's own state type.
190/// Sealed: the engine branches on a closed set of runtime modes, so the
191/// markers are a closed set too. The three above are all of them.
192pub trait InputModeKind: sealed::Sealed + Sized + 'static {
193 /// Whether this kind of input spans more than one line.
194 ///
195 /// The kind decides this, not the layout: [`super::LayoutMode`] carries
196 /// how many rows to show and how to grow, which is a different question
197 /// from whether the input is a text field or a document. Deriving it from
198 /// the layout let the two disagree — an auto-growing textarea capped at
199 /// one row used to report itself as single-line.
200 const MULTI_LINE: bool;
201
202 /// Whether this kind of input is a source-code editor.
203 const CODE_EDITOR: bool = false;
204
205 /// State only this mode needs.
206 ///
207 /// The engine is shared, but its parts are not: a single-line field has no
208 /// use for an LSP client or a search session, and an editor has no use for
209 /// number stepping. Keeping those here means a form full of text fields
210 /// does not carry an editor's worth of machinery.
211 type Extras: InputExtras;
212
213 /// Drives the syntax highlighter after the text changed.
214 ///
215 /// Only a code editor has one. The engine's edit path is generic over the
216 /// mode, so it dispatches here, where `Self` is concrete and the highlighter
217 /// can be handed this mode's own context.
218 fn drive_highlighter(
219 _highlighter: &Rc<RefCell<Option<Box<dyn InputHighlighter>>>>,
220 _edit: InputEdit,
221 _text: &Rope,
222 _folding: bool,
223 _window: &mut Window,
224 _cx: &mut gpui::Context<InputBaseState<Self>>,
225 ) {
226 }
227
228 /// Drives the syntax highlighter once for several edits applied as one
229 /// change, each paired with the text right after it.
230 fn drive_highlighter_batch(
231 _highlighter: &Rc<RefCell<Option<Box<dyn InputHighlighter>>>>,
232 _edits: &[(InputEdit, Rope)],
233 _folding: bool,
234 _window: &mut Window,
235 _cx: &mut gpui::Context<InputBaseState<Self>>,
236 ) {
237 }
238
239 /// The range highlighted while Cmd-hovering a symbol, with its style.
240 fn hover_definition_style(
241 _state: &InputBaseState<Self>,
242 _cx: &gpui::App,
243 ) -> Option<(std::ops::Range<usize>, gpui::HighlightStyle)> {
244 None
245 }
246
247 /// The hitbox for Cmd-hover, when the mode supports go-to-definition.
248 fn hover_definition_hitbox(
249 _state: &InputBaseState<Self>,
250 _window: &mut Window,
251 _cx: &gpui::App,
252 ) -> Option<gpui::Hitbox> {
253 None
254 }
255
256 /// Drops cached language-server results, e.g. after the text is replaced.
257 fn reset_language_features(_state: &mut InputBaseState<Self>) {}
258
259 /// Drops decorations and hover state when the text is replaced wholesale.
260 fn reset_annotations(_state: &mut InputBaseState<Self>) {}
261
262 /// Syntax context at `offset` for editing decisions.
263 ///
264 /// Only a code editor can have a provider installed; the default answer
265 /// is `Code`, which preserves character-heuristic behavior.
266 fn editing_syntax_context(_state: &InputBaseState<Self>, _offset: usize) -> SyntaxContext {
267 SyntaxContext::Code
268 }
269
270 /// Slides decoration ranges along with an edit.
271 fn adjust_annotations(
272 _state: &mut InputBaseState<Self>,
273 _range: &std::ops::Range<usize>,
274 _new_len: usize,
275 ) {
276 }
277
278 /// Refreshes language-server state after the text changed.
279 fn refresh_language_features(
280 _state: &mut InputBaseState<Self>,
281 _window: &mut Window,
282 _cx: &mut gpui::Context<InputBaseState<Self>>,
283 ) {
284 }
285
286 /// Takes the pending inline completion, when Tab should accept it.
287 fn accept_inline_completion(
288 _state: &mut InputBaseState<Self>,
289 _window: &mut Window,
290 _cx: &mut gpui::Context<InputBaseState<Self>>,
291 ) -> bool {
292 false
293 }
294
295 /// Whether an inline completion is waiting to be accepted.
296 fn has_inline_completion(_state: &InputBaseState<Self>) -> bool {
297 false
298 }
299
300 /// Reacts to a click, for Cmd-click go-to-definition.
301 fn on_click(
302 _state: &mut InputBaseState<Self>,
303 _event: &gpui::MouseDownEvent,
304 _offset: usize,
305 _window: &mut Window,
306 _cx: &mut gpui::Context<InputBaseState<Self>>,
307 ) -> bool {
308 false
309 }
310
311 /// Drops hover state when the pointer leaves or focus moves.
312 fn clear_hover_state(
313 _state: &mut InputBaseState<Self>,
314 _cx: &mut gpui::Context<InputBaseState<Self>>,
315 ) {
316 }
317
318 /// Offers freshly typed text to the completion engine.
319 fn on_text_typed(
320 _state: &mut InputBaseState<Self>,
321 _range: &std::ops::Range<usize>,
322 _text: &str,
323 _window: &mut Window,
324 _cx: &mut gpui::Context<InputBaseState<Self>>,
325 ) {
326 }
327
328 /// Drops any inline completion after the text or cursor moved.
329 fn clear_inline_completion(
330 _state: &mut InputBaseState<Self>,
331 _cx: &mut gpui::Context<InputBaseState<Self>>,
332 ) {
333 }
334
335 /// Closes any open completion or code-action menu.
336 fn hide_context_menu(
337 _state: &mut InputBaseState<Self>,
338 _cx: &mut gpui::Context<InputBaseState<Self>>,
339 ) {
340 }
341
342 /// Whether a completion or code-action menu is currently open.
343 fn is_context_menu_open(_state: &InputBaseState<Self>, _cx: &gpui::App) -> bool {
344 false
345 }
346
347 /// Lets an open menu consume the action first. Returns true when it did.
348 fn handle_context_menu_action(
349 _state: &mut InputBaseState<Self>,
350 _action: Box<dyn gpui::Action>,
351 _window: &mut Window,
352 _cx: &mut gpui::Context<InputBaseState<Self>>,
353 ) -> bool {
354 false
355 }
356
357 /// Highlights the symbol under the pointer for go-to-definition.
358 ///
359 /// Separate from [`Self::on_mouse_move`]: this runs on paths that have no
360 /// mouse event to hand over, such as opening the context menu.
361 fn on_hover_definition(
362 _state: &mut InputBaseState<Self>,
363 _offset: usize,
364 _window: &mut Window,
365 _cx: &mut gpui::Context<InputBaseState<Self>>,
366 ) {
367 }
368
369 /// Reacts to the pointer moving, for the hover popover.
370 fn on_mouse_move(
371 _state: &mut InputBaseState<Self>,
372 _offset: usize,
373 _event: &gpui::MouseMoveEvent,
374 _window: &mut Window,
375 _cx: &mut gpui::Context<InputBaseState<Self>>,
376 ) {
377 }
378
379 /// Registers the actions that only this mode handles.
380 fn register_actions(
381 element: Stateful<Div>,
382 _entity: &Entity<InputBaseState<Self>>,
383 _window: &mut Window,
384 ) -> Stateful<Div> {
385 element
386 }
387}
388
389impl InputModeKind for InputMode {
390 const MULTI_LINE: bool = false;
391
392 /// A single-line field needs little beyond the shared engine. Masking,
393 /// validation and number stepping live there: together they are ~120 bytes
394 /// and their access sites sit inside the shared edit path, so separating
395 /// them would cost more in dispatch than it saves. It shares the
396 /// textarea's one layer of decorations its owner sets, such as a search
397 /// field colouring the terms it parsed.
398 type Extras = TextareaExtras;
399
400 fn reset_annotations(state: &mut InputBaseState<Self>) {
401 state.extras.decorations.clear();
402 }
403
404 fn adjust_annotations(
405 state: &mut InputBaseState<Self>,
406 range: &std::ops::Range<usize>,
407 new_len: usize,
408 ) {
409 state.extras.adjust_for_edit(range, new_len);
410 }
411}
412impl InputModeKind for TextareaMode {
413 const MULTI_LINE: bool = true;
414
415 /// Ordinary multi-line text, with decorations its owner sets.
416 type Extras = TextareaExtras;
417
418 fn reset_annotations(state: &mut InputBaseState<Self>) {
419 state.extras.decorations.clear();
420 }
421
422 fn adjust_annotations(
423 state: &mut InputBaseState<Self>,
424 range: &std::ops::Range<usize>,
425 new_len: usize,
426 ) {
427 state.extras.adjust_for_edit(range, new_len);
428 }
429}
430
431/// What a textarea and a single-line input add: one layer of text
432/// decorations, such as inline marks. Their ranges follow edits like an
433/// editor's decoration collections.
434#[derive(Default)]
435pub struct TextareaExtras {
436 pub(crate) decorations: Vec<TextDecoration>,
437 pub(crate) revision: u64,
438}
439
440impl InputExtras for TextareaExtras {
441 fn decoration_layers(&self) -> Vec<&[TextDecoration]> {
442 if self.decorations.is_empty() {
443 Vec::new()
444 } else {
445 vec![&self.decorations[..]]
446 }
447 }
448
449 fn decorations_revision(&self) -> u64 {
450 self.revision
451 }
452}
453// `EditorMode`'s implementation lives with the editor code, next to the
454// language features it dispatches to.
455
456/// What a code editor adds on top of multi-line text: language features.
457pub struct EditorExtras {
458 pub(crate) lsp: Lsp,
459 pub(crate) decorations: DecorationCollections,
460 pub(crate) range_decorations: DecorationCollections<RangeDecoration>,
461 pub(crate) gutter_decorations: DecorationCollections<GutterDecoration>,
462 pub(crate) gutter_decorations_width: gpui::Pixels,
463 pub(crate) overview_ruler_decorations: DecorationCollections<OverviewRulerDecoration>,
464 pub(crate) line_decorations: LineDecorationProviders,
465 pub(crate) spacer_provider: Option<Rc<dyn SpacerProvider>>,
466 pub(crate) inline_completion: InlineCompletion,
467 pub(crate) context_menu_content: ContextMenuContent,
468 pub(crate) hover_popover: Option<HoverPopoverState>,
469 pub(crate) hover_definition: HoverDefinition,
470 pub(crate) context_menu_task: Task<anyhow::Result<()>>,
471}
472
473impl Default for EditorExtras {
474 fn default() -> Self {
475 Self {
476 lsp: Lsp::default(),
477 decorations: DecorationCollections::default(),
478 range_decorations: DecorationCollections::default(),
479 gutter_decorations: DecorationCollections::default(),
480 gutter_decorations_width: gpui::px(3.),
481 overview_ruler_decorations: DecorationCollections::default(),
482 line_decorations: LineDecorationProviders::default(),
483 spacer_provider: None,
484 inline_completion: InlineCompletion::default(),
485 context_menu_content: ContextMenuContent::default(),
486 hover_popover: None,
487 hover_definition: HoverDefinition::default(),
488 context_menu_task: Task::ready(Ok(())),
489 }
490 }
491}