1use std::rc::Rc;
2
3use gpui::{
4 App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,
5 Window, prelude::FluentBuilder as _, relative,
6};
7
8use super::{EditorState, GutterStyle, Input};
9use crate::native_menu::NativeMenu;
10use crate::{ActiveTheme as _, RoleOverride, Sizable, Size, StyledExt as _};
11
12const EDITOR_LINE_HEIGHT: f32 = 1.5;
15
16#[derive(IntoElement)]
18pub struct Editor {
19 state: Entity<EditorState>,
20 gutter_style: GutterStyle,
21 style: StyleRefinement,
22 size: Size,
23 height: Option<DefiniteLength>,
24 appearance: bool,
25 bordered: bool,
26 disabled: bool,
27 readonly: bool,
28 tab_index: isize,
29 role: RoleOverride,
30 aria_label: Option<SharedString>,
31
32 context_menu_builder: Option<Rc<dyn Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu>>,
36
37 paste_handler: Option<Rc<dyn Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool>>,
38}
39
40impl Editor {
41 pub fn new(state: &Entity<EditorState>) -> Self {
42 Self {
43 state: state.clone(),
44 gutter_style: GutterStyle::default(),
45 style: StyleRefinement::default(),
46 size: Size::default(),
47 height: None,
48 appearance: true,
49 bordered: true,
50 disabled: false,
51 readonly: false,
52 tab_index: 0,
53 role: RoleOverride::default(),
54 aria_label: None,
55 context_menu_builder: None,
56 paste_handler: None,
57 }
58 }
59
60 pub fn gutter_style(mut self, style: GutterStyle) -> Self {
64 self.gutter_style.apply_overrides(style);
65 self
66 }
67
68 pub fn h(mut self, height: impl Into<DefiniteLength>) -> Self {
69 self.height = Some(height.into());
70 self
71 }
72
73 pub fn appearance(mut self, appearance: bool) -> Self {
74 self.appearance = appearance;
75 self
76 }
77
78 pub fn bordered(mut self, bordered: bool) -> Self {
79 self.bordered = bordered;
80 self
81 }
82
83 pub fn disabled(mut self, disabled: bool) -> Self {
84 self.disabled = disabled;
85 self
86 }
87
88 pub fn readonly(mut self, readonly: bool) -> Self {
94 self.readonly = readonly;
95 self
96 }
97
98 pub fn tab_index(mut self, index: isize) -> Self {
99 self.tab_index = index;
100 self
101 }
102
103 pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
104 self.role = role.into();
105 self
106 }
107
108 pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
109 self.aria_label = Some(label.into());
110 self
111 }
112
113 pub fn context_menu(
120 mut self,
121 f: impl Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu + 'static,
122 ) -> Self {
123 self.context_menu_builder = Some(Rc::new(f));
124 self
125 }
126
127 pub fn on_paste(
134 mut self,
135 handler: impl Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool + 'static,
136 ) -> Self {
137 self.paste_handler = Some(Rc::new(handler));
138 self
139 }
140}
141
142impl Sizable for Editor {
146 fn with_size(mut self, size: impl Into<Size>) -> Self {
147 self.size = size.into();
148 self
149 }
150}
151
152impl Styled for Editor {
153 fn style(&mut self) -> &mut StyleRefinement {
154 &mut self.style
155 }
156}
157
158impl RenderOnce for Editor {
159 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
160 Input::from_state(self.state.clone())
161 .gutter_style(self.gutter_style)
162 .font_family(cx.theme().mono_font_family.clone())
167 .text_size(cx.theme().mono_font_size)
168 .line_height(relative(EDITOR_LINE_HEIGHT))
169 .with_size(self.size)
170 .appearance(self.appearance)
171 .bordered(self.bordered)
172 .focus_bordered(false)
173 .disabled(self.disabled)
174 .readonly(self.readonly)
175 .tab_index(self.tab_index)
176 .role(self.role)
177 .when_some(self.height, |this, height| this.h(height))
178 .when_some(self.aria_label, |this, label| this.aria_label(label))
179 .when_some(self.context_menu_builder, |this, build| {
180 this.context_menu(move |menu, window, cx| build(menu, window, cx))
181 })
182 .when_some(self.paste_handler, |this, handler| {
183 this.on_paste(move |item, window, cx| handler(item, window, cx))
184 })
185 .refine_style(&self.style)
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use crate::input::EditorState;
193 use gpui::{
194 AppContext as _, Context, InteractiveElement as _, ParentElement as _, Pixels, Render,
195 TestAppContext, VisualTestContext, div, px, rems,
196 };
197
198 #[gpui::test]
199 fn test_editor_gutter_style_builder(cx: &mut TestAppContext) {
200 cx.update(crate::init);
201 cx.add_window_view(|window, cx| {
202 let state = cx.new(|cx| EditorState::new(window, cx));
203 let defaults = GutterStyle::default()
204 .with_gap(px(12.))
205 .with_line_number_color(gpui::rgb(0x808080).into())
206 .with_active_line_number_color(gpui::rgb(0xeeeeee).into())
207 .with_line_number_font_family("Number Font")
208 .with_line_number_font_size(px(12.));
209 let editor = Editor::new(&state)
210 .gutter_style(defaults.clone())
211 .gutter_style(GutterStyle::default().with_gap(px(0.)));
212 assert_eq!(editor.gutter_style, defaults.with_gap(px(0.)));
213 Harness {
214 state,
215 text_size: None,
216 }
217 });
218 }
219
220 struct GutterHarness {
221 state: Entity<EditorState>,
222 overrides: Option<GutterStyle>,
223 }
224
225 impl Render for GutterHarness {
226 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
227 div().size_full().child(
228 Editor::new(&self.state)
229 .font_family(".SystemUIFont")
230 .text_size(rems(1.))
231 .when_some(self.overrides.clone(), |this, style| {
232 this.gutter_style(style)
233 }),
234 )
235 }
236 }
237
238 #[gpui::test]
239 fn gutter_overrides_and_removal_reach_the_rendered_editor(cx: &mut TestAppContext) {
240 cx.update(crate::init);
241 let (view, cx) = cx.add_window_view(|window, cx| GutterHarness {
242 state: cx.new(|cx| EditorState::new(window, cx).default_value("hello\nworld")),
243 overrides: None,
244 });
245 let state = view.read_with(cx, |view, _| view.state.clone());
246 let measure = |cx: &mut VisualTestContext| {
247 cx.update(|window, cx| {
248 window.refresh();
249 window.draw(cx).clear(cx);
250 let state = state.read(cx);
251 let caret = state
252 .prepaint_caret_geometry()
253 .expect("editor must prepaint");
254 (
255 caret.cursor_bounds().left() - caret.input_bounds().left(),
256 caret.line_height(),
257 state.range_to_bounds(&(0..1)).unwrap().size.width,
258 )
259 })
260 };
261 let baseline = measure(cx);
262
263 view.update(cx, |view, cx| {
264 view.overrides = Some(
265 GutterStyle::default()
266 .with_gap(px(18.))
267 .with_line_number_font_family(".SystemUIFont")
268 .with_line_number_font_size(px(16.)),
269 );
270 cx.notify();
271 });
272 let configured = measure(cx);
273 assert_eq!(configured.0 - baseline.0, px(12.));
274 assert_eq!((configured.1, configured.2), (baseline.1, baseline.2));
275
276 view.update(cx, |view, cx| {
277 view.overrides = Some(GutterStyle::default().with_gap(px(0.)));
278 cx.notify();
279 });
280 let overridden = measure(cx);
281 assert_eq!(configured.0 - overridden.0, px(18.));
282
283 view.update(cx, |view, cx| {
284 view.overrides = Some(
285 GutterStyle::default()
286 .with_gap(px(0.))
287 .with_line_number_font_size(px(24.)),
288 );
289 cx.notify();
290 });
291 let changed = measure(cx);
292 assert!(changed.0 > overridden.0);
294 assert_eq!((changed.1, changed.2), (baseline.1, baseline.2));
295
296 view.update(cx, |view, cx| {
297 view.overrides = Some(
298 GutterStyle::default()
299 .with_gap(px(24.))
300 .with_line_number_font_size(px(24.)),
301 );
302 cx.notify();
303 });
304 let restored = measure(cx);
305 assert_eq!(restored.0 - changed.0, px(24.));
306
307 view.update(cx, |view, cx| {
308 view.overrides = None;
309 cx.notify();
310 });
311 assert_eq!(measure(cx), baseline);
312 }
313
314 struct Harness {
315 state: Entity<EditorState>,
316 text_size: Option<Pixels>,
318 }
319
320 impl Render for Harness {
321 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
322 div().size_full().child(
323 Editor::new(&self.state)
324 .when_some(self.text_size, |this, size| this.text_size(size)),
325 )
326 }
327 }
328
329 #[gpui::test]
330 fn gutter_and_body_follow_window_zoom_without_compounding(cx: &mut TestAppContext) {
331 use crate::{ElementExt as _, Root, Theme, init};
332 use std::cell::Cell;
333
334 struct ZoomHarness {
335 editor: Entity<GutterHarness>,
336 spacing_edges: Rc<Cell<(Pixels, Pixels)>>,
337 }
338
339 impl Render for ZoomHarness {
340 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
341 let first = self.spacing_edges.clone();
342 let second = self.spacing_edges.clone();
343 div()
344 .relative()
345 .size_full()
346 .child(self.editor.clone())
347 .child(
348 div()
349 .absolute()
350 .flex()
351 .gap_2()
352 .child(div().w(px(1.)).h(px(1.)).on_prepaint(move |bounds, _, _| {
353 first.set((bounds.right(), first.get().1));
354 }))
355 .child(div().w(px(1.)).h(px(1.)).on_prepaint(move |bounds, _, _| {
356 second.set((second.get().0, bounds.left()));
357 })),
358 )
359 }
360 }
361
362 cx.update(|cx| {
363 init(cx);
364 Theme::update(cx, |theme| theme.font_size = px(22.));
365 });
366 let spacing_edges = Rc::new(Cell::new((px(0.), px(0.))));
367 let mut view = None;
368 let (_, cx) = cx.add_window_view(|window, cx| {
369 let editor = cx.new(|cx| GutterHarness {
370 state: cx.new(|cx| {
371 EditorState::new(window, cx)
372 .folding(false)
373 .default_value("hello\nworld")
374 }),
375 overrides: Some(
376 GutterStyle::default()
377 .with_gap(rems(0.75))
378 .with_line_number_font_size(rems(0.75)),
379 ),
380 });
381 view = Some(editor.clone());
382 let content = cx.new(|_| ZoomHarness {
383 editor,
384 spacing_edges: spacing_edges.clone(),
385 });
386 Root::new(content, window, cx)
388 });
389 let view = view.unwrap();
390 let state = view.read_with(cx, |view, _| view.state.clone());
391 let measure = |cx: &mut VisualTestContext, rem_size: Option<f32>| {
392 cx.update(|window, cx| {
393 if let Some(rem_size) = rem_size {
394 Theme::update(cx, |theme| theme.font_size = px(rem_size));
395 }
396 for _ in 0..2 {
398 window.refresh();
399 window.draw(cx).clear(cx);
400 }
401 let caret = state.read(cx).prepaint_caret_geometry().unwrap();
402 let (first_right, second_left) = spacing_edges.get();
403 (
404 caret.cursor_bounds().left() - caret.input_bounds().left(),
405 caret.line_height(),
406 second_left - first_right,
407 window.rem_size(),
408 )
409 })
410 };
411 let initial = measure(cx, None);
412 assert_eq!(
413 (initial.1, initial.2, initial.3),
414 (px(33.), px(11.), px(22.))
415 );
416 let baseline = measure(cx, Some(16.));
417 for (rem_size, scale, expected_height) in [
418 (12., 0.75, 18.),
419 (24., 1.5, 36.),
420 (32., 2., 48.),
421 (16., 1., 24.),
422 ] {
423 let measured = measure(cx, Some(rem_size));
424 let expected_width = baseline.0 * scale;
425 let tolerance = measured.0.abs().max(expected_width.abs()) * (4. * f32::EPSILON);
428 assert!((measured.0 - expected_width).abs() <= tolerance);
429 assert_eq!(measured.1, px(expected_height));
430 assert_eq!(measured.2, px(rem_size * 0.5));
431 assert_eq!(measured.3, px(rem_size));
432 }
433 assert_eq!(measure(cx, Some(16.)), baseline);
434 assert_eq!(measure(cx, None), baseline);
435 let zoomed = measure(cx, Some(24.));
436 assert_eq!(measure(cx, None), zoomed);
437 view.read_with(cx, |view, _| {
438 let style = view.overrides.as_ref().unwrap();
439 assert_eq!(style.gap(), Some(rems(0.75).into()));
440 assert_eq!(style.line_number_font_size(), Some(rems(0.75).into()));
441 });
442 }
443
444 fn line_height(cx: &mut TestAppContext, text_size: Option<Pixels>) -> Pixels {
446 cx.update(crate::init);
447 let mut state = None;
448 let (_, cx) = cx.add_window_view(|window, cx| {
449 let editor = cx.new(|cx| EditorState::new(window, cx).default_value("fn main() {}"));
450 state = Some(editor.clone());
451 Harness {
452 state: editor,
453 text_size,
454 }
455 });
456 let state = state.unwrap();
457 VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));
458
459 cx.read(|cx| {
460 state
461 .read(cx)
462 .line_height()
463 .expect("the editor must lay out")
464 })
465 }
466
467 #[gpui::test]
468 fn the_rows_follow_the_font_size(cx: &mut TestAppContext) {
469 assert_eq!(line_height(cx, None), px(20.));
471 assert_eq!(line_height(cx, Some(px(24.))), px(36.));
473 assert_eq!(line_height(cx, Some(px(40.))), px(60.));
474 }
475
476 struct SizedHarness {
477 state: Entity<EditorState>,
478 size: Option<Size>,
480 }
481
482 impl Render for SizedHarness {
483 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
484 div().debug_selector(|| "frame".into()).size_full().child(
485 Editor::new(&self.state).when_some(self.size, |this, size| this.with_size(size)),
486 )
487 }
488 }
489
490 fn top_inset(cx: &mut TestAppContext, size: Option<Size>) -> (Pixels, Pixels) {
493 cx.update(crate::init);
494 let mut state = None;
495 let (_, cx) = cx.add_window_view(|window, cx| {
496 let editor = cx.new(|cx| EditorState::new(window, cx).default_value("fn main() {}"));
497 state = Some(editor.clone());
498 SizedHarness {
499 state: editor,
500 size,
501 }
502 });
503 let state = state.unwrap();
504 VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));
505
506 let frame = cx.debug_bounds("frame").expect("the frame must lay out");
507 let (text, line_height) = cx.read(|cx| {
508 let state = state.read(cx);
509 let line_height = state.line_height().expect("the editor must lay out");
510 (state.input_bounds(), line_height)
511 });
512 (text.top() - frame.top(), line_height)
513 }
514
515 #[gpui::test]
516 fn the_insets_follow_the_size(cx: &mut TestAppContext) {
517 let (medium, rows) = top_inset(cx, Some(Size::Medium));
518 assert_eq!(top_inset(cx, None), (medium, rows));
520 for size in [Size::XSmall, Size::Small, Size::Large] {
521 let (inset, line_height) = top_inset(cx, Some(size));
522 assert_eq!(
523 medium - inset,
524 Size::Medium.input_py() - size.input_py(),
525 "{size:?}"
526 );
527 assert_eq!(line_height, rows, "{size:?}");
529 }
530 }
531
532 #[gpui::test]
533 fn language_config_works_without_render_sync(cx: &mut TestAppContext) {
534 use crate::input::{AutoClosingPair, language_config::LanguageConfig, set_language_config};
535 use gpui::EntityInputHandler as _;
536 cx.update(crate::init);
537 let mut state = None;
538 let (_, cx) = cx.add_window_view(|window, cx| {
539 let editor = cx.new(|cx| EditorState::new(window, cx).language("plaintext"));
540 editor.update(cx, |state, cx| {
542 state.replace_text_in_range(None, "(", window, cx);
543 assert_eq!(state.text().to_string(), "(");
544 state.set_value("", window, cx);
545 state.set_highlighter("json", cx);
546 state.replace_text_in_range(None, "[", window, cx);
547 assert_eq!(state.text().to_string(), "[]");
548 });
549 state = Some(editor.clone());
550 Harness {
551 state: editor,
552 text_size: None,
553 }
554 });
555 let state = state.unwrap();
556 VisualTestContext::update(cx, |_, cx| {
557 set_language_config(
558 "json",
559 LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
560 cx,
561 );
562 });
563 VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));
565 VisualTestContext::update(cx, |window, cx| {
566 state.update(cx, |state, cx| {
567 state.set_value("", window, cx);
568 state.replace_text_in_range(None, "«", window, cx);
569 assert_eq!(state.text().to_string(), "«»");
570 state.set_value("if enabled:", window, cx);
571 state.set_selected_range(11..11, cx);
572 state.set_highlighter("python", cx);
573 state.focus(window, cx);
574 });
575 });
576 VisualTestContext::update(cx, |window, cx| window.draw(cx).clear(cx));
577 cx.simulate_keystrokes("enter");
578 cx.read(|cx| assert_eq!(state.read(cx).text().to_string(), "if enabled:\n "));
579 }
580
581 #[gpui::test]
582 fn aliases_share_config_even_when_registered_before_init(cx: &mut TestAppContext) {
583 use crate::input::{AutoClosingPair, language_config::LanguageConfig, set_language_config};
584 use gpui::EntityInputHandler as _;
585 cx.update(|cx| {
586 set_language_config(
587 "py",
588 LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
589 cx,
590 )
591 });
592 cx.update(crate::init);
593 cx.add_window_view(|window, cx| {
594 let editor = cx.new(|cx| EditorState::new(window, cx).language("PYTHON"));
595 editor.update(cx, |state, cx| {
596 state.replace_text_in_range(None, "«", window, cx);
597 assert_eq!(state.text().to_string(), "«»");
598 });
599 set_language_config("pyi", LanguageConfig::default().auto_closing_pairs([]), cx);
600 editor.update(cx, |state, cx| {
601 state.set_value("", window, cx);
602 state.set_highlighter("py", cx);
603 state.replace_text_in_range(None, "(", window, cx);
604 assert_eq!(state.text().to_string(), "(");
605 });
606 Harness {
607 state: editor,
608 text_size: None,
609 }
610 });
611 }
612
613 #[cfg(all(feature = "tree-sitter-python", feature = "tree-sitter-rust"))]
614 #[gpui::test]
615 fn syntax_follows_language_before_first_render_and_after_switch(cx: &mut TestAppContext) {
616 use gpui::EntityInputHandler as _;
617 cx.update(crate::init);
618 cx.add_window_view(|window, cx| {
619 let editor = cx.new(|cx| {
620 EditorState::new(window, cx)
621 .language("python")
622 .default_value("\"hello world\"")
623 });
624 editor.update(cx, |state, cx| {
625 state.set_selected_range(6..6, cx);
626 state.replace_text_in_range(None, "(", window, cx);
627 assert_eq!(state.text().to_string(), "\"hello( world\"");
628 state.set_value("# comment ", window, cx);
629 state.set_selected_range(10..10, cx);
630 state.replace_text_in_range(None, "(", window, cx);
631 assert_eq!(state.text().to_string(), "# comment (");
632 state.set_value("# comment ", window, cx);
633 state.set_selected_range(10..10, cx);
634 state.set_highlighter("rust", cx);
635 state.replace_text_in_range(None, "(", window, cx);
636 assert_eq!(state.text().to_string(), "# comment ()");
637 });
638 Harness {
639 state: editor,
640 text_size: None,
641 }
642 });
643 }
644
645 #[cfg(feature = "tree-sitter-python")]
646 #[gpui::test]
647 fn python_pairing_uses_pre_edit_context(cx: &mut TestAppContext) {
648 use gpui::EntityInputHandler as _;
649 cx.update(crate::init);
650 for (before, cursor, typed, expected) in [
651 ("x = ", 4, "\"", "x = \"\""),
652 ("x = f\"{value}\"", 12, "(", "x = f\"{value()}\""),
653 ("x = \"value\"", 7, "(", "x = \"va(lue\""),
654 ("x = \"value\"", 5, "(", "x = \"(value\""),
655 ("x = \"value\"", 10, "(", "x = \"value(\""),
656 ] {
657 let mut state = None;
658 let (_, cx) = cx.add_window_view(|window, cx| {
659 let editor = cx.new(|cx| EditorState::new(window, cx).default_value(before));
660 state = Some(editor.clone());
661 Harness {
662 state: editor,
663 text_size: None,
664 }
665 });
666 let state = state.unwrap();
667 VisualTestContext::update(cx, |window, cx| {
668 state.update(cx, |state, cx| {
669 state.set_highlighter("python", cx);
670 state.set_selected_range(cursor..cursor, cx);
671 state.replace_text_in_range(None, typed, window, cx);
672 assert_eq!(state.text().to_string(), expected);
673 });
674 });
675 }
676 }
677 #[cfg(feature = "tree-sitter-rust")]
678 #[gpui::test]
679 fn generated_comment_closer_survives_syntax_changes(cx: &mut TestAppContext) {
680 use crate::input::{AutoClosingPair, SyntaxContext, language_config::LanguageConfig};
681 use gpui::EntityInputHandler as _;
682 cx.update(crate::init);
683 cx.update(|cx| {
684 crate::input::set_language_config(
685 "rust",
686 LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("/*", "*/")
687 .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
688 cx,
689 )
690 });
691 let mut state = None;
692 let (_, cx) = cx.add_window_view(|window, cx| {
693 let editor = cx.new(|cx| EditorState::new(window, cx).language("rust"));
694 state = Some(editor.clone());
695 Harness {
696 state: editor,
697 text_size: None,
698 }
699 });
700 let state = state.unwrap();
701 VisualTestContext::update(cx, |window, cx| {
702 state.update(cx, |state, cx| {
703 state.set_highlighter("rust", cx);
704
705 for text in ["/", "*", "x", "*", "/"] {
706 state.replace_text_in_range(None, text, window, cx);
707 }
708 assert_eq!(state.text().to_string(), "/*x*/");
709 state.replace_text_in_range(None, "!", window, cx);
710 assert_eq!(state.text().to_string(), "/*x*/!");
711 });
712 });
713 }
714
715 #[gpui::test]
716 fn test_on_paste_builder(cx: &mut TestAppContext) {
717 use gpui::{AppContext as _, Render};
718
719 struct PasteProbe;
720 impl Render for PasteProbe {
721 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
722 div()
723 }
724 }
725
726 cx.update(crate::init);
727 let _ = cx.add_window_view(|window, cx| {
728 let state = cx.new(|cx| EditorState::new(window, cx));
729 assert!(Editor::new(&state).paste_handler.is_none());
730 let editor = Editor::new(&state).on_paste(|_, _, _| true);
731 assert!(editor.paste_handler.is_some());
732 PasteProbe
733 });
734 }
735}