BlueGit

ict rusty-teams

Files

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

mode.rs

mode.rs 15.9 KiB Download Raw
1use crate::input::InputModeKind;
2use std::rc::Rc;
3use std::{cell::RefCell, ops::Range};
4
5use gpui::{Context, Pixels, Window, px};
6use ropey::Rope;
7
8use super::DisplayMap;
9use crate::input::{
10 DiagnosticSet, EditorLanguage, InputEdit, InputHighlighter, InputHighlighterFactory,
11 LanguageConfig, RopeExt as _, TabSize,
12};
13
14const BLOCK_GROWTH_FACTOR: usize = 2;
15
16/// What changed, handed to the syntax highlighter.
17pub(crate) struct HighlighterUpdate<'a> {
18 pub(super) selected_range: &'a Range<usize>,
19 pub(super) old_text: &'a Rope,
20 pub(super) new_text: &'a Rope,
21 pub(super) change_text: &'a str,
22 pub(super) force: bool,
23}
24
25/// How the input lays its text out: rows, growth, and the code-editor extras.
26///
27/// This does not say what *kind* of input this is — that is fixed at the type
28/// level by [`crate::input::InputModeKind`], and asking it here is what used to
29/// let the two disagree.
30#[derive(Clone)]
31pub(crate) enum LayoutMode {
32 /// A plain text input mode.
33 PlainText { tab: TabSize, rows: usize },
34 /// An auto grow input mode.
35 AutoGrow {
36 rows: usize,
37 min_rows: usize,
38 max_rows: usize,
39 extra: Pixels,
40 },
41 /// A code editor input mode.
42 CodeEditor {
43 tab: TabSize,
44 rows: usize,
45 /// Show line number
46 line_number: bool,
47 language: Box<EditorLanguage>,
48 indent_guides: bool,
49 folding: bool,
50 highlighter: Rc<RefCell<Option<Box<dyn InputHighlighter>>>>,
51 highlighter_factory: Option<InputHighlighterFactory>,
52 diagnostics: DiagnosticSet,
53 /// Automatic delimiter ranges, adjusted with document edits.
54 auto_closed_pairs: super::auto_close::AutoClosedPairs,
55 auto_close: bool,
56 smart_indent: bool,
57 },
58}
59
60impl Default for LayoutMode {
61 fn default() -> Self {
62 LayoutMode::plain_text()
63 }
64}
65
66#[allow(unused)]
67impl LayoutMode {
68 /// Create a plain input mode with default settings.
69 pub(super) fn plain_text() -> Self {
70 LayoutMode::PlainText {
71 tab: TabSize::default(),
72 rows: 1,
73 }
74 }
75
76 /// Create a code editor input mode with default settings.
77 ///
78 /// Starts with no language; the state sets one through its own builder.
79 pub(super) fn code_editor(language: EditorLanguage) -> Self {
80 LayoutMode::CodeEditor {
81 rows: 2,
82 tab: TabSize::default(),
83 language: Box::new(language),
84 highlighter: Rc::new(RefCell::new(None)),
85 highlighter_factory: None,
86 line_number: true,
87 indent_guides: true,
88 folding: true,
89 diagnostics: DiagnosticSet::new(&Rope::new()),
90 auto_closed_pairs: Default::default(),
91 auto_close: true,
92 smart_indent: true,
93 }
94 }
95
96 /// Create an auto grow input mode with given min and max rows.
97 pub(super) fn auto_grow(min_rows: usize, max_rows: usize) -> Self {
98 LayoutMode::AutoGrow {
99 rows: min_rows,
100 min_rows,
101 max_rows,
102 extra: px(0.),
103 }
104 }
105
106 /// Return true if this layout is a code editor with folding enabled.
107 #[inline]
108 pub(crate) fn is_folding(&self) -> bool {
109 if cfg!(target_family = "wasm") {
110 return false;
111 }
112
113 matches!(self, LayoutMode::CodeEditor { folding: true, .. })
114 }
115
116 pub(super) fn language_config(&self) -> Option<Rc<LanguageConfig>> {
117 match self {
118 Self::CodeEditor { language, .. } => Some(language.config()),
119 _ => None,
120 }
121 }
122
123 pub(super) fn syntax_context_at(
124 &self,
125 text: &Rope,
126 offset: usize,
127 ) -> crate::input::SyntaxContext {
128 match self {
129 Self::CodeEditor { language, .. } => language.context_at(text, offset),
130 _ => crate::input::SyntaxContext::Code,
131 }
132 }
133
134 pub(super) fn is_auto_close(&self) -> bool {
135 matches!(
136 self,
137 Self::CodeEditor {
138 auto_close: true,
139 ..
140 }
141 )
142 }
143
144 pub(super) fn is_smart_indent(&self) -> bool {
145 matches!(
146 self,
147 Self::CodeEditor {
148 smart_indent: true,
149 ..
150 }
151 )
152 }
153
154 pub(super) fn set_auto_close(&mut self, enabled: bool) {
155 if let Self::CodeEditor { auto_close, .. } = self {
156 *auto_close = enabled;
157 }
158 }
159
160 pub(super) fn set_smart_indent(&mut self, enabled: bool) {
161 if let Self::CodeEditor { smart_indent, .. } = self {
162 *smart_indent = enabled;
163 }
164 }
165
166 pub(super) fn auto_closed_pairs(&self) -> &super::auto_close::AutoClosedPairs {
167 match self {
168 Self::CodeEditor {
169 auto_closed_pairs, ..
170 } => auto_closed_pairs,
171 _ => super::auto_close::AutoClosedPairs::empty(),
172 }
173 }
174
175 pub(super) fn restore_auto_closed_pairs(&mut self, pairs: super::auto_close::AutoClosedPairs) {
176 if let Self::CodeEditor {
177 auto_closed_pairs, ..
178 } = self
179 {
180 *auto_closed_pairs = pairs;
181 }
182 }
183
184 pub(super) fn track_auto_closed_pair(&mut self, open: Range<usize>, close: Range<usize>) {
185 if let Self::CodeEditor {
186 auto_closed_pairs, ..
187 } = self
188 {
189 auto_closed_pairs.record(open, close);
190 }
191 }
192
193 pub(super) fn adjust_auto_closed_pair(&mut self, edit: &Range<usize>, new_len: usize) {
194 let Self::CodeEditor {
195 auto_closed_pairs, ..
196 } = self
197 else {
198 return;
199 };
200 auto_closed_pairs.adjust(edit, new_len);
201 }
202
203 #[inline]
204 pub(super) fn is_auto_grow(&self) -> bool {
205 matches!(self, LayoutMode::AutoGrow { .. })
206 }
207
208 pub(super) fn set_rows(&mut self, new_rows: usize) {
209 match self {
210 LayoutMode::PlainText { rows, .. } => {
211 *rows = new_rows;
212 }
213 LayoutMode::CodeEditor { rows, .. } => {
214 *rows = new_rows;
215 }
216 LayoutMode::AutoGrow {
217 rows,
218 min_rows,
219 max_rows,
220 ..
221 } => {
222 *rows = new_rows.clamp(*min_rows, *max_rows);
223 }
224 }
225 }
226
227 /// Grow the row count to fit the content. Block tokens add their height on top of
228 /// `max_rows`, up to `BLOCK_GROWTH_FACTOR` times it.
229 ///
230 /// Callers gate this on the input being multi-line; a single-line field
231 /// keeps its one row. Only auto grow follows the content: in the other
232 /// modes `rows` is the configured height.
233 pub(super) fn update_auto_grow(&mut self, display_map: &DisplayMap, line_height: Pixels) {
234 if !self.is_auto_grow() {
235 return;
236 }
237 let content_rows = display_map.content_rows(line_height);
238 let block_rows = content_rows.saturating_sub(display_map.wrap_row_count());
239 if let LayoutMode::AutoGrow {
240 rows,
241 min_rows,
242 max_rows,
243 extra,
244 } = self
245 {
246 let cap = (*max_rows + block_rows).min(*max_rows * BLOCK_GROWTH_FACTOR);
247 *rows = content_rows.clamp(*min_rows, cap.max(*max_rows));
248 *extra = if content_rows > *rows {
249 px(0.)
250 } else {
251 (line_height * content_rows as f32 + display_map.scaled_extra()
252 - line_height * *rows as f32)
253 .max(px(0.))
254 };
255 }
256 }
257
258 pub(super) fn grow_extra(&self) -> Pixels {
259 match self {
260 LayoutMode::AutoGrow { extra, .. } => *extra,
261 _ => px(0.),
262 }
263 }
264
265 /// At least 1 row be return.
266 pub(super) fn rows(&self) -> usize {
267 match self {
268 LayoutMode::PlainText { rows, .. } => *rows,
269 LayoutMode::CodeEditor { rows, .. } => *rows,
270 LayoutMode::AutoGrow { rows, .. } => *rows,
271 }
272 .max(1)
273 }
274
275 /// At least 1 row be return.
276 #[allow(unused)]
277 pub(super) fn min_rows(&self) -> usize {
278 match self {
279 LayoutMode::AutoGrow { min_rows, .. } => *min_rows,
280 _ => 1,
281 }
282 .max(1)
283 }
284
285 #[allow(unused)]
286 pub(super) fn max_rows(&self) -> usize {
287 match self {
288 LayoutMode::AutoGrow { max_rows, .. } => *max_rows,
289 _ => usize::MAX,
290 }
291 }
292
293 /// Return false if the mode is not [`LayoutMode::CodeEditor`].
294 #[inline]
295 pub(super) fn line_number(&self) -> bool {
296 match self {
297 LayoutMode::CodeEditor { line_number, .. } => *line_number,
298 _ => false,
299 }
300 }
301
302 /// Update the syntax highlighter with new text.
303 ///
304 pub(crate) fn update_highlighter<M: InputModeKind>(
305 &mut self,
306 update: HighlighterUpdate<'_>,
307 window: &mut Window,
308 cx: &mut Context<crate::input::InputBaseState<M>>,
309 ) {
310 match &self {
311 LayoutMode::CodeEditor {
312 language,
313 highlighter,
314 highlighter_factory,
315 folding,
316 ..
317 } => {
318 if !update.force && highlighter.borrow().is_some() {
319 return;
320 }
321 if !ensure_highlighter(highlighter, highlighter_factory.as_ref(), language) {
322 return;
323 }
324
325 let edit = replacement_input_edit(
326 update.old_text,
327 update.new_text,
328 update.selected_range,
329 update.change_text,
330 );
331 M::drive_highlighter(highlighter, edit, update.new_text, *folding, window, cx);
332 }
333 _ => {}
334 }
335 }
336
337 /// Drive the highlighter once for several edits applied as one change,
338 /// each paired with the text right after it, in application order.
339 pub(crate) fn update_highlighter_batch<M: InputModeKind>(
340 &mut self,
341 edits: &[(InputEdit, Rope)],
342 window: &mut Window,
343 cx: &mut Context<crate::input::InputBaseState<M>>,
344 ) {
345 let LayoutMode::CodeEditor {
346 language,
347 highlighter,
348 highlighter_factory,
349 folding,
350 ..
351 } = &self
352 else {
353 return;
354 };
355 if !ensure_highlighter(highlighter, highlighter_factory.as_ref(), language) {
356 return;
357 }
358 M::drive_highlighter_batch(highlighter, edits, *folding, window, cx);
359 }
360
361 #[allow(unused)]
362 pub(super) fn diagnostics(&self) -> Option<&DiagnosticSet> {
363 match self {
364 LayoutMode::CodeEditor { diagnostics, .. } => Some(diagnostics),
365 _ => None,
366 }
367 }
368
369 pub(super) fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
370 match self {
371 LayoutMode::CodeEditor { diagnostics, .. } => Some(diagnostics),
372 _ => None,
373 }
374 }
375
376 /// Get a reference to the highlighter (if available)
377 pub(super) fn highlighter(&self) -> Option<&Rc<RefCell<Option<Box<dyn InputHighlighter>>>>> {
378 match self {
379 LayoutMode::CodeEditor { highlighter, .. } => Some(highlighter),
380 _ => None,
381 }
382 }
383
384 pub(super) fn set_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
385 if let LayoutMode::CodeEditor {
386 highlighter_factory,
387 highlighter,
388 ..
389 } = self
390 {
391 *highlighter_factory = Some(factory);
392 *highlighter.borrow_mut() = None;
393 }
394 }
395
396 pub(super) fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
397 if let LayoutMode::CodeEditor {
398 highlighter_factory,
399 ..
400 } = self
401 {
402 if highlighter_factory.is_none() {
403 *highlighter_factory = Some(factory);
404 }
405 }
406 }
407}
408
409/// Create the highlighter from the factory if there is none yet. Returns
410/// whether one is installed.
411fn ensure_highlighter(
412 highlighter: &RefCell<Option<Box<dyn InputHighlighter>>>,
413 highlighter_factory: Option<&InputHighlighterFactory>,
414 language: &EditorLanguage,
415) -> bool {
416 let mut highlighter = highlighter.borrow_mut();
417 if highlighter.is_none()
418 && let Some(factory) = highlighter_factory
419 {
420 *highlighter = factory(&language.name());
421 }
422 highlighter.is_some()
423}
424
425/// Builds the tree-sitter edit for a text replacement.
426///
427/// Byte offsets and positions for `start`/`old_end` come from `old_text`;
428/// `new_end` byte/position come from the post-edit `text`.
429pub(super) fn replacement_input_edit(
430 old_text: &Rope,
431 new_text: &Rope,
432 selected_range: &Range<usize>,
433 change_text: &str,
434) -> InputEdit {
435 let start_byte = selected_range.start.min(old_text.len());
436 let old_end_byte = selected_range.end.min(old_text.len()).max(start_byte);
437 let new_end_byte = (start_byte + change_text.len()).min(new_text.len());
438
439 InputEdit {
440 start_byte,
441 old_end_byte,
442 new_end_byte,
443 start_position: old_text.offset_to_point(start_byte),
444 old_end_position: old_text.offset_to_point(old_end_byte),
445 new_end_position: new_text.offset_to_point(new_end_byte),
446 }
447}
448
449#[cfg(test)]
450mod tests {
451 use ropey::Rope;
452
453 use super::replacement_input_edit;
454 use crate::input::{DiagnosticSet, Point, TabSize, mode::LayoutMode};
455
456 #[test]
457 fn test_replacement_input_edit_backspace_at_end_uses_old_range() {
458 let old_text = Rope::from_str("-=");
459 let text = Rope::from_str("-");
460 let edit = replacement_input_edit(&old_text, &text, &(1..2), "");
461
462 assert_eq!(edit.start_byte, 1);
463 assert_eq!(edit.old_end_byte, 2);
464 assert_eq!(edit.new_end_byte, 1);
465 assert_eq!(edit.start_position, Point::new(0, 1));
466 assert_eq!(edit.old_end_position, Point::new(0, 2));
467 assert_eq!(edit.new_end_position, Point::new(0, 1));
468 }
469
470 #[test]
471 fn test_code_editor() {
472 let mode = LayoutMode::code_editor(Default::default());
473 assert_eq!(mode.line_number(), true);
474 assert_eq!(mode.has_indent_guides(), true);
475 assert_eq!(mode.max_rows(), usize::MAX);
476 assert_eq!(mode.min_rows(), 1);
477 assert_eq!(mode.is_folding(), true);
478
479 let mode = LayoutMode::CodeEditor {
480 line_number: false,
481 indent_guides: false,
482 folding: false,
483 rows: 0,
484 tab: Default::default(),
485 language: Box::default(),
486 highlighter: Default::default(),
487 highlighter_factory: None,
488 diagnostics: DiagnosticSet::new(&Rope::new()),
489 auto_closed_pairs: Default::default(),
490 auto_close: false,
491 smart_indent: false,
492 };
493 assert_eq!(mode.line_number(), false);
494 assert_eq!(mode.has_indent_guides(), false);
495 assert_eq!(mode.min_rows(), 1);
496 assert_eq!(mode.is_folding(), false);
497 assert_eq!(mode.is_auto_close(), false);
498 assert_eq!(mode.is_smart_indent(), false);
499 }
500
501 #[test]
502 fn test_plain() {
503 let mode = LayoutMode::PlainText {
504 tab: TabSize::default(),
505 rows: 5,
506 };
507 assert_eq!(mode.line_number(), false);
508 assert_eq!(mode.rows(), 5);
509 assert_eq!(mode.max_rows(), usize::MAX);
510 assert_eq!(mode.min_rows(), 1);
511
512 let mode = LayoutMode::plain_text();
513 assert_eq!(mode.line_number(), false);
514 assert_eq!(mode.rows(), 1);
515 assert_eq!(mode.min_rows(), 1);
516 }
517
518 #[test]
519 fn test_auto_grow() {
520 let mut mode = LayoutMode::auto_grow(2, 5);
521 assert_eq!(mode.line_number(), false);
522 assert_eq!(mode.rows(), 2);
523 assert_eq!(mode.max_rows(), 5);
524 assert_eq!(mode.min_rows(), 2);
525
526 mode.set_rows(4);
527 assert_eq!(mode.rows(), 4);
528
529 mode.set_rows(1);
530 assert_eq!(mode.rows(), 2);
531
532 mode.set_rows(10);
533 assert_eq!(mode.rows(), 5);
534 }
535}