terminal_view.rs

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