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 TerminalSize, 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, 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: TerminalSize,
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",
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().size.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(
370 &mut self,
371 event: &ScrollWheelEvent,
372 origin: gpui::Point<Pixels>,
373 cx: &mut Context<Self>,
374 ) {
375 let terminal_content = self.terminal.read(cx).last_content();
376
377 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
378 let line_height = terminal_content.size.line_height;
379 let y_delta = event.delta.pixel_delta(line_height).y;
380 if y_delta < Pixels::ZERO || self.scroll_top > Pixels::ZERO {
381 self.scroll_top = cmp::max(
382 Pixels::ZERO,
383 cmp::min(self.scroll_top - y_delta, self.max_scroll_top(cx)),
384 );
385 cx.notify();
386 return;
387 }
388 }
389
390 self.terminal
391 .update(cx, |term, _| term.scroll_wheel(event, origin));
392 }
393
394 fn scroll_line_up(&mut self, _: &ScrollLineUp, _: &mut Window, cx: &mut Context<Self>) {
395 let terminal_content = self.terminal.read(cx).last_content();
396 if self.block_below_cursor.is_some()
397 && terminal_content.display_offset == 0
398 && self.scroll_top > Pixels::ZERO
399 {
400 let line_height = terminal_content.size.line_height;
401 self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
402 return;
403 }
404
405 self.terminal.update(cx, |term, _| term.scroll_line_up());
406 cx.notify();
407 }
408
409 fn scroll_line_down(&mut self, _: &ScrollLineDown, _: &mut Window, cx: &mut Context<Self>) {
410 let terminal_content = self.terminal.read(cx).last_content();
411 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
412 let max_scroll_top = self.max_scroll_top(cx);
413 if self.scroll_top < max_scroll_top {
414 let line_height = terminal_content.size.line_height;
415 self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
416 }
417 return;
418 }
419
420 self.terminal.update(cx, |term, _| term.scroll_line_down());
421 cx.notify();
422 }
423
424 fn scroll_page_up(&mut self, _: &ScrollPageUp, _: &mut Window, cx: &mut Context<Self>) {
425 if self.scroll_top == Pixels::ZERO {
426 self.terminal.update(cx, |term, _| term.scroll_page_up());
427 } else {
428 let line_height = self.terminal.read(cx).last_content.size.line_height();
429 let visible_block_lines = (self.scroll_top / line_height) as usize;
430 let viewport_lines = self.terminal.read(cx).viewport_lines();
431 let visible_content_lines = viewport_lines - visible_block_lines;
432
433 if visible_block_lines >= viewport_lines {
434 self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
435 } else {
436 self.scroll_top = px(0.);
437 self.terminal
438 .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
439 }
440 }
441 cx.notify();
442 }
443
444 fn scroll_page_down(&mut self, _: &ScrollPageDown, _: &mut Window, cx: &mut Context<Self>) {
445 self.terminal.update(cx, |term, _| term.scroll_page_down());
446 let terminal = self.terminal.read(cx);
447 if terminal.last_content().display_offset < terminal.viewport_lines() {
448 self.scroll_top = self.max_scroll_top(cx);
449 }
450 cx.notify();
451 }
452
453 fn scroll_to_top(&mut self, _: &ScrollToTop, _: &mut Window, cx: &mut Context<Self>) {
454 self.terminal.update(cx, |term, _| term.scroll_to_top());
455 cx.notify();
456 }
457
458 fn scroll_to_bottom(&mut self, _: &ScrollToBottom, _: &mut Window, cx: &mut Context<Self>) {
459 self.terminal.update(cx, |term, _| term.scroll_to_bottom());
460 if self.block_below_cursor.is_some() {
461 self.scroll_top = self.max_scroll_top(cx);
462 }
463 cx.notify();
464 }
465
466 fn toggle_vi_mode(&mut self, _: &ToggleViMode, _: &mut Window, cx: &mut Context<Self>) {
467 self.terminal.update(cx, |term, _| term.toggle_vi_mode());
468 cx.notify();
469 }
470
471 pub fn should_show_cursor(&self, focused: bool, cx: &mut Context<Self>) -> bool {
472 //Don't blink the cursor when not focused, blinking is disabled, or paused
473 if !focused
474 || self.blinking_paused
475 || self
476 .terminal
477 .read(cx)
478 .last_content
479 .mode
480 .contains(TermMode::ALT_SCREEN)
481 {
482 return true;
483 }
484
485 match TerminalSettings::get_global(cx).blinking {
486 //If the user requested to never blink, don't blink it.
487 TerminalBlink::Off => true,
488 //If the terminal is controlling it, check terminal mode
489 TerminalBlink::TerminalControlled => {
490 !self.blinking_terminal_enabled || self.blink_state
491 }
492 TerminalBlink::On => self.blink_state,
493 }
494 }
495
496 fn blink_cursors(&mut self, epoch: usize, window: &mut Window, cx: &mut Context<Self>) {
497 if epoch == self.blink_epoch && !self.blinking_paused {
498 self.blink_state = !self.blink_state;
499 cx.notify();
500
501 let epoch = self.next_blink_epoch();
502 cx.spawn_in(window, |this, mut cx| async move {
503 Timer::after(CURSOR_BLINK_INTERVAL).await;
504 this.update_in(&mut cx, |this, window, cx| {
505 this.blink_cursors(epoch, window, cx)
506 })
507 .ok();
508 })
509 .detach();
510 }
511 }
512
513 pub fn pause_cursor_blinking(&mut self, window: &mut Window, cx: &mut Context<Self>) {
514 self.blink_state = true;
515 cx.notify();
516
517 let epoch = self.next_blink_epoch();
518 cx.spawn_in(window, |this, mut cx| async move {
519 Timer::after(CURSOR_BLINK_INTERVAL).await;
520 this.update_in(&mut cx, |this, window, cx| {
521 this.resume_cursor_blinking(epoch, window, cx)
522 })
523 .ok();
524 })
525 .detach();
526 }
527
528 pub fn terminal(&self) -> &Entity<Terminal> {
529 &self.terminal
530 }
531
532 pub fn set_block_below_cursor(
533 &mut self,
534 block: BlockProperties,
535 window: &mut Window,
536 cx: &mut Context<Self>,
537 ) {
538 self.block_below_cursor = Some(Rc::new(block));
539 self.scroll_to_bottom(&ScrollToBottom, window, cx);
540 cx.notify();
541 }
542
543 pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
544 self.block_below_cursor = None;
545 self.scroll_top = Pixels::ZERO;
546 cx.notify();
547 }
548
549 fn next_blink_epoch(&mut self) -> usize {
550 self.blink_epoch += 1;
551 self.blink_epoch
552 }
553
554 fn resume_cursor_blinking(
555 &mut self,
556 epoch: usize,
557 window: &mut Window,
558 cx: &mut Context<Self>,
559 ) {
560 if epoch == self.blink_epoch {
561 self.blinking_paused = false;
562 self.blink_cursors(epoch, window, cx);
563 }
564 }
565
566 ///Attempt to paste the clipboard into the terminal
567 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
568 self.terminal.update(cx, |term, _| term.copy());
569 cx.notify();
570 }
571
572 ///Attempt to paste the clipboard into the terminal
573 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
574 if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
575 self.terminal
576 .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
577 }
578 }
579
580 fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
581 self.clear_bell(cx);
582 self.terminal.update(cx, |term, _| {
583 term.input(text.0.to_string());
584 });
585 }
586
587 fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
588 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
589 self.clear_bell(cx);
590 self.terminal.update(cx, |term, cx| {
591 term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
592 });
593 }
594 }
595
596 fn dispatch_context(&self, cx: &App) -> KeyContext {
597 let mut dispatch_context = KeyContext::new_with_defaults();
598 dispatch_context.add("Terminal");
599
600 let mode = self.terminal.read(cx).last_content.mode;
601 dispatch_context.set(
602 "screen",
603 if mode.contains(TermMode::ALT_SCREEN) {
604 "alt"
605 } else {
606 "normal"
607 },
608 );
609
610 if mode.contains(TermMode::APP_CURSOR) {
611 dispatch_context.add("DECCKM");
612 }
613 if mode.contains(TermMode::APP_KEYPAD) {
614 dispatch_context.add("DECPAM");
615 } else {
616 dispatch_context.add("DECPNM");
617 }
618 if mode.contains(TermMode::SHOW_CURSOR) {
619 dispatch_context.add("DECTCEM");
620 }
621 if mode.contains(TermMode::LINE_WRAP) {
622 dispatch_context.add("DECAWM");
623 }
624 if mode.contains(TermMode::ORIGIN) {
625 dispatch_context.add("DECOM");
626 }
627 if mode.contains(TermMode::INSERT) {
628 dispatch_context.add("IRM");
629 }
630 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
631 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
632 dispatch_context.add("LNM");
633 }
634 if mode.contains(TermMode::FOCUS_IN_OUT) {
635 dispatch_context.add("report_focus");
636 }
637 if mode.contains(TermMode::ALTERNATE_SCROLL) {
638 dispatch_context.add("alternate_scroll");
639 }
640 if mode.contains(TermMode::BRACKETED_PASTE) {
641 dispatch_context.add("bracketed_paste");
642 }
643 if mode.intersects(TermMode::MOUSE_MODE) {
644 dispatch_context.add("any_mouse_reporting");
645 }
646 {
647 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
648 "click"
649 } else if mode.contains(TermMode::MOUSE_DRAG) {
650 "drag"
651 } else if mode.contains(TermMode::MOUSE_MOTION) {
652 "motion"
653 } else {
654 "off"
655 };
656 dispatch_context.set("mouse_reporting", mouse_reporting);
657 }
658 {
659 let format = if mode.contains(TermMode::SGR_MOUSE) {
660 "sgr"
661 } else if mode.contains(TermMode::UTF8_MOUSE) {
662 "utf8"
663 } else {
664 "normal"
665 };
666 dispatch_context.set("mouse_format", format);
667 };
668 dispatch_context
669 }
670
671 fn set_terminal(
672 &mut self,
673 terminal: Entity<Terminal>,
674 window: &mut Window,
675 cx: &mut Context<TerminalView>,
676 ) {
677 self._terminal_subscriptions =
678 subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
679 self.terminal = terminal;
680 }
681
682 // Hack: Using editor in terminal causes cyclic dependency i.e. editor -> terminal -> project -> editor.
683 fn map_show_scrollbar_from_editor_to_terminal(
684 show_scrollbar: editor::ShowScrollbar,
685 ) -> terminal_settings::ShowScrollbar {
686 match show_scrollbar {
687 editor::ShowScrollbar::Auto => terminal_settings::ShowScrollbar::Auto,
688 editor::ShowScrollbar::System => terminal_settings::ShowScrollbar::System,
689 editor::ShowScrollbar::Always => terminal_settings::ShowScrollbar::Always,
690 editor::ShowScrollbar::Never => terminal_settings::ShowScrollbar::Never,
691 }
692 }
693
694 fn should_show_scrollbar(cx: &App) -> bool {
695 let show = TerminalSettings::get_global(cx)
696 .scrollbar
697 .show
698 .unwrap_or_else(|| {
699 Self::map_show_scrollbar_from_editor_to_terminal(
700 EditorSettings::get_global(cx).scrollbar.show,
701 )
702 });
703 match show {
704 terminal_settings::ShowScrollbar::Auto => true,
705 terminal_settings::ShowScrollbar::System => true,
706 terminal_settings::ShowScrollbar::Always => true,
707 terminal_settings::ShowScrollbar::Never => false,
708 }
709 }
710
711 fn should_autohide_scrollbar(cx: &App) -> bool {
712 let show = TerminalSettings::get_global(cx)
713 .scrollbar
714 .show
715 .unwrap_or_else(|| {
716 Self::map_show_scrollbar_from_editor_to_terminal(
717 EditorSettings::get_global(cx).scrollbar.show,
718 )
719 });
720 match show {
721 terminal_settings::ShowScrollbar::Auto => true,
722 terminal_settings::ShowScrollbar::System => cx
723 .try_global::<ScrollbarAutoHide>()
724 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
725 terminal_settings::ShowScrollbar::Always => false,
726 terminal_settings::ShowScrollbar::Never => true,
727 }
728 }
729
730 fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
731 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
732 if !Self::should_autohide_scrollbar(cx) {
733 return;
734 }
735 self.hide_scrollbar_task = Some(cx.spawn(|panel, mut cx| async move {
736 cx.background_executor()
737 .timer(SCROLLBAR_SHOW_INTERVAL)
738 .await;
739 panel
740 .update(&mut cx, |panel, cx| {
741 panel.show_scrollbar = false;
742 cx.notify();
743 })
744 .log_err();
745 }))
746 }
747
748 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
749 if !Self::should_show_scrollbar(cx)
750 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
751 {
752 return None;
753 }
754
755 if self.terminal.read(cx).total_lines() == self.terminal.read(cx).viewport_lines() {
756 return None;
757 }
758
759 self.scroll_handle.update(self.terminal.read(cx));
760
761 if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
762 self.terminal.update(cx, |term, _| {
763 let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
764 match delta.cmp(&0) {
765 std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
766 std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
767 std::cmp::Ordering::Equal => {}
768 }
769 });
770 }
771
772 Some(
773 div()
774 .occlude()
775 .id("terminal-view-scroll")
776 .on_mouse_move(cx.listener(|_, _, _window, cx| {
777 cx.notify();
778 cx.stop_propagation()
779 }))
780 .on_hover(|_, _window, cx| {
781 cx.stop_propagation();
782 })
783 .on_any_mouse_down(|_, _window, cx| {
784 cx.stop_propagation();
785 })
786 .on_mouse_up(
787 MouseButton::Left,
788 cx.listener(|terminal_view, _, window, cx| {
789 if !terminal_view.scrollbar_state.is_dragging()
790 && !terminal_view.focus_handle.contains_focused(window, cx)
791 {
792 terminal_view.hide_scrollbar(cx);
793 cx.notify();
794 }
795 cx.stop_propagation();
796 }),
797 )
798 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
799 cx.notify();
800 }))
801 .h_full()
802 .absolute()
803 .right_1()
804 .top_1()
805 .bottom_0()
806 .w(px(12.))
807 .cursor_default()
808 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
809 )
810 }
811}
812
813fn subscribe_for_terminal_events(
814 terminal: &Entity<Terminal>,
815 workspace: WeakEntity<Workspace>,
816 window: &mut Window,
817 cx: &mut Context<TerminalView>,
818) -> Vec<Subscription> {
819 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
820 let terminal_events_subscription = cx.subscribe_in(
821 terminal,
822 window,
823 move |this, _, event, window, cx| match event {
824 Event::Wakeup => {
825 cx.notify();
826 cx.emit(Event::Wakeup);
827 cx.emit(ItemEvent::UpdateTab);
828 cx.emit(SearchEvent::MatchesInvalidated);
829 }
830
831 Event::Bell => {
832 this.has_bell = true;
833 cx.emit(Event::Wakeup);
834 }
835
836 Event::BlinkChanged(blinking) => {
837 if matches!(
838 TerminalSettings::get_global(cx).blinking,
839 TerminalBlink::TerminalControlled
840 ) {
841 this.blinking_terminal_enabled = *blinking;
842 }
843 }
844
845 Event::TitleChanged => {
846 cx.emit(ItemEvent::UpdateTab);
847 }
848
849 Event::NewNavigationTarget(maybe_navigation_target) => {
850 this.can_navigate_to_selected_word = match maybe_navigation_target {
851 Some(MaybeNavigationTarget::Url(_)) => true,
852 Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
853 if let Ok(fs) = workspace.update(cx, |workspace, cx| {
854 workspace.project().read(cx).fs().clone()
855 }) {
856 let valid_files_to_open_task = possible_open_targets(
857 fs,
858 &workspace,
859 &path_like_target.terminal_dir,
860 &path_like_target.maybe_path,
861 cx,
862 );
863 !smol::block_on(valid_files_to_open_task).is_empty()
864 } else {
865 false
866 }
867 }
868 None => false,
869 }
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 OpenVisible::OnlyDirectories,
911 None,
912 window,
913 cx,
914 )
915 })
916 .context("workspace update")?
917 .await;
918
919 let mut has_dirs = false;
920 for ((path, metadata), opened_item) in valid_files_to_open
921 .into_iter()
922 .zip(opened_items.into_iter())
923 {
924 if metadata.is_dir {
925 has_dirs = true;
926 } else if let Some(Ok(opened_item)) = opened_item {
927 if let Some(row) = path.row {
928 let col = path.column.unwrap_or(0);
929 if let Some(active_editor) = opened_item.downcast::<Editor>() {
930 active_editor
931 .downgrade()
932 .update_in(&mut cx, |editor, window, cx| {
933 editor.go_to_singleton_buffer_point(
934 language::Point::new(
935 row.saturating_sub(1),
936 col.saturating_sub(1),
937 ),
938 window,
939 cx,
940 )
941 })
942 .log_err();
943 }
944 }
945 }
946 }
947
948 if has_dirs {
949 task_workspace.update(&mut cx, |workspace, cx| {
950 workspace.project().update(cx, |_, cx| {
951 cx.emit(project::Event::ActivateProjectPanel);
952 })
953 })?;
954 }
955
956 anyhow::Ok(())
957 })
958 .detach_and_log_err(cx)
959 }
960 },
961 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
962 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
963 Event::SelectionsChanged => {
964 window.invalidate_character_coordinates();
965 cx.emit(SearchEvent::ActiveMatchChanged)
966 }
967 },
968 );
969 vec![terminal_subscription, terminal_events_subscription]
970}
971
972fn possible_open_paths_metadata(
973 fs: Arc<dyn Fs>,
974 row: Option<u32>,
975 column: Option<u32>,
976 potential_paths: HashSet<PathBuf>,
977 cx: &mut Context<TerminalView>,
978) -> Task<Vec<(PathWithPosition, Metadata)>> {
979 cx.background_executor().spawn(async move {
980 let mut canonical_paths = HashSet::default();
981 for path in potential_paths {
982 if let Ok(canonical) = fs.canonicalize(&path).await {
983 let sanitized = SanitizedPath::from(canonical);
984 canonical_paths.insert(sanitized.as_path().to_path_buf());
985 } else {
986 canonical_paths.insert(path);
987 }
988 }
989
990 let mut paths_with_metadata = Vec::with_capacity(canonical_paths.len());
991
992 let mut fetch_metadata_tasks = canonical_paths
993 .into_iter()
994 .map(|potential_path| async {
995 let metadata = fs.metadata(&potential_path).await.ok().flatten();
996 (
997 PathWithPosition {
998 path: potential_path,
999 row,
1000 column,
1001 },
1002 metadata,
1003 )
1004 })
1005 .collect::<FuturesUnordered<_>>();
1006
1007 while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
1008 if let Some(metadata) = metadata {
1009 paths_with_metadata.push((path, metadata));
1010 }
1011 }
1012
1013 paths_with_metadata
1014 })
1015}
1016
1017fn possible_open_targets(
1018 fs: Arc<dyn Fs>,
1019 workspace: &WeakEntity<Workspace>,
1020 cwd: &Option<PathBuf>,
1021 maybe_path: &String,
1022
1023 cx: &mut Context<TerminalView>,
1024) -> Task<Vec<(PathWithPosition, Metadata)>> {
1025 let path_position = PathWithPosition::parse_str(maybe_path.as_str());
1026 let row = path_position.row;
1027 let column = path_position.column;
1028 let maybe_path = path_position.path;
1029
1030 let potential_paths = if maybe_path.is_absolute() {
1031 HashSet::from_iter([maybe_path])
1032 } else if maybe_path.starts_with("~") {
1033 maybe_path
1034 .strip_prefix("~")
1035 .ok()
1036 .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
1037 .map_or_else(HashSet::default, |p| HashSet::from_iter([p]))
1038 } else {
1039 let mut potential_cwd_and_workspace_paths = HashSet::default();
1040 if let Some(cwd) = cwd {
1041 let abs_path = Path::join(cwd, &maybe_path);
1042 potential_cwd_and_workspace_paths.insert(abs_path);
1043 }
1044 if let Some(workspace) = workspace.upgrade() {
1045 workspace.update(cx, |workspace, cx| {
1046 for potential_worktree_path in workspace
1047 .worktrees(cx)
1048 .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
1049 {
1050 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
1051 }
1052
1053 for prefix in GIT_DIFF_PATH_PREFIXES {
1054 let prefix_str = &prefix.to_string();
1055 if maybe_path.starts_with(prefix_str) {
1056 let stripped = maybe_path.strip_prefix(prefix_str).unwrap_or(&maybe_path);
1057 for potential_worktree_path in workspace
1058 .worktrees(cx)
1059 .map(|worktree| worktree.read(cx).abs_path().join(&stripped))
1060 {
1061 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
1062 }
1063 }
1064 }
1065 });
1066 }
1067 potential_cwd_and_workspace_paths
1068 };
1069
1070 possible_open_paths_metadata(fs, row, column, potential_paths, cx)
1071}
1072
1073fn regex_to_literal(regex: &str) -> String {
1074 regex
1075 .chars()
1076 .flat_map(|c| {
1077 if REGEX_SPECIAL_CHARS.contains(&c) {
1078 vec!['\\', c]
1079 } else {
1080 vec![c]
1081 }
1082 })
1083 .collect()
1084}
1085
1086pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
1087 let query = query.as_str();
1088 if query == "." {
1089 return None;
1090 }
1091 let searcher = RegexSearch::new(query);
1092 searcher.ok()
1093}
1094
1095impl TerminalView {
1096 fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1097 self.clear_bell(cx);
1098 self.pause_cursor_blinking(window, cx);
1099
1100 self.terminal.update(cx, |term, cx| {
1101 let handled = term.try_keystroke(
1102 &event.keystroke,
1103 TerminalSettings::get_global(cx).option_as_meta,
1104 );
1105 if handled {
1106 cx.stop_propagation();
1107 }
1108 });
1109 }
1110
1111 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1112 self.terminal.update(cx, |terminal, _| {
1113 terminal.set_cursor_shape(self.cursor_shape);
1114 terminal.focus_in();
1115 });
1116 self.blink_cursors(self.blink_epoch, window, cx);
1117 window.invalidate_character_coordinates();
1118 cx.notify();
1119 }
1120
1121 fn focus_out(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1122 self.terminal.update(cx, |terminal, _| {
1123 terminal.focus_out();
1124 terminal.set_cursor_shape(CursorShape::Hollow);
1125 });
1126 self.hide_scrollbar(cx);
1127 cx.notify();
1128 }
1129}
1130
1131impl Render for TerminalView {
1132 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1133 let terminal_handle = self.terminal.clone();
1134 let terminal_view_handle = cx.entity().clone();
1135
1136 let focused = self.focus_handle.is_focused(window);
1137
1138 div()
1139 .id("terminal-view")
1140 .size_full()
1141 .relative()
1142 .track_focus(&self.focus_handle(cx))
1143 .key_context(self.dispatch_context(cx))
1144 .on_action(cx.listener(TerminalView::send_text))
1145 .on_action(cx.listener(TerminalView::send_keystroke))
1146 .on_action(cx.listener(TerminalView::copy))
1147 .on_action(cx.listener(TerminalView::paste))
1148 .on_action(cx.listener(TerminalView::clear))
1149 .on_action(cx.listener(TerminalView::scroll_line_up))
1150 .on_action(cx.listener(TerminalView::scroll_line_down))
1151 .on_action(cx.listener(TerminalView::scroll_page_up))
1152 .on_action(cx.listener(TerminalView::scroll_page_down))
1153 .on_action(cx.listener(TerminalView::scroll_to_top))
1154 .on_action(cx.listener(TerminalView::scroll_to_bottom))
1155 .on_action(cx.listener(TerminalView::toggle_vi_mode))
1156 .on_action(cx.listener(TerminalView::show_character_palette))
1157 .on_action(cx.listener(TerminalView::select_all))
1158 .on_key_down(cx.listener(Self::key_down))
1159 .on_mouse_down(
1160 MouseButton::Right,
1161 cx.listener(|this, event: &MouseDownEvent, window, cx| {
1162 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1163 this.deploy_context_menu(event.position, window, cx);
1164 cx.notify();
1165 }
1166 }),
1167 )
1168 .on_hover(cx.listener(|this, hovered, window, cx| {
1169 if *hovered {
1170 this.show_scrollbar = true;
1171 this.hide_scrollbar_task.take();
1172 cx.notify();
1173 } else if !this.focus_handle.contains_focused(window, cx) {
1174 this.hide_scrollbar(cx);
1175 }
1176 }))
1177 .child(
1178 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1179 div()
1180 .size_full()
1181 .child(TerminalElement::new(
1182 terminal_handle,
1183 terminal_view_handle,
1184 self.workspace.clone(),
1185 self.focus_handle.clone(),
1186 focused,
1187 self.should_show_cursor(focused, cx),
1188 self.can_navigate_to_selected_word,
1189 self.block_below_cursor.clone(),
1190 ))
1191 .when_some(self.render_scrollbar(cx), |div, scrollbar| {
1192 div.child(scrollbar)
1193 }),
1194 )
1195 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1196 deferred(
1197 anchored()
1198 .position(*position)
1199 .anchor(gpui::Corner::TopLeft)
1200 .child(menu.clone()),
1201 )
1202 .with_priority(1)
1203 }))
1204 }
1205}
1206
1207impl Item for TerminalView {
1208 type Event = ItemEvent;
1209
1210 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1211 let terminal = self.terminal().read(cx);
1212 let title = terminal.title(false);
1213 let pid = terminal.pty_info.pid_getter().fallback_pid();
1214
1215 Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
1216 cx.new(|_| TerminalTooltip::new(title.clone(), pid)).into()
1217 })))
1218 }
1219
1220 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1221 let terminal = self.terminal().read(cx);
1222 let title = terminal.title(true);
1223 let rerun_button = |task_id: task::TaskId| {
1224 IconButton::new("rerun-icon", IconName::Rerun)
1225 .icon_size(IconSize::Small)
1226 .size(ButtonSize::Compact)
1227 .icon_color(Color::Default)
1228 .shape(ui::IconButtonShape::Square)
1229 .tooltip(Tooltip::text("Rerun task"))
1230 .on_click(move |_, window, cx| {
1231 window.dispatch_action(
1232 Box::new(zed_actions::Rerun {
1233 task_id: Some(task_id.0.clone()),
1234 allow_concurrent_runs: Some(true),
1235 use_new_terminal: Some(false),
1236 reevaluate_context: false,
1237 }),
1238 cx,
1239 );
1240 })
1241 };
1242
1243 let (icon, icon_color, rerun_button) = match terminal.task() {
1244 Some(terminal_task) => match &terminal_task.status {
1245 TaskStatus::Running => (
1246 IconName::Play,
1247 Color::Disabled,
1248 Some(rerun_button(terminal_task.id.clone())),
1249 ),
1250 TaskStatus::Unknown => (
1251 IconName::Warning,
1252 Color::Warning,
1253 Some(rerun_button(terminal_task.id.clone())),
1254 ),
1255 TaskStatus::Completed { success } => {
1256 let rerun_button = rerun_button(terminal_task.id.clone());
1257 if *success {
1258 (IconName::Check, Color::Success, Some(rerun_button))
1259 } else {
1260 (IconName::XCircle, Color::Error, Some(rerun_button))
1261 }
1262 }
1263 },
1264 None => (IconName::Terminal, Color::Muted, None),
1265 };
1266
1267 h_flex()
1268 .gap_1()
1269 .group("term-tab-icon")
1270 .child(
1271 h_flex()
1272 .group("term-tab-icon")
1273 .child(
1274 div()
1275 .when(rerun_button.is_some(), |this| {
1276 this.hover(|style| style.invisible().w_0())
1277 })
1278 .child(Icon::new(icon).color(icon_color)),
1279 )
1280 .when_some(rerun_button, |this, rerun_button| {
1281 this.child(
1282 div()
1283 .absolute()
1284 .visible_on_hover("term-tab-icon")
1285 .child(rerun_button),
1286 )
1287 }),
1288 )
1289 .child(Label::new(title).color(params.text_color()))
1290 .into_any()
1291 }
1292
1293 fn telemetry_event_text(&self) -> Option<&'static str> {
1294 None
1295 }
1296
1297 fn clone_on_split(
1298 &self,
1299 workspace_id: Option<WorkspaceId>,
1300 window: &mut Window,
1301 cx: &mut Context<Self>,
1302 ) -> Option<Entity<Self>> {
1303 let window_handle = window.window_handle();
1304 let terminal = self
1305 .project
1306 .update(cx, |project, cx| {
1307 let terminal = self.terminal().read(cx);
1308 let working_directory = terminal
1309 .working_directory()
1310 .or_else(|| Some(project.active_project_directory(cx)?.to_path_buf()));
1311 let python_venv_directory = terminal.python_venv_directory.clone();
1312 project.create_terminal_with_venv(
1313 TerminalKind::Shell(working_directory),
1314 python_venv_directory,
1315 window_handle,
1316 cx,
1317 )
1318 })
1319 .ok()?
1320 .log_err()?;
1321
1322 Some(cx.new(|cx| {
1323 TerminalView::new(
1324 terminal,
1325 self.workspace.clone(),
1326 workspace_id,
1327 self.project.clone(),
1328 window,
1329 cx,
1330 )
1331 }))
1332 }
1333
1334 fn is_dirty(&self, cx: &gpui::App) -> bool {
1335 match self.terminal.read(cx).task() {
1336 Some(task) => task.status == TaskStatus::Running,
1337 None => self.has_bell(),
1338 }
1339 }
1340
1341 fn has_conflict(&self, _cx: &App) -> bool {
1342 false
1343 }
1344
1345 fn is_singleton(&self, _cx: &App) -> bool {
1346 true
1347 }
1348
1349 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1350 Some(Box::new(handle.clone()))
1351 }
1352
1353 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1354 if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1355 ToolbarItemLocation::PrimaryLeft
1356 } else {
1357 ToolbarItemLocation::Hidden
1358 }
1359 }
1360
1361 fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1362 Some(vec![BreadcrumbText {
1363 text: self.terminal().read(cx).breadcrumb_text.clone(),
1364 highlights: None,
1365 font: None,
1366 }])
1367 }
1368
1369 fn added_to_workspace(
1370 &mut self,
1371 workspace: &mut Workspace,
1372 _: &mut Window,
1373 cx: &mut Context<Self>,
1374 ) {
1375 if self.terminal().read(cx).task().is_none() {
1376 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1377 cx.background_executor()
1378 .spawn(TERMINAL_DB.update_workspace_id(new_id, old_id, cx.entity_id().as_u64()))
1379 .detach();
1380 }
1381 self.workspace_id = workspace.database_id();
1382 }
1383 }
1384
1385 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1386 f(*event)
1387 }
1388}
1389
1390impl SerializableItem for TerminalView {
1391 fn serialized_item_kind() -> &'static str {
1392 "Terminal"
1393 }
1394
1395 fn cleanup(
1396 workspace_id: WorkspaceId,
1397 alive_items: Vec<workspace::ItemId>,
1398 window: &mut Window,
1399 cx: &mut App,
1400 ) -> Task<gpui::Result<()>> {
1401 window.spawn(cx, |_| {
1402 TERMINAL_DB.delete_unloaded_items(workspace_id, alive_items)
1403 })
1404 }
1405
1406 fn serialize(
1407 &mut self,
1408 _workspace: &mut Workspace,
1409 item_id: workspace::ItemId,
1410 _closing: bool,
1411 _: &mut Window,
1412 cx: &mut Context<Self>,
1413 ) -> Option<Task<gpui::Result<()>>> {
1414 let terminal = self.terminal().read(cx);
1415 if terminal.task().is_some() {
1416 return None;
1417 }
1418
1419 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1420 Some(cx.background_executor().spawn(async move {
1421 TERMINAL_DB
1422 .save_working_directory(item_id, workspace_id, cwd)
1423 .await
1424 }))
1425 } else {
1426 None
1427 }
1428 }
1429
1430 fn should_serialize(&self, event: &Self::Event) -> bool {
1431 matches!(event, ItemEvent::UpdateTab)
1432 }
1433
1434 fn deserialize(
1435 project: Entity<Project>,
1436 workspace: WeakEntity<Workspace>,
1437 workspace_id: workspace::WorkspaceId,
1438 item_id: workspace::ItemId,
1439 window: &mut Window,
1440 cx: &mut App,
1441 ) -> Task<anyhow::Result<Entity<Self>>> {
1442 let window_handle = window.window_handle();
1443 window.spawn(cx, |mut cx| async move {
1444 let cwd = cx
1445 .update(|_window, cx| {
1446 let from_db = TERMINAL_DB
1447 .get_working_directory(item_id, workspace_id)
1448 .log_err()
1449 .flatten();
1450 if from_db
1451 .as_ref()
1452 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1453 {
1454 from_db
1455 } else {
1456 workspace
1457 .upgrade()
1458 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1459 }
1460 })
1461 .ok()
1462 .flatten();
1463
1464 let terminal = project
1465 .update(&mut cx, |project, cx| {
1466 project.create_terminal(TerminalKind::Shell(cwd), window_handle, cx)
1467 })?
1468 .await?;
1469 cx.update(|window, cx| {
1470 cx.new(|cx| {
1471 TerminalView::new(
1472 terminal,
1473 workspace,
1474 Some(workspace_id),
1475 project.downgrade(),
1476 window,
1477 cx,
1478 )
1479 })
1480 })
1481 })
1482 }
1483}
1484
1485impl SearchableItem for TerminalView {
1486 type Match = RangeInclusive<Point>;
1487
1488 fn supported_options(&self) -> SearchOptions {
1489 SearchOptions {
1490 case: false,
1491 word: false,
1492 regex: true,
1493 replacement: false,
1494 selection: false,
1495 find_in_results: false,
1496 }
1497 }
1498
1499 /// Clear stored matches
1500 fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1501 self.terminal().update(cx, |term, _| term.matches.clear())
1502 }
1503
1504 /// Store matches returned from find_matches somewhere for rendering
1505 fn update_matches(
1506 &mut self,
1507 matches: &[Self::Match],
1508 _window: &mut Window,
1509 cx: &mut Context<Self>,
1510 ) {
1511 self.terminal()
1512 .update(cx, |term, _| term.matches = matches.to_vec())
1513 }
1514
1515 /// Returns the selection content to pre-load into this search
1516 fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1517 self.terminal()
1518 .read(cx)
1519 .last_content
1520 .selection_text
1521 .clone()
1522 .unwrap_or_default()
1523 }
1524
1525 /// Focus match at given index into the Vec of matches
1526 fn activate_match(
1527 &mut self,
1528 index: usize,
1529 _: &[Self::Match],
1530 _window: &mut Window,
1531 cx: &mut Context<Self>,
1532 ) {
1533 self.terminal()
1534 .update(cx, |term, _| term.activate_match(index));
1535 cx.notify();
1536 }
1537
1538 /// Add selections for all matches given.
1539 fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1540 self.terminal()
1541 .update(cx, |term, _| term.select_matches(matches));
1542 cx.notify();
1543 }
1544
1545 /// Get all of the matches for this query, should be done on the background
1546 fn find_matches(
1547 &mut self,
1548 query: Arc<SearchQuery>,
1549 _: &mut Window,
1550 cx: &mut Context<Self>,
1551 ) -> Task<Vec<Self::Match>> {
1552 let searcher = match &*query {
1553 SearchQuery::Text { .. } => regex_search_for_query(
1554 &(SearchQuery::text(
1555 regex_to_literal(query.as_str()),
1556 query.whole_word(),
1557 query.case_sensitive(),
1558 query.include_ignored(),
1559 query.files_to_include().clone(),
1560 query.files_to_exclude().clone(),
1561 None,
1562 )
1563 .unwrap()),
1564 ),
1565 SearchQuery::Regex { .. } => regex_search_for_query(&query),
1566 };
1567
1568 if let Some(s) = searcher {
1569 self.terminal()
1570 .update(cx, |term, cx| term.find_matches(s, cx))
1571 } else {
1572 Task::ready(vec![])
1573 }
1574 }
1575
1576 /// Reports back to the search toolbar what the active match should be (the selection)
1577 fn active_match_index(
1578 &mut self,
1579 matches: &[Self::Match],
1580 _: &mut Window,
1581 cx: &mut Context<Self>,
1582 ) -> Option<usize> {
1583 // Selection head might have a value if there's a selection that isn't
1584 // associated with a match. Therefore, if there are no matches, we should
1585 // report None, no matter the state of the terminal
1586 let res = if !matches.is_empty() {
1587 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1588 // If selection head is contained in a match. Return that match
1589 if let Some(ix) = matches
1590 .iter()
1591 .enumerate()
1592 .find(|(_, search_match)| {
1593 search_match.contains(&selection_head)
1594 || search_match.start() > &selection_head
1595 })
1596 .map(|(ix, _)| ix)
1597 {
1598 Some(ix)
1599 } else {
1600 // If no selection after selection head, return the last match
1601 Some(matches.len().saturating_sub(1))
1602 }
1603 } else {
1604 // Matches found but no active selection, return the first last one (closest to cursor)
1605 Some(matches.len().saturating_sub(1))
1606 }
1607 } else {
1608 None
1609 };
1610
1611 res
1612 }
1613 fn replace(
1614 &mut self,
1615 _: &Self::Match,
1616 _: &SearchQuery,
1617 _window: &mut Window,
1618 _: &mut Context<Self>,
1619 ) {
1620 // Replacement is not supported in terminal view, so this is a no-op.
1621 }
1622}
1623
1624///Gets the working directory for the given workspace, respecting the user's settings.
1625/// None implies "~" on whichever machine we end up on.
1626pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1627 match &TerminalSettings::get_global(cx).working_directory {
1628 WorkingDirectory::CurrentProjectDirectory => workspace
1629 .project()
1630 .read(cx)
1631 .active_project_directory(cx)
1632 .as_deref()
1633 .map(Path::to_path_buf),
1634 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1635 WorkingDirectory::AlwaysHome => None,
1636 WorkingDirectory::Always { directory } => {
1637 shellexpand::full(&directory) //TODO handle this better
1638 .ok()
1639 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1640 .filter(|dir| dir.is_dir())
1641 }
1642 }
1643}
1644///Gets the first project's home directory, or the home directory
1645fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1646 let worktree = workspace.worktrees(cx).next()?.read(cx);
1647 if !worktree.root_entry()?.is_dir() {
1648 return None;
1649 }
1650 Some(worktree.abs_path().to_path_buf())
1651}
1652
1653#[cfg(test)]
1654mod tests {
1655 use super::*;
1656 use gpui::TestAppContext;
1657 use project::{Entry, Project, ProjectPath, Worktree};
1658 use std::path::Path;
1659 use workspace::AppState;
1660
1661 // Working directory calculation tests
1662
1663 // No Worktrees in project -> home_dir()
1664 #[gpui::test]
1665 async fn no_worktree(cx: &mut TestAppContext) {
1666 let (project, workspace) = init_test(cx).await;
1667 cx.read(|cx| {
1668 let workspace = workspace.read(cx);
1669 let active_entry = project.read(cx).active_entry();
1670
1671 //Make sure environment is as expected
1672 assert!(active_entry.is_none());
1673 assert!(workspace.worktrees(cx).next().is_none());
1674
1675 let res = default_working_directory(workspace, cx);
1676 assert_eq!(res, None);
1677 let res = first_project_directory(workspace, cx);
1678 assert_eq!(res, None);
1679 });
1680 }
1681
1682 // No active entry, but a worktree, worktree is a file -> home_dir()
1683 #[gpui::test]
1684 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1685 let (project, workspace) = init_test(cx).await;
1686
1687 create_file_wt(project.clone(), "/root.txt", cx).await;
1688 cx.read(|cx| {
1689 let workspace = workspace.read(cx);
1690 let active_entry = project.read(cx).active_entry();
1691
1692 //Make sure environment is as expected
1693 assert!(active_entry.is_none());
1694 assert!(workspace.worktrees(cx).next().is_some());
1695
1696 let res = default_working_directory(workspace, cx);
1697 assert_eq!(res, None);
1698 let res = first_project_directory(workspace, cx);
1699 assert_eq!(res, None);
1700 });
1701 }
1702
1703 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1704 #[gpui::test]
1705 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1706 let (project, workspace) = init_test(cx).await;
1707
1708 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1709 cx.update(|cx| {
1710 let workspace = workspace.read(cx);
1711 let active_entry = project.read(cx).active_entry();
1712
1713 assert!(active_entry.is_none());
1714 assert!(workspace.worktrees(cx).next().is_some());
1715
1716 let res = default_working_directory(workspace, cx);
1717 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1718 let res = first_project_directory(workspace, cx);
1719 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1720 });
1721 }
1722
1723 // Active entry with a work tree, worktree is a file -> worktree_folder()
1724 #[gpui::test]
1725 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1726 let (project, workspace) = init_test(cx).await;
1727
1728 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1729 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1730 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1731
1732 cx.update(|cx| {
1733 let workspace = workspace.read(cx);
1734 let active_entry = project.read(cx).active_entry();
1735
1736 assert!(active_entry.is_some());
1737
1738 let res = default_working_directory(workspace, cx);
1739 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1740 let res = first_project_directory(workspace, cx);
1741 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1742 });
1743 }
1744
1745 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1746 #[gpui::test]
1747 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1748 let (project, workspace) = init_test(cx).await;
1749
1750 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1751 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1752 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1753
1754 cx.update(|cx| {
1755 let workspace = workspace.read(cx);
1756 let active_entry = project.read(cx).active_entry();
1757
1758 assert!(active_entry.is_some());
1759
1760 let res = default_working_directory(workspace, cx);
1761 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1762 let res = first_project_directory(workspace, cx);
1763 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1764 });
1765 }
1766
1767 /// Creates a worktree with 1 file: /root.txt
1768 pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
1769 let params = cx.update(AppState::test);
1770 cx.update(|cx| {
1771 terminal::init(cx);
1772 theme::init(theme::LoadThemes::JustBase, cx);
1773 Project::init_settings(cx);
1774 language::init(cx);
1775 });
1776
1777 let project = Project::test(params.fs.clone(), [], cx).await;
1778 let workspace = cx
1779 .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
1780 .root(cx)
1781 .unwrap();
1782
1783 (project, workspace)
1784 }
1785
1786 /// Creates a worktree with 1 folder: /root{suffix}/
1787 async fn create_folder_wt(
1788 project: Entity<Project>,
1789 path: impl AsRef<Path>,
1790 cx: &mut TestAppContext,
1791 ) -> (Entity<Worktree>, Entry) {
1792 create_wt(project, true, path, cx).await
1793 }
1794
1795 /// Creates a worktree with 1 file: /root{suffix}.txt
1796 async fn create_file_wt(
1797 project: Entity<Project>,
1798 path: impl AsRef<Path>,
1799 cx: &mut TestAppContext,
1800 ) -> (Entity<Worktree>, Entry) {
1801 create_wt(project, false, path, cx).await
1802 }
1803
1804 async fn create_wt(
1805 project: Entity<Project>,
1806 is_dir: bool,
1807 path: impl AsRef<Path>,
1808 cx: &mut TestAppContext,
1809 ) -> (Entity<Worktree>, Entry) {
1810 let (wt, _) = project
1811 .update(cx, |project, cx| {
1812 project.find_or_create_worktree(path, true, cx)
1813 })
1814 .await
1815 .unwrap();
1816
1817 let entry = cx
1818 .update(|cx| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1819 .await
1820 .unwrap()
1821 .to_included()
1822 .unwrap();
1823
1824 (wt, entry)
1825 }
1826
1827 pub fn insert_active_entry_for(
1828 wt: Entity<Worktree>,
1829 entry: Entry,
1830 project: Entity<Project>,
1831 cx: &mut TestAppContext,
1832 ) {
1833 cx.update(|cx| {
1834 let p = ProjectPath {
1835 worktree_id: wt.read(cx).id(),
1836 path: entry.path,
1837 };
1838 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1839 });
1840 }
1841
1842 #[test]
1843 fn escapes_only_special_characters() {
1844 assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1845 }
1846
1847 #[test]
1848 fn empty_string_stays_empty() {
1849 assert_eq!(regex_to_literal(""), "".to_string());
1850 }
1851}