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