1mod persistence;
2pub mod terminal_element;
3pub mod terminal_panel;
4mod terminal_path_like_target;
5pub mod terminal_scrollbar;
6mod terminal_slash_command;
7pub mod terminal_tab_tooltip;
8
9use assistant_slash_command::SlashCommandRegistry;
10use editor::{EditorSettings, actions::SelectAll, blink_manager::BlinkManager};
11use gpui::{
12 Action, AnyElement, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
13 KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render,
14 ScrollWheelEvent, Styled, Subscription, Task, WeakEntity, actions, anchored, deferred, div,
15};
16use persistence::TERMINAL_DB;
17use project::{Project, search::SearchQuery};
18use schemars::JsonSchema;
19use task::TaskId;
20use terminal::{
21 Clear, Copy, Event, HoveredWord, MaybeNavigationTarget, Paste, ScrollLineDown, ScrollLineUp,
22 ScrollPageDown, ScrollPageUp, ScrollToBottom, ScrollToTop, ShowCharacterPalette, TaskState,
23 TaskStatus, Terminal, TerminalBounds, ToggleViMode,
24 alacritty_terminal::{
25 index::Point,
26 term::{TermMode, point_to_viewport, search::RegexSearch},
27 },
28 terminal_settings::{CursorShape, TerminalSettings},
29};
30use terminal_element::TerminalElement;
31use terminal_panel::TerminalPanel;
32use terminal_path_like_target::{hover_path_like_target, open_path_like_target};
33use terminal_scrollbar::TerminalScrollHandle;
34use terminal_slash_command::TerminalSlashCommand;
35use terminal_tab_tooltip::TerminalTooltip;
36use ui::{
37 ContextMenu, Icon, IconName, Label, ScrollAxes, Scrollbars, Tooltip, WithScrollbar, h_flex,
38 prelude::*,
39 scrollbars::{self, GlobalSetting, ScrollbarVisibility},
40};
41use util::ResultExt;
42use workspace::{
43 CloseActiveItem, NewCenterTerminal, NewTerminal, ToolbarItemLocation, Workspace, WorkspaceId,
44 delete_unloaded_items,
45 item::{
46 BreadcrumbText, Item, ItemEvent, SerializableItem, TabContentParams, TabTooltipContent,
47 },
48 register_serializable_item,
49 searchable::{Direction, SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
50};
51
52use serde::Deserialize;
53use settings::{Settings, SettingsStore, TerminalBlink, WorkingDirectory};
54use zed_actions::assistant::InlineAssist;
55
56use std::{
57 cmp,
58 ops::{Range, RangeInclusive},
59 path::{Path, PathBuf},
60 rc::Rc,
61 sync::Arc,
62 time::Duration,
63};
64
65struct ImeState {
66 marked_text: String,
67 marked_range_utf16: Option<Range<usize>>,
68}
69
70const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
71
72/// Event to transmit the scroll from the element to the view
73#[derive(Clone, Debug, PartialEq)]
74pub struct ScrollTerminal(pub i32);
75
76/// Sends the specified text directly to the terminal.
77#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
78#[action(namespace = terminal)]
79pub struct SendText(String);
80
81/// Sends a keystroke sequence to the terminal.
82#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
83#[action(namespace = terminal)]
84pub struct SendKeystroke(String);
85
86actions!(
87 terminal,
88 [
89 /// Reruns the last executed task in the terminal.
90 RerunTask
91 ]
92);
93
94pub fn init(cx: &mut App) {
95 assistant_slash_command::init(cx);
96 terminal_panel::init(cx);
97
98 register_serializable_item::<TerminalView>(cx);
99
100 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
101 workspace.register_action(TerminalView::deploy);
102 })
103 .detach();
104 SlashCommandRegistry::global(cx).register_command(TerminalSlashCommand, true);
105}
106
107pub struct BlockProperties {
108 pub height: u8,
109 pub render: Box<dyn Send + Fn(&mut BlockContext) -> AnyElement>,
110}
111
112pub struct BlockContext<'a, 'b> {
113 pub window: &'a mut Window,
114 pub context: &'b mut App,
115 pub dimensions: TerminalBounds,
116}
117
118///A terminal view, maintains the PTY's file handles and communicates with the terminal
119pub struct TerminalView {
120 terminal: Entity<Terminal>,
121 workspace: WeakEntity<Workspace>,
122 project: WeakEntity<Project>,
123 focus_handle: FocusHandle,
124 //Currently using iTerm bell, show bell emoji in tab until input is received
125 has_bell: bool,
126 context_menu: Option<(Entity<ContextMenu>, gpui::Point<Pixels>, Subscription)>,
127 cursor_shape: CursorShape,
128 blink_manager: Entity<BlinkManager>,
129 mode: TerminalMode,
130 blinking_terminal_enabled: bool,
131 cwd_serialized: bool,
132 hover: Option<HoverTarget>,
133 hover_tooltip_update: Task<()>,
134 workspace_id: Option<WorkspaceId>,
135 show_breadcrumbs: bool,
136 block_below_cursor: Option<Rc<BlockProperties>>,
137 scroll_top: Pixels,
138 scroll_handle: TerminalScrollHandle,
139 ime_state: Option<ImeState>,
140 _subscriptions: Vec<Subscription>,
141 _terminal_subscriptions: Vec<Subscription>,
142}
143
144#[derive(Default, Clone)]
145pub enum TerminalMode {
146 #[default]
147 Standalone,
148 Embedded {
149 max_lines_when_unfocused: Option<usize>,
150 },
151}
152
153#[derive(Clone)]
154pub enum ContentMode {
155 Scrollable,
156 Inline {
157 displayed_lines: usize,
158 total_lines: usize,
159 },
160}
161
162impl ContentMode {
163 pub fn is_limited(&self) -> bool {
164 match self {
165 ContentMode::Scrollable => false,
166 ContentMode::Inline {
167 displayed_lines,
168 total_lines,
169 } => displayed_lines < total_lines,
170 }
171 }
172
173 pub fn is_scrollable(&self) -> bool {
174 matches!(self, ContentMode::Scrollable)
175 }
176}
177
178#[derive(Debug)]
179#[cfg_attr(test, derive(Clone, Eq, PartialEq))]
180struct HoverTarget {
181 tooltip: String,
182 hovered_word: HoveredWord,
183}
184
185impl EventEmitter<Event> for TerminalView {}
186impl EventEmitter<ItemEvent> for TerminalView {}
187impl EventEmitter<SearchEvent> for TerminalView {}
188
189impl Focusable for TerminalView {
190 fn focus_handle(&self, _cx: &App) -> FocusHandle {
191 self.focus_handle.clone()
192 }
193}
194
195impl TerminalView {
196 ///Create a new Terminal in the current working directory or the user's home directory
197 pub fn deploy(
198 workspace: &mut Workspace,
199 _: &NewCenterTerminal,
200 window: &mut Window,
201 cx: &mut Context<Workspace>,
202 ) {
203 let working_directory = default_working_directory(workspace, cx);
204 TerminalPanel::add_center_terminal(workspace, window, cx, |project, cx| {
205 project.create_terminal_shell(working_directory, cx)
206 })
207 .detach_and_log_err(cx);
208 }
209
210 pub fn new(
211 terminal: Entity<Terminal>,
212 workspace: WeakEntity<Workspace>,
213 workspace_id: Option<WorkspaceId>,
214 project: WeakEntity<Project>,
215 window: &mut Window,
216 cx: &mut Context<Self>,
217 ) -> Self {
218 let workspace_handle = workspace.clone();
219 let terminal_subscriptions =
220 subscribe_for_terminal_events(&terminal, workspace, window, cx);
221
222 let focus_handle = cx.focus_handle();
223 let focus_in = cx.on_focus_in(&focus_handle, window, |terminal_view, window, cx| {
224 terminal_view.focus_in(window, cx);
225 });
226 let focus_out = cx.on_focus_out(
227 &focus_handle,
228 window,
229 |terminal_view, _event, window, cx| {
230 terminal_view.focus_out(window, cx);
231 },
232 );
233 let cursor_shape = TerminalSettings::get_global(cx).cursor_shape;
234
235 let scroll_handle = TerminalScrollHandle::new(terminal.read(cx));
236
237 let blink_manager = cx.new(|cx| {
238 BlinkManager::new(
239 CURSOR_BLINK_INTERVAL,
240 |cx| {
241 !matches!(
242 TerminalSettings::get_global(cx).blinking,
243 TerminalBlink::Off
244 )
245 },
246 cx,
247 )
248 });
249
250 let _subscriptions = vec![
251 focus_in,
252 focus_out,
253 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
254 cx.observe_global::<SettingsStore>(Self::settings_changed),
255 ];
256 Self {
257 terminal,
258 workspace: workspace_handle,
259 project,
260 has_bell: false,
261 focus_handle,
262 context_menu: None,
263 cursor_shape,
264 blink_manager,
265 blinking_terminal_enabled: false,
266 hover: None,
267 hover_tooltip_update: Task::ready(()),
268 mode: TerminalMode::Standalone,
269 workspace_id,
270 show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
271 block_below_cursor: None,
272 scroll_top: Pixels::ZERO,
273 scroll_handle,
274 cwd_serialized: false,
275 ime_state: None,
276 _subscriptions,
277 _terminal_subscriptions: terminal_subscriptions,
278 }
279 }
280
281 /// Enable 'embedded' mode where the terminal displays the full content with an optional limit of lines.
282 pub fn set_embedded_mode(
283 &mut self,
284 max_lines_when_unfocused: Option<usize>,
285 cx: &mut Context<Self>,
286 ) {
287 self.mode = TerminalMode::Embedded {
288 max_lines_when_unfocused,
289 };
290 cx.notify();
291 }
292
293 const MAX_EMBEDDED_LINES: usize = 1_000;
294
295 /// Returns the current `ContentMode` depending on the set `TerminalMode` and the current number of lines
296 ///
297 /// Note: Even in embedded mode, the terminal will fallback to scrollable when its content exceeds `MAX_EMBEDDED_LINES`
298 pub fn content_mode(&self, window: &Window, cx: &App) -> ContentMode {
299 match &self.mode {
300 TerminalMode::Standalone => ContentMode::Scrollable,
301 TerminalMode::Embedded {
302 max_lines_when_unfocused,
303 } => {
304 let total_lines = self.terminal.read(cx).total_lines();
305
306 if total_lines > Self::MAX_EMBEDDED_LINES {
307 ContentMode::Scrollable
308 } else {
309 let mut displayed_lines = total_lines;
310
311 if !self.focus_handle.is_focused(window)
312 && let Some(max_lines) = max_lines_when_unfocused
313 {
314 displayed_lines = displayed_lines.min(*max_lines)
315 }
316
317 ContentMode::Inline {
318 displayed_lines,
319 total_lines,
320 }
321 }
322 }
323 }
324 }
325
326 /// Sets the marked (pre-edit) text from the IME.
327 pub(crate) fn set_marked_text(
328 &mut self,
329 text: String,
330 range: Option<Range<usize>>,
331 cx: &mut Context<Self>,
332 ) {
333 self.ime_state = Some(ImeState {
334 marked_text: text,
335 marked_range_utf16: range,
336 });
337 cx.notify();
338 }
339
340 /// Gets the current marked range (UTF-16).
341 pub(crate) fn marked_text_range(&self) -> Option<Range<usize>> {
342 self.ime_state
343 .as_ref()
344 .and_then(|state| state.marked_range_utf16.clone())
345 }
346
347 /// Clears the marked (pre-edit) text state.
348 pub(crate) fn clear_marked_text(&mut self, cx: &mut Context<Self>) {
349 if self.ime_state.is_some() {
350 self.ime_state = None;
351 cx.notify();
352 }
353 }
354
355 /// Commits (sends) the given text to the PTY. Called by InputHandler::replace_text_in_range.
356 pub(crate) fn commit_text(&mut self, text: &str, cx: &mut Context<Self>) {
357 if !text.is_empty() {
358 self.terminal.update(cx, |term, _| {
359 term.input(text.to_string().into_bytes());
360 });
361 }
362 }
363
364 pub(crate) fn terminal_bounds(&self, cx: &App) -> TerminalBounds {
365 self.terminal.read(cx).last_content().terminal_bounds
366 }
367
368 pub fn entity(&self) -> &Entity<Terminal> {
369 &self.terminal
370 }
371
372 pub fn has_bell(&self) -> bool {
373 self.has_bell
374 }
375
376 pub fn clear_bell(&mut self, cx: &mut Context<TerminalView>) {
377 self.has_bell = false;
378 cx.emit(Event::Wakeup);
379 }
380
381 pub fn deploy_context_menu(
382 &mut self,
383 position: gpui::Point<Pixels>,
384 window: &mut Window,
385 cx: &mut Context<Self>,
386 ) {
387 let assistant_enabled = self
388 .workspace
389 .upgrade()
390 .and_then(|workspace| workspace.read(cx).panel::<TerminalPanel>(cx))
391 .is_some_and(|terminal_panel| terminal_panel.read(cx).assistant_enabled());
392 let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
393 menu.context(self.focus_handle.clone())
394 .action("New Terminal", Box::new(NewTerminal))
395 .separator()
396 .action("Copy", Box::new(Copy))
397 .action("Paste", Box::new(Paste))
398 .action("Select All", Box::new(SelectAll))
399 .action("Clear", Box::new(Clear))
400 .when(assistant_enabled, |menu| {
401 menu.separator()
402 .action("Inline Assist", Box::new(InlineAssist::default()))
403 })
404 .separator()
405 .action(
406 "Close Terminal Tab",
407 Box::new(CloseActiveItem {
408 save_intent: None,
409 close_pinned: true,
410 }),
411 )
412 });
413
414 window.focus(&context_menu.focus_handle(cx));
415 let subscription = cx.subscribe_in(
416 &context_menu,
417 window,
418 |this, _, _: &DismissEvent, window, cx| {
419 if this.context_menu.as_ref().is_some_and(|context_menu| {
420 context_menu.0.focus_handle(cx).contains_focused(window, cx)
421 }) {
422 cx.focus_self(window);
423 }
424 this.context_menu.take();
425 cx.notify();
426 },
427 );
428
429 self.context_menu = Some((context_menu, position, subscription));
430 }
431
432 fn settings_changed(&mut self, cx: &mut Context<Self>) {
433 let settings = TerminalSettings::get_global(cx);
434 let breadcrumb_visibility_changed = self.show_breadcrumbs != settings.toolbar.breadcrumbs;
435 self.show_breadcrumbs = settings.toolbar.breadcrumbs;
436
437 let should_blink = match settings.blinking {
438 TerminalBlink::Off => false,
439 TerminalBlink::On => true,
440 TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
441 };
442 let new_cursor_shape = settings.cursor_shape;
443 let old_cursor_shape = self.cursor_shape;
444 if old_cursor_shape != new_cursor_shape {
445 self.cursor_shape = new_cursor_shape;
446 self.terminal.update(cx, |term, _| {
447 term.set_cursor_shape(self.cursor_shape);
448 });
449 }
450
451 self.blink_manager.update(
452 cx,
453 if should_blink {
454 BlinkManager::enable
455 } else {
456 BlinkManager::disable
457 },
458 );
459
460 if breadcrumb_visibility_changed {
461 cx.emit(ItemEvent::UpdateBreadcrumbs);
462 }
463 cx.notify();
464 }
465
466 fn show_character_palette(
467 &mut self,
468 _: &ShowCharacterPalette,
469 window: &mut Window,
470 cx: &mut Context<Self>,
471 ) {
472 if self
473 .terminal
474 .read(cx)
475 .last_content
476 .mode
477 .contains(TermMode::ALT_SCREEN)
478 {
479 self.terminal.update(cx, |term, cx| {
480 term.try_keystroke(
481 &Keystroke::parse("ctrl-cmd-space").unwrap(),
482 TerminalSettings::get_global(cx).option_as_meta,
483 )
484 });
485 } else {
486 window.show_character_palette();
487 }
488 }
489
490 fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
491 self.terminal.update(cx, |term, _| term.select_all());
492 cx.notify();
493 }
494
495 fn rerun_task(&mut self, _: &RerunTask, window: &mut Window, cx: &mut Context<Self>) {
496 let task = self
497 .terminal
498 .read(cx)
499 .task()
500 .map(|task| terminal_rerun_override(&task.spawned_task.id))
501 .unwrap_or_default();
502 window.dispatch_action(Box::new(task), cx);
503 }
504
505 fn clear(&mut self, _: &Clear, _: &mut Window, cx: &mut Context<Self>) {
506 self.scroll_top = px(0.);
507 self.terminal.update(cx, |term, _| term.clear());
508 cx.notify();
509 }
510
511 fn max_scroll_top(&self, cx: &App) -> Pixels {
512 let terminal = self.terminal.read(cx);
513
514 let Some(block) = self.block_below_cursor.as_ref() else {
515 return Pixels::ZERO;
516 };
517
518 let line_height = terminal.last_content().terminal_bounds.line_height;
519 let viewport_lines = terminal.viewport_lines();
520 let cursor = point_to_viewport(
521 terminal.last_content.display_offset,
522 terminal.last_content.cursor.point,
523 )
524 .unwrap_or_default();
525 let max_scroll_top_in_lines =
526 (block.height as usize).saturating_sub(viewport_lines.saturating_sub(cursor.line + 1));
527
528 max_scroll_top_in_lines as f32 * line_height
529 }
530
531 fn scroll_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
532 let terminal_content = self.terminal.read(cx).last_content();
533
534 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
535 let line_height = terminal_content.terminal_bounds.line_height;
536 let y_delta = event.delta.pixel_delta(line_height).y;
537 if y_delta < Pixels::ZERO || self.scroll_top > Pixels::ZERO {
538 self.scroll_top = cmp::max(
539 Pixels::ZERO,
540 cmp::min(self.scroll_top - y_delta, self.max_scroll_top(cx)),
541 );
542 cx.notify();
543 return;
544 }
545 }
546 self.terminal.update(cx, |term, cx| {
547 term.scroll_wheel(
548 event,
549 TerminalSettings::get_global(cx).scroll_multiplier.max(0.01),
550 )
551 });
552 }
553
554 fn scroll_line_up(&mut self, _: &ScrollLineUp, _: &mut Window, cx: &mut Context<Self>) {
555 let terminal_content = self.terminal.read(cx).last_content();
556 if self.block_below_cursor.is_some()
557 && terminal_content.display_offset == 0
558 && self.scroll_top > Pixels::ZERO
559 {
560 let line_height = terminal_content.terminal_bounds.line_height;
561 self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
562 return;
563 }
564
565 self.terminal.update(cx, |term, _| term.scroll_line_up());
566 cx.notify();
567 }
568
569 fn scroll_line_down(&mut self, _: &ScrollLineDown, _: &mut Window, cx: &mut Context<Self>) {
570 let terminal_content = self.terminal.read(cx).last_content();
571 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
572 let max_scroll_top = self.max_scroll_top(cx);
573 if self.scroll_top < max_scroll_top {
574 let line_height = terminal_content.terminal_bounds.line_height;
575 self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
576 }
577 return;
578 }
579
580 self.terminal.update(cx, |term, _| term.scroll_line_down());
581 cx.notify();
582 }
583
584 fn scroll_page_up(&mut self, _: &ScrollPageUp, _: &mut Window, cx: &mut Context<Self>) {
585 if self.scroll_top == Pixels::ZERO {
586 self.terminal.update(cx, |term, _| term.scroll_page_up());
587 } else {
588 let line_height = self
589 .terminal
590 .read(cx)
591 .last_content
592 .terminal_bounds
593 .line_height();
594 let visible_block_lines = (self.scroll_top / line_height) as usize;
595 let viewport_lines = self.terminal.read(cx).viewport_lines();
596 let visible_content_lines = viewport_lines - visible_block_lines;
597
598 if visible_block_lines >= viewport_lines {
599 self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
600 } else {
601 self.scroll_top = px(0.);
602 self.terminal
603 .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
604 }
605 }
606 cx.notify();
607 }
608
609 fn scroll_page_down(&mut self, _: &ScrollPageDown, _: &mut Window, cx: &mut Context<Self>) {
610 self.terminal.update(cx, |term, _| term.scroll_page_down());
611 let terminal = self.terminal.read(cx);
612 if terminal.last_content().display_offset < terminal.viewport_lines() {
613 self.scroll_top = self.max_scroll_top(cx);
614 }
615 cx.notify();
616 }
617
618 fn scroll_to_top(&mut self, _: &ScrollToTop, _: &mut Window, cx: &mut Context<Self>) {
619 self.terminal.update(cx, |term, _| term.scroll_to_top());
620 cx.notify();
621 }
622
623 fn scroll_to_bottom(&mut self, _: &ScrollToBottom, _: &mut Window, cx: &mut Context<Self>) {
624 self.terminal.update(cx, |term, _| term.scroll_to_bottom());
625 if self.block_below_cursor.is_some() {
626 self.scroll_top = self.max_scroll_top(cx);
627 }
628 cx.notify();
629 }
630
631 fn toggle_vi_mode(&mut self, _: &ToggleViMode, _: &mut Window, cx: &mut Context<Self>) {
632 self.terminal.update(cx, |term, _| term.toggle_vi_mode());
633 cx.notify();
634 }
635
636 pub fn should_show_cursor(&self, focused: bool, cx: &mut Context<Self>) -> bool {
637 // Always show cursor when not focused or in special modes
638 if !focused
639 || self
640 .terminal
641 .read(cx)
642 .last_content
643 .mode
644 .contains(TermMode::ALT_SCREEN)
645 {
646 return true;
647 }
648
649 // When focused, check blinking settings and blink manager state
650 match TerminalSettings::get_global(cx).blinking {
651 TerminalBlink::Off => true,
652 TerminalBlink::On | TerminalBlink::TerminalControlled => {
653 self.blink_manager.read(cx).visible()
654 }
655 }
656 }
657
658 pub fn pause_cursor_blinking(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
659 self.blink_manager.update(cx, BlinkManager::pause_blinking);
660 }
661
662 pub fn terminal(&self) -> &Entity<Terminal> {
663 &self.terminal
664 }
665
666 pub fn set_block_below_cursor(
667 &mut self,
668 block: BlockProperties,
669 window: &mut Window,
670 cx: &mut Context<Self>,
671 ) {
672 self.block_below_cursor = Some(Rc::new(block));
673 self.scroll_to_bottom(&ScrollToBottom, window, cx);
674 cx.notify();
675 }
676
677 pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
678 self.block_below_cursor = None;
679 self.scroll_top = Pixels::ZERO;
680 cx.notify();
681 }
682
683 ///Attempt to paste the clipboard into the terminal
684 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
685 self.terminal.update(cx, |term, _| term.copy(None));
686 cx.notify();
687 }
688
689 ///Attempt to paste the clipboard into the terminal
690 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
691 if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
692 self.terminal
693 .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
694 }
695 }
696
697 fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
698 self.clear_bell(cx);
699 self.terminal.update(cx, |term, _| {
700 term.input(text.0.to_string().into_bytes());
701 });
702 }
703
704 fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
705 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
706 self.clear_bell(cx);
707 self.terminal.update(cx, |term, cx| {
708 let processed =
709 term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
710 if processed && term.vi_mode_enabled() {
711 cx.notify();
712 }
713 processed
714 });
715 }
716 }
717
718 fn dispatch_context(&self, cx: &App) -> KeyContext {
719 let mut dispatch_context = KeyContext::new_with_defaults();
720 dispatch_context.add("Terminal");
721
722 if self.terminal.read(cx).vi_mode_enabled() {
723 dispatch_context.add("vi_mode");
724 }
725
726 let mode = self.terminal.read(cx).last_content.mode;
727 dispatch_context.set(
728 "screen",
729 if mode.contains(TermMode::ALT_SCREEN) {
730 "alt"
731 } else {
732 "normal"
733 },
734 );
735
736 if mode.contains(TermMode::APP_CURSOR) {
737 dispatch_context.add("DECCKM");
738 }
739 if mode.contains(TermMode::APP_KEYPAD) {
740 dispatch_context.add("DECPAM");
741 } else {
742 dispatch_context.add("DECPNM");
743 }
744 if mode.contains(TermMode::SHOW_CURSOR) {
745 dispatch_context.add("DECTCEM");
746 }
747 if mode.contains(TermMode::LINE_WRAP) {
748 dispatch_context.add("DECAWM");
749 }
750 if mode.contains(TermMode::ORIGIN) {
751 dispatch_context.add("DECOM");
752 }
753 if mode.contains(TermMode::INSERT) {
754 dispatch_context.add("IRM");
755 }
756 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
757 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
758 dispatch_context.add("LNM");
759 }
760 if mode.contains(TermMode::FOCUS_IN_OUT) {
761 dispatch_context.add("report_focus");
762 }
763 if mode.contains(TermMode::ALTERNATE_SCROLL) {
764 dispatch_context.add("alternate_scroll");
765 }
766 if mode.contains(TermMode::BRACKETED_PASTE) {
767 dispatch_context.add("bracketed_paste");
768 }
769 if mode.intersects(TermMode::MOUSE_MODE) {
770 dispatch_context.add("any_mouse_reporting");
771 }
772 {
773 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
774 "click"
775 } else if mode.contains(TermMode::MOUSE_DRAG) {
776 "drag"
777 } else if mode.contains(TermMode::MOUSE_MOTION) {
778 "motion"
779 } else {
780 "off"
781 };
782 dispatch_context.set("mouse_reporting", mouse_reporting);
783 }
784 {
785 let format = if mode.contains(TermMode::SGR_MOUSE) {
786 "sgr"
787 } else if mode.contains(TermMode::UTF8_MOUSE) {
788 "utf8"
789 } else {
790 "normal"
791 };
792 dispatch_context.set("mouse_format", format);
793 };
794
795 if self.terminal.read(cx).last_content.selection.is_some() {
796 dispatch_context.add("selection");
797 }
798
799 dispatch_context
800 }
801
802 fn set_terminal(
803 &mut self,
804 terminal: Entity<Terminal>,
805 window: &mut Window,
806 cx: &mut Context<TerminalView>,
807 ) {
808 self._terminal_subscriptions =
809 subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
810 self.terminal = terminal;
811 }
812
813 fn rerun_button(task: &TaskState) -> Option<IconButton> {
814 if !task.spawned_task.show_rerun {
815 return None;
816 }
817
818 let task_id = task.spawned_task.id.clone();
819 Some(
820 IconButton::new("rerun-icon", IconName::Rerun)
821 .icon_size(IconSize::Small)
822 .size(ButtonSize::Compact)
823 .icon_color(Color::Default)
824 .shape(ui::IconButtonShape::Square)
825 .tooltip(move |_window, cx| Tooltip::for_action("Rerun task", &RerunTask, cx))
826 .on_click(move |_, window, cx| {
827 window.dispatch_action(Box::new(terminal_rerun_override(&task_id)), cx);
828 }),
829 )
830 }
831}
832
833fn terminal_rerun_override(task: &TaskId) -> zed_actions::Rerun {
834 zed_actions::Rerun {
835 task_id: Some(task.0.clone()),
836 allow_concurrent_runs: Some(true),
837 use_new_terminal: Some(false),
838 reevaluate_context: false,
839 }
840}
841
842fn subscribe_for_terminal_events(
843 terminal: &Entity<Terminal>,
844 workspace: WeakEntity<Workspace>,
845 window: &mut Window,
846 cx: &mut Context<TerminalView>,
847) -> Vec<Subscription> {
848 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
849 let mut previous_cwd = None;
850 let terminal_events_subscription = cx.subscribe_in(
851 terminal,
852 window,
853 move |terminal_view, terminal, event, window, cx| {
854 let current_cwd = terminal.read(cx).working_directory();
855 if current_cwd != previous_cwd {
856 previous_cwd = current_cwd;
857 terminal_view.cwd_serialized = false;
858 }
859
860 match event {
861 Event::Wakeup => {
862 cx.notify();
863 cx.emit(Event::Wakeup);
864 cx.emit(ItemEvent::UpdateTab);
865 cx.emit(SearchEvent::MatchesInvalidated);
866 }
867
868 Event::Bell => {
869 terminal_view.has_bell = true;
870 cx.emit(Event::Wakeup);
871 }
872
873 Event::BlinkChanged(blinking) => {
874 terminal_view.blinking_terminal_enabled = *blinking;
875
876 // If in terminal-controlled mode and focused, update blink manager
877 if matches!(
878 TerminalSettings::get_global(cx).blinking,
879 TerminalBlink::TerminalControlled
880 ) && terminal_view.focus_handle.is_focused(window)
881 {
882 terminal_view.blink_manager.update(cx, |manager, cx| {
883 if *blinking {
884 manager.enable(cx);
885 } else {
886 manager.disable(cx);
887 }
888 });
889 }
890 }
891
892 Event::TitleChanged => {
893 cx.emit(ItemEvent::UpdateTab);
894 }
895
896 Event::NewNavigationTarget(maybe_navigation_target) => {
897 match maybe_navigation_target
898 .as_ref()
899 .zip(terminal.read(cx).last_content.last_hovered_word.as_ref())
900 {
901 Some((MaybeNavigationTarget::Url(url), hovered_word)) => {
902 if Some(hovered_word)
903 != terminal_view
904 .hover
905 .as_ref()
906 .map(|hover| &hover.hovered_word)
907 {
908 terminal_view.hover = Some(HoverTarget {
909 tooltip: url.clone(),
910 hovered_word: hovered_word.clone(),
911 });
912 terminal_view.hover_tooltip_update = Task::ready(());
913 cx.notify();
914 }
915 }
916 Some((MaybeNavigationTarget::PathLike(path_like_target), hovered_word)) => {
917 if Some(hovered_word)
918 != terminal_view
919 .hover
920 .as_ref()
921 .map(|hover| &hover.hovered_word)
922 {
923 terminal_view.hover = None;
924 terminal_view.hover_tooltip_update = hover_path_like_target(
925 &workspace,
926 hovered_word.clone(),
927 path_like_target,
928 cx,
929 );
930 cx.notify();
931 }
932 }
933 None => {
934 terminal_view.hover = None;
935 terminal_view.hover_tooltip_update = Task::ready(());
936 cx.notify();
937 }
938 }
939 }
940
941 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
942 MaybeNavigationTarget::Url(url) => cx.open_url(url),
943 MaybeNavigationTarget::PathLike(path_like_target) => open_path_like_target(
944 &workspace,
945 terminal_view,
946 path_like_target,
947 window,
948 cx,
949 ),
950 },
951 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
952 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
953 Event::SelectionsChanged => {
954 window.invalidate_character_coordinates();
955 cx.emit(SearchEvent::ActiveMatchChanged)
956 }
957 }
958 },
959 );
960 vec![terminal_subscription, terminal_events_subscription]
961}
962
963fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
964 let str = query.as_str();
965 if query.is_regex() {
966 if str == "." {
967 return None;
968 }
969 RegexSearch::new(str).ok()
970 } else {
971 RegexSearch::new(®ex::escape(str)).ok()
972 }
973}
974
975struct TerminalScrollbarSettingsWrapper;
976
977impl GlobalSetting for TerminalScrollbarSettingsWrapper {
978 fn get_value(_cx: &App) -> &Self {
979 &Self
980 }
981}
982
983impl ScrollbarVisibility for TerminalScrollbarSettingsWrapper {
984 fn visibility(&self, cx: &App) -> scrollbars::ShowScrollbar {
985 TerminalSettings::get_global(cx)
986 .scrollbar
987 .show
988 .map(Into::into)
989 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
990 }
991}
992
993impl TerminalView {
994 fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
995 self.clear_bell(cx);
996 self.pause_cursor_blinking(window, cx);
997
998 self.terminal.update(cx, |term, cx| {
999 let handled = term.try_keystroke(
1000 &event.keystroke,
1001 TerminalSettings::get_global(cx).option_as_meta,
1002 );
1003 if handled {
1004 cx.stop_propagation();
1005 }
1006 });
1007 }
1008
1009 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1010 self.terminal.update(cx, |terminal, _| {
1011 terminal.set_cursor_shape(self.cursor_shape);
1012 terminal.focus_in();
1013 });
1014
1015 let should_blink = match TerminalSettings::get_global(cx).blinking {
1016 TerminalBlink::Off => false,
1017 TerminalBlink::On => true,
1018 TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
1019 };
1020
1021 if should_blink {
1022 self.blink_manager.update(cx, BlinkManager::enable);
1023 }
1024
1025 window.invalidate_character_coordinates();
1026 cx.notify();
1027 }
1028
1029 fn focus_out(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1030 self.blink_manager.update(cx, BlinkManager::disable);
1031 self.terminal.update(cx, |terminal, _| {
1032 terminal.focus_out();
1033 terminal.set_cursor_shape(CursorShape::Hollow);
1034 });
1035 cx.notify();
1036 }
1037}
1038
1039impl Render for TerminalView {
1040 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1041 // TODO: this should be moved out of render
1042 self.scroll_handle.update(self.terminal.read(cx));
1043
1044 if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
1045 self.terminal.update(cx, |term, _| {
1046 let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
1047 match delta.cmp(&0) {
1048 std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
1049 std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
1050 std::cmp::Ordering::Equal => {}
1051 }
1052 });
1053 }
1054
1055 let terminal_handle = self.terminal.clone();
1056 let terminal_view_handle = cx.entity();
1057
1058 let focused = self.focus_handle.is_focused(window);
1059
1060 div()
1061 .id("terminal-view")
1062 .size_full()
1063 .relative()
1064 .track_focus(&self.focus_handle(cx))
1065 .key_context(self.dispatch_context(cx))
1066 .on_action(cx.listener(TerminalView::send_text))
1067 .on_action(cx.listener(TerminalView::send_keystroke))
1068 .on_action(cx.listener(TerminalView::copy))
1069 .on_action(cx.listener(TerminalView::paste))
1070 .on_action(cx.listener(TerminalView::clear))
1071 .on_action(cx.listener(TerminalView::scroll_line_up))
1072 .on_action(cx.listener(TerminalView::scroll_line_down))
1073 .on_action(cx.listener(TerminalView::scroll_page_up))
1074 .on_action(cx.listener(TerminalView::scroll_page_down))
1075 .on_action(cx.listener(TerminalView::scroll_to_top))
1076 .on_action(cx.listener(TerminalView::scroll_to_bottom))
1077 .on_action(cx.listener(TerminalView::toggle_vi_mode))
1078 .on_action(cx.listener(TerminalView::show_character_palette))
1079 .on_action(cx.listener(TerminalView::select_all))
1080 .on_action(cx.listener(TerminalView::rerun_task))
1081 .on_key_down(cx.listener(Self::key_down))
1082 .on_mouse_down(
1083 MouseButton::Right,
1084 cx.listener(|this, event: &MouseDownEvent, window, cx| {
1085 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1086 if this.terminal.read(cx).last_content.selection.is_none() {
1087 this.terminal.update(cx, |terminal, _| {
1088 terminal.select_word_at_event_position(event);
1089 });
1090 };
1091 this.deploy_context_menu(event.position, window, cx);
1092 cx.notify();
1093 }
1094 }),
1095 )
1096 .child(
1097 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1098 div()
1099 .id("terminal-view-container")
1100 .size_full()
1101 .bg(cx.theme().colors().editor_background)
1102 .child(TerminalElement::new(
1103 terminal_handle,
1104 terminal_view_handle,
1105 self.workspace.clone(),
1106 self.focus_handle.clone(),
1107 focused,
1108 self.should_show_cursor(focused, cx),
1109 self.block_below_cursor.clone(),
1110 self.mode.clone(),
1111 ))
1112 .when(self.content_mode(window, cx).is_scrollable(), |div| {
1113 div.custom_scrollbars(
1114 Scrollbars::for_settings::<TerminalScrollbarSettingsWrapper>()
1115 .show_along(ScrollAxes::Vertical)
1116 .with_track_along(
1117 ScrollAxes::Vertical,
1118 cx.theme().colors().editor_background,
1119 )
1120 .tracked_scroll_handle(self.scroll_handle.clone()),
1121 window,
1122 cx,
1123 )
1124 }),
1125 )
1126 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1127 deferred(
1128 anchored()
1129 .position(*position)
1130 .anchor(gpui::Corner::TopLeft)
1131 .child(menu.clone()),
1132 )
1133 .with_priority(1)
1134 }))
1135 }
1136}
1137
1138impl Item for TerminalView {
1139 type Event = ItemEvent;
1140
1141 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1142 let terminal = self.terminal().read(cx);
1143 let title = terminal.title(false);
1144 let pid = terminal.pid_getter()?.fallback_pid();
1145
1146 Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
1147 cx.new(|_| TerminalTooltip::new(title.clone(), pid.as_u32()))
1148 .into()
1149 })))
1150 }
1151
1152 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1153 let terminal = self.terminal().read(cx);
1154 let title = terminal.title(true);
1155
1156 let (icon, icon_color, rerun_button) = match terminal.task() {
1157 Some(terminal_task) => match &terminal_task.status {
1158 TaskStatus::Running => (
1159 IconName::PlayFilled,
1160 Color::Disabled,
1161 TerminalView::rerun_button(terminal_task),
1162 ),
1163 TaskStatus::Unknown => (
1164 IconName::Warning,
1165 Color::Warning,
1166 TerminalView::rerun_button(terminal_task),
1167 ),
1168 TaskStatus::Completed { success } => {
1169 let rerun_button = TerminalView::rerun_button(terminal_task);
1170
1171 if *success {
1172 (IconName::Check, Color::Success, rerun_button)
1173 } else {
1174 (IconName::XCircle, Color::Error, rerun_button)
1175 }
1176 }
1177 },
1178 None => (IconName::Terminal, Color::Muted, None),
1179 };
1180
1181 h_flex()
1182 .gap_1()
1183 .group("term-tab-icon")
1184 .child(
1185 h_flex()
1186 .group("term-tab-icon")
1187 .child(
1188 div()
1189 .when(rerun_button.is_some(), |this| {
1190 this.hover(|style| style.invisible().w_0())
1191 })
1192 .child(Icon::new(icon).color(icon_color)),
1193 )
1194 .when_some(rerun_button, |this, rerun_button| {
1195 this.child(
1196 div()
1197 .absolute()
1198 .visible_on_hover("term-tab-icon")
1199 .child(rerun_button),
1200 )
1201 }),
1202 )
1203 .child(Label::new(title).color(params.text_color()))
1204 .into_any()
1205 }
1206
1207 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
1208 let terminal = self.terminal().read(cx);
1209 terminal.title(detail == 0).into()
1210 }
1211
1212 fn telemetry_event_text(&self) -> Option<&'static str> {
1213 None
1214 }
1215
1216 fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
1217 workspace::item::ItemBufferKind::Singleton
1218 }
1219
1220 fn can_split(&self) -> bool {
1221 true
1222 }
1223
1224 fn clone_on_split(
1225 &self,
1226 workspace_id: Option<WorkspaceId>,
1227 window: &mut Window,
1228 cx: &mut Context<Self>,
1229 ) -> Task<Option<Entity<Self>>> {
1230 let Ok(terminal) = self.project.update(cx, |project, cx| {
1231 let cwd = project
1232 .active_project_directory(cx)
1233 .map(|it| it.to_path_buf());
1234 project.clone_terminal(self.terminal(), cx, cwd)
1235 }) else {
1236 return Task::ready(None);
1237 };
1238 cx.spawn_in(window, async move |this, cx| {
1239 let terminal = terminal.await.log_err()?;
1240 this.update_in(cx, |this, window, cx| {
1241 cx.new(|cx| {
1242 TerminalView::new(
1243 terminal,
1244 this.workspace.clone(),
1245 workspace_id,
1246 this.project.clone(),
1247 window,
1248 cx,
1249 )
1250 })
1251 })
1252 .ok()
1253 })
1254 }
1255
1256 fn is_dirty(&self, cx: &gpui::App) -> bool {
1257 match self.terminal.read(cx).task() {
1258 Some(task) => task.status == TaskStatus::Running,
1259 None => self.has_bell(),
1260 }
1261 }
1262
1263 fn has_conflict(&self, _cx: &App) -> bool {
1264 false
1265 }
1266
1267 fn can_save_as(&self, _cx: &App) -> bool {
1268 false
1269 }
1270
1271 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1272 Some(Box::new(handle.clone()))
1273 }
1274
1275 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1276 if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1277 ToolbarItemLocation::PrimaryLeft
1278 } else {
1279 ToolbarItemLocation::Hidden
1280 }
1281 }
1282
1283 fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1284 Some(vec![BreadcrumbText {
1285 text: self.terminal().read(cx).breadcrumb_text.clone(),
1286 highlights: None,
1287 font: None,
1288 }])
1289 }
1290
1291 fn added_to_workspace(
1292 &mut self,
1293 workspace: &mut Workspace,
1294 _: &mut Window,
1295 cx: &mut Context<Self>,
1296 ) {
1297 if self.terminal().read(cx).task().is_none() {
1298 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1299 log::debug!(
1300 "Updating workspace id for the terminal, old: {old_id:?}, new: {new_id:?}",
1301 );
1302 cx.background_spawn(TERMINAL_DB.update_workspace_id(
1303 new_id,
1304 old_id,
1305 cx.entity_id().as_u64(),
1306 ))
1307 .detach();
1308 }
1309 self.workspace_id = workspace.database_id();
1310 }
1311 }
1312
1313 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1314 f(*event)
1315 }
1316}
1317
1318impl SerializableItem for TerminalView {
1319 fn serialized_item_kind() -> &'static str {
1320 "Terminal"
1321 }
1322
1323 fn cleanup(
1324 workspace_id: WorkspaceId,
1325 alive_items: Vec<workspace::ItemId>,
1326 _window: &mut Window,
1327 cx: &mut App,
1328 ) -> Task<anyhow::Result<()>> {
1329 delete_unloaded_items(alive_items, workspace_id, "terminals", &TERMINAL_DB, cx)
1330 }
1331
1332 fn serialize(
1333 &mut self,
1334 _workspace: &mut Workspace,
1335 item_id: workspace::ItemId,
1336 _closing: bool,
1337 _: &mut Window,
1338 cx: &mut Context<Self>,
1339 ) -> Option<Task<anyhow::Result<()>>> {
1340 let terminal = self.terminal().read(cx);
1341 if terminal.task().is_some() {
1342 return None;
1343 }
1344
1345 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1346 self.cwd_serialized = true;
1347 Some(cx.background_spawn(async move {
1348 TERMINAL_DB
1349 .save_working_directory(item_id, workspace_id, cwd)
1350 .await
1351 }))
1352 } else {
1353 None
1354 }
1355 }
1356
1357 fn should_serialize(&self, _: &Self::Event) -> bool {
1358 !self.cwd_serialized
1359 }
1360
1361 fn deserialize(
1362 project: Entity<Project>,
1363 workspace: WeakEntity<Workspace>,
1364 workspace_id: workspace::WorkspaceId,
1365 item_id: workspace::ItemId,
1366 window: &mut Window,
1367 cx: &mut App,
1368 ) -> Task<anyhow::Result<Entity<Self>>> {
1369 window.spawn(cx, async move |cx| {
1370 let cwd = cx
1371 .update(|_window, cx| {
1372 let from_db = TERMINAL_DB
1373 .get_working_directory(item_id, workspace_id)
1374 .log_err()
1375 .flatten();
1376 if from_db
1377 .as_ref()
1378 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1379 {
1380 from_db
1381 } else {
1382 workspace
1383 .upgrade()
1384 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1385 }
1386 })
1387 .ok()
1388 .flatten();
1389
1390 let terminal = project
1391 .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
1392 .await?;
1393 cx.update(|window, cx| {
1394 cx.new(|cx| {
1395 TerminalView::new(
1396 terminal,
1397 workspace,
1398 Some(workspace_id),
1399 project.downgrade(),
1400 window,
1401 cx,
1402 )
1403 })
1404 })
1405 })
1406 }
1407}
1408
1409impl SearchableItem for TerminalView {
1410 type Match = RangeInclusive<Point>;
1411
1412 fn supported_options(&self) -> SearchOptions {
1413 SearchOptions {
1414 case: false,
1415 word: false,
1416 regex: true,
1417 replacement: false,
1418 selection: false,
1419 find_in_results: false,
1420 }
1421 }
1422
1423 /// Clear stored matches
1424 fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1425 self.terminal().update(cx, |term, _| term.matches.clear())
1426 }
1427
1428 /// Store matches returned from find_matches somewhere for rendering
1429 fn update_matches(
1430 &mut self,
1431 matches: &[Self::Match],
1432 _window: &mut Window,
1433 cx: &mut Context<Self>,
1434 ) {
1435 self.terminal()
1436 .update(cx, |term, _| term.matches = matches.to_vec())
1437 }
1438
1439 /// Returns the selection content to pre-load into this search
1440 fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1441 self.terminal()
1442 .read(cx)
1443 .last_content
1444 .selection_text
1445 .clone()
1446 .unwrap_or_default()
1447 }
1448
1449 /// Focus match at given index into the Vec of matches
1450 fn activate_match(
1451 &mut self,
1452 index: usize,
1453 _: &[Self::Match],
1454 _window: &mut Window,
1455 cx: &mut Context<Self>,
1456 ) {
1457 self.terminal()
1458 .update(cx, |term, _| term.activate_match(index));
1459 cx.notify();
1460 }
1461
1462 /// Add selections for all matches given.
1463 fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1464 self.terminal()
1465 .update(cx, |term, _| term.select_matches(matches));
1466 cx.notify();
1467 }
1468
1469 /// Get all of the matches for this query, should be done on the background
1470 fn find_matches(
1471 &mut self,
1472 query: Arc<SearchQuery>,
1473 _: &mut Window,
1474 cx: &mut Context<Self>,
1475 ) -> Task<Vec<Self::Match>> {
1476 if let Some(s) = regex_search_for_query(&query) {
1477 self.terminal()
1478 .update(cx, |term, cx| term.find_matches(s, cx))
1479 } else {
1480 Task::ready(vec![])
1481 }
1482 }
1483
1484 /// Reports back to the search toolbar what the active match should be (the selection)
1485 fn active_match_index(
1486 &mut self,
1487 direction: Direction,
1488 matches: &[Self::Match],
1489 _: &mut Window,
1490 cx: &mut Context<Self>,
1491 ) -> Option<usize> {
1492 // Selection head might have a value if there's a selection that isn't
1493 // associated with a match. Therefore, if there are no matches, we should
1494 // report None, no matter the state of the terminal
1495
1496 if !matches.is_empty() {
1497 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1498 // If selection head is contained in a match. Return that match
1499 match direction {
1500 Direction::Prev => {
1501 // If no selection before selection head, return the first match
1502 Some(
1503 matches
1504 .iter()
1505 .enumerate()
1506 .rev()
1507 .find(|(_, search_match)| {
1508 search_match.contains(&selection_head)
1509 || search_match.start() < &selection_head
1510 })
1511 .map(|(ix, _)| ix)
1512 .unwrap_or(0),
1513 )
1514 }
1515 Direction::Next => {
1516 // If no selection after selection head, return the last match
1517 Some(
1518 matches
1519 .iter()
1520 .enumerate()
1521 .find(|(_, search_match)| {
1522 search_match.contains(&selection_head)
1523 || search_match.start() > &selection_head
1524 })
1525 .map(|(ix, _)| ix)
1526 .unwrap_or(matches.len().saturating_sub(1)),
1527 )
1528 }
1529 }
1530 } else {
1531 // Matches found but no active selection, return the first last one (closest to cursor)
1532 Some(matches.len().saturating_sub(1))
1533 }
1534 } else {
1535 None
1536 }
1537 }
1538 fn replace(
1539 &mut self,
1540 _: &Self::Match,
1541 _: &SearchQuery,
1542 _window: &mut Window,
1543 _: &mut Context<Self>,
1544 ) {
1545 // Replacement is not supported in terminal view, so this is a no-op.
1546 }
1547}
1548
1549///Gets the working directory for the given workspace, respecting the user's settings.
1550/// None implies "~" on whichever machine we end up on.
1551pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1552 match &TerminalSettings::get_global(cx).working_directory {
1553 WorkingDirectory::CurrentProjectDirectory => workspace
1554 .project()
1555 .read(cx)
1556 .active_project_directory(cx)
1557 .as_deref()
1558 .map(Path::to_path_buf)
1559 .or_else(|| first_project_directory(workspace, cx)),
1560 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1561 WorkingDirectory::AlwaysHome => None,
1562 WorkingDirectory::Always { directory } => {
1563 shellexpand::full(&directory) //TODO handle this better
1564 .ok()
1565 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1566 .filter(|dir| dir.is_dir())
1567 }
1568 }
1569}
1570///Gets the first project's home directory, or the home directory
1571fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1572 let worktree = workspace.worktrees(cx).next()?.read(cx);
1573 let worktree_path = worktree.abs_path();
1574 if worktree.root_entry()?.is_dir() {
1575 Some(worktree_path.to_path_buf())
1576 } else {
1577 // If worktree is a file, return its parent directory
1578 worktree_path.parent().map(|p| p.to_path_buf())
1579 }
1580}
1581
1582#[cfg(test)]
1583mod tests {
1584 use super::*;
1585 use gpui::TestAppContext;
1586 use project::{Entry, Project, ProjectPath, Worktree};
1587 use std::path::Path;
1588 use util::rel_path::RelPath;
1589 use workspace::AppState;
1590
1591 // Working directory calculation tests
1592
1593 // No Worktrees in project -> home_dir()
1594 #[gpui::test]
1595 async fn no_worktree(cx: &mut TestAppContext) {
1596 let (project, workspace) = init_test(cx).await;
1597 cx.read(|cx| {
1598 let workspace = workspace.read(cx);
1599 let active_entry = project.read(cx).active_entry();
1600
1601 //Make sure environment is as expected
1602 assert!(active_entry.is_none());
1603 assert!(workspace.worktrees(cx).next().is_none());
1604
1605 let res = default_working_directory(workspace, cx);
1606 assert_eq!(res, None);
1607 let res = first_project_directory(workspace, cx);
1608 assert_eq!(res, None);
1609 });
1610 }
1611
1612 // No active entry, but a worktree, worktree is a file -> parent directory
1613 #[gpui::test]
1614 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1615 let (project, workspace) = init_test(cx).await;
1616
1617 create_file_wt(project.clone(), "/root.txt", cx).await;
1618 cx.read(|cx| {
1619 let workspace = workspace.read(cx);
1620 let active_entry = project.read(cx).active_entry();
1621
1622 //Make sure environment is as expected
1623 assert!(active_entry.is_none());
1624 assert!(workspace.worktrees(cx).next().is_some());
1625
1626 let res = default_working_directory(workspace, cx);
1627 assert_eq!(res, Some(Path::new("/").to_path_buf()));
1628 let res = first_project_directory(workspace, cx);
1629 assert_eq!(res, Some(Path::new("/").to_path_buf()));
1630 });
1631 }
1632
1633 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1634 #[gpui::test]
1635 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1636 let (project, workspace) = init_test(cx).await;
1637
1638 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1639 cx.update(|cx| {
1640 let workspace = workspace.read(cx);
1641 let active_entry = project.read(cx).active_entry();
1642
1643 assert!(active_entry.is_none());
1644 assert!(workspace.worktrees(cx).next().is_some());
1645
1646 let res = default_working_directory(workspace, cx);
1647 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1648 let res = first_project_directory(workspace, cx);
1649 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1650 });
1651 }
1652
1653 // Active entry with a work tree, worktree is a file -> worktree_folder()
1654 #[gpui::test]
1655 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1656 let (project, workspace) = init_test(cx).await;
1657
1658 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1659 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1660 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1661
1662 cx.update(|cx| {
1663 let workspace = workspace.read(cx);
1664 let active_entry = project.read(cx).active_entry();
1665
1666 assert!(active_entry.is_some());
1667
1668 let res = default_working_directory(workspace, cx);
1669 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1670 let res = first_project_directory(workspace, cx);
1671 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1672 });
1673 }
1674
1675 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1676 #[gpui::test]
1677 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1678 let (project, workspace) = init_test(cx).await;
1679
1680 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1681 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1682 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1683
1684 cx.update(|cx| {
1685 let workspace = workspace.read(cx);
1686 let active_entry = project.read(cx).active_entry();
1687
1688 assert!(active_entry.is_some());
1689
1690 let res = default_working_directory(workspace, cx);
1691 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1692 let res = first_project_directory(workspace, cx);
1693 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1694 });
1695 }
1696
1697 /// Creates a worktree with 1 file: /root.txt
1698 pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
1699 let params = cx.update(AppState::test);
1700 cx.update(|cx| {
1701 theme::init(theme::LoadThemes::JustBase, cx);
1702 });
1703
1704 let project = Project::test(params.fs.clone(), [], cx).await;
1705 let workspace = cx
1706 .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
1707 .root(cx)
1708 .unwrap();
1709
1710 (project, workspace)
1711 }
1712
1713 /// Creates a worktree with 1 folder: /root{suffix}/
1714 async fn create_folder_wt(
1715 project: Entity<Project>,
1716 path: impl AsRef<Path>,
1717 cx: &mut TestAppContext,
1718 ) -> (Entity<Worktree>, Entry) {
1719 create_wt(project, true, path, cx).await
1720 }
1721
1722 /// Creates a worktree with 1 file: /root{suffix}.txt
1723 async fn create_file_wt(
1724 project: Entity<Project>,
1725 path: impl AsRef<Path>,
1726 cx: &mut TestAppContext,
1727 ) -> (Entity<Worktree>, Entry) {
1728 create_wt(project, false, path, cx).await
1729 }
1730
1731 async fn create_wt(
1732 project: Entity<Project>,
1733 is_dir: bool,
1734 path: impl AsRef<Path>,
1735 cx: &mut TestAppContext,
1736 ) -> (Entity<Worktree>, Entry) {
1737 let (wt, _) = project
1738 .update(cx, |project, cx| {
1739 project.find_or_create_worktree(path, true, cx)
1740 })
1741 .await
1742 .unwrap();
1743
1744 let entry = cx
1745 .update(|cx| {
1746 wt.update(cx, |wt, cx| {
1747 wt.create_entry(RelPath::empty().into(), is_dir, None, cx)
1748 })
1749 })
1750 .await
1751 .unwrap()
1752 .into_included()
1753 .unwrap();
1754
1755 (wt, entry)
1756 }
1757
1758 pub fn insert_active_entry_for(
1759 wt: Entity<Worktree>,
1760 entry: Entry,
1761 project: Entity<Project>,
1762 cx: &mut TestAppContext,
1763 ) {
1764 cx.update(|cx| {
1765 let p = ProjectPath {
1766 worktree_id: wt.read(cx).id(),
1767 path: entry.path,
1768 };
1769 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1770 });
1771 }
1772}