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            .occlude()
1098            .id("terminal-view")
1099            .size_full()
1100            .relative()
1101            .track_focus(&self.focus_handle(cx))
1102            .key_context(self.dispatch_context(cx))
1103            .on_action(cx.listener(TerminalView::send_text))
1104            .on_action(cx.listener(TerminalView::send_keystroke))
1105            .on_action(cx.listener(TerminalView::copy))
1106            .on_action(cx.listener(TerminalView::paste))
1107            .on_action(cx.listener(TerminalView::clear))
1108            .on_action(cx.listener(TerminalView::scroll_line_up))
1109            .on_action(cx.listener(TerminalView::scroll_line_down))
1110            .on_action(cx.listener(TerminalView::scroll_page_up))
1111            .on_action(cx.listener(TerminalView::scroll_page_down))
1112            .on_action(cx.listener(TerminalView::scroll_to_top))
1113            .on_action(cx.listener(TerminalView::scroll_to_bottom))
1114            .on_action(cx.listener(TerminalView::toggle_vi_mode))
1115            .on_action(cx.listener(TerminalView::show_character_palette))
1116            .on_action(cx.listener(TerminalView::select_all))
1117            .on_key_down(cx.listener(Self::key_down))
1118            .on_mouse_down(
1119                MouseButton::Right,
1120                cx.listener(|this, event: &MouseDownEvent, cx| {
1121                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1122                        this.deploy_context_menu(event.position, cx);
1123                        cx.notify();
1124                    }
1125                }),
1126            )
1127            .on_hover(cx.listener(|this, hovered, cx| {
1128                if *hovered {
1129                    this.show_scrollbar = true;
1130                    this.hide_scrollbar_task.take();
1131                    cx.notify();
1132                } else if !this.focus_handle.contains_focused(cx) {
1133                    this.hide_scrollbar(cx);
1134                }
1135            }))
1136            .child(
1137                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1138                div()
1139                    .size_full()
1140                    .child(TerminalElement::new(
1141                        terminal_handle,
1142                        terminal_view_handle,
1143                        self.workspace.clone(),
1144                        self.focus_handle.clone(),
1145                        focused,
1146                        self.should_show_cursor(focused, cx),
1147                        self.can_navigate_to_selected_word,
1148                        self.block_below_cursor.clone(),
1149                    ))
1150                    .when_some(self.render_scrollbar(cx), |div, scrollbar| {
1151                        div.child(scrollbar)
1152                    }),
1153            )
1154            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1155                deferred(
1156                    anchored()
1157                        .position(*position)
1158                        .anchor(gpui::Corner::TopLeft)
1159                        .child(menu.clone()),
1160                )
1161                .with_priority(1)
1162            }))
1163    }
1164}
1165
1166impl Item for TerminalView {
1167    type Event = ItemEvent;
1168
1169    fn tab_tooltip_content(&self, cx: &AppContext) -> Option<TabTooltipContent> {
1170        let terminal = self.terminal().read(cx);
1171        let title = terminal.title(false);
1172        let pid = terminal.pty_info.pid_getter().fallback_pid();
1173
1174        Some(TabTooltipContent::Custom(Box::new(
1175            move |cx: &mut WindowContext| {
1176                cx.new_view(|_| TerminalTooltip::new(title.clone(), pid))
1177                    .into()
1178            },
1179        )))
1180    }
1181
1182    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
1183        let terminal = self.terminal().read(cx);
1184        let title = terminal.title(true);
1185        let rerun_button = |task_id: task::TaskId| {
1186            IconButton::new("rerun-icon", IconName::Rerun)
1187                .icon_size(IconSize::Small)
1188                .size(ButtonSize::Compact)
1189                .icon_color(Color::Default)
1190                .shape(ui::IconButtonShape::Square)
1191                .tooltip(|cx| Tooltip::text("Rerun task", cx))
1192                .on_click(move |_, cx| {
1193                    cx.dispatch_action(Box::new(zed_actions::Rerun {
1194                        task_id: Some(task_id.0.clone()),
1195                        allow_concurrent_runs: Some(true),
1196                        use_new_terminal: Some(false),
1197                        reevaluate_context: false,
1198                    }));
1199                })
1200        };
1201
1202        let (icon, icon_color, rerun_button) = match terminal.task() {
1203            Some(terminal_task) => match &terminal_task.status {
1204                TaskStatus::Running => (
1205                    IconName::Play,
1206                    Color::Disabled,
1207                    Some(rerun_button(terminal_task.id.clone())),
1208                ),
1209                TaskStatus::Unknown => (
1210                    IconName::Warning,
1211                    Color::Warning,
1212                    Some(rerun_button(terminal_task.id.clone())),
1213                ),
1214                TaskStatus::Completed { success } => {
1215                    let rerun_button = rerun_button(terminal_task.id.clone());
1216                    if *success {
1217                        (IconName::Check, Color::Success, Some(rerun_button))
1218                    } else {
1219                        (IconName::XCircle, Color::Error, Some(rerun_button))
1220                    }
1221                }
1222            },
1223            None => (IconName::Terminal, Color::Muted, None),
1224        };
1225
1226        h_flex()
1227            .gap_1()
1228            .group("term-tab-icon")
1229            .child(
1230                h_flex()
1231                    .group("term-tab-icon")
1232                    .child(
1233                        div()
1234                            .when(rerun_button.is_some(), |this| {
1235                                this.hover(|style| style.invisible().w_0())
1236                            })
1237                            .child(Icon::new(icon).color(icon_color)),
1238                    )
1239                    .when_some(rerun_button, |this, rerun_button| {
1240                        this.child(
1241                            div()
1242                                .absolute()
1243                                .visible_on_hover("term-tab-icon")
1244                                .child(rerun_button),
1245                        )
1246                    }),
1247            )
1248            .child(Label::new(title).color(params.text_color()))
1249            .into_any()
1250    }
1251
1252    fn telemetry_event_text(&self) -> Option<&'static str> {
1253        None
1254    }
1255
1256    fn clone_on_split(
1257        &self,
1258        workspace_id: Option<WorkspaceId>,
1259        cx: &mut ViewContext<Self>,
1260    ) -> Option<View<Self>> {
1261        let window = cx.window_handle();
1262        let terminal = self
1263            .project
1264            .update(cx, |project, cx| {
1265                let terminal = self.terminal().read(cx);
1266                let working_directory = terminal
1267                    .working_directory()
1268                    .or_else(|| Some(project.active_project_directory(cx)?.to_path_buf()));
1269                let python_venv_directory = terminal.python_venv_directory.clone();
1270                project.create_terminal_with_venv(
1271                    TerminalKind::Shell(working_directory),
1272                    python_venv_directory,
1273                    window,
1274                    cx,
1275                )
1276            })
1277            .ok()?
1278            .log_err()?;
1279
1280        Some(cx.new_view(|cx| {
1281            TerminalView::new(
1282                terminal,
1283                self.workspace.clone(),
1284                workspace_id,
1285                self.project.clone(),
1286                cx,
1287            )
1288        }))
1289    }
1290
1291    fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
1292        match self.terminal.read(cx).task() {
1293            Some(task) => task.status == TaskStatus::Running,
1294            None => self.has_bell(),
1295        }
1296    }
1297
1298    fn has_conflict(&self, _cx: &AppContext) -> bool {
1299        false
1300    }
1301
1302    fn is_singleton(&self, _cx: &AppContext) -> bool {
1303        true
1304    }
1305
1306    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1307        Some(Box::new(handle.clone()))
1308    }
1309
1310    fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
1311        if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1312            ToolbarItemLocation::PrimaryLeft
1313        } else {
1314            ToolbarItemLocation::Hidden
1315        }
1316    }
1317
1318    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
1319        Some(vec![BreadcrumbText {
1320            text: self.terminal().read(cx).breadcrumb_text.clone(),
1321            highlights: None,
1322            font: None,
1323        }])
1324    }
1325
1326    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
1327        if self.terminal().read(cx).task().is_none() {
1328            if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1329                cx.background_executor()
1330                    .spawn(TERMINAL_DB.update_workspace_id(new_id, old_id, cx.entity_id().as_u64()))
1331                    .detach();
1332            }
1333            self.workspace_id = workspace.database_id();
1334        }
1335    }
1336
1337    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1338        f(*event)
1339    }
1340}
1341
1342impl SerializableItem for TerminalView {
1343    fn serialized_item_kind() -> &'static str {
1344        "Terminal"
1345    }
1346
1347    fn cleanup(
1348        workspace_id: WorkspaceId,
1349        alive_items: Vec<workspace::ItemId>,
1350        cx: &mut WindowContext,
1351    ) -> Task<gpui::Result<()>> {
1352        cx.spawn(|_| TERMINAL_DB.delete_unloaded_items(workspace_id, alive_items))
1353    }
1354
1355    fn serialize(
1356        &mut self,
1357        _workspace: &mut Workspace,
1358        item_id: workspace::ItemId,
1359        _closing: bool,
1360        cx: &mut ViewContext<Self>,
1361    ) -> Option<Task<gpui::Result<()>>> {
1362        let terminal = self.terminal().read(cx);
1363        if terminal.task().is_some() {
1364            return None;
1365        }
1366
1367        if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1368            Some(cx.background_executor().spawn(async move {
1369                TERMINAL_DB
1370                    .save_working_directory(item_id, workspace_id, cwd)
1371                    .await
1372            }))
1373        } else {
1374            None
1375        }
1376    }
1377
1378    fn should_serialize(&self, event: &Self::Event) -> bool {
1379        matches!(event, ItemEvent::UpdateTab)
1380    }
1381
1382    fn deserialize(
1383        project: Model<Project>,
1384        workspace: WeakView<Workspace>,
1385        workspace_id: workspace::WorkspaceId,
1386        item_id: workspace::ItemId,
1387        cx: &mut WindowContext,
1388    ) -> Task<anyhow::Result<View<Self>>> {
1389        let window = cx.window_handle();
1390        cx.spawn(|mut cx| async move {
1391            let cwd = cx
1392                .update(|cx| {
1393                    let from_db = TERMINAL_DB
1394                        .get_working_directory(item_id, workspace_id)
1395                        .log_err()
1396                        .flatten();
1397                    if from_db
1398                        .as_ref()
1399                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1400                    {
1401                        from_db
1402                    } else {
1403                        workspace
1404                            .upgrade()
1405                            .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1406                    }
1407                })
1408                .ok()
1409                .flatten();
1410
1411            let terminal = project
1412                .update(&mut cx, |project, cx| {
1413                    project.create_terminal(TerminalKind::Shell(cwd), window, cx)
1414                })?
1415                .await?;
1416            cx.update(|cx| {
1417                cx.new_view(|cx| {
1418                    TerminalView::new(
1419                        terminal,
1420                        workspace,
1421                        Some(workspace_id),
1422                        project.downgrade(),
1423                        cx,
1424                    )
1425                })
1426            })
1427        })
1428    }
1429}
1430
1431impl SearchableItem for TerminalView {
1432    type Match = RangeInclusive<Point>;
1433
1434    fn supported_options() -> SearchOptions {
1435        SearchOptions {
1436            case: false,
1437            word: false,
1438            regex: true,
1439            replacement: false,
1440            selection: false,
1441        }
1442    }
1443
1444    /// Clear stored matches
1445    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1446        self.terminal().update(cx, |term, _| term.matches.clear())
1447    }
1448
1449    /// Store matches returned from find_matches somewhere for rendering
1450    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1451        self.terminal()
1452            .update(cx, |term, _| term.matches = matches.to_vec())
1453    }
1454
1455    /// Returns the selection content to pre-load into this search
1456    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1457        self.terminal()
1458            .read(cx)
1459            .last_content
1460            .selection_text
1461            .clone()
1462            .unwrap_or_default()
1463    }
1464
1465    /// Focus match at given index into the Vec of matches
1466    fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
1467        self.terminal()
1468            .update(cx, |term, _| term.activate_match(index));
1469        cx.notify();
1470    }
1471
1472    /// Add selections for all matches given.
1473    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1474        self.terminal()
1475            .update(cx, |term, _| term.select_matches(matches));
1476        cx.notify();
1477    }
1478
1479    /// Get all of the matches for this query, should be done on the background
1480    fn find_matches(
1481        &mut self,
1482        query: Arc<SearchQuery>,
1483        cx: &mut ViewContext<Self>,
1484    ) -> Task<Vec<Self::Match>> {
1485        let searcher = match &*query {
1486            SearchQuery::Text { .. } => regex_search_for_query(
1487                &(SearchQuery::text(
1488                    regex_to_literal(query.as_str()),
1489                    query.whole_word(),
1490                    query.case_sensitive(),
1491                    query.include_ignored(),
1492                    query.files_to_include().clone(),
1493                    query.files_to_exclude().clone(),
1494                    None,
1495                )
1496                .unwrap()),
1497            ),
1498            SearchQuery::Regex { .. } => regex_search_for_query(&query),
1499        };
1500
1501        if let Some(s) = searcher {
1502            self.terminal()
1503                .update(cx, |term, cx| term.find_matches(s, cx))
1504        } else {
1505            Task::ready(vec![])
1506        }
1507    }
1508
1509    /// Reports back to the search toolbar what the active match should be (the selection)
1510    fn active_match_index(
1511        &mut self,
1512        matches: &[Self::Match],
1513        cx: &mut ViewContext<Self>,
1514    ) -> Option<usize> {
1515        // Selection head might have a value if there's a selection that isn't
1516        // associated with a match. Therefore, if there are no matches, we should
1517        // report None, no matter the state of the terminal
1518        let res = if !matches.is_empty() {
1519            if let Some(selection_head) = self.terminal().read(cx).selection_head {
1520                // If selection head is contained in a match. Return that match
1521                if let Some(ix) = matches
1522                    .iter()
1523                    .enumerate()
1524                    .find(|(_, search_match)| {
1525                        search_match.contains(&selection_head)
1526                            || search_match.start() > &selection_head
1527                    })
1528                    .map(|(ix, _)| ix)
1529                {
1530                    Some(ix)
1531                } else {
1532                    // If no selection after selection head, return the last match
1533                    Some(matches.len().saturating_sub(1))
1534                }
1535            } else {
1536                // Matches found but no active selection, return the first last one (closest to cursor)
1537                Some(matches.len().saturating_sub(1))
1538            }
1539        } else {
1540            None
1541        };
1542
1543        res
1544    }
1545    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1546        // Replacement is not supported in terminal view, so this is a no-op.
1547    }
1548}
1549
1550///Gets the working directory for the given workspace, respecting the user's settings.
1551/// None implies "~" on whichever machine we end up on.
1552pub(crate) fn default_working_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1553    match &TerminalSettings::get_global(cx).working_directory {
1554        WorkingDirectory::CurrentProjectDirectory => workspace
1555            .project()
1556            .read(cx)
1557            .active_project_directory(cx)
1558            .as_deref()
1559            .map(Path::to_path_buf),
1560        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1561        WorkingDirectory::AlwaysHome => None,
1562        WorkingDirectory::Always { directory } => {
1563            shellexpand::full(&directory) //TODO handle this better
1564                .ok()
1565                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1566                .filter(|dir| dir.is_dir())
1567        }
1568    }
1569}
1570///Gets the first project's home directory, or the home directory
1571fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1572    let worktree = workspace.worktrees(cx).next()?.read(cx);
1573    if !worktree.root_entry()?.is_dir() {
1574        return None;
1575    }
1576    Some(worktree.abs_path().to_path_buf())
1577}
1578
1579#[cfg(test)]
1580mod tests {
1581    use super::*;
1582    use gpui::TestAppContext;
1583    use project::{Entry, Project, ProjectPath, Worktree};
1584    use std::path::Path;
1585    use workspace::AppState;
1586
1587    // Working directory calculation tests
1588
1589    // No Worktrees in project -> home_dir()
1590    #[gpui::test]
1591    async fn no_worktree(cx: &mut TestAppContext) {
1592        let (project, workspace) = init_test(cx).await;
1593        cx.read(|cx| {
1594            let workspace = workspace.read(cx);
1595            let active_entry = project.read(cx).active_entry();
1596
1597            //Make sure environment is as expected
1598            assert!(active_entry.is_none());
1599            assert!(workspace.worktrees(cx).next().is_none());
1600
1601            let res = default_working_directory(workspace, cx);
1602            assert_eq!(res, None);
1603            let res = first_project_directory(workspace, cx);
1604            assert_eq!(res, None);
1605        });
1606    }
1607
1608    // No active entry, but a worktree, worktree is a file -> home_dir()
1609    #[gpui::test]
1610    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1611        let (project, workspace) = init_test(cx).await;
1612
1613        create_file_wt(project.clone(), "/root.txt", cx).await;
1614        cx.read(|cx| {
1615            let workspace = workspace.read(cx);
1616            let active_entry = project.read(cx).active_entry();
1617
1618            //Make sure environment is as expected
1619            assert!(active_entry.is_none());
1620            assert!(workspace.worktrees(cx).next().is_some());
1621
1622            let res = default_working_directory(workspace, cx);
1623            assert_eq!(res, None);
1624            let res = first_project_directory(workspace, cx);
1625            assert_eq!(res, None);
1626        });
1627    }
1628
1629    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1630    #[gpui::test]
1631    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1632        let (project, workspace) = init_test(cx).await;
1633
1634        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1635        cx.update(|cx| {
1636            let workspace = workspace.read(cx);
1637            let active_entry = project.read(cx).active_entry();
1638
1639            assert!(active_entry.is_none());
1640            assert!(workspace.worktrees(cx).next().is_some());
1641
1642            let res = default_working_directory(workspace, cx);
1643            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1644            let res = first_project_directory(workspace, cx);
1645            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1646        });
1647    }
1648
1649    // Active entry with a work tree, worktree is a file -> worktree_folder()
1650    #[gpui::test]
1651    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1652        let (project, workspace) = init_test(cx).await;
1653
1654        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1655        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1656        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1657
1658        cx.update(|cx| {
1659            let workspace = workspace.read(cx);
1660            let active_entry = project.read(cx).active_entry();
1661
1662            assert!(active_entry.is_some());
1663
1664            let res = default_working_directory(workspace, cx);
1665            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1666            let res = first_project_directory(workspace, cx);
1667            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1668        });
1669    }
1670
1671    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1672    #[gpui::test]
1673    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1674        let (project, workspace) = init_test(cx).await;
1675
1676        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1677        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1678        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1679
1680        cx.update(|cx| {
1681            let workspace = workspace.read(cx);
1682            let active_entry = project.read(cx).active_entry();
1683
1684            assert!(active_entry.is_some());
1685
1686            let res = default_working_directory(workspace, cx);
1687            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1688            let res = first_project_directory(workspace, cx);
1689            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1690        });
1691    }
1692
1693    /// Creates a worktree with 1 file: /root.txt
1694    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1695        let params = cx.update(AppState::test);
1696        cx.update(|cx| {
1697            terminal::init(cx);
1698            theme::init(theme::LoadThemes::JustBase, cx);
1699            Project::init_settings(cx);
1700            language::init(cx);
1701        });
1702
1703        let project = Project::test(params.fs.clone(), [], cx).await;
1704        let workspace = cx
1705            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1706            .root_view(cx)
1707            .unwrap();
1708
1709        (project, workspace)
1710    }
1711
1712    /// Creates a worktree with 1 folder: /root{suffix}/
1713    async fn create_folder_wt(
1714        project: Model<Project>,
1715        path: impl AsRef<Path>,
1716        cx: &mut TestAppContext,
1717    ) -> (Model<Worktree>, Entry) {
1718        create_wt(project, true, path, cx).await
1719    }
1720
1721    /// Creates a worktree with 1 file: /root{suffix}.txt
1722    async fn create_file_wt(
1723        project: Model<Project>,
1724        path: impl AsRef<Path>,
1725        cx: &mut TestAppContext,
1726    ) -> (Model<Worktree>, Entry) {
1727        create_wt(project, false, path, cx).await
1728    }
1729
1730    async fn create_wt(
1731        project: Model<Project>,
1732        is_dir: bool,
1733        path: impl AsRef<Path>,
1734        cx: &mut TestAppContext,
1735    ) -> (Model<Worktree>, Entry) {
1736        let (wt, _) = project
1737            .update(cx, |project, cx| {
1738                project.find_or_create_worktree(path, true, cx)
1739            })
1740            .await
1741            .unwrap();
1742
1743        let entry = cx
1744            .update(|cx| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1745            .await
1746            .unwrap()
1747            .to_included()
1748            .unwrap();
1749
1750        (wt, entry)
1751    }
1752
1753    pub fn insert_active_entry_for(
1754        wt: Model<Worktree>,
1755        entry: Entry,
1756        project: Model<Project>,
1757        cx: &mut TestAppContext,
1758    ) {
1759        cx.update(|cx| {
1760            let p = ProjectPath {
1761                worktree_id: wt.read(cx).id(),
1762                path: entry.path,
1763            };
1764            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1765        });
1766    }
1767
1768    #[test]
1769    fn escapes_only_special_characters() {
1770        assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1771    }
1772
1773    #[test]
1774    fn empty_string_stays_empty() {
1775        assert_eq!(regex_to_literal(""), "".to_string());
1776    }
1777}