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