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