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