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        let mut fetch_metadata_tasks = potential_paths
 802            .into_iter()
 803            .map(|potential_path| async {
 804                let metadata = fs.metadata(&potential_path).await.ok().flatten();
 805                (
 806                    PathWithPosition {
 807                        path: potential_path,
 808                        row,
 809                        column,
 810                    },
 811                    metadata,
 812                )
 813            })
 814            .collect::<FuturesUnordered<_>>();
 815
 816        while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
 817            if let Some(metadata) = metadata {
 818                paths_with_metadata.push((path, metadata));
 819            }
 820        }
 821
 822        paths_with_metadata
 823    })
 824}
 825
 826fn possible_open_targets(
 827    fs: Arc<dyn Fs>,
 828    workspace: &WeakView<Workspace>,
 829    cwd: &Option<PathBuf>,
 830    maybe_path: &String,
 831    cx: &mut ViewContext<TerminalView>,
 832) -> Task<Vec<(PathWithPosition, Metadata)>> {
 833    let path_position = PathWithPosition::parse_str(maybe_path.as_str());
 834    let row = path_position.row;
 835    let column = path_position.column;
 836    let maybe_path = path_position.path;
 837
 838    let abs_path = if maybe_path.is_absolute() {
 839        Some(maybe_path)
 840    } else if maybe_path.starts_with("~") {
 841        maybe_path
 842            .strip_prefix("~")
 843            .ok()
 844            .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
 845    } else {
 846        let mut potential_cwd_and_workspace_paths = HashSet::default();
 847        if let Some(cwd) = cwd {
 848            let abs_path = Path::join(cwd, &maybe_path);
 849            let canonicalized_path = abs_path.canonicalize().unwrap_or(abs_path);
 850            potential_cwd_and_workspace_paths.insert(canonicalized_path);
 851        }
 852        if let Some(workspace) = workspace.upgrade() {
 853            workspace.update(cx, |workspace, cx| {
 854                for potential_worktree_path in workspace
 855                    .worktrees(cx)
 856                    .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
 857                {
 858                    potential_cwd_and_workspace_paths.insert(potential_worktree_path);
 859                }
 860
 861                for prefix in GIT_DIFF_PATH_PREFIXES {
 862                    let prefix_str = &prefix.to_string();
 863                    if maybe_path.starts_with(prefix_str) {
 864                        let stripped = maybe_path.strip_prefix(prefix_str).unwrap_or(&maybe_path);
 865                        for potential_worktree_path in workspace
 866                            .worktrees(cx)
 867                            .map(|worktree| worktree.read(cx).abs_path().join(&stripped))
 868                        {
 869                            potential_cwd_and_workspace_paths.insert(potential_worktree_path);
 870                        }
 871                    }
 872                }
 873            });
 874        }
 875
 876        return possible_open_paths_metadata(
 877            fs,
 878            row,
 879            column,
 880            potential_cwd_and_workspace_paths,
 881            cx,
 882        );
 883    };
 884
 885    let canonicalized_paths = match abs_path {
 886        Some(abs_path) => match abs_path.canonicalize() {
 887            Ok(path) => HashSet::from_iter([path]),
 888            Err(_) => HashSet::default(),
 889        },
 890        None => HashSet::default(),
 891    };
 892
 893    possible_open_paths_metadata(fs, row, column, canonicalized_paths, cx)
 894}
 895
 896fn regex_to_literal(regex: &str) -> String {
 897    regex
 898        .chars()
 899        .flat_map(|c| {
 900            if REGEX_SPECIAL_CHARS.contains(&c) {
 901                vec!['\\', c]
 902            } else {
 903                vec![c]
 904            }
 905        })
 906        .collect()
 907}
 908
 909pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
 910    let query = query.as_str();
 911    if query == "." {
 912        return None;
 913    }
 914    let searcher = RegexSearch::new(query);
 915    searcher.ok()
 916}
 917
 918impl TerminalView {
 919    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) {
 920        self.clear_bell(cx);
 921        self.pause_cursor_blinking(cx);
 922
 923        self.terminal.update(cx, |term, cx| {
 924            let handled = term.try_keystroke(
 925                &event.keystroke,
 926                TerminalSettings::get_global(cx).option_as_meta,
 927            );
 928            if handled {
 929                cx.stop_propagation();
 930            }
 931        });
 932    }
 933
 934    fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
 935        self.terminal.update(cx, |terminal, _| {
 936            terminal.set_cursor_shape(self.cursor_shape);
 937            terminal.focus_in();
 938        });
 939        self.blink_cursors(self.blink_epoch, cx);
 940        cx.invalidate_character_coordinates();
 941        cx.notify();
 942    }
 943
 944    fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
 945        self.terminal.update(cx, |terminal, _| {
 946            terminal.focus_out();
 947            terminal.set_cursor_shape(CursorShape::Hollow);
 948        });
 949        cx.notify();
 950    }
 951}
 952
 953impl Render for TerminalView {
 954    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 955        let terminal_handle = self.terminal.clone();
 956        let terminal_view_handle = cx.view().clone();
 957
 958        let focused = self.focus_handle.is_focused(cx);
 959
 960        div()
 961            .size_full()
 962            .relative()
 963            .track_focus(&self.focus_handle)
 964            .key_context(self.dispatch_context(cx))
 965            .on_action(cx.listener(TerminalView::send_text))
 966            .on_action(cx.listener(TerminalView::send_keystroke))
 967            .on_action(cx.listener(TerminalView::copy))
 968            .on_action(cx.listener(TerminalView::paste))
 969            .on_action(cx.listener(TerminalView::clear))
 970            .on_action(cx.listener(TerminalView::scroll_line_up))
 971            .on_action(cx.listener(TerminalView::scroll_line_down))
 972            .on_action(cx.listener(TerminalView::scroll_page_up))
 973            .on_action(cx.listener(TerminalView::scroll_page_down))
 974            .on_action(cx.listener(TerminalView::scroll_to_top))
 975            .on_action(cx.listener(TerminalView::scroll_to_bottom))
 976            .on_action(cx.listener(TerminalView::toggle_vi_mode))
 977            .on_action(cx.listener(TerminalView::show_character_palette))
 978            .on_action(cx.listener(TerminalView::select_all))
 979            .on_key_down(cx.listener(Self::key_down))
 980            .on_mouse_down(
 981                MouseButton::Right,
 982                cx.listener(|this, event: &MouseDownEvent, cx| {
 983                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
 984                        this.deploy_context_menu(event.position, cx);
 985                        cx.notify();
 986                    }
 987                }),
 988            )
 989            .child(
 990                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
 991                div().size_full().child(TerminalElement::new(
 992                    terminal_handle,
 993                    terminal_view_handle,
 994                    self.workspace.clone(),
 995                    self.focus_handle.clone(),
 996                    focused,
 997                    self.should_show_cursor(focused, cx),
 998                    self.can_navigate_to_selected_word,
 999                    self.block_below_cursor.clone(),
1000                )),
1001            )
1002            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1003                deferred(
1004                    anchored()
1005                        .position(*position)
1006                        .anchor(gpui::AnchorCorner::TopLeft)
1007                        .child(menu.clone()),
1008                )
1009                .with_priority(1)
1010            }))
1011    }
1012}
1013
1014impl Item for TerminalView {
1015    type Event = ItemEvent;
1016
1017    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
1018        Some(self.terminal().read(cx).title(false).into())
1019    }
1020
1021    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
1022        let terminal = self.terminal().read(cx);
1023        let title = terminal.title(true);
1024        let rerun_button = |task_id: task::TaskId| {
1025            IconButton::new("rerun-icon", IconName::Rerun)
1026                .icon_size(IconSize::Small)
1027                .size(ButtonSize::Compact)
1028                .icon_color(Color::Default)
1029                .shape(ui::IconButtonShape::Square)
1030                .tooltip(|cx| Tooltip::text("Rerun task", cx))
1031                .on_click(move |_, cx| {
1032                    cx.dispatch_action(Box::new(tasks_ui::Rerun {
1033                        task_id: Some(task_id.clone()),
1034                        ..tasks_ui::Rerun::default()
1035                    }));
1036                })
1037        };
1038
1039        let (icon, icon_color, rerun_button) = match terminal.task() {
1040            Some(terminal_task) => match &terminal_task.status {
1041                TaskStatus::Running => (IconName::Play, Color::Disabled, None),
1042                TaskStatus::Unknown => (
1043                    IconName::Warning,
1044                    Color::Warning,
1045                    Some(rerun_button(terminal_task.id.clone())),
1046                ),
1047                TaskStatus::Completed { success } => {
1048                    let rerun_button = rerun_button(terminal_task.id.clone());
1049                    if *success {
1050                        (IconName::Check, Color::Success, Some(rerun_button))
1051                    } else {
1052                        (IconName::XCircle, Color::Error, Some(rerun_button))
1053                    }
1054                }
1055            },
1056            None => (IconName::Terminal, Color::Muted, None),
1057        };
1058
1059        h_flex()
1060            .gap_1()
1061            .group("term-tab-icon")
1062            .child(
1063                h_flex()
1064                    .group("term-tab-icon")
1065                    .child(
1066                        div()
1067                            .when(rerun_button.is_some(), |this| {
1068                                this.hover(|style| style.invisible().w_0())
1069                            })
1070                            .child(Icon::new(icon).color(icon_color)),
1071                    )
1072                    .when_some(rerun_button, |this, rerun_button| {
1073                        this.child(
1074                            div()
1075                                .absolute()
1076                                .visible_on_hover("term-tab-icon")
1077                                .child(rerun_button),
1078                        )
1079                    }),
1080            )
1081            .child(Label::new(title).color(params.text_color()))
1082            .into_any()
1083    }
1084
1085    fn telemetry_event_text(&self) -> Option<&'static str> {
1086        None
1087    }
1088
1089    fn clone_on_split(
1090        &self,
1091        _workspace_id: Option<WorkspaceId>,
1092        _cx: &mut ViewContext<Self>,
1093    ) -> Option<View<Self>> {
1094        //From what I can tell, there's no  way to tell the current working
1095        //Directory of the terminal from outside the shell. There might be
1096        //solutions to this, but they are non-trivial and require more IPC
1097
1098        // Some(TerminalContainer::new(
1099        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
1100        //     workspace_id,
1101        //     cx,
1102        // ))
1103
1104        // TODO
1105        None
1106    }
1107
1108    fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
1109        match self.terminal.read(cx).task() {
1110            Some(task) => task.status == TaskStatus::Running,
1111            None => self.has_bell(),
1112        }
1113    }
1114
1115    fn has_conflict(&self, _cx: &AppContext) -> bool {
1116        false
1117    }
1118
1119    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1120        Some(Box::new(handle.clone()))
1121    }
1122
1123    fn breadcrumb_location(&self) -> ToolbarItemLocation {
1124        if self.show_title {
1125            ToolbarItemLocation::PrimaryLeft
1126        } else {
1127            ToolbarItemLocation::Hidden
1128        }
1129    }
1130
1131    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
1132        Some(vec![BreadcrumbText {
1133            text: self.terminal().read(cx).breadcrumb_text.clone(),
1134            highlights: None,
1135            font: None,
1136        }])
1137    }
1138
1139    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
1140        if self.terminal().read(cx).task().is_none() {
1141            if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1142                cx.background_executor()
1143                    .spawn(TERMINAL_DB.update_workspace_id(new_id, old_id, cx.entity_id().as_u64()))
1144                    .detach();
1145            }
1146            self.workspace_id = workspace.database_id();
1147        }
1148    }
1149
1150    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1151        f(*event)
1152    }
1153}
1154
1155impl SerializableItem for TerminalView {
1156    fn serialized_item_kind() -> &'static str {
1157        "Terminal"
1158    }
1159
1160    fn cleanup(
1161        workspace_id: WorkspaceId,
1162        alive_items: Vec<workspace::ItemId>,
1163        cx: &mut WindowContext,
1164    ) -> Task<gpui::Result<()>> {
1165        cx.spawn(|_| TERMINAL_DB.delete_unloaded_items(workspace_id, alive_items))
1166    }
1167
1168    fn serialize(
1169        &mut self,
1170        _workspace: &mut Workspace,
1171        item_id: workspace::ItemId,
1172        _closing: bool,
1173        cx: &mut ViewContext<Self>,
1174    ) -> Option<Task<gpui::Result<()>>> {
1175        let terminal = self.terminal().read(cx);
1176        if terminal.task().is_some() {
1177            return None;
1178        }
1179
1180        if let Some((cwd, workspace_id)) = terminal.get_cwd().zip(self.workspace_id) {
1181            Some(cx.background_executor().spawn(async move {
1182                TERMINAL_DB
1183                    .save_working_directory(item_id, workspace_id, cwd)
1184                    .await
1185            }))
1186        } else {
1187            None
1188        }
1189    }
1190
1191    fn should_serialize(&self, event: &Self::Event) -> bool {
1192        matches!(event, ItemEvent::UpdateTab)
1193    }
1194
1195    fn deserialize(
1196        project: Model<Project>,
1197        workspace: WeakView<Workspace>,
1198        workspace_id: workspace::WorkspaceId,
1199        item_id: workspace::ItemId,
1200        cx: &mut ViewContext<Pane>,
1201    ) -> Task<anyhow::Result<View<Self>>> {
1202        let window = cx.window_handle();
1203        cx.spawn(|pane, mut cx| async move {
1204            let cwd = cx
1205                .update(|cx| {
1206                    let from_db = TERMINAL_DB
1207                        .get_working_directory(item_id, workspace_id)
1208                        .log_err()
1209                        .flatten();
1210                    if from_db
1211                        .as_ref()
1212                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1213                    {
1214                        from_db
1215                    } else {
1216                        workspace
1217                            .upgrade()
1218                            .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1219                    }
1220                })
1221                .ok()
1222                .flatten();
1223
1224            let terminal = project.update(&mut cx, |project, cx| {
1225                project.create_terminal(TerminalKind::Shell(cwd), window, cx)
1226            })??;
1227            pane.update(&mut cx, |_, cx| {
1228                cx.new_view(|cx| TerminalView::new(terminal, workspace, Some(workspace_id), cx))
1229            })
1230        })
1231    }
1232}
1233
1234impl SearchableItem for TerminalView {
1235    type Match = RangeInclusive<Point>;
1236
1237    fn supported_options() -> SearchOptions {
1238        SearchOptions {
1239            case: false,
1240            word: false,
1241            regex: true,
1242            replacement: false,
1243            selection: false,
1244        }
1245    }
1246
1247    /// Clear stored matches
1248    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1249        self.terminal().update(cx, |term, _| term.matches.clear())
1250    }
1251
1252    /// Store matches returned from find_matches somewhere for rendering
1253    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1254        self.terminal()
1255            .update(cx, |term, _| term.matches = matches.to_vec())
1256    }
1257
1258    /// Returns the selection content to pre-load into this search
1259    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1260        self.terminal()
1261            .read(cx)
1262            .last_content
1263            .selection_text
1264            .clone()
1265            .unwrap_or_default()
1266    }
1267
1268    /// Focus match at given index into the Vec of matches
1269    fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
1270        self.terminal()
1271            .update(cx, |term, _| term.activate_match(index));
1272        cx.notify();
1273    }
1274
1275    /// Add selections for all matches given.
1276    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1277        self.terminal()
1278            .update(cx, |term, _| term.select_matches(matches));
1279        cx.notify();
1280    }
1281
1282    /// Get all of the matches for this query, should be done on the background
1283    fn find_matches(
1284        &mut self,
1285        query: Arc<SearchQuery>,
1286        cx: &mut ViewContext<Self>,
1287    ) -> Task<Vec<Self::Match>> {
1288        let searcher = match &*query {
1289            SearchQuery::Text { .. } => regex_search_for_query(
1290                &(SearchQuery::text(
1291                    regex_to_literal(query.as_str()),
1292                    query.whole_word(),
1293                    query.case_sensitive(),
1294                    query.include_ignored(),
1295                    query.files_to_include().clone(),
1296                    query.files_to_exclude().clone(),
1297                    None,
1298                )
1299                .unwrap()),
1300            ),
1301            SearchQuery::Regex { .. } => regex_search_for_query(&query),
1302        };
1303
1304        if let Some(s) = searcher {
1305            self.terminal()
1306                .update(cx, |term, cx| term.find_matches(s, cx))
1307        } else {
1308            Task::ready(vec![])
1309        }
1310    }
1311
1312    /// Reports back to the search toolbar what the active match should be (the selection)
1313    fn active_match_index(
1314        &mut self,
1315        matches: &[Self::Match],
1316        cx: &mut ViewContext<Self>,
1317    ) -> Option<usize> {
1318        // Selection head might have a value if there's a selection that isn't
1319        // associated with a match. Therefore, if there are no matches, we should
1320        // report None, no matter the state of the terminal
1321        let res = if !matches.is_empty() {
1322            if let Some(selection_head) = self.terminal().read(cx).selection_head {
1323                // If selection head is contained in a match. Return that match
1324                if let Some(ix) = matches
1325                    .iter()
1326                    .enumerate()
1327                    .find(|(_, search_match)| {
1328                        search_match.contains(&selection_head)
1329                            || search_match.start() > &selection_head
1330                    })
1331                    .map(|(ix, _)| ix)
1332                {
1333                    Some(ix)
1334                } else {
1335                    // If no selection after selection head, return the last match
1336                    Some(matches.len().saturating_sub(1))
1337                }
1338            } else {
1339                // Matches found but no active selection, return the first last one (closest to cursor)
1340                Some(matches.len().saturating_sub(1))
1341            }
1342        } else {
1343            None
1344        };
1345
1346        res
1347    }
1348    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1349        // Replacement is not supported in terminal view, so this is a no-op.
1350    }
1351}
1352
1353///Gets the working directory for the given workspace, respecting the user's settings.
1354/// None implies "~" on whichever machine we end up on.
1355pub fn default_working_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1356    match &TerminalSettings::get_global(cx).working_directory {
1357        WorkingDirectory::CurrentProjectDirectory => {
1358            workspace.project().read(cx).active_project_directory(cx)
1359        }
1360        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1361        WorkingDirectory::AlwaysHome => None,
1362        WorkingDirectory::Always { directory } => {
1363            shellexpand::full(&directory) //TODO handle this better
1364                .ok()
1365                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1366                .filter(|dir| dir.is_dir())
1367        }
1368    }
1369}
1370///Gets the first project's home directory, or the home directory
1371fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1372    let worktree = workspace.worktrees(cx).next()?.read(cx);
1373    if !worktree.root_entry()?.is_dir() {
1374        return None;
1375    }
1376    Some(worktree.abs_path().to_path_buf())
1377}
1378
1379#[cfg(test)]
1380mod tests {
1381    use super::*;
1382    use gpui::TestAppContext;
1383    use project::{Entry, Project, ProjectPath, Worktree};
1384    use std::path::Path;
1385    use workspace::AppState;
1386
1387    // Working directory calculation tests
1388
1389    // No Worktrees in project -> home_dir()
1390    #[gpui::test]
1391    async fn no_worktree(cx: &mut TestAppContext) {
1392        let (project, workspace) = init_test(cx).await;
1393        cx.read(|cx| {
1394            let workspace = workspace.read(cx);
1395            let active_entry = project.read(cx).active_entry();
1396
1397            //Make sure environment is as expected
1398            assert!(active_entry.is_none());
1399            assert!(workspace.worktrees(cx).next().is_none());
1400
1401            let res = default_working_directory(workspace, cx);
1402            assert_eq!(res, None);
1403            let res = first_project_directory(workspace, cx);
1404            assert_eq!(res, None);
1405        });
1406    }
1407
1408    // No active entry, but a worktree, worktree is a file -> home_dir()
1409    #[gpui::test]
1410    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1411        let (project, workspace) = init_test(cx).await;
1412
1413        create_file_wt(project.clone(), "/root.txt", 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_some());
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 folder -> worktree_folder
1430    #[gpui::test]
1431    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1432        let (project, workspace) = init_test(cx).await;
1433
1434        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1435        cx.update(|cx| {
1436            let workspace = workspace.read(cx);
1437            let active_entry = project.read(cx).active_entry();
1438
1439            assert!(active_entry.is_none());
1440            assert!(workspace.worktrees(cx).next().is_some());
1441
1442            let res = default_working_directory(workspace, cx);
1443            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1444            let res = first_project_directory(workspace, cx);
1445            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1446        });
1447    }
1448
1449    // Active entry with a work tree, worktree is a file -> home_dir()
1450    #[gpui::test]
1451    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1452        let (project, workspace) = init_test(cx).await;
1453
1454        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1455        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1456        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1457
1458        cx.update(|cx| {
1459            let workspace = workspace.read(cx);
1460            let active_entry = project.read(cx).active_entry();
1461
1462            assert!(active_entry.is_some());
1463
1464            let res = default_working_directory(workspace, cx);
1465            assert_eq!(res, None);
1466            let res = first_project_directory(workspace, cx);
1467            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1468        });
1469    }
1470
1471    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1472    #[gpui::test]
1473    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1474        let (project, workspace) = init_test(cx).await;
1475
1476        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1477        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1478        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1479
1480        cx.update(|cx| {
1481            let workspace = workspace.read(cx);
1482            let active_entry = project.read(cx).active_entry();
1483
1484            assert!(active_entry.is_some());
1485
1486            let res = default_working_directory(workspace, cx);
1487            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1488            let res = first_project_directory(workspace, cx);
1489            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1490        });
1491    }
1492
1493    /// Creates a worktree with 1 file: /root.txt
1494    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1495        let params = cx.update(AppState::test);
1496        cx.update(|cx| {
1497            terminal::init(cx);
1498            theme::init(theme::LoadThemes::JustBase, cx);
1499            Project::init_settings(cx);
1500            language::init(cx);
1501        });
1502
1503        let project = Project::test(params.fs.clone(), [], cx).await;
1504        let workspace = cx
1505            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1506            .root_view(cx)
1507            .unwrap();
1508
1509        (project, workspace)
1510    }
1511
1512    /// Creates a worktree with 1 folder: /root{suffix}/
1513    async fn create_folder_wt(
1514        project: Model<Project>,
1515        path: impl AsRef<Path>,
1516        cx: &mut TestAppContext,
1517    ) -> (Model<Worktree>, Entry) {
1518        create_wt(project, true, path, cx).await
1519    }
1520
1521    /// Creates a worktree with 1 file: /root{suffix}.txt
1522    async fn create_file_wt(
1523        project: Model<Project>,
1524        path: impl AsRef<Path>,
1525        cx: &mut TestAppContext,
1526    ) -> (Model<Worktree>, Entry) {
1527        create_wt(project, false, path, cx).await
1528    }
1529
1530    async fn create_wt(
1531        project: Model<Project>,
1532        is_dir: bool,
1533        path: impl AsRef<Path>,
1534        cx: &mut TestAppContext,
1535    ) -> (Model<Worktree>, Entry) {
1536        let (wt, _) = project
1537            .update(cx, |project, cx| {
1538                project.find_or_create_worktree(path, true, cx)
1539            })
1540            .await
1541            .unwrap();
1542
1543        let entry = cx
1544            .update(|cx| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1545            .await
1546            .unwrap()
1547            .to_included()
1548            .unwrap();
1549
1550        (wt, entry)
1551    }
1552
1553    pub fn insert_active_entry_for(
1554        wt: Model<Worktree>,
1555        entry: Entry,
1556        project: Model<Project>,
1557        cx: &mut TestAppContext,
1558    ) {
1559        cx.update(|cx| {
1560            let p = ProjectPath {
1561                worktree_id: wt.read(cx).id(),
1562                path: entry.path,
1563            };
1564            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1565        });
1566    }
1567
1568    #[test]
1569    fn escapes_only_special_characters() {
1570        assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1571    }
1572
1573    #[test]
1574    fn empty_string_stays_empty() {
1575        assert_eq!(regex_to_literal(""), "".to_string());
1576    }
1577}