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::TerminalControlled => {
653 !self.blinking_terminal_enabled || self.blink_manager.read(cx).visible()
654 }
655 TerminalBlink::On => self.blink_manager.read(cx).visible(),
656 }
657 }
658
659 pub fn pause_cursor_blinking(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
660 self.blink_manager.update(cx, BlinkManager::pause_blinking);
661 }
662
663 pub fn terminal(&self) -> &Entity<Terminal> {
664 &self.terminal
665 }
666
667 pub fn set_block_below_cursor(
668 &mut self,
669 block: BlockProperties,
670 window: &mut Window,
671 cx: &mut Context<Self>,
672 ) {
673 self.block_below_cursor = Some(Rc::new(block));
674 self.scroll_to_bottom(&ScrollToBottom, window, cx);
675 cx.notify();
676 }
677
678 pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
679 self.block_below_cursor = None;
680 self.scroll_top = Pixels::ZERO;
681 cx.notify();
682 }
683
684 ///Attempt to paste the clipboard into the terminal
685 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
686 self.terminal.update(cx, |term, _| term.copy(None));
687 cx.notify();
688 }
689
690 ///Attempt to paste the clipboard into the terminal
691 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
692 if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
693 self.terminal
694 .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
695 }
696 }
697
698 fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
699 self.clear_bell(cx);
700 self.terminal.update(cx, |term, _| {
701 term.input(text.0.to_string().into_bytes());
702 });
703 }
704
705 fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
706 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
707 self.clear_bell(cx);
708 self.terminal.update(cx, |term, cx| {
709 let processed =
710 term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
711 if processed && term.vi_mode_enabled() {
712 cx.notify();
713 }
714 processed
715 });
716 }
717 }
718
719 fn dispatch_context(&self, cx: &App) -> KeyContext {
720 let mut dispatch_context = KeyContext::new_with_defaults();
721 dispatch_context.add("Terminal");
722
723 if self.terminal.read(cx).vi_mode_enabled() {
724 dispatch_context.add("vi_mode");
725 }
726
727 let mode = self.terminal.read(cx).last_content.mode;
728 dispatch_context.set(
729 "screen",
730 if mode.contains(TermMode::ALT_SCREEN) {
731 "alt"
732 } else {
733 "normal"
734 },
735 );
736
737 if mode.contains(TermMode::APP_CURSOR) {
738 dispatch_context.add("DECCKM");
739 }
740 if mode.contains(TermMode::APP_KEYPAD) {
741 dispatch_context.add("DECPAM");
742 } else {
743 dispatch_context.add("DECPNM");
744 }
745 if mode.contains(TermMode::SHOW_CURSOR) {
746 dispatch_context.add("DECTCEM");
747 }
748 if mode.contains(TermMode::LINE_WRAP) {
749 dispatch_context.add("DECAWM");
750 }
751 if mode.contains(TermMode::ORIGIN) {
752 dispatch_context.add("DECOM");
753 }
754 if mode.contains(TermMode::INSERT) {
755 dispatch_context.add("IRM");
756 }
757 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
758 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
759 dispatch_context.add("LNM");
760 }
761 if mode.contains(TermMode::FOCUS_IN_OUT) {
762 dispatch_context.add("report_focus");
763 }
764 if mode.contains(TermMode::ALTERNATE_SCROLL) {
765 dispatch_context.add("alternate_scroll");
766 }
767 if mode.contains(TermMode::BRACKETED_PASTE) {
768 dispatch_context.add("bracketed_paste");
769 }
770 if mode.intersects(TermMode::MOUSE_MODE) {
771 dispatch_context.add("any_mouse_reporting");
772 }
773 {
774 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
775 "click"
776 } else if mode.contains(TermMode::MOUSE_DRAG) {
777 "drag"
778 } else if mode.contains(TermMode::MOUSE_MOTION) {
779 "motion"
780 } else {
781 "off"
782 };
783 dispatch_context.set("mouse_reporting", mouse_reporting);
784 }
785 {
786 let format = if mode.contains(TermMode::SGR_MOUSE) {
787 "sgr"
788 } else if mode.contains(TermMode::UTF8_MOUSE) {
789 "utf8"
790 } else {
791 "normal"
792 };
793 dispatch_context.set("mouse_format", format);
794 };
795
796 if self.terminal.read(cx).last_content.selection.is_some() {
797 dispatch_context.add("selection");
798 }
799
800 dispatch_context
801 }
802
803 fn set_terminal(
804 &mut self,
805 terminal: Entity<Terminal>,
806 window: &mut Window,
807 cx: &mut Context<TerminalView>,
808 ) {
809 self._terminal_subscriptions =
810 subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
811 self.terminal = terminal;
812 }
813
814 fn rerun_button(task: &TaskState) -> Option<IconButton> {
815 if !task.spawned_task.show_rerun {
816 return None;
817 }
818
819 let task_id = task.spawned_task.id.clone();
820 Some(
821 IconButton::new("rerun-icon", IconName::Rerun)
822 .icon_size(IconSize::Small)
823 .size(ButtonSize::Compact)
824 .icon_color(Color::Default)
825 .shape(ui::IconButtonShape::Square)
826 .tooltip(move |_window, cx| Tooltip::for_action("Rerun task", &RerunTask, cx))
827 .on_click(move |_, window, cx| {
828 window.dispatch_action(Box::new(terminal_rerun_override(&task_id)), cx);
829 }),
830 )
831 }
832}
833
834fn terminal_rerun_override(task: &TaskId) -> zed_actions::Rerun {
835 zed_actions::Rerun {
836 task_id: Some(task.0.clone()),
837 allow_concurrent_runs: Some(true),
838 use_new_terminal: Some(false),
839 reevaluate_context: false,
840 }
841}
842
843fn subscribe_for_terminal_events(
844 terminal: &Entity<Terminal>,
845 workspace: WeakEntity<Workspace>,
846 window: &mut Window,
847 cx: &mut Context<TerminalView>,
848) -> Vec<Subscription> {
849 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
850 let mut previous_cwd = None;
851 let terminal_events_subscription = cx.subscribe_in(
852 terminal,
853 window,
854 move |terminal_view, terminal, event, window, cx| {
855 let current_cwd = terminal.read(cx).working_directory();
856 if current_cwd != previous_cwd {
857 previous_cwd = current_cwd;
858 terminal_view.cwd_serialized = false;
859 }
860
861 match event {
862 Event::Wakeup => {
863 cx.notify();
864 cx.emit(Event::Wakeup);
865 cx.emit(ItemEvent::UpdateTab);
866 cx.emit(SearchEvent::MatchesInvalidated);
867 }
868
869 Event::Bell => {
870 terminal_view.has_bell = true;
871 cx.emit(Event::Wakeup);
872 }
873
874 Event::BlinkChanged(blinking) => {
875 terminal_view.blinking_terminal_enabled = *blinking;
876
877 // If in terminal-controlled mode and focused, update blink manager
878 if matches!(
879 TerminalSettings::get_global(cx).blinking,
880 TerminalBlink::TerminalControlled
881 ) && terminal_view.focus_handle.is_focused(window)
882 {
883 terminal_view.blink_manager.update(cx, |manager, cx| {
884 if *blinking {
885 manager.enable(cx);
886 } else {
887 manager.disable(cx);
888 }
889 });
890 }
891 }
892
893 Event::TitleChanged => {
894 cx.emit(ItemEvent::UpdateTab);
895 }
896
897 Event::NewNavigationTarget(maybe_navigation_target) => {
898 match maybe_navigation_target
899 .as_ref()
900 .zip(terminal.read(cx).last_content.last_hovered_word.as_ref())
901 {
902 Some((MaybeNavigationTarget::Url(url), hovered_word)) => {
903 if Some(hovered_word)
904 != terminal_view
905 .hover
906 .as_ref()
907 .map(|hover| &hover.hovered_word)
908 {
909 terminal_view.hover = Some(HoverTarget {
910 tooltip: url.clone(),
911 hovered_word: hovered_word.clone(),
912 });
913 terminal_view.hover_tooltip_update = Task::ready(());
914 cx.notify();
915 }
916 }
917 Some((MaybeNavigationTarget::PathLike(path_like_target), hovered_word)) => {
918 if Some(hovered_word)
919 != terminal_view
920 .hover
921 .as_ref()
922 .map(|hover| &hover.hovered_word)
923 {
924 terminal_view.hover = None;
925 terminal_view.hover_tooltip_update = hover_path_like_target(
926 &workspace,
927 hovered_word.clone(),
928 path_like_target,
929 cx,
930 );
931 cx.notify();
932 }
933 }
934 None => {
935 terminal_view.hover = None;
936 terminal_view.hover_tooltip_update = Task::ready(());
937 cx.notify();
938 }
939 }
940 }
941
942 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
943 MaybeNavigationTarget::Url(url) => cx.open_url(url),
944 MaybeNavigationTarget::PathLike(path_like_target) => open_path_like_target(
945 &workspace,
946 terminal_view,
947 path_like_target,
948 window,
949 cx,
950 ),
951 },
952 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
953 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
954 Event::SelectionsChanged => {
955 window.invalidate_character_coordinates();
956 cx.emit(SearchEvent::ActiveMatchChanged)
957 }
958 }
959 },
960 );
961 vec![terminal_subscription, terminal_events_subscription]
962}
963
964fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
965 let str = query.as_str();
966 if query.is_regex() {
967 if str == "." {
968 return None;
969 }
970 RegexSearch::new(str).ok()
971 } else {
972 RegexSearch::new(®ex::escape(str)).ok()
973 }
974}
975
976struct TerminalScrollbarSettingsWrapper;
977
978impl GlobalSetting for TerminalScrollbarSettingsWrapper {
979 fn get_value(_cx: &App) -> &Self {
980 &Self
981 }
982}
983
984impl ScrollbarVisibility for TerminalScrollbarSettingsWrapper {
985 fn visibility(&self, cx: &App) -> scrollbars::ShowScrollbar {
986 TerminalSettings::get_global(cx)
987 .scrollbar
988 .show
989 .map(Into::into)
990 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
991 }
992}
993
994impl TerminalView {
995 fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
996 self.clear_bell(cx);
997 self.pause_cursor_blinking(window, cx);
998
999 self.terminal.update(cx, |term, cx| {
1000 let handled = term.try_keystroke(
1001 &event.keystroke,
1002 TerminalSettings::get_global(cx).option_as_meta,
1003 );
1004 if handled {
1005 cx.stop_propagation();
1006 }
1007 });
1008 }
1009
1010 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1011 self.terminal.update(cx, |terminal, _| {
1012 terminal.set_cursor_shape(self.cursor_shape);
1013 terminal.focus_in();
1014 });
1015
1016 let should_blink = match TerminalSettings::get_global(cx).blinking {
1017 TerminalBlink::Off => false,
1018 TerminalBlink::On => true,
1019 TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
1020 };
1021
1022 if should_blink {
1023 self.blink_manager.update(cx, BlinkManager::enable);
1024 }
1025
1026 window.invalidate_character_coordinates();
1027 cx.notify();
1028 }
1029
1030 fn focus_out(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1031 self.blink_manager.update(cx, BlinkManager::disable);
1032 self.terminal.update(cx, |terminal, _| {
1033 terminal.focus_out();
1034 terminal.set_cursor_shape(CursorShape::Hollow);
1035 });
1036 cx.notify();
1037 }
1038}
1039
1040impl Render for TerminalView {
1041 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1042 // TODO: this should be moved out of render
1043 self.scroll_handle.update(self.terminal.read(cx));
1044
1045 if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
1046 self.terminal.update(cx, |term, _| {
1047 let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
1048 match delta.cmp(&0) {
1049 std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
1050 std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
1051 std::cmp::Ordering::Equal => {}
1052 }
1053 });
1054 }
1055
1056 let terminal_handle = self.terminal.clone();
1057 let terminal_view_handle = cx.entity();
1058
1059 let focused = self.focus_handle.is_focused(window);
1060
1061 div()
1062 .id("terminal-view")
1063 .size_full()
1064 .relative()
1065 .track_focus(&self.focus_handle(cx))
1066 .key_context(self.dispatch_context(cx))
1067 .on_action(cx.listener(TerminalView::send_text))
1068 .on_action(cx.listener(TerminalView::send_keystroke))
1069 .on_action(cx.listener(TerminalView::copy))
1070 .on_action(cx.listener(TerminalView::paste))
1071 .on_action(cx.listener(TerminalView::clear))
1072 .on_action(cx.listener(TerminalView::scroll_line_up))
1073 .on_action(cx.listener(TerminalView::scroll_line_down))
1074 .on_action(cx.listener(TerminalView::scroll_page_up))
1075 .on_action(cx.listener(TerminalView::scroll_page_down))
1076 .on_action(cx.listener(TerminalView::scroll_to_top))
1077 .on_action(cx.listener(TerminalView::scroll_to_bottom))
1078 .on_action(cx.listener(TerminalView::toggle_vi_mode))
1079 .on_action(cx.listener(TerminalView::show_character_palette))
1080 .on_action(cx.listener(TerminalView::select_all))
1081 .on_action(cx.listener(TerminalView::rerun_task))
1082 .on_key_down(cx.listener(Self::key_down))
1083 .on_mouse_down(
1084 MouseButton::Right,
1085 cx.listener(|this, event: &MouseDownEvent, window, cx| {
1086 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1087 if this.terminal.read(cx).last_content.selection.is_none() {
1088 this.terminal.update(cx, |terminal, _| {
1089 terminal.select_word_at_event_position(event);
1090 });
1091 };
1092 this.deploy_context_menu(event.position, window, cx);
1093 cx.notify();
1094 }
1095 }),
1096 )
1097 .child(
1098 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1099 div()
1100 .id("terminal-view-container")
1101 .size_full()
1102 .bg(cx.theme().colors().editor_background)
1103 .child(TerminalElement::new(
1104 terminal_handle,
1105 terminal_view_handle,
1106 self.workspace.clone(),
1107 self.focus_handle.clone(),
1108 focused,
1109 self.should_show_cursor(focused, cx),
1110 self.block_below_cursor.clone(),
1111 self.mode.clone(),
1112 ))
1113 .when(self.content_mode(window, cx).is_scrollable(), |div| {
1114 div.custom_scrollbars(
1115 Scrollbars::for_settings::<TerminalScrollbarSettingsWrapper>()
1116 .show_along(ScrollAxes::Vertical)
1117 .with_track_along(
1118 ScrollAxes::Vertical,
1119 cx.theme().colors().editor_background,
1120 )
1121 .tracked_scroll_handle(&self.scroll_handle),
1122 window,
1123 cx,
1124 )
1125 }),
1126 )
1127 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1128 deferred(
1129 anchored()
1130 .position(*position)
1131 .anchor(gpui::Corner::TopLeft)
1132 .child(menu.clone()),
1133 )
1134 .with_priority(1)
1135 }))
1136 }
1137}
1138
1139impl Item for TerminalView {
1140 type Event = ItemEvent;
1141
1142 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1143 let terminal = self.terminal().read(cx);
1144 let title = terminal.title(false);
1145 let pid = terminal.pid_getter()?.fallback_pid();
1146
1147 Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
1148 cx.new(|_| TerminalTooltip::new(title.clone(), pid.as_u32()))
1149 .into()
1150 })))
1151 }
1152
1153 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1154 let terminal = self.terminal().read(cx);
1155 let title = terminal.title(true);
1156
1157 let (icon, icon_color, rerun_button) = match terminal.task() {
1158 Some(terminal_task) => match &terminal_task.status {
1159 TaskStatus::Running => (
1160 IconName::PlayFilled,
1161 Color::Disabled,
1162 TerminalView::rerun_button(terminal_task),
1163 ),
1164 TaskStatus::Unknown => (
1165 IconName::Warning,
1166 Color::Warning,
1167 TerminalView::rerun_button(terminal_task),
1168 ),
1169 TaskStatus::Completed { success } => {
1170 let rerun_button = TerminalView::rerun_button(terminal_task);
1171
1172 if *success {
1173 (IconName::Check, Color::Success, rerun_button)
1174 } else {
1175 (IconName::XCircle, Color::Error, rerun_button)
1176 }
1177 }
1178 },
1179 None => (IconName::Terminal, Color::Muted, None),
1180 };
1181
1182 h_flex()
1183 .gap_1()
1184 .group("term-tab-icon")
1185 .child(
1186 h_flex()
1187 .group("term-tab-icon")
1188 .child(
1189 div()
1190 .when(rerun_button.is_some(), |this| {
1191 this.hover(|style| style.invisible().w_0())
1192 })
1193 .child(Icon::new(icon).color(icon_color)),
1194 )
1195 .when_some(rerun_button, |this, rerun_button| {
1196 this.child(
1197 div()
1198 .absolute()
1199 .visible_on_hover("term-tab-icon")
1200 .child(rerun_button),
1201 )
1202 }),
1203 )
1204 .child(Label::new(title).color(params.text_color()))
1205 .into_any()
1206 }
1207
1208 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
1209 let terminal = self.terminal().read(cx);
1210 terminal.title(detail == 0).into()
1211 }
1212
1213 fn telemetry_event_text(&self) -> Option<&'static str> {
1214 None
1215 }
1216
1217 fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
1218 workspace::item::ItemBufferKind::Singleton
1219 }
1220
1221 fn can_split(&self) -> bool {
1222 true
1223 }
1224
1225 fn clone_on_split(
1226 &self,
1227 workspace_id: Option<WorkspaceId>,
1228 window: &mut Window,
1229 cx: &mut Context<Self>,
1230 ) -> Task<Option<Entity<Self>>> {
1231 let Ok(terminal) = self.project.update(cx, |project, cx| {
1232 let cwd = project
1233 .active_project_directory(cx)
1234 .map(|it| it.to_path_buf());
1235 project.clone_terminal(self.terminal(), cx, cwd)
1236 }) else {
1237 return Task::ready(None);
1238 };
1239 cx.spawn_in(window, async move |this, cx| {
1240 let terminal = terminal.await.log_err()?;
1241 this.update_in(cx, |this, window, cx| {
1242 cx.new(|cx| {
1243 TerminalView::new(
1244 terminal,
1245 this.workspace.clone(),
1246 workspace_id,
1247 this.project.clone(),
1248 window,
1249 cx,
1250 )
1251 })
1252 })
1253 .ok()
1254 })
1255 }
1256
1257 fn is_dirty(&self, cx: &gpui::App) -> bool {
1258 match self.terminal.read(cx).task() {
1259 Some(task) => task.status == TaskStatus::Running,
1260 None => self.has_bell(),
1261 }
1262 }
1263
1264 fn has_conflict(&self, _cx: &App) -> bool {
1265 false
1266 }
1267
1268 fn can_save_as(&self, _cx: &App) -> bool {
1269 false
1270 }
1271
1272 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1273 Some(Box::new(handle.clone()))
1274 }
1275
1276 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1277 if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1278 ToolbarItemLocation::PrimaryLeft
1279 } else {
1280 ToolbarItemLocation::Hidden
1281 }
1282 }
1283
1284 fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1285 Some(vec![BreadcrumbText {
1286 text: self.terminal().read(cx).breadcrumb_text.clone(),
1287 highlights: None,
1288 font: None,
1289 }])
1290 }
1291
1292 fn added_to_workspace(
1293 &mut self,
1294 workspace: &mut Workspace,
1295 _: &mut Window,
1296 cx: &mut Context<Self>,
1297 ) {
1298 if self.terminal().read(cx).task().is_none() {
1299 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1300 log::debug!(
1301 "Updating workspace id for the terminal, old: {old_id:?}, new: {new_id:?}",
1302 );
1303 cx.background_spawn(TERMINAL_DB.update_workspace_id(
1304 new_id,
1305 old_id,
1306 cx.entity_id().as_u64(),
1307 ))
1308 .detach();
1309 }
1310 self.workspace_id = workspace.database_id();
1311 }
1312 }
1313
1314 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1315 f(*event)
1316 }
1317}
1318
1319impl SerializableItem for TerminalView {
1320 fn serialized_item_kind() -> &'static str {
1321 "Terminal"
1322 }
1323
1324 fn cleanup(
1325 workspace_id: WorkspaceId,
1326 alive_items: Vec<workspace::ItemId>,
1327 _window: &mut Window,
1328 cx: &mut App,
1329 ) -> Task<anyhow::Result<()>> {
1330 delete_unloaded_items(alive_items, workspace_id, "terminals", &TERMINAL_DB, cx)
1331 }
1332
1333 fn serialize(
1334 &mut self,
1335 _workspace: &mut Workspace,
1336 item_id: workspace::ItemId,
1337 _closing: bool,
1338 _: &mut Window,
1339 cx: &mut Context<Self>,
1340 ) -> Option<Task<anyhow::Result<()>>> {
1341 let terminal = self.terminal().read(cx);
1342 if terminal.task().is_some() {
1343 return None;
1344 }
1345
1346 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1347 self.cwd_serialized = true;
1348 Some(cx.background_spawn(async move {
1349 TERMINAL_DB
1350 .save_working_directory(item_id, workspace_id, cwd)
1351 .await
1352 }))
1353 } else {
1354 None
1355 }
1356 }
1357
1358 fn should_serialize(&self, _: &Self::Event) -> bool {
1359 !self.cwd_serialized
1360 }
1361
1362 fn deserialize(
1363 project: Entity<Project>,
1364 workspace: WeakEntity<Workspace>,
1365 workspace_id: workspace::WorkspaceId,
1366 item_id: workspace::ItemId,
1367 window: &mut Window,
1368 cx: &mut App,
1369 ) -> Task<anyhow::Result<Entity<Self>>> {
1370 window.spawn(cx, async move |cx| {
1371 let cwd = cx
1372 .update(|_window, cx| {
1373 let from_db = TERMINAL_DB
1374 .get_working_directory(item_id, workspace_id)
1375 .log_err()
1376 .flatten();
1377 if from_db
1378 .as_ref()
1379 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1380 {
1381 from_db
1382 } else {
1383 workspace
1384 .upgrade()
1385 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1386 }
1387 })
1388 .ok()
1389 .flatten();
1390
1391 let terminal = project
1392 .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
1393 .await?;
1394 cx.update(|window, cx| {
1395 cx.new(|cx| {
1396 TerminalView::new(
1397 terminal,
1398 workspace,
1399 Some(workspace_id),
1400 project.downgrade(),
1401 window,
1402 cx,
1403 )
1404 })
1405 })
1406 })
1407 }
1408}
1409
1410impl SearchableItem for TerminalView {
1411 type Match = RangeInclusive<Point>;
1412
1413 fn supported_options(&self) -> SearchOptions {
1414 SearchOptions {
1415 case: false,
1416 word: false,
1417 regex: true,
1418 replacement: false,
1419 selection: false,
1420 find_in_results: false,
1421 }
1422 }
1423
1424 /// Clear stored matches
1425 fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1426 self.terminal().update(cx, |term, _| term.matches.clear())
1427 }
1428
1429 /// Store matches returned from find_matches somewhere for rendering
1430 fn update_matches(
1431 &mut self,
1432 matches: &[Self::Match],
1433 _window: &mut Window,
1434 cx: &mut Context<Self>,
1435 ) {
1436 self.terminal()
1437 .update(cx, |term, _| term.matches = matches.to_vec())
1438 }
1439
1440 /// Returns the selection content to pre-load into this search
1441 fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1442 self.terminal()
1443 .read(cx)
1444 .last_content
1445 .selection_text
1446 .clone()
1447 .unwrap_or_default()
1448 }
1449
1450 /// Focus match at given index into the Vec of matches
1451 fn activate_match(
1452 &mut self,
1453 index: usize,
1454 _: &[Self::Match],
1455 _window: &mut Window,
1456 cx: &mut Context<Self>,
1457 ) {
1458 self.terminal()
1459 .update(cx, |term, _| term.activate_match(index));
1460 cx.notify();
1461 }
1462
1463 /// Add selections for all matches given.
1464 fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1465 self.terminal()
1466 .update(cx, |term, _| term.select_matches(matches));
1467 cx.notify();
1468 }
1469
1470 /// Get all of the matches for this query, should be done on the background
1471 fn find_matches(
1472 &mut self,
1473 query: Arc<SearchQuery>,
1474 _: &mut Window,
1475 cx: &mut Context<Self>,
1476 ) -> Task<Vec<Self::Match>> {
1477 if let Some(s) = regex_search_for_query(&query) {
1478 self.terminal()
1479 .update(cx, |term, cx| term.find_matches(s, cx))
1480 } else {
1481 Task::ready(vec![])
1482 }
1483 }
1484
1485 /// Reports back to the search toolbar what the active match should be (the selection)
1486 fn active_match_index(
1487 &mut self,
1488 direction: Direction,
1489 matches: &[Self::Match],
1490 _: &mut Window,
1491 cx: &mut Context<Self>,
1492 ) -> Option<usize> {
1493 // Selection head might have a value if there's a selection that isn't
1494 // associated with a match. Therefore, if there are no matches, we should
1495 // report None, no matter the state of the terminal
1496
1497 if !matches.is_empty() {
1498 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1499 // If selection head is contained in a match. Return that match
1500 match direction {
1501 Direction::Prev => {
1502 // If no selection before selection head, return the first match
1503 Some(
1504 matches
1505 .iter()
1506 .enumerate()
1507 .rev()
1508 .find(|(_, search_match)| {
1509 search_match.contains(&selection_head)
1510 || search_match.start() < &selection_head
1511 })
1512 .map(|(ix, _)| ix)
1513 .unwrap_or(0),
1514 )
1515 }
1516 Direction::Next => {
1517 // If no selection after selection head, return the last match
1518 Some(
1519 matches
1520 .iter()
1521 .enumerate()
1522 .find(|(_, search_match)| {
1523 search_match.contains(&selection_head)
1524 || search_match.start() > &selection_head
1525 })
1526 .map(|(ix, _)| ix)
1527 .unwrap_or(matches.len().saturating_sub(1)),
1528 )
1529 }
1530 }
1531 } else {
1532 // Matches found but no active selection, return the first last one (closest to cursor)
1533 Some(matches.len().saturating_sub(1))
1534 }
1535 } else {
1536 None
1537 }
1538 }
1539 fn replace(
1540 &mut self,
1541 _: &Self::Match,
1542 _: &SearchQuery,
1543 _window: &mut Window,
1544 _: &mut Context<Self>,
1545 ) {
1546 // Replacement is not supported in terminal view, so this is a no-op.
1547 }
1548}
1549
1550///Gets the working directory for the given workspace, respecting the user's settings.
1551/// None implies "~" on whichever machine we end up on.
1552pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1553 match &TerminalSettings::get_global(cx).working_directory {
1554 WorkingDirectory::CurrentProjectDirectory => workspace
1555 .project()
1556 .read(cx)
1557 .active_project_directory(cx)
1558 .as_deref()
1559 .map(Path::to_path_buf)
1560 .or_else(|| first_project_directory(workspace, cx)),
1561 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1562 WorkingDirectory::AlwaysHome => None,
1563 WorkingDirectory::Always { directory } => {
1564 shellexpand::full(&directory) //TODO handle this better
1565 .ok()
1566 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1567 .filter(|dir| dir.is_dir())
1568 }
1569 }
1570}
1571///Gets the first project's home directory, or the home directory
1572fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1573 let worktree = workspace.worktrees(cx).next()?.read(cx);
1574 let worktree_path = worktree.abs_path();
1575 if worktree.root_entry()?.is_dir() {
1576 Some(worktree_path.to_path_buf())
1577 } else {
1578 // If worktree is a file, return its parent directory
1579 worktree_path.parent().map(|p| p.to_path_buf())
1580 }
1581}
1582
1583#[cfg(test)]
1584mod tests {
1585 use super::*;
1586 use gpui::TestAppContext;
1587 use project::{Entry, Project, ProjectPath, Worktree};
1588 use std::path::Path;
1589 use util::rel_path::RelPath;
1590 use workspace::AppState;
1591
1592 // Working directory calculation tests
1593
1594 // No Worktrees in project -> home_dir()
1595 #[gpui::test]
1596 async fn no_worktree(cx: &mut TestAppContext) {
1597 let (project, workspace) = init_test(cx).await;
1598 cx.read(|cx| {
1599 let workspace = workspace.read(cx);
1600 let active_entry = project.read(cx).active_entry();
1601
1602 //Make sure environment is as expected
1603 assert!(active_entry.is_none());
1604 assert!(workspace.worktrees(cx).next().is_none());
1605
1606 let res = default_working_directory(workspace, cx);
1607 assert_eq!(res, None);
1608 let res = first_project_directory(workspace, cx);
1609 assert_eq!(res, None);
1610 });
1611 }
1612
1613 // No active entry, but a worktree, worktree is a file -> parent directory
1614 #[gpui::test]
1615 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1616 let (project, workspace) = init_test(cx).await;
1617
1618 create_file_wt(project.clone(), "/root.txt", cx).await;
1619 cx.read(|cx| {
1620 let workspace = workspace.read(cx);
1621 let active_entry = project.read(cx).active_entry();
1622
1623 //Make sure environment is as expected
1624 assert!(active_entry.is_none());
1625 assert!(workspace.worktrees(cx).next().is_some());
1626
1627 let res = default_working_directory(workspace, cx);
1628 assert_eq!(res, Some(Path::new("/").to_path_buf()));
1629 let res = first_project_directory(workspace, cx);
1630 assert_eq!(res, Some(Path::new("/").to_path_buf()));
1631 });
1632 }
1633
1634 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1635 #[gpui::test]
1636 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1637 let (project, workspace) = init_test(cx).await;
1638
1639 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1640 cx.update(|cx| {
1641 let workspace = workspace.read(cx);
1642 let active_entry = project.read(cx).active_entry();
1643
1644 assert!(active_entry.is_none());
1645 assert!(workspace.worktrees(cx).next().is_some());
1646
1647 let res = default_working_directory(workspace, cx);
1648 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1649 let res = first_project_directory(workspace, cx);
1650 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1651 });
1652 }
1653
1654 // Active entry with a work tree, worktree is a file -> worktree_folder()
1655 #[gpui::test]
1656 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1657 let (project, workspace) = init_test(cx).await;
1658
1659 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1660 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1661 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1662
1663 cx.update(|cx| {
1664 let workspace = workspace.read(cx);
1665 let active_entry = project.read(cx).active_entry();
1666
1667 assert!(active_entry.is_some());
1668
1669 let res = default_working_directory(workspace, cx);
1670 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1671 let res = first_project_directory(workspace, cx);
1672 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1673 });
1674 }
1675
1676 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1677 #[gpui::test]
1678 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1679 let (project, workspace) = init_test(cx).await;
1680
1681 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1682 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1683 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1684
1685 cx.update(|cx| {
1686 let workspace = workspace.read(cx);
1687 let active_entry = project.read(cx).active_entry();
1688
1689 assert!(active_entry.is_some());
1690
1691 let res = default_working_directory(workspace, cx);
1692 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1693 let res = first_project_directory(workspace, cx);
1694 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1695 });
1696 }
1697
1698 /// Creates a worktree with 1 file: /root.txt
1699 pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
1700 let params = cx.update(AppState::test);
1701 cx.update(|cx| {
1702 theme::init(theme::LoadThemes::JustBase, cx);
1703 });
1704
1705 let project = Project::test(params.fs.clone(), [], cx).await;
1706 let workspace = cx
1707 .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
1708 .root(cx)
1709 .unwrap();
1710
1711 (project, workspace)
1712 }
1713
1714 /// Creates a worktree with 1 folder: /root{suffix}/
1715 async fn create_folder_wt(
1716 project: Entity<Project>,
1717 path: impl AsRef<Path>,
1718 cx: &mut TestAppContext,
1719 ) -> (Entity<Worktree>, Entry) {
1720 create_wt(project, true, path, cx).await
1721 }
1722
1723 /// Creates a worktree with 1 file: /root{suffix}.txt
1724 async fn create_file_wt(
1725 project: Entity<Project>,
1726 path: impl AsRef<Path>,
1727 cx: &mut TestAppContext,
1728 ) -> (Entity<Worktree>, Entry) {
1729 create_wt(project, false, path, cx).await
1730 }
1731
1732 async fn create_wt(
1733 project: Entity<Project>,
1734 is_dir: bool,
1735 path: impl AsRef<Path>,
1736 cx: &mut TestAppContext,
1737 ) -> (Entity<Worktree>, Entry) {
1738 let (wt, _) = project
1739 .update(cx, |project, cx| {
1740 project.find_or_create_worktree(path, true, cx)
1741 })
1742 .await
1743 .unwrap();
1744
1745 let entry = cx
1746 .update(|cx| {
1747 wt.update(cx, |wt, cx| {
1748 wt.create_entry(RelPath::empty().into(), is_dir, None, cx)
1749 })
1750 })
1751 .await
1752 .unwrap()
1753 .into_included()
1754 .unwrap();
1755
1756 (wt, entry)
1757 }
1758
1759 pub fn insert_active_entry_for(
1760 wt: Entity<Worktree>,
1761 entry: Entry,
1762 project: Entity<Project>,
1763 cx: &mut TestAppContext,
1764 ) {
1765 cx.update(|cx| {
1766 let p = ProjectPath {
1767 worktree_id: wt.read(cx).id(),
1768 path: entry.path,
1769 };
1770 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1771 });
1772 }
1773}