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