terminal_view.rs

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