terminal_view.rs

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