BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / input / base / kind.rs

kind.rs

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