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