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