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