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, _| term.scroll_wheel(event));
 523    }
 524
 525    fn scroll_line_up(&mut self, _: &ScrollLineUp, _: &mut Window, cx: &mut Context<Self>) {
 526        let terminal_content = self.terminal.read(cx).last_content();
 527        if self.block_below_cursor.is_some()
 528            && terminal_content.display_offset == 0
 529            && self.scroll_top > Pixels::ZERO
 530        {
 531            let line_height = terminal_content.terminal_bounds.line_height;
 532            self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
 533            return;
 534        }
 535
 536        self.terminal.update(cx, |term, _| term.scroll_line_up());
 537        cx.notify();
 538    }
 539
 540    fn scroll_line_down(&mut self, _: &ScrollLineDown, _: &mut Window, cx: &mut Context<Self>) {
 541        let terminal_content = self.terminal.read(cx).last_content();
 542        if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
 543            let max_scroll_top = self.max_scroll_top(cx);
 544            if self.scroll_top < max_scroll_top {
 545                let line_height = terminal_content.terminal_bounds.line_height;
 546                self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
 547            }
 548            return;
 549        }
 550
 551        self.terminal.update(cx, |term, _| term.scroll_line_down());
 552        cx.notify();
 553    }
 554
 555    fn scroll_page_up(&mut self, _: &ScrollPageUp, _: &mut Window, cx: &mut Context<Self>) {
 556        if self.scroll_top == Pixels::ZERO {
 557            self.terminal.update(cx, |term, _| term.scroll_page_up());
 558        } else {
 559            let line_height = self
 560                .terminal
 561                .read(cx)
 562                .last_content
 563                .terminal_bounds
 564                .line_height();
 565            let visible_block_lines = (self.scroll_top / line_height) as usize;
 566            let viewport_lines = self.terminal.read(cx).viewport_lines();
 567            let visible_content_lines = viewport_lines - visible_block_lines;
 568
 569            if visible_block_lines >= viewport_lines {
 570                self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
 571            } else {
 572                self.scroll_top = px(0.);
 573                self.terminal
 574                    .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
 575            }
 576        }
 577        cx.notify();
 578    }
 579
 580    fn scroll_page_down(&mut self, _: &ScrollPageDown, _: &mut Window, cx: &mut Context<Self>) {
 581        self.terminal.update(cx, |term, _| term.scroll_page_down());
 582        let terminal = self.terminal.read(cx);
 583        if terminal.last_content().display_offset < terminal.viewport_lines() {
 584            self.scroll_top = self.max_scroll_top(cx);
 585        }
 586        cx.notify();
 587    }
 588
 589    fn scroll_to_top(&mut self, _: &ScrollToTop, _: &mut Window, cx: &mut Context<Self>) {
 590        self.terminal.update(cx, |term, _| term.scroll_to_top());
 591        cx.notify();
 592    }
 593
 594    fn scroll_to_bottom(&mut self, _: &ScrollToBottom, _: &mut Window, cx: &mut Context<Self>) {
 595        self.terminal.update(cx, |term, _| term.scroll_to_bottom());
 596        if self.block_below_cursor.is_some() {
 597            self.scroll_top = self.max_scroll_top(cx);
 598        }
 599        cx.notify();
 600    }
 601
 602    fn toggle_vi_mode(&mut self, _: &ToggleViMode, _: &mut Window, cx: &mut Context<Self>) {
 603        self.terminal.update(cx, |term, _| term.toggle_vi_mode());
 604        cx.notify();
 605    }
 606
 607    pub fn should_show_cursor(&self, focused: bool, cx: &mut Context<Self>) -> bool {
 608        //Don't blink the cursor when not focused, blinking is disabled, or paused
 609        if !focused
 610            || self.blinking_paused
 611            || self
 612                .terminal
 613                .read(cx)
 614                .last_content
 615                .mode
 616                .contains(TermMode::ALT_SCREEN)
 617        {
 618            return true;
 619        }
 620
 621        match TerminalSettings::get_global(cx).blinking {
 622            //If the user requested to never blink, don't blink it.
 623            TerminalBlink::Off => true,
 624            //If the terminal is controlling it, check terminal mode
 625            TerminalBlink::TerminalControlled => {
 626                !self.blinking_terminal_enabled || self.blink_state
 627            }
 628            TerminalBlink::On => self.blink_state,
 629        }
 630    }
 631
 632    fn blink_cursors(&mut self, epoch: usize, window: &mut Window, cx: &mut Context<Self>) {
 633        if epoch == self.blink_epoch && !self.blinking_paused {
 634            self.blink_state = !self.blink_state;
 635            cx.notify();
 636
 637            let epoch = self.next_blink_epoch();
 638            cx.spawn_in(window, async move |this, cx| {
 639                Timer::after(CURSOR_BLINK_INTERVAL).await;
 640                this.update_in(cx, |this, window, cx| this.blink_cursors(epoch, window, cx))
 641                    .ok();
 642            })
 643            .detach();
 644        }
 645    }
 646
 647    pub fn pause_cursor_blinking(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 648        self.blink_state = true;
 649        cx.notify();
 650
 651        let epoch = self.next_blink_epoch();
 652        cx.spawn_in(window, async move |this, cx| {
 653            Timer::after(CURSOR_BLINK_INTERVAL).await;
 654            this.update_in(cx, |this, window, cx| {
 655                this.resume_cursor_blinking(epoch, window, cx)
 656            })
 657            .ok();
 658        })
 659        .detach();
 660    }
 661
 662    pub fn terminal(&self) -> &Entity<Terminal> {
 663        &self.terminal
 664    }
 665
 666    pub fn set_block_below_cursor(
 667        &mut self,
 668        block: BlockProperties,
 669        window: &mut Window,
 670        cx: &mut Context<Self>,
 671    ) {
 672        self.block_below_cursor = Some(Rc::new(block));
 673        self.scroll_to_bottom(&ScrollToBottom, window, cx);
 674        cx.notify();
 675    }
 676
 677    pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
 678        self.block_below_cursor = None;
 679        self.scroll_top = Pixels::ZERO;
 680        cx.notify();
 681    }
 682
 683    fn next_blink_epoch(&mut self) -> usize {
 684        self.blink_epoch += 1;
 685        self.blink_epoch
 686    }
 687
 688    fn resume_cursor_blinking(
 689        &mut self,
 690        epoch: usize,
 691        window: &mut Window,
 692        cx: &mut Context<Self>,
 693    ) {
 694        if epoch == self.blink_epoch {
 695            self.blinking_paused = false;
 696            self.blink_cursors(epoch, window, cx);
 697        }
 698    }
 699
 700    ///Attempt to paste the clipboard into the terminal
 701    fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 702        self.terminal.update(cx, |term, _| term.copy(None));
 703        cx.notify();
 704    }
 705
 706    ///Attempt to paste the clipboard into the terminal
 707    fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
 708        if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
 709            self.terminal
 710                .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
 711        }
 712    }
 713
 714    fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
 715        self.clear_bell(cx);
 716        self.terminal.update(cx, |term, _| {
 717            term.input(text.0.to_string().into_bytes());
 718        });
 719    }
 720
 721    fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
 722        if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
 723            self.clear_bell(cx);
 724            self.terminal.update(cx, |term, cx| {
 725                let processed =
 726                    term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
 727                if processed && term.vi_mode_enabled() {
 728                    cx.notify();
 729                }
 730                processed
 731            });
 732        }
 733    }
 734
 735    fn dispatch_context(&self, cx: &App) -> KeyContext {
 736        let mut dispatch_context = KeyContext::new_with_defaults();
 737        dispatch_context.add("Terminal");
 738
 739        if self.terminal.read(cx).vi_mode_enabled() {
 740            dispatch_context.add("vi_mode");
 741        }
 742
 743        let mode = self.terminal.read(cx).last_content.mode;
 744        dispatch_context.set(
 745            "screen",
 746            if mode.contains(TermMode::ALT_SCREEN) {
 747                "alt"
 748            } else {
 749                "normal"
 750            },
 751        );
 752
 753        if mode.contains(TermMode::APP_CURSOR) {
 754            dispatch_context.add("DECCKM");
 755        }
 756        if mode.contains(TermMode::APP_KEYPAD) {
 757            dispatch_context.add("DECPAM");
 758        } else {
 759            dispatch_context.add("DECPNM");
 760        }
 761        if mode.contains(TermMode::SHOW_CURSOR) {
 762            dispatch_context.add("DECTCEM");
 763        }
 764        if mode.contains(TermMode::LINE_WRAP) {
 765            dispatch_context.add("DECAWM");
 766        }
 767        if mode.contains(TermMode::ORIGIN) {
 768            dispatch_context.add("DECOM");
 769        }
 770        if mode.contains(TermMode::INSERT) {
 771            dispatch_context.add("IRM");
 772        }
 773        //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 774        if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 775            dispatch_context.add("LNM");
 776        }
 777        if mode.contains(TermMode::FOCUS_IN_OUT) {
 778            dispatch_context.add("report_focus");
 779        }
 780        if mode.contains(TermMode::ALTERNATE_SCROLL) {
 781            dispatch_context.add("alternate_scroll");
 782        }
 783        if mode.contains(TermMode::BRACKETED_PASTE) {
 784            dispatch_context.add("bracketed_paste");
 785        }
 786        if mode.intersects(TermMode::MOUSE_MODE) {
 787            dispatch_context.add("any_mouse_reporting");
 788        }
 789        {
 790            let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 791                "click"
 792            } else if mode.contains(TermMode::MOUSE_DRAG) {
 793                "drag"
 794            } else if mode.contains(TermMode::MOUSE_MOTION) {
 795                "motion"
 796            } else {
 797                "off"
 798            };
 799            dispatch_context.set("mouse_reporting", mouse_reporting);
 800        }
 801        {
 802            let format = if mode.contains(TermMode::SGR_MOUSE) {
 803                "sgr"
 804            } else if mode.contains(TermMode::UTF8_MOUSE) {
 805                "utf8"
 806            } else {
 807                "normal"
 808            };
 809            dispatch_context.set("mouse_format", format);
 810        };
 811
 812        if self.terminal.read(cx).last_content.selection.is_some() {
 813            dispatch_context.add("selection");
 814        }
 815
 816        dispatch_context
 817    }
 818
 819    fn set_terminal(
 820        &mut self,
 821        terminal: Entity<Terminal>,
 822        window: &mut Window,
 823        cx: &mut Context<TerminalView>,
 824    ) {
 825        self._terminal_subscriptions =
 826            subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
 827        self.terminal = terminal;
 828    }
 829
 830    fn rerun_button(task: &TaskState) -> Option<IconButton> {
 831        if !task.spawned_task.show_rerun {
 832            return None;
 833        }
 834
 835        let task_id = task.spawned_task.id.clone();
 836        Some(
 837            IconButton::new("rerun-icon", IconName::Rerun)
 838                .icon_size(IconSize::Small)
 839                .size(ButtonSize::Compact)
 840                .icon_color(Color::Default)
 841                .shape(ui::IconButtonShape::Square)
 842                .tooltip(move |_window, cx| Tooltip::for_action("Rerun task", &RerunTask, cx))
 843                .on_click(move |_, window, cx| {
 844                    window.dispatch_action(Box::new(terminal_rerun_override(&task_id)), cx);
 845                }),
 846        )
 847    }
 848}
 849
 850fn terminal_rerun_override(task: &TaskId) -> zed_actions::Rerun {
 851    zed_actions::Rerun {
 852        task_id: Some(task.0.clone()),
 853        allow_concurrent_runs: Some(true),
 854        use_new_terminal: Some(false),
 855        reevaluate_context: false,
 856    }
 857}
 858
 859fn subscribe_for_terminal_events(
 860    terminal: &Entity<Terminal>,
 861    workspace: WeakEntity<Workspace>,
 862    window: &mut Window,
 863    cx: &mut Context<TerminalView>,
 864) -> Vec<Subscription> {
 865    let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
 866    let mut previous_cwd = None;
 867    let terminal_events_subscription = cx.subscribe_in(
 868        terminal,
 869        window,
 870        move |terminal_view, terminal, event, window, cx| {
 871            let current_cwd = terminal.read(cx).working_directory();
 872            if current_cwd != previous_cwd {
 873                previous_cwd = current_cwd;
 874                terminal_view.cwd_serialized = false;
 875            }
 876
 877            match event {
 878                Event::Wakeup => {
 879                    cx.notify();
 880                    cx.emit(Event::Wakeup);
 881                    cx.emit(ItemEvent::UpdateTab);
 882                    cx.emit(SearchEvent::MatchesInvalidated);
 883                }
 884
 885                Event::Bell => {
 886                    terminal_view.has_bell = true;
 887                    cx.emit(Event::Wakeup);
 888                }
 889
 890                Event::BlinkChanged(blinking) => {
 891                    if matches!(
 892                        TerminalSettings::get_global(cx).blinking,
 893                        TerminalBlink::TerminalControlled
 894                    ) {
 895                        terminal_view.blinking_terminal_enabled = *blinking;
 896                    }
 897                }
 898
 899                Event::TitleChanged => {
 900                    cx.emit(ItemEvent::UpdateTab);
 901                }
 902
 903                Event::NewNavigationTarget(maybe_navigation_target) => {
 904                    match maybe_navigation_target
 905                        .as_ref()
 906                        .zip(terminal.read(cx).last_content.last_hovered_word.as_ref())
 907                    {
 908                        Some((MaybeNavigationTarget::Url(url), hovered_word)) => {
 909                            if Some(hovered_word)
 910                                != terminal_view
 911                                    .hover
 912                                    .as_ref()
 913                                    .map(|hover| &hover.hovered_word)
 914                            {
 915                                terminal_view.hover = Some(HoverTarget {
 916                                    tooltip: url.clone(),
 917                                    hovered_word: hovered_word.clone(),
 918                                });
 919                                terminal_view.hover_tooltip_update = Task::ready(());
 920                                cx.notify();
 921                            }
 922                        }
 923                        Some((MaybeNavigationTarget::PathLike(path_like_target), hovered_word)) => {
 924                            if Some(hovered_word)
 925                                != terminal_view
 926                                    .hover
 927                                    .as_ref()
 928                                    .map(|hover| &hover.hovered_word)
 929                            {
 930                                terminal_view.hover = None;
 931                                terminal_view.hover_tooltip_update = hover_path_like_target(
 932                                    &workspace,
 933                                    hovered_word.clone(),
 934                                    path_like_target,
 935                                    cx,
 936                                );
 937                                cx.notify();
 938                            }
 939                        }
 940                        None => {
 941                            terminal_view.hover = None;
 942                            terminal_view.hover_tooltip_update = Task::ready(());
 943                            cx.notify();
 944                        }
 945                    }
 946                }
 947
 948                Event::Open(maybe_navigation_target) => match maybe_navigation_target {
 949                    MaybeNavigationTarget::Url(url) => cx.open_url(url),
 950                    MaybeNavigationTarget::PathLike(path_like_target) => open_path_like_target(
 951                        &workspace,
 952                        terminal_view,
 953                        path_like_target,
 954                        window,
 955                        cx,
 956                    ),
 957                },
 958                Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
 959                Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
 960                Event::SelectionsChanged => {
 961                    window.invalidate_character_coordinates();
 962                    cx.emit(SearchEvent::ActiveMatchChanged)
 963                }
 964            }
 965        },
 966    );
 967    vec![terminal_subscription, terminal_events_subscription]
 968}
 969
 970fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
 971    let str = query.as_str();
 972    if query.is_regex() {
 973        if str == "." {
 974            return None;
 975        }
 976        RegexSearch::new(str).ok()
 977    } else {
 978        RegexSearch::new(&regex::escape(str)).ok()
 979    }
 980}
 981
 982struct TerminalScrollbarSettingsWrapper;
 983
 984impl GlobalSetting for TerminalScrollbarSettingsWrapper {
 985    fn get_value(_cx: &App) -> &Self {
 986        &Self
 987    }
 988}
 989
 990impl ScrollbarVisibility for TerminalScrollbarSettingsWrapper {
 991    fn visibility(&self, cx: &App) -> scrollbars::ShowScrollbar {
 992        TerminalSettings::get_global(cx)
 993            .scrollbar
 994            .show
 995            .map(Into::into)
 996            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
 997    }
 998}
 999
1000impl TerminalView {
1001    fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1002        self.clear_bell(cx);
1003        self.pause_cursor_blinking(window, cx);
1004
1005        self.terminal.update(cx, |term, cx| {
1006            let handled = term.try_keystroke(
1007                &event.keystroke,
1008                TerminalSettings::get_global(cx).option_as_meta,
1009            );
1010            if handled {
1011                cx.stop_propagation();
1012            }
1013        });
1014    }
1015
1016    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1017        self.terminal.update(cx, |terminal, _| {
1018            terminal.set_cursor_shape(self.cursor_shape);
1019            terminal.focus_in();
1020        });
1021        self.blink_cursors(self.blink_epoch, window, cx);
1022        window.invalidate_character_coordinates();
1023        cx.notify();
1024    }
1025
1026    fn focus_out(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1027        self.terminal.update(cx, |terminal, _| {
1028            terminal.focus_out();
1029            terminal.set_cursor_shape(CursorShape::Hollow);
1030        });
1031        cx.notify();
1032    }
1033}
1034
1035impl Render for TerminalView {
1036    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1037        // TODO: this should be moved out of render
1038        self.scroll_handle.update(self.terminal.read(cx));
1039
1040        if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
1041            self.terminal.update(cx, |term, _| {
1042                let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
1043                match delta.cmp(&0) {
1044                    std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
1045                    std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
1046                    std::cmp::Ordering::Equal => {}
1047                }
1048            });
1049        }
1050
1051        let terminal_handle = self.terminal.clone();
1052        let terminal_view_handle = cx.entity();
1053
1054        let focused = self.focus_handle.is_focused(window);
1055
1056        div()
1057            .id("terminal-view")
1058            .size_full()
1059            .relative()
1060            .track_focus(&self.focus_handle(cx))
1061            .key_context(self.dispatch_context(cx))
1062            .on_action(cx.listener(TerminalView::send_text))
1063            .on_action(cx.listener(TerminalView::send_keystroke))
1064            .on_action(cx.listener(TerminalView::copy))
1065            .on_action(cx.listener(TerminalView::paste))
1066            .on_action(cx.listener(TerminalView::clear))
1067            .on_action(cx.listener(TerminalView::scroll_line_up))
1068            .on_action(cx.listener(TerminalView::scroll_line_down))
1069            .on_action(cx.listener(TerminalView::scroll_page_up))
1070            .on_action(cx.listener(TerminalView::scroll_page_down))
1071            .on_action(cx.listener(TerminalView::scroll_to_top))
1072            .on_action(cx.listener(TerminalView::scroll_to_bottom))
1073            .on_action(cx.listener(TerminalView::toggle_vi_mode))
1074            .on_action(cx.listener(TerminalView::show_character_palette))
1075            .on_action(cx.listener(TerminalView::select_all))
1076            .on_action(cx.listener(TerminalView::rerun_task))
1077            .on_key_down(cx.listener(Self::key_down))
1078            .on_mouse_down(
1079                MouseButton::Right,
1080                cx.listener(|this, event: &MouseDownEvent, window, cx| {
1081                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1082                        if this.terminal.read(cx).last_content.selection.is_none() {
1083                            this.terminal.update(cx, |terminal, _| {
1084                                terminal.select_word_at_event_position(event);
1085                            });
1086                        };
1087                        this.deploy_context_menu(event.position, window, cx);
1088                        cx.notify();
1089                    }
1090                }),
1091            )
1092            .child(
1093                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1094                div()
1095                    .id("terminal-view-container")
1096                    .size_full()
1097                    .bg(cx.theme().colors().editor_background)
1098                    .child(TerminalElement::new(
1099                        terminal_handle,
1100                        terminal_view_handle,
1101                        self.workspace.clone(),
1102                        self.focus_handle.clone(),
1103                        focused,
1104                        self.should_show_cursor(focused, cx),
1105                        self.block_below_cursor.clone(),
1106                        self.mode.clone(),
1107                    ))
1108                    .when(self.content_mode(window, cx).is_scrollable(), |div| {
1109                        div.custom_scrollbars(
1110                            Scrollbars::for_settings::<TerminalScrollbarSettingsWrapper>()
1111                                .show_along(ScrollAxes::Vertical)
1112                                .with_track_along(
1113                                    ScrollAxes::Vertical,
1114                                    cx.theme().colors().editor_background,
1115                                )
1116                                .tracked_scroll_handle(self.scroll_handle.clone()),
1117                            window,
1118                            cx,
1119                        )
1120                    }),
1121            )
1122            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1123                deferred(
1124                    anchored()
1125                        .position(*position)
1126                        .anchor(gpui::Corner::TopLeft)
1127                        .child(menu.clone()),
1128                )
1129                .with_priority(1)
1130            }))
1131    }
1132}
1133
1134impl Item for TerminalView {
1135    type Event = ItemEvent;
1136
1137    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1138        let terminal = self.terminal().read(cx);
1139        let title = terminal.title(false);
1140        let pid = terminal.pid_getter()?.fallback_pid();
1141
1142        Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
1143            cx.new(|_| TerminalTooltip::new(title.clone(), pid.as_u32()))
1144                .into()
1145        })))
1146    }
1147
1148    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1149        let terminal = self.terminal().read(cx);
1150        let title = terminal.title(true);
1151
1152        let (icon, icon_color, rerun_button) = match terminal.task() {
1153            Some(terminal_task) => match &terminal_task.status {
1154                TaskStatus::Running => (
1155                    IconName::PlayFilled,
1156                    Color::Disabled,
1157                    TerminalView::rerun_button(terminal_task),
1158                ),
1159                TaskStatus::Unknown => (
1160                    IconName::Warning,
1161                    Color::Warning,
1162                    TerminalView::rerun_button(terminal_task),
1163                ),
1164                TaskStatus::Completed { success } => {
1165                    let rerun_button = TerminalView::rerun_button(terminal_task);
1166
1167                    if *success {
1168                        (IconName::Check, Color::Success, rerun_button)
1169                    } else {
1170                        (IconName::XCircle, Color::Error, rerun_button)
1171                    }
1172                }
1173            },
1174            None => (IconName::Terminal, Color::Muted, None),
1175        };
1176
1177        h_flex()
1178            .gap_1()
1179            .group("term-tab-icon")
1180            .child(
1181                h_flex()
1182                    .group("term-tab-icon")
1183                    .child(
1184                        div()
1185                            .when(rerun_button.is_some(), |this| {
1186                                this.hover(|style| style.invisible().w_0())
1187                            })
1188                            .child(Icon::new(icon).color(icon_color)),
1189                    )
1190                    .when_some(rerun_button, |this, rerun_button| {
1191                        this.child(
1192                            div()
1193                                .absolute()
1194                                .visible_on_hover("term-tab-icon")
1195                                .child(rerun_button),
1196                        )
1197                    }),
1198            )
1199            .child(Label::new(title).color(params.text_color()))
1200            .into_any()
1201    }
1202
1203    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
1204        let terminal = self.terminal().read(cx);
1205        terminal.title(detail == 0).into()
1206    }
1207
1208    fn telemetry_event_text(&self) -> Option<&'static str> {
1209        None
1210    }
1211
1212    fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
1213        workspace::item::ItemBufferKind::Singleton
1214    }
1215
1216    fn can_split(&self) -> bool {
1217        true
1218    }
1219
1220    fn clone_on_split(
1221        &self,
1222        workspace_id: Option<WorkspaceId>,
1223        window: &mut Window,
1224        cx: &mut Context<Self>,
1225    ) -> Task<Option<Entity<Self>>> {
1226        let Ok(terminal) = self.project.update(cx, |project, cx| {
1227            let cwd = project
1228                .active_project_directory(cx)
1229                .map(|it| it.to_path_buf());
1230            project.clone_terminal(self.terminal(), cx, cwd)
1231        }) else {
1232            return Task::ready(None);
1233        };
1234        cx.spawn_in(window, async move |this, cx| {
1235            let terminal = terminal.await.log_err()?;
1236            this.update_in(cx, |this, window, cx| {
1237                cx.new(|cx| {
1238                    TerminalView::new(
1239                        terminal,
1240                        this.workspace.clone(),
1241                        workspace_id,
1242                        this.project.clone(),
1243                        window,
1244                        cx,
1245                    )
1246                })
1247            })
1248            .ok()
1249        })
1250    }
1251
1252    fn is_dirty(&self, cx: &gpui::App) -> bool {
1253        match self.terminal.read(cx).task() {
1254            Some(task) => task.status == TaskStatus::Running,
1255            None => self.has_bell(),
1256        }
1257    }
1258
1259    fn has_conflict(&self, _cx: &App) -> bool {
1260        false
1261    }
1262
1263    fn can_save_as(&self, _cx: &App) -> bool {
1264        false
1265    }
1266
1267    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1268        Some(Box::new(handle.clone()))
1269    }
1270
1271    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1272        if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1273            ToolbarItemLocation::PrimaryLeft
1274        } else {
1275            ToolbarItemLocation::Hidden
1276        }
1277    }
1278
1279    fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1280        Some(vec![BreadcrumbText {
1281            text: self.terminal().read(cx).breadcrumb_text.clone(),
1282            highlights: None,
1283            font: None,
1284        }])
1285    }
1286
1287    fn added_to_workspace(
1288        &mut self,
1289        workspace: &mut Workspace,
1290        _: &mut Window,
1291        cx: &mut Context<Self>,
1292    ) {
1293        if self.terminal().read(cx).task().is_none() {
1294            if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1295                log::debug!(
1296                    "Updating workspace id for the terminal, old: {old_id:?}, new: {new_id:?}",
1297                );
1298                cx.background_spawn(TERMINAL_DB.update_workspace_id(
1299                    new_id,
1300                    old_id,
1301                    cx.entity_id().as_u64(),
1302                ))
1303                .detach();
1304            }
1305            self.workspace_id = workspace.database_id();
1306        }
1307    }
1308
1309    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1310        f(*event)
1311    }
1312}
1313
1314impl SerializableItem for TerminalView {
1315    fn serialized_item_kind() -> &'static str {
1316        "Terminal"
1317    }
1318
1319    fn cleanup(
1320        workspace_id: WorkspaceId,
1321        alive_items: Vec<workspace::ItemId>,
1322        _window: &mut Window,
1323        cx: &mut App,
1324    ) -> Task<anyhow::Result<()>> {
1325        delete_unloaded_items(alive_items, workspace_id, "terminals", &TERMINAL_DB, cx)
1326    }
1327
1328    fn serialize(
1329        &mut self,
1330        _workspace: &mut Workspace,
1331        item_id: workspace::ItemId,
1332        _closing: bool,
1333        _: &mut Window,
1334        cx: &mut Context<Self>,
1335    ) -> Option<Task<anyhow::Result<()>>> {
1336        let terminal = self.terminal().read(cx);
1337        if terminal.task().is_some() {
1338            return None;
1339        }
1340
1341        if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1342            self.cwd_serialized = true;
1343            Some(cx.background_spawn(async move {
1344                TERMINAL_DB
1345                    .save_working_directory(item_id, workspace_id, cwd)
1346                    .await
1347            }))
1348        } else {
1349            None
1350        }
1351    }
1352
1353    fn should_serialize(&self, _: &Self::Event) -> bool {
1354        !self.cwd_serialized
1355    }
1356
1357    fn deserialize(
1358        project: Entity<Project>,
1359        workspace: WeakEntity<Workspace>,
1360        workspace_id: workspace::WorkspaceId,
1361        item_id: workspace::ItemId,
1362        window: &mut Window,
1363        cx: &mut App,
1364    ) -> Task<anyhow::Result<Entity<Self>>> {
1365        window.spawn(cx, async move |cx| {
1366            let cwd = cx
1367                .update(|_window, cx| {
1368                    let from_db = TERMINAL_DB
1369                        .get_working_directory(item_id, workspace_id)
1370                        .log_err()
1371                        .flatten();
1372                    if from_db
1373                        .as_ref()
1374                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1375                    {
1376                        from_db
1377                    } else {
1378                        workspace
1379                            .upgrade()
1380                            .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1381                    }
1382                })
1383                .ok()
1384                .flatten();
1385
1386            let terminal = project
1387                .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
1388                .await?;
1389            cx.update(|window, cx| {
1390                cx.new(|cx| {
1391                    TerminalView::new(
1392                        terminal,
1393                        workspace,
1394                        Some(workspace_id),
1395                        project.downgrade(),
1396                        window,
1397                        cx,
1398                    )
1399                })
1400            })
1401        })
1402    }
1403}
1404
1405impl SearchableItem for TerminalView {
1406    type Match = RangeInclusive<Point>;
1407
1408    fn supported_options(&self) -> SearchOptions {
1409        SearchOptions {
1410            case: false,
1411            word: false,
1412            regex: true,
1413            replacement: false,
1414            selection: false,
1415            find_in_results: false,
1416        }
1417    }
1418
1419    /// Clear stored matches
1420    fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1421        self.terminal().update(cx, |term, _| term.matches.clear())
1422    }
1423
1424    /// Store matches returned from find_matches somewhere for rendering
1425    fn update_matches(
1426        &mut self,
1427        matches: &[Self::Match],
1428        _window: &mut Window,
1429        cx: &mut Context<Self>,
1430    ) {
1431        self.terminal()
1432            .update(cx, |term, _| term.matches = matches.to_vec())
1433    }
1434
1435    /// Returns the selection content to pre-load into this search
1436    fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1437        self.terminal()
1438            .read(cx)
1439            .last_content
1440            .selection_text
1441            .clone()
1442            .unwrap_or_default()
1443    }
1444
1445    /// Focus match at given index into the Vec of matches
1446    fn activate_match(
1447        &mut self,
1448        index: usize,
1449        _: &[Self::Match],
1450        _collapse: bool,
1451        _window: &mut Window,
1452        cx: &mut Context<Self>,
1453    ) {
1454        self.terminal()
1455            .update(cx, |term, _| term.activate_match(index));
1456        cx.notify();
1457    }
1458
1459    /// Add selections for all matches given.
1460    fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1461        self.terminal()
1462            .update(cx, |term, _| term.select_matches(matches));
1463        cx.notify();
1464    }
1465
1466    /// Get all of the matches for this query, should be done on the background
1467    fn find_matches(
1468        &mut self,
1469        query: Arc<SearchQuery>,
1470        _: &mut Window,
1471        cx: &mut Context<Self>,
1472    ) -> Task<Vec<Self::Match>> {
1473        if let Some(s) = regex_search_for_query(&query) {
1474            self.terminal()
1475                .update(cx, |term, cx| term.find_matches(s, cx))
1476        } else {
1477            Task::ready(vec![])
1478        }
1479    }
1480
1481    /// Reports back to the search toolbar what the active match should be (the selection)
1482    fn active_match_index(
1483        &mut self,
1484        direction: Direction,
1485        matches: &[Self::Match],
1486        _: &mut Window,
1487        cx: &mut Context<Self>,
1488    ) -> Option<usize> {
1489        // Selection head might have a value if there's a selection that isn't
1490        // associated with a match. Therefore, if there are no matches, we should
1491        // report None, no matter the state of the terminal
1492
1493        if !matches.is_empty() {
1494            if let Some(selection_head) = self.terminal().read(cx).selection_head {
1495                // If selection head is contained in a match. Return that match
1496                match direction {
1497                    Direction::Prev => {
1498                        // If no selection before selection head, return the first match
1499                        Some(
1500                            matches
1501                                .iter()
1502                                .enumerate()
1503                                .rev()
1504                                .find(|(_, search_match)| {
1505                                    search_match.contains(&selection_head)
1506                                        || search_match.start() < &selection_head
1507                                })
1508                                .map(|(ix, _)| ix)
1509                                .unwrap_or(0),
1510                        )
1511                    }
1512                    Direction::Next => {
1513                        // If no selection after selection head, return the last match
1514                        Some(
1515                            matches
1516                                .iter()
1517                                .enumerate()
1518                                .find(|(_, search_match)| {
1519                                    search_match.contains(&selection_head)
1520                                        || search_match.start() > &selection_head
1521                                })
1522                                .map(|(ix, _)| ix)
1523                                .unwrap_or(matches.len().saturating_sub(1)),
1524                        )
1525                    }
1526                }
1527            } else {
1528                // Matches found but no active selection, return the first last one (closest to cursor)
1529                Some(matches.len().saturating_sub(1))
1530            }
1531        } else {
1532            None
1533        }
1534    }
1535    fn replace(
1536        &mut self,
1537        _: &Self::Match,
1538        _: &SearchQuery,
1539        _window: &mut Window,
1540        _: &mut Context<Self>,
1541    ) {
1542        // Replacement is not supported in terminal view, so this is a no-op.
1543    }
1544}
1545
1546///Gets the working directory for the given workspace, respecting the user's settings.
1547/// None implies "~" on whichever machine we end up on.
1548pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1549    match &TerminalSettings::get_global(cx).working_directory {
1550        WorkingDirectory::CurrentProjectDirectory => workspace
1551            .project()
1552            .read(cx)
1553            .active_project_directory(cx)
1554            .as_deref()
1555            .map(Path::to_path_buf),
1556        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1557        WorkingDirectory::AlwaysHome => None,
1558        WorkingDirectory::Always { directory } => {
1559            shellexpand::full(&directory) //TODO handle this better
1560                .ok()
1561                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1562                .filter(|dir| dir.is_dir())
1563        }
1564    }
1565}
1566///Gets the first project's home directory, or the home directory
1567fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1568    let worktree = workspace.worktrees(cx).next()?.read(cx);
1569    if !worktree.root_entry()?.is_dir() {
1570        return None;
1571    }
1572    Some(worktree.abs_path().to_path_buf())
1573}
1574
1575#[cfg(test)]
1576mod tests {
1577    use super::*;
1578    use gpui::TestAppContext;
1579    use project::{Entry, Project, ProjectPath, Worktree};
1580    use std::path::Path;
1581    use util::rel_path::RelPath;
1582    use workspace::AppState;
1583
1584    // Working directory calculation tests
1585
1586    // No Worktrees in project -> home_dir()
1587    #[gpui::test]
1588    async fn no_worktree(cx: &mut TestAppContext) {
1589        let (project, workspace) = init_test(cx).await;
1590        cx.read(|cx| {
1591            let workspace = workspace.read(cx);
1592            let active_entry = project.read(cx).active_entry();
1593
1594            //Make sure environment is as expected
1595            assert!(active_entry.is_none());
1596            assert!(workspace.worktrees(cx).next().is_none());
1597
1598            let res = default_working_directory(workspace, cx);
1599            assert_eq!(res, None);
1600            let res = first_project_directory(workspace, cx);
1601            assert_eq!(res, None);
1602        });
1603    }
1604
1605    // No active entry, but a worktree, worktree is a file -> home_dir()
1606    #[gpui::test]
1607    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1608        let (project, workspace) = init_test(cx).await;
1609
1610        create_file_wt(project.clone(), "/root.txt", cx).await;
1611        cx.read(|cx| {
1612            let workspace = workspace.read(cx);
1613            let active_entry = project.read(cx).active_entry();
1614
1615            //Make sure environment is as expected
1616            assert!(active_entry.is_none());
1617            assert!(workspace.worktrees(cx).next().is_some());
1618
1619            let res = default_working_directory(workspace, cx);
1620            assert_eq!(res, None);
1621            let res = first_project_directory(workspace, cx);
1622            assert_eq!(res, None);
1623        });
1624    }
1625
1626    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1627    #[gpui::test]
1628    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1629        let (project, workspace) = init_test(cx).await;
1630
1631        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1632        cx.update(|cx| {
1633            let workspace = workspace.read(cx);
1634            let active_entry = project.read(cx).active_entry();
1635
1636            assert!(active_entry.is_none());
1637            assert!(workspace.worktrees(cx).next().is_some());
1638
1639            let res = default_working_directory(workspace, cx);
1640            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1641            let res = first_project_directory(workspace, cx);
1642            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1643        });
1644    }
1645
1646    // Active entry with a work tree, worktree is a file -> worktree_folder()
1647    #[gpui::test]
1648    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1649        let (project, workspace) = init_test(cx).await;
1650
1651        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1652        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1653        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1654
1655        cx.update(|cx| {
1656            let workspace = workspace.read(cx);
1657            let active_entry = project.read(cx).active_entry();
1658
1659            assert!(active_entry.is_some());
1660
1661            let res = default_working_directory(workspace, cx);
1662            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1663            let res = first_project_directory(workspace, cx);
1664            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1665        });
1666    }
1667
1668    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1669    #[gpui::test]
1670    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1671        let (project, workspace) = init_test(cx).await;
1672
1673        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1674        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1675        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1676
1677        cx.update(|cx| {
1678            let workspace = workspace.read(cx);
1679            let active_entry = project.read(cx).active_entry();
1680
1681            assert!(active_entry.is_some());
1682
1683            let res = default_working_directory(workspace, cx);
1684            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1685            let res = first_project_directory(workspace, cx);
1686            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1687        });
1688    }
1689
1690    /// Creates a worktree with 1 file: /root.txt
1691    pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
1692        let params = cx.update(AppState::test);
1693        cx.update(|cx| {
1694            theme::init(theme::LoadThemes::JustBase, cx);
1695        });
1696
1697        let project = Project::test(params.fs.clone(), [], cx).await;
1698        let workspace = cx
1699            .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
1700            .root(cx)
1701            .unwrap();
1702
1703        (project, workspace)
1704    }
1705
1706    /// Creates a worktree with 1 folder: /root{suffix}/
1707    async fn create_folder_wt(
1708        project: Entity<Project>,
1709        path: impl AsRef<Path>,
1710        cx: &mut TestAppContext,
1711    ) -> (Entity<Worktree>, Entry) {
1712        create_wt(project, true, path, cx).await
1713    }
1714
1715    /// Creates a worktree with 1 file: /root{suffix}.txt
1716    async fn create_file_wt(
1717        project: Entity<Project>,
1718        path: impl AsRef<Path>,
1719        cx: &mut TestAppContext,
1720    ) -> (Entity<Worktree>, Entry) {
1721        create_wt(project, false, path, cx).await
1722    }
1723
1724    async fn create_wt(
1725        project: Entity<Project>,
1726        is_dir: bool,
1727        path: impl AsRef<Path>,
1728        cx: &mut TestAppContext,
1729    ) -> (Entity<Worktree>, Entry) {
1730        let (wt, _) = project
1731            .update(cx, |project, cx| {
1732                project.find_or_create_worktree(path, true, cx)
1733            })
1734            .await
1735            .unwrap();
1736
1737        let entry = cx
1738            .update(|cx| {
1739                wt.update(cx, |wt, cx| {
1740                    wt.create_entry(RelPath::empty().into(), is_dir, None, cx)
1741                })
1742            })
1743            .await
1744            .unwrap()
1745            .into_included()
1746            .unwrap();
1747
1748        (wt, entry)
1749    }
1750
1751    pub fn insert_active_entry_for(
1752        wt: Entity<Worktree>,
1753        entry: Entry,
1754        project: Entity<Project>,
1755        cx: &mut TestAppContext,
1756    ) {
1757        cx.update(|cx| {
1758            let p = ProjectPath {
1759                worktree_id: wt.read(cx).id(),
1760                path: entry.path,
1761            };
1762            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1763        });
1764    }
1765}