terminal_view.rs

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