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, TaskStatus, Terminal,
26 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::{SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
45 CloseActiveItem, NewCenterTerminal, NewTerminal, OpenOptions, OpenVisible, ToolbarItemLocation,
46 Workspace, 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
812fn subscribe_for_terminal_events(
813 terminal: &Entity<Terminal>,
814 workspace: WeakEntity<Workspace>,
815 window: &mut Window,
816 cx: &mut Context<TerminalView>,
817) -> Vec<Subscription> {
818 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
819 let terminal_events_subscription = cx.subscribe_in(
820 terminal,
821 window,
822 move |this, _, event, window, cx| match event {
823 Event::Wakeup => {
824 cx.notify();
825 cx.emit(Event::Wakeup);
826 cx.emit(ItemEvent::UpdateTab);
827 cx.emit(SearchEvent::MatchesInvalidated);
828 }
829
830 Event::Bell => {
831 this.has_bell = true;
832 cx.emit(Event::Wakeup);
833 }
834
835 Event::BlinkChanged(blinking) => {
836 if matches!(
837 TerminalSettings::get_global(cx).blinking,
838 TerminalBlink::TerminalControlled
839 ) {
840 this.blinking_terminal_enabled = *blinking;
841 }
842 }
843
844 Event::TitleChanged => {
845 cx.emit(ItemEvent::UpdateTab);
846 }
847
848 Event::NewNavigationTarget(maybe_navigation_target) => {
849 this.can_navigate_to_selected_word = match maybe_navigation_target {
850 Some(MaybeNavigationTarget::Url(_)) => true,
851 Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
852 if let Ok(fs) = workspace.update(cx, |workspace, cx| {
853 workspace.project().read(cx).fs().clone()
854 }) {
855 let valid_files_to_open_task = possible_open_targets(
856 fs,
857 &workspace,
858 &path_like_target.terminal_dir,
859 &path_like_target.maybe_path,
860 cx,
861 );
862 !smol::block_on(valid_files_to_open_task).is_empty()
863 } else {
864 false
865 }
866 }
867 None => false,
868 };
869 cx.notify()
870 }
871
872 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
873 MaybeNavigationTarget::Url(url) => cx.open_url(url),
874
875 MaybeNavigationTarget::PathLike(path_like_target) => {
876 if !this.can_navigate_to_selected_word {
877 return;
878 }
879 let task_workspace = workspace.clone();
880 let Some(fs) = workspace
881 .update(cx, |workspace, cx| {
882 workspace.project().read(cx).fs().clone()
883 })
884 .ok()
885 else {
886 return;
887 };
888
889 let path_like_target = path_like_target.clone();
890 cx.spawn_in(window, |terminal_view, mut cx| async move {
891 let valid_files_to_open = terminal_view
892 .update(&mut cx, |_, cx| {
893 possible_open_targets(
894 fs,
895 &task_workspace,
896 &path_like_target.terminal_dir,
897 &path_like_target.maybe_path,
898 cx,
899 )
900 })?
901 .await;
902 let paths_to_open = valid_files_to_open
903 .iter()
904 .map(|(p, _)| p.path.clone())
905 .collect();
906 let opened_items = task_workspace
907 .update_in(&mut cx, |workspace, window, cx| {
908 workspace.open_paths(
909 paths_to_open,
910 OpenOptions {
911 visible: Some(OpenVisible::OnlyDirectories),
912 ..Default::default()
913 },
914 None,
915 window,
916 cx,
917 )
918 })
919 .context("workspace update")?
920 .await;
921
922 let mut has_dirs = false;
923 for ((path, metadata), opened_item) in valid_files_to_open
924 .into_iter()
925 .zip(opened_items.into_iter())
926 {
927 if metadata.is_dir {
928 has_dirs = true;
929 } else if let Some(Ok(opened_item)) = opened_item {
930 if let Some(row) = path.row {
931 let col = path.column.unwrap_or(0);
932 if let Some(active_editor) = opened_item.downcast::<Editor>() {
933 active_editor
934 .downgrade()
935 .update_in(&mut cx, |editor, window, cx| {
936 editor.go_to_singleton_buffer_point(
937 language::Point::new(
938 row.saturating_sub(1),
939 col.saturating_sub(1),
940 ),
941 window,
942 cx,
943 )
944 })
945 .log_err();
946 }
947 }
948 }
949 }
950
951 if has_dirs {
952 task_workspace.update(&mut cx, |workspace, cx| {
953 workspace.project().update(cx, |_, cx| {
954 cx.emit(project::Event::ActivateProjectPanel);
955 })
956 })?;
957 }
958
959 anyhow::Ok(())
960 })
961 .detach_and_log_err(cx)
962 }
963 },
964 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
965 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
966 Event::SelectionsChanged => {
967 window.invalidate_character_coordinates();
968 cx.emit(SearchEvent::ActiveMatchChanged)
969 }
970 },
971 );
972 vec![terminal_subscription, terminal_events_subscription]
973}
974
975fn possible_open_paths_metadata(
976 fs: Arc<dyn Fs>,
977 row: Option<u32>,
978 column: Option<u32>,
979 potential_paths: HashSet<PathBuf>,
980 cx: &mut Context<TerminalView>,
981) -> Task<Vec<(PathWithPosition, Metadata)>> {
982 cx.background_spawn(async move {
983 let mut canonical_paths = HashSet::default();
984 for path in potential_paths {
985 if let Ok(canonical) = fs.canonicalize(&path).await {
986 let sanitized = SanitizedPath::from(canonical);
987 canonical_paths.insert(sanitized.as_path().to_path_buf());
988 } else {
989 canonical_paths.insert(path);
990 }
991 }
992
993 let mut paths_with_metadata = Vec::with_capacity(canonical_paths.len());
994
995 let mut fetch_metadata_tasks = canonical_paths
996 .into_iter()
997 .map(|potential_path| async {
998 let metadata = fs.metadata(&potential_path).await.ok().flatten();
999 (
1000 PathWithPosition {
1001 path: potential_path,
1002 row,
1003 column,
1004 },
1005 metadata,
1006 )
1007 })
1008 .collect::<FuturesUnordered<_>>();
1009
1010 while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
1011 if let Some(metadata) = metadata {
1012 paths_with_metadata.push((path, metadata));
1013 }
1014 }
1015
1016 paths_with_metadata
1017 })
1018}
1019
1020fn possible_open_targets(
1021 fs: Arc<dyn Fs>,
1022 workspace: &WeakEntity<Workspace>,
1023 cwd: &Option<PathBuf>,
1024 maybe_path: &String,
1025
1026 cx: &mut Context<TerminalView>,
1027) -> Task<Vec<(PathWithPosition, Metadata)>> {
1028 let path_position = PathWithPosition::parse_str(maybe_path.as_str());
1029 let row = path_position.row;
1030 let column = path_position.column;
1031 let maybe_path = path_position.path;
1032
1033 let potential_paths = if maybe_path.is_absolute() {
1034 HashSet::from_iter([maybe_path])
1035 } else if maybe_path.starts_with("~") {
1036 maybe_path
1037 .strip_prefix("~")
1038 .ok()
1039 .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
1040 .map_or_else(HashSet::default, |p| HashSet::from_iter([p]))
1041 } else {
1042 let mut potential_cwd_and_workspace_paths = HashSet::default();
1043 if let Some(cwd) = cwd {
1044 let abs_path = Path::join(cwd, &maybe_path);
1045 potential_cwd_and_workspace_paths.insert(abs_path);
1046 }
1047 if let Some(workspace) = workspace.upgrade() {
1048 workspace.update(cx, |workspace, cx| {
1049 for potential_worktree_path in workspace
1050 .worktrees(cx)
1051 .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
1052 {
1053 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
1054 }
1055
1056 for prefix in GIT_DIFF_PATH_PREFIXES {
1057 let prefix_str = &prefix.to_string();
1058 if maybe_path.starts_with(prefix_str) {
1059 let stripped = maybe_path.strip_prefix(prefix_str).unwrap_or(&maybe_path);
1060 for potential_worktree_path in workspace
1061 .worktrees(cx)
1062 .map(|worktree| worktree.read(cx).abs_path().join(&stripped))
1063 {
1064 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
1065 }
1066 }
1067 }
1068 });
1069 }
1070 potential_cwd_and_workspace_paths
1071 };
1072
1073 possible_open_paths_metadata(fs, row, column, potential_paths, cx)
1074}
1075
1076fn regex_to_literal(regex: &str) -> String {
1077 regex
1078 .chars()
1079 .flat_map(|c| {
1080 if REGEX_SPECIAL_CHARS.contains(&c) {
1081 vec!['\\', c]
1082 } else {
1083 vec![c]
1084 }
1085 })
1086 .collect()
1087}
1088
1089pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
1090 let query = query.as_str();
1091 if query == "." {
1092 return None;
1093 }
1094 let searcher = RegexSearch::new(query);
1095 searcher.ok()
1096}
1097
1098impl TerminalView {
1099 fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1100 self.clear_bell(cx);
1101 self.pause_cursor_blinking(window, cx);
1102
1103 self.terminal.update(cx, |term, cx| {
1104 let handled = term.try_keystroke(
1105 &event.keystroke,
1106 TerminalSettings::get_global(cx).option_as_meta,
1107 );
1108 if handled {
1109 cx.stop_propagation();
1110 }
1111 });
1112 }
1113
1114 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1115 self.terminal.update(cx, |terminal, _| {
1116 terminal.set_cursor_shape(self.cursor_shape);
1117 terminal.focus_in();
1118 });
1119 self.blink_cursors(self.blink_epoch, window, cx);
1120 window.invalidate_character_coordinates();
1121 cx.notify();
1122 }
1123
1124 fn focus_out(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1125 self.terminal.update(cx, |terminal, _| {
1126 terminal.focus_out();
1127 terminal.set_cursor_shape(CursorShape::Hollow);
1128 });
1129 self.hide_scrollbar(cx);
1130 cx.notify();
1131 }
1132}
1133
1134impl Render for TerminalView {
1135 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1136 let terminal_handle = self.terminal.clone();
1137 let terminal_view_handle = cx.entity().clone();
1138
1139 let focused = self.focus_handle.is_focused(window);
1140
1141 div()
1142 .id("terminal-view")
1143 .size_full()
1144 .relative()
1145 .track_focus(&self.focus_handle(cx))
1146 .key_context(self.dispatch_context(cx))
1147 .on_action(cx.listener(TerminalView::send_text))
1148 .on_action(cx.listener(TerminalView::send_keystroke))
1149 .on_action(cx.listener(TerminalView::copy))
1150 .on_action(cx.listener(TerminalView::paste))
1151 .on_action(cx.listener(TerminalView::clear))
1152 .on_action(cx.listener(TerminalView::scroll_line_up))
1153 .on_action(cx.listener(TerminalView::scroll_line_down))
1154 .on_action(cx.listener(TerminalView::scroll_page_up))
1155 .on_action(cx.listener(TerminalView::scroll_page_down))
1156 .on_action(cx.listener(TerminalView::scroll_to_top))
1157 .on_action(cx.listener(TerminalView::scroll_to_bottom))
1158 .on_action(cx.listener(TerminalView::toggle_vi_mode))
1159 .on_action(cx.listener(TerminalView::show_character_palette))
1160 .on_action(cx.listener(TerminalView::select_all))
1161 .on_key_down(cx.listener(Self::key_down))
1162 .on_mouse_down(
1163 MouseButton::Right,
1164 cx.listener(|this, event: &MouseDownEvent, window, cx| {
1165 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1166 this.deploy_context_menu(event.position, window, cx);
1167 cx.notify();
1168 }
1169 }),
1170 )
1171 .on_hover(cx.listener(|this, hovered, window, cx| {
1172 if *hovered {
1173 this.show_scrollbar = true;
1174 this.hide_scrollbar_task.take();
1175 cx.notify();
1176 } else if !this.focus_handle.contains_focused(window, cx) {
1177 this.hide_scrollbar(cx);
1178 }
1179 }))
1180 .child(
1181 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1182 div()
1183 .size_full()
1184 .child(TerminalElement::new(
1185 terminal_handle,
1186 terminal_view_handle,
1187 self.workspace.clone(),
1188 self.focus_handle.clone(),
1189 focused,
1190 self.should_show_cursor(focused, cx),
1191 self.can_navigate_to_selected_word,
1192 self.block_below_cursor.clone(),
1193 ))
1194 .when_some(self.render_scrollbar(cx), |div, scrollbar| {
1195 div.child(scrollbar)
1196 }),
1197 )
1198 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1199 deferred(
1200 anchored()
1201 .position(*position)
1202 .anchor(gpui::Corner::TopLeft)
1203 .child(menu.clone()),
1204 )
1205 .with_priority(1)
1206 }))
1207 }
1208}
1209
1210impl Item for TerminalView {
1211 type Event = ItemEvent;
1212
1213 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1214 let terminal = self.terminal().read(cx);
1215 let title = terminal.title(false);
1216 let pid = terminal.pty_info.pid_getter().fallback_pid();
1217
1218 Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
1219 cx.new(|_| TerminalTooltip::new(title.clone(), pid)).into()
1220 })))
1221 }
1222
1223 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1224 let terminal = self.terminal().read(cx);
1225 let title = terminal.title(true);
1226 let rerun_button = |task_id: task::TaskId| {
1227 IconButton::new("rerun-icon", IconName::Rerun)
1228 .icon_size(IconSize::Small)
1229 .size(ButtonSize::Compact)
1230 .icon_color(Color::Default)
1231 .shape(ui::IconButtonShape::Square)
1232 .tooltip(Tooltip::text("Rerun task"))
1233 .on_click(move |_, window, cx| {
1234 window.dispatch_action(
1235 Box::new(zed_actions::Rerun {
1236 task_id: Some(task_id.0.clone()),
1237 allow_concurrent_runs: Some(true),
1238 use_new_terminal: Some(false),
1239 reevaluate_context: false,
1240 }),
1241 cx,
1242 );
1243 })
1244 };
1245
1246 let (icon, icon_color, rerun_button) = match terminal.task() {
1247 Some(terminal_task) => match &terminal_task.status {
1248 TaskStatus::Running => (
1249 IconName::Play,
1250 Color::Disabled,
1251 Some(rerun_button(terminal_task.id.clone())),
1252 ),
1253 TaskStatus::Unknown => (
1254 IconName::Warning,
1255 Color::Warning,
1256 Some(rerun_button(terminal_task.id.clone())),
1257 ),
1258 TaskStatus::Completed { success } => {
1259 let rerun_button = rerun_button(terminal_task.id.clone());
1260 if *success {
1261 (IconName::Check, Color::Success, Some(rerun_button))
1262 } else {
1263 (IconName::XCircle, Color::Error, Some(rerun_button))
1264 }
1265 }
1266 },
1267 None => (IconName::Terminal, Color::Muted, None),
1268 };
1269
1270 h_flex()
1271 .gap_1()
1272 .group("term-tab-icon")
1273 .child(
1274 h_flex()
1275 .group("term-tab-icon")
1276 .child(
1277 div()
1278 .when(rerun_button.is_some(), |this| {
1279 this.hover(|style| style.invisible().w_0())
1280 })
1281 .child(Icon::new(icon).color(icon_color)),
1282 )
1283 .when_some(rerun_button, |this, rerun_button| {
1284 this.child(
1285 div()
1286 .absolute()
1287 .visible_on_hover("term-tab-icon")
1288 .child(rerun_button),
1289 )
1290 }),
1291 )
1292 .child(Label::new(title).color(params.text_color()))
1293 .into_any()
1294 }
1295
1296 fn telemetry_event_text(&self) -> Option<&'static str> {
1297 None
1298 }
1299
1300 fn clone_on_split(
1301 &self,
1302 workspace_id: Option<WorkspaceId>,
1303 window: &mut Window,
1304 cx: &mut Context<Self>,
1305 ) -> Option<Entity<Self>> {
1306 let window_handle = window.window_handle();
1307 let terminal = self
1308 .project
1309 .update(cx, |project, cx| {
1310 let terminal = self.terminal().read(cx);
1311 let working_directory = terminal
1312 .working_directory()
1313 .or_else(|| Some(project.active_project_directory(cx)?.to_path_buf()));
1314 let python_venv_directory = terminal.python_venv_directory.clone();
1315 project.create_terminal_with_venv(
1316 TerminalKind::Shell(working_directory),
1317 python_venv_directory,
1318 window_handle,
1319 cx,
1320 )
1321 })
1322 .ok()?
1323 .log_err()?;
1324
1325 Some(cx.new(|cx| {
1326 TerminalView::new(
1327 terminal,
1328 self.workspace.clone(),
1329 workspace_id,
1330 self.project.clone(),
1331 window,
1332 cx,
1333 )
1334 }))
1335 }
1336
1337 fn is_dirty(&self, cx: &gpui::App) -> bool {
1338 match self.terminal.read(cx).task() {
1339 Some(task) => task.status == TaskStatus::Running,
1340 None => self.has_bell(),
1341 }
1342 }
1343
1344 fn has_conflict(&self, _cx: &App) -> bool {
1345 false
1346 }
1347
1348 fn can_save_as(&self, _cx: &App) -> bool {
1349 false
1350 }
1351
1352 fn is_singleton(&self, _cx: &App) -> bool {
1353 true
1354 }
1355
1356 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1357 Some(Box::new(handle.clone()))
1358 }
1359
1360 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1361 if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1362 ToolbarItemLocation::PrimaryLeft
1363 } else {
1364 ToolbarItemLocation::Hidden
1365 }
1366 }
1367
1368 fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1369 Some(vec![BreadcrumbText {
1370 text: self.terminal().read(cx).breadcrumb_text.clone(),
1371 highlights: None,
1372 font: None,
1373 }])
1374 }
1375
1376 fn added_to_workspace(
1377 &mut self,
1378 workspace: &mut Workspace,
1379 _: &mut Window,
1380 cx: &mut Context<Self>,
1381 ) {
1382 if self.terminal().read(cx).task().is_none() {
1383 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1384 cx.background_spawn(TERMINAL_DB.update_workspace_id(
1385 new_id,
1386 old_id,
1387 cx.entity_id().as_u64(),
1388 ))
1389 .detach();
1390 }
1391 self.workspace_id = workspace.database_id();
1392 }
1393 }
1394
1395 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1396 f(*event)
1397 }
1398}
1399
1400impl SerializableItem for TerminalView {
1401 fn serialized_item_kind() -> &'static str {
1402 "Terminal"
1403 }
1404
1405 fn cleanup(
1406 workspace_id: WorkspaceId,
1407 alive_items: Vec<workspace::ItemId>,
1408 window: &mut Window,
1409 cx: &mut App,
1410 ) -> Task<gpui::Result<()>> {
1411 window.spawn(cx, |_| {
1412 TERMINAL_DB.delete_unloaded_items(workspace_id, alive_items)
1413 })
1414 }
1415
1416 fn serialize(
1417 &mut self,
1418 _workspace: &mut Workspace,
1419 item_id: workspace::ItemId,
1420 _closing: bool,
1421 _: &mut Window,
1422 cx: &mut Context<Self>,
1423 ) -> Option<Task<gpui::Result<()>>> {
1424 let terminal = self.terminal().read(cx);
1425 if terminal.task().is_some() {
1426 return None;
1427 }
1428
1429 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1430 Some(cx.background_spawn(async move {
1431 TERMINAL_DB
1432 .save_working_directory(item_id, workspace_id, cwd)
1433 .await
1434 }))
1435 } else {
1436 None
1437 }
1438 }
1439
1440 fn should_serialize(&self, event: &Self::Event) -> bool {
1441 matches!(event, ItemEvent::UpdateTab)
1442 }
1443
1444 fn deserialize(
1445 project: Entity<Project>,
1446 workspace: WeakEntity<Workspace>,
1447 workspace_id: workspace::WorkspaceId,
1448 item_id: workspace::ItemId,
1449 window: &mut Window,
1450 cx: &mut App,
1451 ) -> Task<anyhow::Result<Entity<Self>>> {
1452 let window_handle = window.window_handle();
1453 window.spawn(cx, |mut cx| async move {
1454 let cwd = cx
1455 .update(|_window, cx| {
1456 let from_db = TERMINAL_DB
1457 .get_working_directory(item_id, workspace_id)
1458 .log_err()
1459 .flatten();
1460 if from_db
1461 .as_ref()
1462 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1463 {
1464 from_db
1465 } else {
1466 workspace
1467 .upgrade()
1468 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1469 }
1470 })
1471 .ok()
1472 .flatten();
1473
1474 let terminal = project
1475 .update(&mut cx, |project, cx| {
1476 project.create_terminal(TerminalKind::Shell(cwd), window_handle, cx)
1477 })?
1478 .await?;
1479 cx.update(|window, cx| {
1480 cx.new(|cx| {
1481 TerminalView::new(
1482 terminal,
1483 workspace,
1484 Some(workspace_id),
1485 project.downgrade(),
1486 window,
1487 cx,
1488 )
1489 })
1490 })
1491 })
1492 }
1493}
1494
1495impl SearchableItem for TerminalView {
1496 type Match = RangeInclusive<Point>;
1497
1498 fn supported_options(&self) -> SearchOptions {
1499 SearchOptions {
1500 case: false,
1501 word: false,
1502 regex: true,
1503 replacement: false,
1504 selection: false,
1505 find_in_results: false,
1506 }
1507 }
1508
1509 /// Clear stored matches
1510 fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1511 self.terminal().update(cx, |term, _| term.matches.clear())
1512 }
1513
1514 /// Store matches returned from find_matches somewhere for rendering
1515 fn update_matches(
1516 &mut self,
1517 matches: &[Self::Match],
1518 _window: &mut Window,
1519 cx: &mut Context<Self>,
1520 ) {
1521 self.terminal()
1522 .update(cx, |term, _| term.matches = matches.to_vec())
1523 }
1524
1525 /// Returns the selection content to pre-load into this search
1526 fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1527 self.terminal()
1528 .read(cx)
1529 .last_content
1530 .selection_text
1531 .clone()
1532 .unwrap_or_default()
1533 }
1534
1535 /// Focus match at given index into the Vec of matches
1536 fn activate_match(
1537 &mut self,
1538 index: usize,
1539 _: &[Self::Match],
1540 _window: &mut Window,
1541 cx: &mut Context<Self>,
1542 ) {
1543 self.terminal()
1544 .update(cx, |term, _| term.activate_match(index));
1545 cx.notify();
1546 }
1547
1548 /// Add selections for all matches given.
1549 fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1550 self.terminal()
1551 .update(cx, |term, _| term.select_matches(matches));
1552 cx.notify();
1553 }
1554
1555 /// Get all of the matches for this query, should be done on the background
1556 fn find_matches(
1557 &mut self,
1558 query: Arc<SearchQuery>,
1559 _: &mut Window,
1560 cx: &mut Context<Self>,
1561 ) -> Task<Vec<Self::Match>> {
1562 let searcher = match &*query {
1563 SearchQuery::Text { .. } => regex_search_for_query(
1564 &(SearchQuery::text(
1565 regex_to_literal(query.as_str()),
1566 query.whole_word(),
1567 query.case_sensitive(),
1568 query.include_ignored(),
1569 query.files_to_include().clone(),
1570 query.files_to_exclude().clone(),
1571 None,
1572 )
1573 .unwrap()),
1574 ),
1575 SearchQuery::Regex { .. } => regex_search_for_query(&query),
1576 };
1577
1578 if let Some(s) = searcher {
1579 self.terminal()
1580 .update(cx, |term, cx| term.find_matches(s, cx))
1581 } else {
1582 Task::ready(vec![])
1583 }
1584 }
1585
1586 /// Reports back to the search toolbar what the active match should be (the selection)
1587 fn active_match_index(
1588 &mut self,
1589 matches: &[Self::Match],
1590 _: &mut Window,
1591 cx: &mut Context<Self>,
1592 ) -> Option<usize> {
1593 // Selection head might have a value if there's a selection that isn't
1594 // associated with a match. Therefore, if there are no matches, we should
1595 // report None, no matter the state of the terminal
1596 let res = if !matches.is_empty() {
1597 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1598 // If selection head is contained in a match. Return that match
1599 if let Some(ix) = matches
1600 .iter()
1601 .enumerate()
1602 .find(|(_, search_match)| {
1603 search_match.contains(&selection_head)
1604 || search_match.start() > &selection_head
1605 })
1606 .map(|(ix, _)| ix)
1607 {
1608 Some(ix)
1609 } else {
1610 // If no selection after selection head, return the last match
1611 Some(matches.len().saturating_sub(1))
1612 }
1613 } else {
1614 // Matches found but no active selection, return the first last one (closest to cursor)
1615 Some(matches.len().saturating_sub(1))
1616 }
1617 } else {
1618 None
1619 };
1620
1621 res
1622 }
1623 fn replace(
1624 &mut self,
1625 _: &Self::Match,
1626 _: &SearchQuery,
1627 _window: &mut Window,
1628 _: &mut Context<Self>,
1629 ) {
1630 // Replacement is not supported in terminal view, so this is a no-op.
1631 }
1632}
1633
1634///Gets the working directory for the given workspace, respecting the user's settings.
1635/// None implies "~" on whichever machine we end up on.
1636pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1637 match &TerminalSettings::get_global(cx).working_directory {
1638 WorkingDirectory::CurrentProjectDirectory => workspace
1639 .project()
1640 .read(cx)
1641 .active_project_directory(cx)
1642 .as_deref()
1643 .map(Path::to_path_buf),
1644 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1645 WorkingDirectory::AlwaysHome => None,
1646 WorkingDirectory::Always { directory } => {
1647 shellexpand::full(&directory) //TODO handle this better
1648 .ok()
1649 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1650 .filter(|dir| dir.is_dir())
1651 }
1652 }
1653}
1654///Gets the first project's home directory, or the home directory
1655fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1656 let worktree = workspace.worktrees(cx).next()?.read(cx);
1657 if !worktree.root_entry()?.is_dir() {
1658 return None;
1659 }
1660 Some(worktree.abs_path().to_path_buf())
1661}
1662
1663#[cfg(test)]
1664mod tests {
1665 use super::*;
1666 use gpui::TestAppContext;
1667 use project::{Entry, Project, ProjectPath, Worktree};
1668 use std::path::Path;
1669 use workspace::AppState;
1670
1671 // Working directory calculation tests
1672
1673 // No Worktrees in project -> home_dir()
1674 #[gpui::test]
1675 async fn no_worktree(cx: &mut TestAppContext) {
1676 let (project, workspace) = init_test(cx).await;
1677 cx.read(|cx| {
1678 let workspace = workspace.read(cx);
1679 let active_entry = project.read(cx).active_entry();
1680
1681 //Make sure environment is as expected
1682 assert!(active_entry.is_none());
1683 assert!(workspace.worktrees(cx).next().is_none());
1684
1685 let res = default_working_directory(workspace, cx);
1686 assert_eq!(res, None);
1687 let res = first_project_directory(workspace, cx);
1688 assert_eq!(res, None);
1689 });
1690 }
1691
1692 // No active entry, but a worktree, worktree is a file -> home_dir()
1693 #[gpui::test]
1694 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1695 let (project, workspace) = init_test(cx).await;
1696
1697 create_file_wt(project.clone(), "/root.txt", cx).await;
1698 cx.read(|cx| {
1699 let workspace = workspace.read(cx);
1700 let active_entry = project.read(cx).active_entry();
1701
1702 //Make sure environment is as expected
1703 assert!(active_entry.is_none());
1704 assert!(workspace.worktrees(cx).next().is_some());
1705
1706 let res = default_working_directory(workspace, cx);
1707 assert_eq!(res, None);
1708 let res = first_project_directory(workspace, cx);
1709 assert_eq!(res, None);
1710 });
1711 }
1712
1713 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1714 #[gpui::test]
1715 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1716 let (project, workspace) = init_test(cx).await;
1717
1718 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1719 cx.update(|cx| {
1720 let workspace = workspace.read(cx);
1721 let active_entry = project.read(cx).active_entry();
1722
1723 assert!(active_entry.is_none());
1724 assert!(workspace.worktrees(cx).next().is_some());
1725
1726 let res = default_working_directory(workspace, cx);
1727 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1728 let res = first_project_directory(workspace, cx);
1729 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1730 });
1731 }
1732
1733 // Active entry with a work tree, worktree is a file -> worktree_folder()
1734 #[gpui::test]
1735 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1736 let (project, workspace) = init_test(cx).await;
1737
1738 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1739 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1740 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1741
1742 cx.update(|cx| {
1743 let workspace = workspace.read(cx);
1744 let active_entry = project.read(cx).active_entry();
1745
1746 assert!(active_entry.is_some());
1747
1748 let res = default_working_directory(workspace, cx);
1749 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1750 let res = first_project_directory(workspace, cx);
1751 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1752 });
1753 }
1754
1755 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1756 #[gpui::test]
1757 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1758 let (project, workspace) = init_test(cx).await;
1759
1760 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1761 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1762 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1763
1764 cx.update(|cx| {
1765 let workspace = workspace.read(cx);
1766 let active_entry = project.read(cx).active_entry();
1767
1768 assert!(active_entry.is_some());
1769
1770 let res = default_working_directory(workspace, cx);
1771 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1772 let res = first_project_directory(workspace, cx);
1773 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1774 });
1775 }
1776
1777 /// Creates a worktree with 1 file: /root.txt
1778 pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
1779 let params = cx.update(AppState::test);
1780 cx.update(|cx| {
1781 terminal::init(cx);
1782 theme::init(theme::LoadThemes::JustBase, cx);
1783 Project::init_settings(cx);
1784 language::init(cx);
1785 });
1786
1787 let project = Project::test(params.fs.clone(), [], cx).await;
1788 let workspace = cx
1789 .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
1790 .root(cx)
1791 .unwrap();
1792
1793 (project, workspace)
1794 }
1795
1796 /// Creates a worktree with 1 folder: /root{suffix}/
1797 async fn create_folder_wt(
1798 project: Entity<Project>,
1799 path: impl AsRef<Path>,
1800 cx: &mut TestAppContext,
1801 ) -> (Entity<Worktree>, Entry) {
1802 create_wt(project, true, path, cx).await
1803 }
1804
1805 /// Creates a worktree with 1 file: /root{suffix}.txt
1806 async fn create_file_wt(
1807 project: Entity<Project>,
1808 path: impl AsRef<Path>,
1809 cx: &mut TestAppContext,
1810 ) -> (Entity<Worktree>, Entry) {
1811 create_wt(project, false, path, cx).await
1812 }
1813
1814 async fn create_wt(
1815 project: Entity<Project>,
1816 is_dir: bool,
1817 path: impl AsRef<Path>,
1818 cx: &mut TestAppContext,
1819 ) -> (Entity<Worktree>, Entry) {
1820 let (wt, _) = project
1821 .update(cx, |project, cx| {
1822 project.find_or_create_worktree(path, true, cx)
1823 })
1824 .await
1825 .unwrap();
1826
1827 let entry = cx
1828 .update(|cx| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1829 .await
1830 .unwrap()
1831 .to_included()
1832 .unwrap();
1833
1834 (wt, entry)
1835 }
1836
1837 pub fn insert_active_entry_for(
1838 wt: Entity<Worktree>,
1839 entry: Entry,
1840 project: Entity<Project>,
1841 cx: &mut TestAppContext,
1842 ) {
1843 cx.update(|cx| {
1844 let p = ProjectPath {
1845 worktree_id: wt.read(cx).id(),
1846 path: entry.path,
1847 };
1848 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1849 });
1850 }
1851
1852 #[test]
1853 fn escapes_only_special_characters() {
1854 assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1855 }
1856
1857 #[test]
1858 fn empty_string_stays_empty() {
1859 assert_eq!(regex_to_literal(""), "".to_string());
1860 }
1861}