terminal_view.rs

   1mod persistence;
   2pub mod terminal_element;
   3pub mod terminal_panel;
   4mod terminal_path_like_target;
   5pub mod terminal_scrollbar;
   6
   7use editor::{
   8    Editor, EditorSettings, actions::SelectAll, blink_manager::BlinkManager,
   9    ui_scrollbar_settings_from_raw,
  10};
  11use gpui::{
  12    Action, AnyElement, App, ClipboardEntry, DismissEvent, Entity, EventEmitter, ExternalPaths,
  13    FocusHandle, Focusable, Font, KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent,
  14    Pixels, Point, Render, ScrollWheelEvent, Styled, Subscription, Task, WeakEntity, actions,
  15    anchored, deferred, div,
  16};
  17use itertools::Itertools;
  18use menu;
  19use persistence::TerminalDb;
  20use project::{Project, ProjectEntryId, search::SearchQuery};
  21use schemars::JsonSchema;
  22use serde::Deserialize;
  23use settings::{Settings, SettingsStore, TerminalBlink, WorkingDirectory};
  24use std::{
  25    any::Any,
  26    cmp,
  27    ops::{Range, RangeInclusive},
  28    path::{Path, PathBuf},
  29    rc::Rc,
  30    sync::Arc,
  31    time::Duration,
  32};
  33use task::TaskId;
  34use terminal::{
  35    Clear, Copy, Event, HoveredWord, MaybeNavigationTarget, Paste, ScrollLineDown, ScrollLineUp,
  36    ScrollPageDown, ScrollPageUp, ScrollToBottom, ScrollToTop, ShowCharacterPalette, TaskState,
  37    TaskStatus, Terminal, TerminalBounds, ToggleViMode,
  38    alacritty_terminal::{
  39        index::Point as AlacPoint,
  40        term::{TermMode, point_to_viewport, search::RegexSearch},
  41    },
  42    terminal_settings::{CursorShape, TerminalSettings},
  43};
  44use terminal_element::TerminalElement;
  45use terminal_panel::TerminalPanel;
  46use terminal_path_like_target::{hover_path_like_target, open_path_like_target};
  47use terminal_scrollbar::TerminalScrollHandle;
  48use ui::{
  49    ContextMenu, Divider, ScrollAxes, Scrollbars, Tooltip, WithScrollbar,
  50    prelude::*,
  51    scrollbars::{self, ScrollbarVisibility},
  52};
  53use util::ResultExt;
  54use workspace::{
  55    CloseActiveItem, DraggedSelection, DraggedTab, NewCenterTerminal, NewTerminal, Pane,
  56    ToolbarItemLocation, Workspace, WorkspaceId, delete_unloaded_items,
  57    item::{
  58        HighlightedText, Item, ItemEvent, SerializableItem, TabContentParams, TabTooltipContent,
  59    },
  60    register_serializable_item,
  61    searchable::{
  62        Direction, SearchEvent, SearchOptions, SearchToken, SearchableItem, SearchableItemHandle,
  63    },
  64};
  65use zed_actions::{agent::AddSelectionToThread, assistant::InlineAssist};
  66
  67struct ImeState {
  68    marked_text: String,
  69}
  70
  71const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  72
  73/// Event to transmit the scroll from the element to the view
  74#[derive(Clone, Debug, PartialEq)]
  75pub struct ScrollTerminal(pub i32);
  76
  77/// Sends the specified text directly to the terminal.
  78#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
  79#[action(namespace = terminal)]
  80pub struct SendText(String);
  81
  82/// Sends a keystroke sequence to the terminal.
  83#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
  84#[action(namespace = terminal)]
  85pub struct SendKeystroke(String);
  86
  87actions!(
  88    terminal,
  89    [
  90        /// Reruns the last executed task in the terminal.
  91        RerunTask,
  92    ]
  93);
  94
  95/// Renames the terminal tab.
  96#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
  97#[action(namespace = terminal)]
  98pub struct RenameTerminal;
  99
 100pub fn init(cx: &mut App) {
 101    terminal_panel::init(cx);
 102
 103    register_serializable_item::<TerminalView>(cx);
 104
 105    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
 106        workspace.register_action(TerminalView::deploy);
 107    })
 108    .detach();
 109}
 110
 111pub struct BlockProperties {
 112    pub height: u8,
 113    pub render: Box<dyn Send + Fn(&mut BlockContext) -> AnyElement>,
 114}
 115
 116pub struct BlockContext<'a, 'b> {
 117    pub window: &'a mut Window,
 118    pub context: &'b mut App,
 119    pub dimensions: TerminalBounds,
 120}
 121
 122///A terminal view, maintains the PTY's file handles and communicates with the terminal
 123pub struct TerminalView {
 124    terminal: Entity<Terminal>,
 125    workspace: WeakEntity<Workspace>,
 126    project: WeakEntity<Project>,
 127    focus_handle: FocusHandle,
 128    //Currently using iTerm bell, show bell emoji in tab until input is received
 129    has_bell: bool,
 130    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 131    cursor_shape: CursorShape,
 132    blink_manager: Entity<BlinkManager>,
 133    mode: TerminalMode,
 134    blinking_terminal_enabled: bool,
 135    needs_serialize: bool,
 136    custom_title: Option<String>,
 137    hover: Option<HoverTarget>,
 138    hover_tooltip_update: Task<()>,
 139    workspace_id: Option<WorkspaceId>,
 140    show_breadcrumbs: bool,
 141    block_below_cursor: Option<Rc<BlockProperties>>,
 142    scroll_top: Pixels,
 143    scroll_handle: TerminalScrollHandle,
 144    ime_state: Option<ImeState>,
 145    self_handle: WeakEntity<Self>,
 146    rename_editor: Option<Entity<Editor>>,
 147    rename_editor_subscription: Option<Subscription>,
 148    _subscriptions: Vec<Subscription>,
 149    _terminal_subscriptions: Vec<Subscription>,
 150}
 151
 152#[derive(Default, Clone)]
 153pub enum TerminalMode {
 154    #[default]
 155    Standalone,
 156    Embedded {
 157        max_lines_when_unfocused: Option<usize>,
 158    },
 159}
 160
 161#[derive(Clone)]
 162pub enum ContentMode {
 163    Scrollable,
 164    Inline {
 165        displayed_lines: usize,
 166        total_lines: usize,
 167    },
 168}
 169
 170impl ContentMode {
 171    pub fn is_limited(&self) -> bool {
 172        match self {
 173            ContentMode::Scrollable => false,
 174            ContentMode::Inline {
 175                displayed_lines,
 176                total_lines,
 177            } => displayed_lines < total_lines,
 178        }
 179    }
 180
 181    pub fn is_scrollable(&self) -> bool {
 182        matches!(self, ContentMode::Scrollable)
 183    }
 184}
 185
 186#[derive(Debug)]
 187#[cfg_attr(test, derive(Clone, Eq, PartialEq))]
 188struct HoverTarget {
 189    tooltip: String,
 190    hovered_word: HoveredWord,
 191}
 192
 193impl EventEmitter<Event> for TerminalView {}
 194impl EventEmitter<ItemEvent> for TerminalView {}
 195impl EventEmitter<SearchEvent> for TerminalView {}
 196
 197impl Focusable for TerminalView {
 198    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 199        self.focus_handle.clone()
 200    }
 201}
 202
 203impl TerminalView {
 204    ///Create a new Terminal in the current working directory or the user's home directory
 205    pub fn deploy(
 206        workspace: &mut Workspace,
 207        action: &NewCenterTerminal,
 208        window: &mut Window,
 209        cx: &mut Context<Workspace>,
 210    ) {
 211        let local = action.local;
 212        let working_directory = default_working_directory(workspace, cx);
 213        TerminalPanel::add_center_terminal(workspace, window, cx, move |project, cx| {
 214            if local {
 215                project.create_local_terminal(cx)
 216            } else {
 217                project.create_terminal_shell(working_directory, cx)
 218            }
 219        })
 220        .detach_and_log_err(cx);
 221    }
 222
 223    pub fn new(
 224        terminal: Entity<Terminal>,
 225        workspace: WeakEntity<Workspace>,
 226        workspace_id: Option<WorkspaceId>,
 227        project: WeakEntity<Project>,
 228        window: &mut Window,
 229        cx: &mut Context<Self>,
 230    ) -> Self {
 231        let workspace_handle = workspace.clone();
 232        let terminal_subscriptions =
 233            subscribe_for_terminal_events(&terminal, workspace, window, cx);
 234
 235        let focus_handle = cx.focus_handle();
 236        let focus_in = cx.on_focus_in(&focus_handle, window, |terminal_view, window, cx| {
 237            terminal_view.focus_in(window, cx);
 238        });
 239        let focus_out = cx.on_focus_out(
 240            &focus_handle,
 241            window,
 242            |terminal_view, _event, window, cx| {
 243                terminal_view.focus_out(window, cx);
 244            },
 245        );
 246        let cursor_shape = TerminalSettings::get_global(cx).cursor_shape;
 247
 248        let scroll_handle = TerminalScrollHandle::new(terminal.read(cx));
 249
 250        let blink_manager = cx.new(|cx| {
 251            BlinkManager::new(
 252                CURSOR_BLINK_INTERVAL,
 253                |cx| {
 254                    !matches!(
 255                        TerminalSettings::get_global(cx).blinking,
 256                        TerminalBlink::Off
 257                    )
 258                },
 259                cx,
 260            )
 261        });
 262
 263        let subscriptions = vec![
 264            focus_in,
 265            focus_out,
 266            cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 267            cx.observe_global::<SettingsStore>(Self::settings_changed),
 268        ];
 269
 270        Self {
 271            terminal,
 272            workspace: workspace_handle,
 273            project,
 274            has_bell: false,
 275            focus_handle,
 276            context_menu: None,
 277            cursor_shape,
 278            blink_manager,
 279            blinking_terminal_enabled: false,
 280            hover: None,
 281            hover_tooltip_update: Task::ready(()),
 282            mode: TerminalMode::Standalone,
 283            workspace_id,
 284            show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
 285            block_below_cursor: None,
 286            scroll_top: Pixels::ZERO,
 287            scroll_handle,
 288            needs_serialize: false,
 289            custom_title: None,
 290            ime_state: None,
 291            self_handle: cx.entity().downgrade(),
 292            rename_editor: None,
 293            rename_editor_subscription: None,
 294            _subscriptions: subscriptions,
 295            _terminal_subscriptions: terminal_subscriptions,
 296        }
 297    }
 298
 299    /// Enable 'embedded' mode where the terminal displays the full content with an optional limit of lines.
 300    pub fn set_embedded_mode(
 301        &mut self,
 302        max_lines_when_unfocused: Option<usize>,
 303        cx: &mut Context<Self>,
 304    ) {
 305        self.mode = TerminalMode::Embedded {
 306            max_lines_when_unfocused,
 307        };
 308        cx.notify();
 309    }
 310
 311    const MAX_EMBEDDED_LINES: usize = 1_000;
 312
 313    /// Returns the current `ContentMode` depending on the set `TerminalMode` and the current number of lines
 314    ///
 315    /// Note: Even in embedded mode, the terminal will fallback to scrollable when its content exceeds `MAX_EMBEDDED_LINES`
 316    pub fn content_mode(&self, window: &Window, cx: &App) -> ContentMode {
 317        match &self.mode {
 318            TerminalMode::Standalone => ContentMode::Scrollable,
 319            TerminalMode::Embedded {
 320                max_lines_when_unfocused,
 321            } => {
 322                let total_lines = self.terminal.read(cx).total_lines();
 323
 324                if total_lines > Self::MAX_EMBEDDED_LINES {
 325                    ContentMode::Scrollable
 326                } else {
 327                    let mut displayed_lines = total_lines;
 328
 329                    if !self.focus_handle.is_focused(window)
 330                        && let Some(max_lines) = max_lines_when_unfocused
 331                    {
 332                        displayed_lines = displayed_lines.min(*max_lines)
 333                    }
 334
 335                    ContentMode::Inline {
 336                        displayed_lines,
 337                        total_lines,
 338                    }
 339                }
 340            }
 341        }
 342    }
 343
 344    /// Sets the marked (pre-edit) text from the IME.
 345    pub(crate) fn set_marked_text(&mut self, text: String, cx: &mut Context<Self>) {
 346        if text.is_empty() {
 347            return self.clear_marked_text(cx);
 348        }
 349        self.ime_state = Some(ImeState { marked_text: text });
 350        cx.notify();
 351    }
 352
 353    /// Gets the current marked range (UTF-16).
 354    pub(crate) fn marked_text_range(&self) -> Option<Range<usize>> {
 355        self.ime_state
 356            .as_ref()
 357            .map(|state| 0..state.marked_text.encode_utf16().count())
 358    }
 359
 360    /// Clears the marked (pre-edit) text state.
 361    pub(crate) fn clear_marked_text(&mut self, cx: &mut Context<Self>) {
 362        if self.ime_state.is_some() {
 363            self.ime_state = None;
 364            cx.notify();
 365        }
 366    }
 367
 368    /// Commits (sends) the given text to the PTY. Called by InputHandler::replace_text_in_range.
 369    pub(crate) fn commit_text(&mut self, text: &str, cx: &mut Context<Self>) {
 370        if !text.is_empty() {
 371            self.terminal.update(cx, |term, _| {
 372                term.input(text.to_string().into_bytes());
 373            });
 374        }
 375    }
 376
 377    pub(crate) fn terminal_bounds(&self, cx: &App) -> TerminalBounds {
 378        self.terminal.read(cx).last_content().terminal_bounds
 379    }
 380
 381    pub fn entity(&self) -> &Entity<Terminal> {
 382        &self.terminal
 383    }
 384
 385    pub fn has_bell(&self) -> bool {
 386        self.has_bell
 387    }
 388
 389    pub fn custom_title(&self) -> Option<&str> {
 390        self.custom_title.as_deref()
 391    }
 392
 393    pub fn set_custom_title(&mut self, label: Option<String>, cx: &mut Context<Self>) {
 394        let label = label.filter(|l| !l.trim().is_empty());
 395        if self.custom_title != label {
 396            self.custom_title = label;
 397            self.needs_serialize = true;
 398            cx.emit(ItemEvent::UpdateTab);
 399            cx.notify();
 400        }
 401    }
 402
 403    pub fn is_renaming(&self) -> bool {
 404        self.rename_editor.is_some()
 405    }
 406
 407    pub fn rename_editor_is_focused(&self, window: &Window, cx: &App) -> bool {
 408        self.rename_editor
 409            .as_ref()
 410            .is_some_and(|editor| editor.focus_handle(cx).is_focused(window))
 411    }
 412
 413    fn finish_renaming(&mut self, save: bool, window: &mut Window, cx: &mut Context<Self>) {
 414        let Some(editor) = self.rename_editor.take() else {
 415            return;
 416        };
 417        self.rename_editor_subscription = None;
 418        if save {
 419            let new_label = editor.read(cx).text(cx).trim().to_string();
 420            let label = if new_label.is_empty() {
 421                None
 422            } else {
 423                // Only set custom_title if the text differs from the terminal's dynamic title.
 424                // This prevents subtle layout changes when clicking away without making changes.
 425                let terminal_title = self.terminal.read(cx).title(true);
 426                if new_label == terminal_title {
 427                    None
 428                } else {
 429                    Some(new_label)
 430                }
 431            };
 432            self.set_custom_title(label, cx);
 433        }
 434        cx.notify();
 435        self.focus_handle.focus(window, cx);
 436    }
 437
 438    pub fn rename_terminal(
 439        &mut self,
 440        _: &RenameTerminal,
 441        window: &mut Window,
 442        cx: &mut Context<Self>,
 443    ) {
 444        if self.terminal.read(cx).task().is_some() {
 445            return;
 446        }
 447
 448        let current_label = self
 449            .custom_title
 450            .clone()
 451            .unwrap_or_else(|| self.terminal.read(cx).title(true));
 452
 453        let rename_editor = cx.new(|cx| Editor::single_line(window, cx));
 454        let rename_editor_subscription = cx.subscribe_in(&rename_editor, window, {
 455            let rename_editor = rename_editor.clone();
 456            move |_this, _, event, window, cx| {
 457                if let editor::EditorEvent::Blurred = event {
 458                    // Defer to let focus settle (avoids canceling during double-click).
 459                    let rename_editor = rename_editor.clone();
 460                    cx.defer_in(window, move |this, window, cx| {
 461                        let still_current = this
 462                            .rename_editor
 463                            .as_ref()
 464                            .is_some_and(|current| current == &rename_editor);
 465                        if still_current && !rename_editor.focus_handle(cx).is_focused(window) {
 466                            this.finish_renaming(false, window, cx);
 467                        }
 468                    });
 469                }
 470            }
 471        });
 472
 473        self.rename_editor = Some(rename_editor.clone());
 474        self.rename_editor_subscription = Some(rename_editor_subscription);
 475
 476        rename_editor.update(cx, |editor, cx| {
 477            editor.set_text(current_label, window, cx);
 478            editor.select_all(&SelectAll, window, cx);
 479            editor.focus_handle(cx).focus(window, cx);
 480        });
 481        cx.notify();
 482    }
 483
 484    pub fn clear_bell(&mut self, cx: &mut Context<TerminalView>) {
 485        self.has_bell = false;
 486        cx.emit(Event::Wakeup);
 487    }
 488
 489    pub fn deploy_context_menu(
 490        &mut self,
 491        position: Point<Pixels>,
 492        window: &mut Window,
 493        cx: &mut Context<Self>,
 494    ) {
 495        let assistant_enabled = self
 496            .workspace
 497            .upgrade()
 498            .and_then(|workspace| workspace.read(cx).panel::<TerminalPanel>(cx))
 499            .is_some_and(|terminal_panel| terminal_panel.read(cx).assistant_enabled());
 500        let has_selection = self
 501            .terminal
 502            .read(cx)
 503            .last_content
 504            .selection_text
 505            .as_ref()
 506            .is_some_and(|text| !text.is_empty());
 507        let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
 508            menu.context(self.focus_handle.clone())
 509                .action("New Terminal", Box::new(NewTerminal::default()))
 510                .separator()
 511                .action("Copy", Box::new(Copy))
 512                .action("Paste", Box::new(Paste))
 513                .action("Select All", Box::new(SelectAll))
 514                .action("Clear", Box::new(Clear))
 515                .when(assistant_enabled, |menu| {
 516                    menu.separator()
 517                        .action("Inline Assist", Box::new(InlineAssist::default()))
 518                        .when(has_selection, |menu| {
 519                            menu.action("Add to Agent Thread", Box::new(AddSelectionToThread))
 520                        })
 521                })
 522                .separator()
 523                .action(
 524                    "Close Terminal Tab",
 525                    Box::new(CloseActiveItem {
 526                        save_intent: None,
 527                        close_pinned: true,
 528                    }),
 529                )
 530        });
 531
 532        window.focus(&context_menu.focus_handle(cx), cx);
 533        let subscription = cx.subscribe_in(
 534            &context_menu,
 535            window,
 536            |this, _, _: &DismissEvent, window, cx| {
 537                if this.context_menu.as_ref().is_some_and(|context_menu| {
 538                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
 539                }) {
 540                    cx.focus_self(window);
 541                }
 542                this.context_menu.take();
 543                cx.notify();
 544            },
 545        );
 546
 547        self.context_menu = Some((context_menu, position, subscription));
 548    }
 549
 550    fn settings_changed(&mut self, cx: &mut Context<Self>) {
 551        let settings = TerminalSettings::get_global(cx);
 552        let breadcrumb_visibility_changed = self.show_breadcrumbs != settings.toolbar.breadcrumbs;
 553        self.show_breadcrumbs = settings.toolbar.breadcrumbs;
 554
 555        let should_blink = match settings.blinking {
 556            TerminalBlink::Off => false,
 557            TerminalBlink::On => true,
 558            TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
 559        };
 560        let new_cursor_shape = settings.cursor_shape;
 561        let old_cursor_shape = self.cursor_shape;
 562        if old_cursor_shape != new_cursor_shape {
 563            self.cursor_shape = new_cursor_shape;
 564            self.terminal.update(cx, |term, _| {
 565                term.set_cursor_shape(self.cursor_shape);
 566            });
 567        }
 568
 569        self.blink_manager.update(
 570            cx,
 571            if should_blink {
 572                BlinkManager::enable
 573            } else {
 574                BlinkManager::disable
 575            },
 576        );
 577
 578        if breadcrumb_visibility_changed {
 579            cx.emit(ItemEvent::UpdateBreadcrumbs);
 580        }
 581        cx.notify();
 582    }
 583
 584    fn show_character_palette(
 585        &mut self,
 586        _: &ShowCharacterPalette,
 587        window: &mut Window,
 588        cx: &mut Context<Self>,
 589    ) {
 590        if self
 591            .terminal
 592            .read(cx)
 593            .last_content
 594            .mode
 595            .contains(TermMode::ALT_SCREEN)
 596        {
 597            self.terminal.update(cx, |term, cx| {
 598                term.try_keystroke(
 599                    &Keystroke::parse("ctrl-cmd-space").unwrap(),
 600                    TerminalSettings::get_global(cx).option_as_meta,
 601                )
 602            });
 603        } else {
 604            window.show_character_palette();
 605        }
 606    }
 607
 608    fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
 609        self.terminal.update(cx, |term, _| term.select_all());
 610        cx.notify();
 611    }
 612
 613    fn rerun_task(&mut self, _: &RerunTask, window: &mut Window, cx: &mut Context<Self>) {
 614        let task = self
 615            .terminal
 616            .read(cx)
 617            .task()
 618            .map(|task| terminal_rerun_override(&task.spawned_task.id))
 619            .unwrap_or_default();
 620        window.dispatch_action(Box::new(task), cx);
 621    }
 622
 623    fn clear(&mut self, _: &Clear, _: &mut Window, cx: &mut Context<Self>) {
 624        self.scroll_top = px(0.);
 625        self.terminal.update(cx, |term, _| term.clear());
 626        cx.notify();
 627    }
 628
 629    fn max_scroll_top(&self, cx: &App) -> Pixels {
 630        let terminal = self.terminal.read(cx);
 631
 632        let Some(block) = self.block_below_cursor.as_ref() else {
 633            return Pixels::ZERO;
 634        };
 635
 636        let line_height = terminal.last_content().terminal_bounds.line_height;
 637        let viewport_lines = terminal.viewport_lines();
 638        let cursor = point_to_viewport(
 639            terminal.last_content.display_offset,
 640            terminal.last_content.cursor.point,
 641        )
 642        .unwrap_or_default();
 643        let max_scroll_top_in_lines =
 644            (block.height as usize).saturating_sub(viewport_lines.saturating_sub(cursor.line + 1));
 645
 646        max_scroll_top_in_lines as f32 * line_height
 647    }
 648
 649    fn scroll_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
 650        let terminal_content = self.terminal.read(cx).last_content();
 651
 652        if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
 653            let line_height = terminal_content.terminal_bounds.line_height;
 654            let y_delta = event.delta.pixel_delta(line_height).y;
 655            if y_delta < Pixels::ZERO || self.scroll_top > Pixels::ZERO {
 656                self.scroll_top = cmp::max(
 657                    Pixels::ZERO,
 658                    cmp::min(self.scroll_top - y_delta, self.max_scroll_top(cx)),
 659                );
 660                cx.notify();
 661                return;
 662            }
 663        }
 664        self.terminal.update(cx, |term, cx| {
 665            term.scroll_wheel(
 666                event,
 667                TerminalSettings::get_global(cx).scroll_multiplier.max(0.01),
 668            )
 669        });
 670    }
 671
 672    fn scroll_line_up(&mut self, _: &ScrollLineUp, _: &mut Window, cx: &mut Context<Self>) {
 673        let terminal_content = self.terminal.read(cx).last_content();
 674        if self.block_below_cursor.is_some()
 675            && terminal_content.display_offset == 0
 676            && self.scroll_top > Pixels::ZERO
 677        {
 678            let line_height = terminal_content.terminal_bounds.line_height;
 679            self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
 680            return;
 681        }
 682
 683        self.terminal.update(cx, |term, _| term.scroll_line_up());
 684        cx.notify();
 685    }
 686
 687    fn scroll_line_down(&mut self, _: &ScrollLineDown, _: &mut Window, cx: &mut Context<Self>) {
 688        let terminal_content = self.terminal.read(cx).last_content();
 689        if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
 690            let max_scroll_top = self.max_scroll_top(cx);
 691            if self.scroll_top < max_scroll_top {
 692                let line_height = terminal_content.terminal_bounds.line_height;
 693                self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
 694            }
 695            return;
 696        }
 697
 698        self.terminal.update(cx, |term, _| term.scroll_line_down());
 699        cx.notify();
 700    }
 701
 702    fn scroll_page_up(&mut self, _: &ScrollPageUp, _: &mut Window, cx: &mut Context<Self>) {
 703        if self.scroll_top == Pixels::ZERO {
 704            self.terminal.update(cx, |term, _| term.scroll_page_up());
 705        } else {
 706            let line_height = self
 707                .terminal
 708                .read(cx)
 709                .last_content
 710                .terminal_bounds
 711                .line_height();
 712            let visible_block_lines = (self.scroll_top / line_height) as usize;
 713            let viewport_lines = self.terminal.read(cx).viewport_lines();
 714            let visible_content_lines = viewport_lines - visible_block_lines;
 715
 716            if visible_block_lines >= viewport_lines {
 717                self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
 718            } else {
 719                self.scroll_top = px(0.);
 720                self.terminal
 721                    .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
 722            }
 723        }
 724        cx.notify();
 725    }
 726
 727    fn scroll_page_down(&mut self, _: &ScrollPageDown, _: &mut Window, cx: &mut Context<Self>) {
 728        self.terminal.update(cx, |term, _| term.scroll_page_down());
 729        let terminal = self.terminal.read(cx);
 730        if terminal.last_content().display_offset < terminal.viewport_lines() {
 731            self.scroll_top = self.max_scroll_top(cx);
 732        }
 733        cx.notify();
 734    }
 735
 736    fn scroll_to_top(&mut self, _: &ScrollToTop, _: &mut Window, cx: &mut Context<Self>) {
 737        self.terminal.update(cx, |term, _| term.scroll_to_top());
 738        cx.notify();
 739    }
 740
 741    fn scroll_to_bottom(&mut self, _: &ScrollToBottom, _: &mut Window, cx: &mut Context<Self>) {
 742        self.terminal.update(cx, |term, _| term.scroll_to_bottom());
 743        if self.block_below_cursor.is_some() {
 744            self.scroll_top = self.max_scroll_top(cx);
 745        }
 746        cx.notify();
 747    }
 748
 749    fn toggle_vi_mode(&mut self, _: &ToggleViMode, _: &mut Window, cx: &mut Context<Self>) {
 750        self.terminal.update(cx, |term, _| term.toggle_vi_mode());
 751        cx.notify();
 752    }
 753
 754    pub fn should_show_cursor(&self, focused: bool, cx: &mut Context<Self>) -> bool {
 755        // Hide cursor when in embedded mode and not focused (read-only output like Agent panel)
 756        if let TerminalMode::Embedded { .. } = &self.mode {
 757            if !focused {
 758                return false;
 759            }
 760        }
 761
 762        // For Standalone mode: always show cursor when not focused or in special modes
 763        if !focused
 764            || self
 765                .terminal
 766                .read(cx)
 767                .last_content
 768                .mode
 769                .contains(TermMode::ALT_SCREEN)
 770        {
 771            return true;
 772        }
 773
 774        // When focused, check blinking settings and blink manager state
 775        match TerminalSettings::get_global(cx).blinking {
 776            TerminalBlink::Off => true,
 777            TerminalBlink::TerminalControlled => {
 778                !self.blinking_terminal_enabled || self.blink_manager.read(cx).visible()
 779            }
 780            TerminalBlink::On => self.blink_manager.read(cx).visible(),
 781        }
 782    }
 783
 784    pub fn pause_cursor_blinking(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
 785        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 786    }
 787
 788    pub fn terminal(&self) -> &Entity<Terminal> {
 789        &self.terminal
 790    }
 791
 792    pub fn set_block_below_cursor(
 793        &mut self,
 794        block: BlockProperties,
 795        window: &mut Window,
 796        cx: &mut Context<Self>,
 797    ) {
 798        self.block_below_cursor = Some(Rc::new(block));
 799        self.scroll_to_bottom(&ScrollToBottom, window, cx);
 800        cx.notify();
 801    }
 802
 803    pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
 804        self.block_below_cursor = None;
 805        self.scroll_top = Pixels::ZERO;
 806        cx.notify();
 807    }
 808
 809    ///Attempt to paste the clipboard into the terminal
 810    fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 811        self.terminal.update(cx, |term, _| term.copy(None));
 812        cx.notify();
 813    }
 814
 815    ///Attempt to paste the clipboard into the terminal
 816    fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
 817        let Some(clipboard) = cx.read_from_clipboard() else {
 818            return;
 819        };
 820
 821        match clipboard.entries().first() {
 822            Some(ClipboardEntry::Image(image)) if !image.bytes.is_empty() => {
 823                self.forward_ctrl_v(cx);
 824            }
 825            _ => {
 826                if let Some(text) = clipboard.text() {
 827                    self.terminal
 828                        .update(cx, |terminal, _cx| terminal.paste(&text));
 829                }
 830            }
 831        }
 832    }
 833
 834    /// Emits a raw Ctrl+V so TUI agents can read the OS clipboard directly
 835    /// and attach images using their native workflows.
 836    fn forward_ctrl_v(&self, cx: &mut Context<Self>) {
 837        self.terminal.update(cx, |term, _| {
 838            term.input(vec![0x16]);
 839        });
 840    }
 841
 842    fn add_paths_to_terminal(&self, paths: &[PathBuf], window: &mut Window, cx: &mut App) {
 843        let mut text = paths.iter().map(|path| format!(" {path:?}")).join("");
 844        text.push(' ');
 845        window.focus(&self.focus_handle(cx), cx);
 846        self.terminal.update(cx, |terminal, _| {
 847            terminal.paste(&text);
 848        });
 849    }
 850
 851    fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
 852        self.clear_bell(cx);
 853        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 854        self.terminal.update(cx, |term, _| {
 855            term.input(text.0.to_string().into_bytes());
 856        });
 857    }
 858
 859    fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
 860        if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
 861            self.clear_bell(cx);
 862            self.blink_manager.update(cx, BlinkManager::pause_blinking);
 863            self.process_keystroke(&keystroke, cx);
 864        }
 865    }
 866
 867    fn dispatch_context(&self, cx: &App) -> KeyContext {
 868        let mut dispatch_context = KeyContext::new_with_defaults();
 869        dispatch_context.add("Terminal");
 870
 871        if self.terminal.read(cx).vi_mode_enabled() {
 872            dispatch_context.add("vi_mode");
 873        }
 874
 875        let mode = self.terminal.read(cx).last_content.mode;
 876        dispatch_context.set(
 877            "screen",
 878            if mode.contains(TermMode::ALT_SCREEN) {
 879                "alt"
 880            } else {
 881                "normal"
 882            },
 883        );
 884
 885        if mode.contains(TermMode::APP_CURSOR) {
 886            dispatch_context.add("DECCKM");
 887        }
 888        if mode.contains(TermMode::APP_KEYPAD) {
 889            dispatch_context.add("DECPAM");
 890        } else {
 891            dispatch_context.add("DECPNM");
 892        }
 893        if mode.contains(TermMode::SHOW_CURSOR) {
 894            dispatch_context.add("DECTCEM");
 895        }
 896        if mode.contains(TermMode::LINE_WRAP) {
 897            dispatch_context.add("DECAWM");
 898        }
 899        if mode.contains(TermMode::ORIGIN) {
 900            dispatch_context.add("DECOM");
 901        }
 902        if mode.contains(TermMode::INSERT) {
 903            dispatch_context.add("IRM");
 904        }
 905        //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 906        if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 907            dispatch_context.add("LNM");
 908        }
 909        if mode.contains(TermMode::FOCUS_IN_OUT) {
 910            dispatch_context.add("report_focus");
 911        }
 912        if mode.contains(TermMode::ALTERNATE_SCROLL) {
 913            dispatch_context.add("alternate_scroll");
 914        }
 915        if mode.contains(TermMode::BRACKETED_PASTE) {
 916            dispatch_context.add("bracketed_paste");
 917        }
 918        if mode.intersects(TermMode::MOUSE_MODE) {
 919            dispatch_context.add("any_mouse_reporting");
 920        }
 921        {
 922            let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 923                "click"
 924            } else if mode.contains(TermMode::MOUSE_DRAG) {
 925                "drag"
 926            } else if mode.contains(TermMode::MOUSE_MOTION) {
 927                "motion"
 928            } else {
 929                "off"
 930            };
 931            dispatch_context.set("mouse_reporting", mouse_reporting);
 932        }
 933        {
 934            let format = if mode.contains(TermMode::SGR_MOUSE) {
 935                "sgr"
 936            } else if mode.contains(TermMode::UTF8_MOUSE) {
 937                "utf8"
 938            } else {
 939                "normal"
 940            };
 941            dispatch_context.set("mouse_format", format);
 942        };
 943
 944        if self.terminal.read(cx).last_content.selection.is_some() {
 945            dispatch_context.add("selection");
 946        }
 947
 948        dispatch_context
 949    }
 950
 951    fn set_terminal(
 952        &mut self,
 953        terminal: Entity<Terminal>,
 954        window: &mut Window,
 955        cx: &mut Context<TerminalView>,
 956    ) {
 957        self._terminal_subscriptions =
 958            subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
 959        self.terminal = terminal;
 960    }
 961
 962    fn rerun_button(task: &TaskState) -> Option<IconButton> {
 963        if !task.spawned_task.show_rerun {
 964            return None;
 965        }
 966
 967        let task_id = task.spawned_task.id.clone();
 968        Some(
 969            IconButton::new("rerun-icon", IconName::Rerun)
 970                .icon_size(IconSize::Small)
 971                .size(ButtonSize::Compact)
 972                .icon_color(Color::Default)
 973                .shape(ui::IconButtonShape::Square)
 974                .tooltip(move |_window, cx| Tooltip::for_action("Rerun task", &RerunTask, cx))
 975                .on_click(move |_, window, cx| {
 976                    window.dispatch_action(Box::new(terminal_rerun_override(&task_id)), cx);
 977                }),
 978        )
 979    }
 980}
 981
 982fn terminal_rerun_override(task: &TaskId) -> zed_actions::Rerun {
 983    zed_actions::Rerun {
 984        task_id: Some(task.0.clone()),
 985        allow_concurrent_runs: Some(true),
 986        use_new_terminal: Some(false),
 987        reevaluate_context: false,
 988    }
 989}
 990
 991fn subscribe_for_terminal_events(
 992    terminal: &Entity<Terminal>,
 993    workspace: WeakEntity<Workspace>,
 994    window: &mut Window,
 995    cx: &mut Context<TerminalView>,
 996) -> Vec<Subscription> {
 997    let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
 998    let mut previous_cwd = None;
 999    let terminal_events_subscription = cx.subscribe_in(
1000        terminal,
1001        window,
1002        move |terminal_view, terminal, event, window, cx| {
1003            let current_cwd = terminal.read(cx).working_directory();
1004            if current_cwd != previous_cwd {
1005                previous_cwd = current_cwd;
1006                terminal_view.needs_serialize = true;
1007            }
1008
1009            match event {
1010                Event::Wakeup => {
1011                    cx.notify();
1012                    cx.emit(Event::Wakeup);
1013                    cx.emit(ItemEvent::UpdateTab);
1014                    cx.emit(SearchEvent::MatchesInvalidated);
1015                }
1016
1017                Event::Bell => {
1018                    terminal_view.has_bell = true;
1019                    cx.emit(Event::Wakeup);
1020                }
1021
1022                Event::BlinkChanged(blinking) => {
1023                    terminal_view.blinking_terminal_enabled = *blinking;
1024
1025                    // If in terminal-controlled mode and focused, update blink manager
1026                    if matches!(
1027                        TerminalSettings::get_global(cx).blinking,
1028                        TerminalBlink::TerminalControlled
1029                    ) && terminal_view.focus_handle.is_focused(window)
1030                    {
1031                        terminal_view.blink_manager.update(cx, |manager, cx| {
1032                            if *blinking {
1033                                manager.enable(cx);
1034                            } else {
1035                                manager.disable(cx);
1036                            }
1037                        });
1038                    }
1039                }
1040
1041                Event::TitleChanged => {
1042                    cx.emit(ItemEvent::UpdateTab);
1043                }
1044
1045                Event::NewNavigationTarget(maybe_navigation_target) => {
1046                    match maybe_navigation_target
1047                        .as_ref()
1048                        .zip(terminal.read(cx).last_content.last_hovered_word.as_ref())
1049                    {
1050                        Some((MaybeNavigationTarget::Url(url), hovered_word)) => {
1051                            if Some(hovered_word)
1052                                != terminal_view
1053                                    .hover
1054                                    .as_ref()
1055                                    .map(|hover| &hover.hovered_word)
1056                            {
1057                                terminal_view.hover = Some(HoverTarget {
1058                                    tooltip: url.clone(),
1059                                    hovered_word: hovered_word.clone(),
1060                                });
1061                                terminal_view.hover_tooltip_update = Task::ready(());
1062                                cx.notify();
1063                            }
1064                        }
1065                        Some((MaybeNavigationTarget::PathLike(path_like_target), hovered_word)) => {
1066                            if Some(hovered_word)
1067                                != terminal_view
1068                                    .hover
1069                                    .as_ref()
1070                                    .map(|hover| &hover.hovered_word)
1071                            {
1072                                terminal_view.hover = None;
1073                                terminal_view.hover_tooltip_update = hover_path_like_target(
1074                                    &workspace,
1075                                    hovered_word.clone(),
1076                                    path_like_target,
1077                                    cx,
1078                                );
1079                                cx.notify();
1080                            }
1081                        }
1082                        None => {
1083                            terminal_view.hover = None;
1084                            terminal_view.hover_tooltip_update = Task::ready(());
1085                            cx.notify();
1086                        }
1087                    }
1088                }
1089
1090                Event::Open(maybe_navigation_target) => match maybe_navigation_target {
1091                    MaybeNavigationTarget::Url(url) => cx.open_url(url),
1092                    MaybeNavigationTarget::PathLike(path_like_target) => open_path_like_target(
1093                        &workspace,
1094                        terminal_view,
1095                        path_like_target,
1096                        window,
1097                        cx,
1098                    ),
1099                },
1100                Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
1101                Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
1102                Event::SelectionsChanged => {
1103                    window.invalidate_character_coordinates();
1104                    cx.emit(SearchEvent::ActiveMatchChanged)
1105                }
1106            }
1107        },
1108    );
1109    vec![terminal_subscription, terminal_events_subscription]
1110}
1111
1112fn regex_search_for_query(query: &SearchQuery) -> Option<RegexSearch> {
1113    let str = query.as_str();
1114    if query.is_regex() {
1115        if str == "." {
1116            return None;
1117        }
1118        RegexSearch::new(str).ok()
1119    } else {
1120        RegexSearch::new(&regex::escape(str)).ok()
1121    }
1122}
1123
1124#[derive(Default)]
1125struct TerminalScrollbarSettingsWrapper;
1126
1127impl ScrollbarVisibility for TerminalScrollbarSettingsWrapper {
1128    fn visibility(&self, cx: &App) -> scrollbars::ShowScrollbar {
1129        TerminalSettings::get_global(cx)
1130            .scrollbar
1131            .show
1132            .map(ui_scrollbar_settings_from_raw)
1133            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
1134    }
1135}
1136
1137impl TerminalView {
1138    /// Attempts to process a keystroke in the terminal. Returns true if handled.
1139    ///
1140    /// In vi mode, explicitly triggers a re-render because vi navigation (like j/k)
1141    /// updates the cursor locally without sending data to the shell, so there's no
1142    /// shell output to automatically trigger a re-render.
1143    fn process_keystroke(&mut self, keystroke: &Keystroke, cx: &mut Context<Self>) -> bool {
1144        let (handled, vi_mode_enabled) = self.terminal.update(cx, |term, cx| {
1145            (
1146                term.try_keystroke(keystroke, TerminalSettings::get_global(cx).option_as_meta),
1147                term.vi_mode_enabled(),
1148            )
1149        });
1150
1151        if handled && vi_mode_enabled {
1152            cx.notify();
1153        }
1154
1155        handled
1156    }
1157
1158    fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1159        self.clear_bell(cx);
1160        self.pause_cursor_blinking(window, cx);
1161
1162        if self.process_keystroke(&event.keystroke, cx) {
1163            cx.stop_propagation();
1164        }
1165    }
1166
1167    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1168        self.terminal.update(cx, |terminal, _| {
1169            terminal.set_cursor_shape(self.cursor_shape);
1170            terminal.focus_in();
1171        });
1172
1173        let should_blink = match TerminalSettings::get_global(cx).blinking {
1174            TerminalBlink::Off => false,
1175            TerminalBlink::On => true,
1176            TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
1177        };
1178
1179        if should_blink {
1180            self.blink_manager.update(cx, BlinkManager::enable);
1181        }
1182
1183        window.invalidate_character_coordinates();
1184        cx.notify();
1185    }
1186
1187    fn focus_out(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1188        self.blink_manager.update(cx, BlinkManager::disable);
1189        self.terminal.update(cx, |terminal, _| {
1190            terminal.focus_out();
1191            terminal.set_cursor_shape(CursorShape::Hollow);
1192        });
1193        cx.notify();
1194    }
1195}
1196
1197impl Render for TerminalView {
1198    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1199        // TODO: this should be moved out of render
1200        self.scroll_handle.update(self.terminal.read(cx));
1201
1202        if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
1203            self.terminal.update(cx, |term, _| {
1204                let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
1205                match delta.cmp(&0) {
1206                    cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
1207                    cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
1208                    cmp::Ordering::Equal => {}
1209                }
1210            });
1211        }
1212
1213        let terminal_handle = self.terminal.clone();
1214        let terminal_view_handle = cx.entity();
1215
1216        let focused = self.focus_handle.is_focused(window);
1217
1218        div()
1219            .id("terminal-view")
1220            .size_full()
1221            .relative()
1222            .track_focus(&self.focus_handle(cx))
1223            .key_context(self.dispatch_context(cx))
1224            .on_action(cx.listener(TerminalView::send_text))
1225            .on_action(cx.listener(TerminalView::send_keystroke))
1226            .on_action(cx.listener(TerminalView::copy))
1227            .on_action(cx.listener(TerminalView::paste))
1228            .on_action(cx.listener(TerminalView::clear))
1229            .on_action(cx.listener(TerminalView::scroll_line_up))
1230            .on_action(cx.listener(TerminalView::scroll_line_down))
1231            .on_action(cx.listener(TerminalView::scroll_page_up))
1232            .on_action(cx.listener(TerminalView::scroll_page_down))
1233            .on_action(cx.listener(TerminalView::scroll_to_top))
1234            .on_action(cx.listener(TerminalView::scroll_to_bottom))
1235            .on_action(cx.listener(TerminalView::toggle_vi_mode))
1236            .on_action(cx.listener(TerminalView::show_character_palette))
1237            .on_action(cx.listener(TerminalView::select_all))
1238            .on_action(cx.listener(TerminalView::rerun_task))
1239            .on_action(cx.listener(TerminalView::rename_terminal))
1240            .on_key_down(cx.listener(Self::key_down))
1241            .on_mouse_down(
1242                MouseButton::Right,
1243                cx.listener(|this, event: &MouseDownEvent, window, cx| {
1244                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1245                        if this.terminal.read(cx).last_content.selection.is_none() {
1246                            this.terminal.update(cx, |terminal, _| {
1247                                terminal.select_word_at_event_position(event);
1248                            });
1249                        };
1250                        this.deploy_context_menu(event.position, window, cx);
1251                        cx.notify();
1252                    }
1253                }),
1254            )
1255            .child(
1256                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1257                div()
1258                    .id("terminal-view-container")
1259                    .size_full()
1260                    .bg(cx.theme().colors().editor_background)
1261                    .child(TerminalElement::new(
1262                        terminal_handle,
1263                        terminal_view_handle,
1264                        self.workspace.clone(),
1265                        self.focus_handle.clone(),
1266                        focused,
1267                        self.should_show_cursor(focused, cx),
1268                        self.block_below_cursor.clone(),
1269                        self.mode.clone(),
1270                    ))
1271                    .when(self.content_mode(window, cx).is_scrollable(), |div| {
1272                        div.custom_scrollbars(
1273                            Scrollbars::for_settings::<TerminalScrollbarSettingsWrapper>()
1274                                .show_along(ScrollAxes::Vertical)
1275                                .with_track_along(
1276                                    ScrollAxes::Vertical,
1277                                    cx.theme().colors().editor_background,
1278                                )
1279                                .tracked_scroll_handle(&self.scroll_handle),
1280                            window,
1281                            cx,
1282                        )
1283                    }),
1284            )
1285            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1286                deferred(
1287                    anchored()
1288                        .position(*position)
1289                        .anchor(gpui::Corner::TopLeft)
1290                        .child(menu.clone()),
1291                )
1292                .with_priority(1)
1293            }))
1294    }
1295}
1296
1297impl Item for TerminalView {
1298    type Event = ItemEvent;
1299
1300    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1301        Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
1302            let terminal = self.terminal().read(cx);
1303            let title = terminal.title(false);
1304            let pid = terminal.pid_getter()?.fallback_pid();
1305
1306            move |_, _| {
1307                v_flex()
1308                    .gap_1()
1309                    .child(Label::new(title.clone()))
1310                    .child(h_flex().flex_grow().child(Divider::horizontal()))
1311                    .child(
1312                        Label::new(format!("Process ID (PID): {}", pid))
1313                            .color(Color::Muted)
1314                            .size(LabelSize::Small),
1315                    )
1316                    .into_any_element()
1317            }
1318        }))))
1319    }
1320
1321    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1322        let terminal = self.terminal().read(cx);
1323        let title = self
1324            .custom_title
1325            .as_ref()
1326            .filter(|title| !title.trim().is_empty())
1327            .cloned()
1328            .unwrap_or_else(|| terminal.title(true));
1329
1330        let (icon, icon_color, rerun_button) = match terminal.task() {
1331            Some(terminal_task) => match &terminal_task.status {
1332                TaskStatus::Running => (
1333                    IconName::PlayFilled,
1334                    Color::Disabled,
1335                    TerminalView::rerun_button(terminal_task),
1336                ),
1337                TaskStatus::Unknown => (
1338                    IconName::Warning,
1339                    Color::Warning,
1340                    TerminalView::rerun_button(terminal_task),
1341                ),
1342                TaskStatus::Completed { success } => {
1343                    let rerun_button = TerminalView::rerun_button(terminal_task);
1344
1345                    if *success {
1346                        (IconName::Check, Color::Success, rerun_button)
1347                    } else {
1348                        (IconName::XCircle, Color::Error, rerun_button)
1349                    }
1350                }
1351            },
1352            None => (IconName::Terminal, Color::Muted, None),
1353        };
1354
1355        let self_handle = self.self_handle.clone();
1356        h_flex()
1357            .gap_1()
1358            .group("term-tab-icon")
1359            .when(!params.selected, |this| {
1360                this.track_focus(&self.focus_handle)
1361            })
1362            .on_action(move |action: &RenameTerminal, window, cx| {
1363                self_handle
1364                    .update(cx, |this, cx| this.rename_terminal(action, window, cx))
1365                    .ok();
1366            })
1367            .child(
1368                h_flex()
1369                    .group("term-tab-icon")
1370                    .child(
1371                        div()
1372                            .when(rerun_button.is_some(), |this| {
1373                                this.hover(|style| style.invisible().w_0())
1374                            })
1375                            .child(Icon::new(icon).color(icon_color)),
1376                    )
1377                    .when_some(rerun_button, |this, rerun_button| {
1378                        this.child(
1379                            div()
1380                                .absolute()
1381                                .visible_on_hover("term-tab-icon")
1382                                .child(rerun_button),
1383                        )
1384                    }),
1385            )
1386            .child(
1387                div()
1388                    .relative()
1389                    .child(
1390                        Label::new(title)
1391                            .color(params.text_color())
1392                            .when(self.is_renaming(), |this| this.alpha(0.)),
1393                    )
1394                    .when_some(self.rename_editor.clone(), |this, editor| {
1395                        let self_handle = self.self_handle.clone();
1396                        let self_handle_cancel = self.self_handle.clone();
1397                        this.child(
1398                            div()
1399                                .absolute()
1400                                .top_0()
1401                                .left_0()
1402                                .size_full()
1403                                .child(editor)
1404                                .on_action(move |_: &menu::Confirm, window, cx| {
1405                                    self_handle
1406                                        .update(cx, |this, cx| {
1407                                            this.finish_renaming(true, window, cx)
1408                                        })
1409                                        .ok();
1410                                })
1411                                .on_action(move |_: &menu::Cancel, window, cx| {
1412                                    self_handle_cancel
1413                                        .update(cx, |this, cx| {
1414                                            this.finish_renaming(false, window, cx)
1415                                        })
1416                                        .ok();
1417                                }),
1418                        )
1419                    }),
1420            )
1421            .into_any()
1422    }
1423
1424    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
1425        if let Some(custom_title) = self.custom_title.as_ref().filter(|l| !l.trim().is_empty()) {
1426            return custom_title.clone().into();
1427        }
1428        let terminal = self.terminal().read(cx);
1429        terminal.title(detail == 0).into()
1430    }
1431
1432    fn telemetry_event_text(&self) -> Option<&'static str> {
1433        None
1434    }
1435
1436    fn handle_drop(
1437        &self,
1438        active_pane: &Pane,
1439        dropped: &dyn Any,
1440        window: &mut Window,
1441        cx: &mut App,
1442    ) -> bool {
1443        let Some(project) = self.project.upgrade() else {
1444            return false;
1445        };
1446
1447        if let Some(paths) = dropped.downcast_ref::<ExternalPaths>() {
1448            let is_local = project.read(cx).is_local();
1449            if is_local {
1450                self.add_paths_to_terminal(paths.paths(), window, cx);
1451                return true;
1452            }
1453
1454            return false;
1455        } else if let Some(tab) = dropped.downcast_ref::<DraggedTab>() {
1456            let Some(self_handle) = self.self_handle.upgrade() else {
1457                return false;
1458            };
1459
1460            let Some(workspace) = self.workspace.upgrade() else {
1461                return false;
1462            };
1463
1464            let Some(this_pane) = workspace.read(cx).pane_for(&self_handle) else {
1465                return false;
1466            };
1467
1468            let item = if tab.pane == this_pane {
1469                active_pane.item_for_index(tab.ix)
1470            } else {
1471                tab.pane.read(cx).item_for_index(tab.ix)
1472            };
1473
1474            let Some(item) = item else {
1475                return false;
1476            };
1477
1478            if item.downcast::<TerminalView>().is_some() {
1479                let Some(split_direction) = active_pane.drag_split_direction() else {
1480                    return false;
1481                };
1482
1483                let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1484                    return false;
1485                };
1486
1487                if !terminal_panel.read(cx).center.panes().contains(&&this_pane) {
1488                    return false;
1489                }
1490
1491                let source = tab.pane.clone();
1492                let item_id_to_move = item.item_id();
1493                let is_zoomed = {
1494                    let terminal_panel = terminal_panel.read(cx);
1495                    if terminal_panel.active_pane == this_pane {
1496                        active_pane.is_zoomed()
1497                    } else {
1498                        terminal_panel.active_pane.read(cx).is_zoomed()
1499                    }
1500                };
1501
1502                let workspace = workspace.downgrade();
1503                let terminal_panel = terminal_panel.downgrade();
1504                // Defer the split operation to avoid re-entrancy panic.
1505                // The pane may be the one currently being updated, so we cannot
1506                // call mark_positions (via split) synchronously.
1507                window
1508                    .spawn(cx, async move |cx| {
1509                        cx.update(|window, cx| {
1510                            let Ok(new_pane) = terminal_panel.update(cx, |terminal_panel, cx| {
1511                                let new_pane = terminal_panel::new_terminal_pane(
1512                                    workspace, project, is_zoomed, window, cx,
1513                                );
1514                                terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1515                                terminal_panel.center.split(
1516                                    &this_pane,
1517                                    &new_pane,
1518                                    split_direction,
1519                                    cx,
1520                                );
1521                                anyhow::Ok(new_pane)
1522                            }) else {
1523                                return;
1524                            };
1525
1526                            let Some(new_pane) = new_pane.log_err() else {
1527                                return;
1528                            };
1529
1530                            workspace::move_item(
1531                                &source,
1532                                &new_pane,
1533                                item_id_to_move,
1534                                new_pane.read(cx).active_item_index(),
1535                                true,
1536                                window,
1537                                cx,
1538                            );
1539                        })
1540                        .ok();
1541                    })
1542                    .detach();
1543
1544                return true;
1545            } else {
1546                if let Some(project_path) = item.project_path(cx)
1547                    && let Some(path) = project.read(cx).absolute_path(&project_path, cx)
1548                {
1549                    self.add_paths_to_terminal(&[path], window, cx);
1550                    return true;
1551                }
1552            }
1553
1554            return false;
1555        } else if let Some(selection) = dropped.downcast_ref::<DraggedSelection>() {
1556            let project = project.read(cx);
1557            let paths = selection
1558                .items()
1559                .map(|selected_entry| selected_entry.entry_id)
1560                .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1561                .filter_map(|project_path| project.absolute_path(&project_path, cx))
1562                .collect::<Vec<_>>();
1563
1564            if !paths.is_empty() {
1565                self.add_paths_to_terminal(&paths, window, cx);
1566            }
1567
1568            return true;
1569        } else if let Some(&entry_id) = dropped.downcast_ref::<ProjectEntryId>() {
1570            let project = project.read(cx);
1571            if let Some(path) = project
1572                .path_for_entry(entry_id, cx)
1573                .and_then(|project_path| project.absolute_path(&project_path, cx))
1574            {
1575                self.add_paths_to_terminal(&[path], window, cx);
1576            }
1577
1578            return true;
1579        }
1580
1581        false
1582    }
1583
1584    fn tab_extra_context_menu_actions(
1585        &self,
1586        _window: &mut Window,
1587        cx: &mut Context<Self>,
1588    ) -> Vec<(SharedString, Box<dyn gpui::Action>)> {
1589        let terminal = self.terminal.read(cx);
1590        if terminal.task().is_none() {
1591            vec![("Rename".into(), Box::new(RenameTerminal))]
1592        } else {
1593            Vec::new()
1594        }
1595    }
1596
1597    fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
1598        workspace::item::ItemBufferKind::Singleton
1599    }
1600
1601    fn can_split(&self) -> bool {
1602        true
1603    }
1604
1605    fn clone_on_split(
1606        &self,
1607        workspace_id: Option<WorkspaceId>,
1608        window: &mut Window,
1609        cx: &mut Context<Self>,
1610    ) -> Task<Option<Entity<Self>>> {
1611        let Ok(terminal) = self.project.update(cx, |project, cx| {
1612            let cwd = project
1613                .active_project_directory(cx)
1614                .map(|it| it.to_path_buf());
1615            project.clone_terminal(self.terminal(), cx, cwd)
1616        }) else {
1617            return Task::ready(None);
1618        };
1619        cx.spawn_in(window, async move |this, cx| {
1620            let terminal = terminal.await.log_err()?;
1621            this.update_in(cx, |this, window, cx| {
1622                cx.new(|cx| {
1623                    TerminalView::new(
1624                        terminal,
1625                        this.workspace.clone(),
1626                        workspace_id,
1627                        this.project.clone(),
1628                        window,
1629                        cx,
1630                    )
1631                })
1632            })
1633            .ok()
1634        })
1635    }
1636
1637    fn is_dirty(&self, cx: &App) -> bool {
1638        match self.terminal.read(cx).task() {
1639            Some(task) => task.status == TaskStatus::Running,
1640            None => self.has_bell(),
1641        }
1642    }
1643
1644    fn has_conflict(&self, _cx: &App) -> bool {
1645        false
1646    }
1647
1648    fn can_save_as(&self, _cx: &App) -> bool {
1649        false
1650    }
1651
1652    fn as_searchable(
1653        &self,
1654        handle: &Entity<Self>,
1655        _: &App,
1656    ) -> Option<Box<dyn SearchableItemHandle>> {
1657        Some(Box::new(handle.clone()))
1658    }
1659
1660    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1661        if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1662            ToolbarItemLocation::PrimaryLeft
1663        } else {
1664            ToolbarItemLocation::Hidden
1665        }
1666    }
1667
1668    fn breadcrumbs(&self, cx: &App) -> Option<(Vec<HighlightedText>, Option<Font>)> {
1669        Some((
1670            vec![HighlightedText {
1671                text: self.terminal().read(cx).breadcrumb_text.clone().into(),
1672                highlights: vec![],
1673            }],
1674            None,
1675        ))
1676    }
1677
1678    fn added_to_workspace(
1679        &mut self,
1680        workspace: &mut Workspace,
1681        _: &mut Window,
1682        cx: &mut Context<Self>,
1683    ) {
1684        if self.terminal().read(cx).task().is_none() {
1685            if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1686                log::debug!(
1687                    "Updating workspace id for the terminal, old: {old_id:?}, new: {new_id:?}",
1688                );
1689                let db = TerminalDb::global(cx);
1690                let entity_id = cx.entity_id().as_u64();
1691                cx.background_spawn(async move {
1692                    db.update_workspace_id(new_id, old_id, entity_id).await
1693                })
1694                .detach();
1695            }
1696            self.workspace_id = workspace.database_id();
1697        }
1698    }
1699
1700    fn to_item_events(event: &Self::Event, f: &mut dyn FnMut(ItemEvent)) {
1701        f(*event)
1702    }
1703}
1704
1705impl SerializableItem for TerminalView {
1706    fn serialized_item_kind() -> &'static str {
1707        "Terminal"
1708    }
1709
1710    fn cleanup(
1711        workspace_id: WorkspaceId,
1712        alive_items: Vec<workspace::ItemId>,
1713        _window: &mut Window,
1714        cx: &mut App,
1715    ) -> Task<anyhow::Result<()>> {
1716        let db = TerminalDb::global(cx);
1717        delete_unloaded_items(alive_items, workspace_id, "terminals", &db, cx)
1718    }
1719
1720    fn serialize(
1721        &mut self,
1722        _workspace: &mut Workspace,
1723        item_id: workspace::ItemId,
1724        _closing: bool,
1725        _: &mut Window,
1726        cx: &mut Context<Self>,
1727    ) -> Option<Task<anyhow::Result<()>>> {
1728        let terminal = self.terminal().read(cx);
1729        if terminal.task().is_some() {
1730            return None;
1731        }
1732
1733        if !self.needs_serialize {
1734            return None;
1735        }
1736
1737        let workspace_id = self.workspace_id?;
1738        let cwd = terminal.working_directory();
1739        let custom_title = self.custom_title.clone();
1740        self.needs_serialize = false;
1741
1742        let db = TerminalDb::global(cx);
1743        Some(cx.background_spawn(async move {
1744            if let Some(cwd) = cwd {
1745                db.save_working_directory(item_id, workspace_id, cwd)
1746                    .await?;
1747            }
1748            db.save_custom_title(item_id, workspace_id, custom_title)
1749                .await?;
1750            Ok(())
1751        }))
1752    }
1753
1754    fn should_serialize(&self, _: &Self::Event) -> bool {
1755        self.needs_serialize
1756    }
1757
1758    fn deserialize(
1759        project: Entity<Project>,
1760        workspace: WeakEntity<Workspace>,
1761        workspace_id: WorkspaceId,
1762        item_id: workspace::ItemId,
1763        window: &mut Window,
1764        cx: &mut App,
1765    ) -> Task<anyhow::Result<Entity<Self>>> {
1766        window.spawn(cx, async move |cx| {
1767            let (cwd, custom_title) = cx
1768                .update(|_window, cx| {
1769                    let db = TerminalDb::global(cx);
1770                    let from_db = db
1771                        .get_working_directory(item_id, workspace_id)
1772                        .log_err()
1773                        .flatten();
1774                    let cwd = if from_db
1775                        .as_ref()
1776                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1777                    {
1778                        from_db
1779                    } else {
1780                        workspace
1781                            .upgrade()
1782                            .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1783                    };
1784                    let custom_title = db
1785                        .get_custom_title(item_id, workspace_id)
1786                        .log_err()
1787                        .flatten()
1788                        .filter(|title| !title.trim().is_empty());
1789                    (cwd, custom_title)
1790                })
1791                .ok()
1792                .unwrap_or((None, None));
1793
1794            let terminal = project
1795                .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))
1796                .await?;
1797            cx.update(|window, cx| {
1798                cx.new(|cx| {
1799                    let mut view = TerminalView::new(
1800                        terminal,
1801                        workspace,
1802                        Some(workspace_id),
1803                        project.downgrade(),
1804                        window,
1805                        cx,
1806                    );
1807                    if custom_title.is_some() {
1808                        view.custom_title = custom_title;
1809                    }
1810                    view
1811                })
1812            })
1813        })
1814    }
1815}
1816
1817impl SearchableItem for TerminalView {
1818    type Match = RangeInclusive<AlacPoint>;
1819
1820    fn supported_options(&self) -> SearchOptions {
1821        SearchOptions {
1822            case: false,
1823            word: false,
1824            regex: true,
1825            replacement: false,
1826            selection: false,
1827            select_all: false,
1828            find_in_results: false,
1829        }
1830    }
1831
1832    /// Clear stored matches
1833    fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1834        self.terminal().update(cx, |term, _| term.matches.clear())
1835    }
1836
1837    /// Store matches returned from find_matches somewhere for rendering
1838    fn update_matches(
1839        &mut self,
1840        matches: &[Self::Match],
1841        _active_match_index: Option<usize>,
1842        _token: SearchToken,
1843        _window: &mut Window,
1844        cx: &mut Context<Self>,
1845    ) {
1846        self.terminal()
1847            .update(cx, |term, _| term.matches = matches.to_vec())
1848    }
1849
1850    /// Returns the selection content to pre-load into this search
1851    fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1852        self.terminal()
1853            .read(cx)
1854            .last_content
1855            .selection_text
1856            .clone()
1857            .unwrap_or_default()
1858    }
1859
1860    /// Focus match at given index into the Vec of matches
1861    fn activate_match(
1862        &mut self,
1863        index: usize,
1864        _: &[Self::Match],
1865        _token: SearchToken,
1866        _window: &mut Window,
1867        cx: &mut Context<Self>,
1868    ) {
1869        self.terminal()
1870            .update(cx, |term, _| term.activate_match(index));
1871        cx.notify();
1872    }
1873
1874    /// Add selections for all matches given.
1875    fn select_matches(
1876        &mut self,
1877        matches: &[Self::Match],
1878        _token: SearchToken,
1879        _: &mut Window,
1880        cx: &mut Context<Self>,
1881    ) {
1882        self.terminal()
1883            .update(cx, |term, _| term.select_matches(matches));
1884        cx.notify();
1885    }
1886
1887    /// Get all of the matches for this query, should be done on the background
1888    fn find_matches(
1889        &mut self,
1890        query: Arc<SearchQuery>,
1891        _: &mut Window,
1892        cx: &mut Context<Self>,
1893    ) -> Task<Vec<Self::Match>> {
1894        if let Some(s) = regex_search_for_query(&query) {
1895            self.terminal()
1896                .update(cx, |term, cx| term.find_matches(s, cx))
1897        } else {
1898            Task::ready(vec![])
1899        }
1900    }
1901
1902    /// Reports back to the search toolbar what the active match should be (the selection)
1903    fn active_match_index(
1904        &mut self,
1905        direction: Direction,
1906        matches: &[Self::Match],
1907        _token: SearchToken,
1908        _: &mut Window,
1909        cx: &mut Context<Self>,
1910    ) -> Option<usize> {
1911        // Selection head might have a value if there's a selection that isn't
1912        // associated with a match. Therefore, if there are no matches, we should
1913        // report None, no matter the state of the terminal
1914
1915        if !matches.is_empty() {
1916            if let Some(selection_head) = self.terminal().read(cx).selection_head {
1917                // If selection head is contained in a match. Return that match
1918                match direction {
1919                    Direction::Prev => {
1920                        // If no selection before selection head, return the first match
1921                        Some(
1922                            matches
1923                                .iter()
1924                                .enumerate()
1925                                .rev()
1926                                .find(|(_, search_match)| {
1927                                    search_match.contains(&selection_head)
1928                                        || search_match.start() < &selection_head
1929                                })
1930                                .map(|(ix, _)| ix)
1931                                .unwrap_or(0),
1932                        )
1933                    }
1934                    Direction::Next => {
1935                        // If no selection after selection head, return the last match
1936                        Some(
1937                            matches
1938                                .iter()
1939                                .enumerate()
1940                                .find(|(_, search_match)| {
1941                                    search_match.contains(&selection_head)
1942                                        || search_match.start() > &selection_head
1943                                })
1944                                .map(|(ix, _)| ix)
1945                                .unwrap_or(matches.len().saturating_sub(1)),
1946                        )
1947                    }
1948                }
1949            } else {
1950                // Matches found but no active selection, return the first last one (closest to cursor)
1951                Some(matches.len().saturating_sub(1))
1952            }
1953        } else {
1954            None
1955        }
1956    }
1957    fn replace(
1958        &mut self,
1959        _: &Self::Match,
1960        _: &SearchQuery,
1961        _token: SearchToken,
1962        _window: &mut Window,
1963        _: &mut Context<Self>,
1964    ) {
1965        // Replacement is not supported in terminal view, so this is a no-op.
1966    }
1967}
1968
1969/// Gets the working directory for the given workspace, respecting the user's settings.
1970/// Falls back to home directory when no project directory is available.
1971pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1972    let directory = match &TerminalSettings::get_global(cx).working_directory {
1973        WorkingDirectory::CurrentFileDirectory => workspace
1974            .project()
1975            .read(cx)
1976            .active_entry_directory(cx)
1977            .or_else(|| current_project_directory(workspace, cx)),
1978        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx),
1979        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1980        WorkingDirectory::AlwaysHome => None,
1981        WorkingDirectory::Always { directory } => shellexpand::full(directory)
1982            .ok()
1983            .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1984            .filter(|dir| dir.is_dir()),
1985    };
1986    directory.or_else(dirs::home_dir)
1987}
1988
1989fn current_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1990    workspace
1991        .project()
1992        .read(cx)
1993        .active_project_directory(cx)
1994        .as_deref()
1995        .map(Path::to_path_buf)
1996        .or_else(|| first_project_directory(workspace, cx))
1997}
1998
1999///Gets the first project's home directory, or the home directory
2000fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
2001    let worktree = workspace.worktrees(cx).next()?.read(cx);
2002    let worktree_path = worktree.abs_path();
2003    if worktree.root_entry()?.is_dir() {
2004        Some(worktree_path.to_path_buf())
2005    } else {
2006        // If worktree is a file, return its parent directory
2007        worktree_path.parent().map(|p| p.to_path_buf())
2008    }
2009}
2010
2011#[cfg(test)]
2012mod tests {
2013    use super::*;
2014    use gpui::TestAppContext;
2015    use project::{Entry, Project, ProjectPath, Worktree};
2016    use std::path::{Path, PathBuf};
2017    use util::paths::PathStyle;
2018    use util::rel_path::RelPath;
2019    use workspace::item::test::{TestItem, TestProjectItem};
2020    use workspace::{AppState, MultiWorkspace, SelectedEntry};
2021
2022    fn expected_drop_text(paths: &[PathBuf]) -> String {
2023        let mut text = String::new();
2024        for path in paths {
2025            text.push(' ');
2026            text.push_str(&format!("{path:?}"));
2027        }
2028        text.push(' ');
2029        text
2030    }
2031
2032    fn assert_drop_writes_to_terminal(
2033        pane: &Entity<Pane>,
2034        terminal_view_index: usize,
2035        terminal: &Entity<Terminal>,
2036        dropped: &dyn Any,
2037        expected_text: &str,
2038        window: &mut Window,
2039        cx: &mut Context<MultiWorkspace>,
2040    ) {
2041        let _ = terminal.update(cx, |terminal, _| terminal.take_input_log());
2042
2043        let handled = pane.update(cx, |pane, cx| {
2044            pane.item_for_index(terminal_view_index)
2045                .unwrap()
2046                .handle_drop(pane, dropped, window, cx)
2047        });
2048        assert!(handled, "handle_drop should return true for {:?}", dropped);
2049
2050        let mut input_log = terminal.update(cx, |terminal, _| terminal.take_input_log());
2051        assert_eq!(input_log.len(), 1, "expected exactly one write to terminal");
2052        let written =
2053            String::from_utf8(input_log.remove(0)).expect("terminal write should be valid UTF-8");
2054        assert_eq!(written, expected_text);
2055    }
2056
2057    // Working directory calculation tests
2058
2059    // No Worktrees in project -> home_dir()
2060    #[gpui::test]
2061    async fn no_worktree(cx: &mut TestAppContext) {
2062        let (project, workspace) = init_test(cx).await;
2063        cx.read(|cx| {
2064            let workspace = workspace.read(cx);
2065            let active_entry = project.read(cx).active_entry();
2066
2067            //Make sure environment is as expected
2068            assert!(active_entry.is_none());
2069            assert!(workspace.worktrees(cx).next().is_none());
2070
2071            let res = default_working_directory(workspace, cx);
2072            assert_eq!(res, dirs::home_dir());
2073            let res = first_project_directory(workspace, cx);
2074            assert_eq!(res, None);
2075        });
2076    }
2077
2078    // No active entry, but a worktree, worktree is a file -> parent directory
2079    #[gpui::test]
2080    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
2081        let (project, workspace) = init_test(cx).await;
2082
2083        create_file_wt(project.clone(), "/root.txt", cx).await;
2084        cx.read(|cx| {
2085            let workspace = workspace.read(cx);
2086            let active_entry = project.read(cx).active_entry();
2087
2088            //Make sure environment is as expected
2089            assert!(active_entry.is_none());
2090            assert!(workspace.worktrees(cx).next().is_some());
2091
2092            let res = default_working_directory(workspace, cx);
2093            assert_eq!(res, Some(Path::new("/").to_path_buf()));
2094            let res = first_project_directory(workspace, cx);
2095            assert_eq!(res, Some(Path::new("/").to_path_buf()));
2096        });
2097    }
2098
2099    // No active entry, but a worktree, worktree is a folder -> worktree_folder
2100    #[gpui::test]
2101    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
2102        let (project, workspace) = init_test(cx).await;
2103
2104        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2105        cx.update(|cx| {
2106            let workspace = workspace.read(cx);
2107            let active_entry = project.read(cx).active_entry();
2108
2109            assert!(active_entry.is_none());
2110            assert!(workspace.worktrees(cx).next().is_some());
2111
2112            let res = default_working_directory(workspace, cx);
2113            assert_eq!(res, Some(Path::new("/root/").to_path_buf()));
2114            let res = first_project_directory(workspace, cx);
2115            assert_eq!(res, Some(Path::new("/root/").to_path_buf()));
2116        });
2117    }
2118
2119    // Active entry with a work tree, worktree is a file -> worktree_folder()
2120    #[gpui::test]
2121    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
2122        let (project, workspace) = init_test(cx).await;
2123
2124        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
2125        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
2126        insert_active_entry_for(wt2, entry2, project.clone(), cx);
2127
2128        cx.update(|cx| {
2129            let workspace = workspace.read(cx);
2130            let active_entry = project.read(cx).active_entry();
2131
2132            assert!(active_entry.is_some());
2133
2134            let res = default_working_directory(workspace, cx);
2135            assert_eq!(res, Some(Path::new("/root1/").to_path_buf()));
2136            let res = first_project_directory(workspace, cx);
2137            assert_eq!(res, Some(Path::new("/root1/").to_path_buf()));
2138        });
2139    }
2140
2141    // Active entry, with a worktree, worktree is a folder -> worktree_folder
2142    #[gpui::test]
2143    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
2144        let (project, workspace) = init_test(cx).await;
2145
2146        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
2147        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
2148        insert_active_entry_for(wt2, entry2, project.clone(), cx);
2149
2150        cx.update(|cx| {
2151            let workspace = workspace.read(cx);
2152            let active_entry = project.read(cx).active_entry();
2153
2154            assert!(active_entry.is_some());
2155
2156            let res = default_working_directory(workspace, cx);
2157            assert_eq!(res, Some(Path::new("/root2/").to_path_buf()));
2158            let res = first_project_directory(workspace, cx);
2159            assert_eq!(res, Some(Path::new("/root1/").to_path_buf()));
2160        });
2161    }
2162
2163    // active_entry_directory: No active entry -> returns None (used by CurrentFileDirectory)
2164    #[gpui::test]
2165    async fn active_entry_directory_no_active_entry(cx: &mut TestAppContext) {
2166        let (project, _workspace) = init_test(cx).await;
2167
2168        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2169
2170        cx.update(|cx| {
2171            assert!(project.read(cx).active_entry().is_none());
2172
2173            let res = project.read(cx).active_entry_directory(cx);
2174            assert_eq!(res, None);
2175        });
2176    }
2177
2178    // active_entry_directory: Active entry is file -> returns parent directory (used by CurrentFileDirectory)
2179    #[gpui::test]
2180    async fn active_entry_directory_active_file(cx: &mut TestAppContext) {
2181        let (project, _workspace) = init_test(cx).await;
2182
2183        let (wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2184        let entry = create_file_in_worktree(wt.clone(), "src/main.rs", cx).await;
2185        insert_active_entry_for(wt, entry, project.clone(), cx);
2186
2187        cx.update(|cx| {
2188            let res = project.read(cx).active_entry_directory(cx);
2189            assert_eq!(res, Some(Path::new("/root/src").to_path_buf()));
2190        });
2191    }
2192
2193    // active_entry_directory: Active entry is directory -> returns that directory (used by CurrentFileDirectory)
2194    #[gpui::test]
2195    async fn active_entry_directory_active_dir(cx: &mut TestAppContext) {
2196        let (project, _workspace) = init_test(cx).await;
2197
2198        let (wt, entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2199        insert_active_entry_for(wt, entry, project.clone(), cx);
2200
2201        cx.update(|cx| {
2202            let res = project.read(cx).active_entry_directory(cx);
2203            assert_eq!(res, Some(Path::new("/root/").to_path_buf()));
2204        });
2205    }
2206
2207    /// Creates a worktree with 1 file: /root.txt
2208    pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
2209        let (project, workspace, _) = init_test_with_window(cx).await;
2210        (project, workspace)
2211    }
2212
2213    /// Creates a worktree with 1 file /root.txt and returns the project, workspace, and window handle.
2214    async fn init_test_with_window(
2215        cx: &mut TestAppContext,
2216    ) -> (
2217        Entity<Project>,
2218        Entity<Workspace>,
2219        gpui::WindowHandle<MultiWorkspace>,
2220    ) {
2221        let params = cx.update(AppState::test);
2222        cx.update(|cx| {
2223            theme_settings::init(theme::LoadThemes::JustBase, cx);
2224        });
2225
2226        let project = Project::test(params.fs.clone(), [], cx).await;
2227        let window_handle =
2228            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2229        let workspace = window_handle
2230            .read_with(cx, |mw, _| mw.workspace().clone())
2231            .unwrap();
2232
2233        (project, workspace, window_handle)
2234    }
2235
2236    /// Creates a file in the given worktree and returns its entry.
2237    async fn create_file_in_worktree(
2238        worktree: Entity<Worktree>,
2239        relative_path: impl AsRef<Path>,
2240        cx: &mut TestAppContext,
2241    ) -> Entry {
2242        cx.update(|cx| {
2243            worktree.update(cx, |worktree, cx| {
2244                worktree.create_entry(
2245                    RelPath::new(relative_path.as_ref(), PathStyle::local())
2246                        .unwrap()
2247                        .as_ref()
2248                        .into(),
2249                    false,
2250                    None,
2251                    cx,
2252                )
2253            })
2254        })
2255        .await
2256        .unwrap()
2257        .into_included()
2258        .unwrap()
2259    }
2260
2261    /// Creates a worktree with 1 folder: /root{suffix}/
2262    async fn create_folder_wt(
2263        project: Entity<Project>,
2264        path: impl AsRef<Path>,
2265        cx: &mut TestAppContext,
2266    ) -> (Entity<Worktree>, Entry) {
2267        create_wt(project, true, path, cx).await
2268    }
2269
2270    /// Creates a worktree with 1 file: /root{suffix}.txt
2271    async fn create_file_wt(
2272        project: Entity<Project>,
2273        path: impl AsRef<Path>,
2274        cx: &mut TestAppContext,
2275    ) -> (Entity<Worktree>, Entry) {
2276        create_wt(project, false, path, cx).await
2277    }
2278
2279    async fn create_wt(
2280        project: Entity<Project>,
2281        is_dir: bool,
2282        path: impl AsRef<Path>,
2283        cx: &mut TestAppContext,
2284    ) -> (Entity<Worktree>, Entry) {
2285        let (wt, _) = project
2286            .update(cx, |project, cx| {
2287                project.find_or_create_worktree(path, true, cx)
2288            })
2289            .await
2290            .unwrap();
2291
2292        let entry = cx
2293            .update(|cx| {
2294                wt.update(cx, |wt, cx| {
2295                    wt.create_entry(RelPath::empty().into(), is_dir, None, cx)
2296                })
2297            })
2298            .await
2299            .unwrap()
2300            .into_included()
2301            .unwrap();
2302
2303        (wt, entry)
2304    }
2305
2306    pub fn insert_active_entry_for(
2307        wt: Entity<Worktree>,
2308        entry: Entry,
2309        project: Entity<Project>,
2310        cx: &mut TestAppContext,
2311    ) {
2312        cx.update(|cx| {
2313            let p = ProjectPath {
2314                worktree_id: wt.read(cx).id(),
2315                path: entry.path,
2316            };
2317            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
2318        });
2319    }
2320
2321    // Terminal drag/drop test
2322
2323    #[gpui::test]
2324    async fn test_handle_drop_writes_paths_for_all_drop_types(cx: &mut TestAppContext) {
2325        let (project, _workspace, window_handle) = init_test_with_window(cx).await;
2326
2327        let (worktree, _) = create_folder_wt(project.clone(), "/root/", cx).await;
2328        let first_entry = create_file_in_worktree(worktree.clone(), "first.txt", cx).await;
2329        let second_entry = create_file_in_worktree(worktree.clone(), "second.txt", cx).await;
2330
2331        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
2332        let first_path = project
2333            .read_with(cx, |project, cx| {
2334                project.absolute_path(
2335                    &ProjectPath {
2336                        worktree_id,
2337                        path: first_entry.path.clone(),
2338                    },
2339                    cx,
2340                )
2341            })
2342            .unwrap();
2343        let second_path = project
2344            .read_with(cx, |project, cx| {
2345                project.absolute_path(
2346                    &ProjectPath {
2347                        worktree_id,
2348                        path: second_entry.path.clone(),
2349                    },
2350                    cx,
2351                )
2352            })
2353            .unwrap();
2354
2355        let (active_pane, terminal, terminal_view, tab_item) = window_handle
2356            .update(cx, |multi_workspace, window, cx| {
2357                let workspace = multi_workspace.workspace().clone();
2358                let active_pane = workspace.read(cx).active_pane().clone();
2359
2360                let terminal = cx.new(|cx| {
2361                    terminal::TerminalBuilder::new_display_only(
2362                        CursorShape::default(),
2363                        terminal::terminal_settings::AlternateScroll::On,
2364                        None,
2365                        0,
2366                        cx.background_executor(),
2367                        PathStyle::local(),
2368                    )
2369                    .unwrap()
2370                    .subscribe(cx)
2371                });
2372                let terminal_view = cx.new(|cx| {
2373                    TerminalView::new(
2374                        terminal.clone(),
2375                        workspace.downgrade(),
2376                        None,
2377                        project.downgrade(),
2378                        window,
2379                        cx,
2380                    )
2381                });
2382
2383                active_pane.update(cx, |pane, cx| {
2384                    pane.add_item(
2385                        Box::new(terminal_view.clone()),
2386                        true,
2387                        false,
2388                        None,
2389                        window,
2390                        cx,
2391                    );
2392                });
2393
2394                let tab_project_item = cx.new(|_| TestProjectItem {
2395                    entry_id: Some(second_entry.id),
2396                    project_path: Some(ProjectPath {
2397                        worktree_id,
2398                        path: second_entry.path.clone(),
2399                    }),
2400                    is_dirty: false,
2401                });
2402                let tab_item =
2403                    cx.new(|cx| TestItem::new(cx).with_project_items(&[tab_project_item]));
2404                active_pane.update(cx, |pane, cx| {
2405                    pane.add_item(Box::new(tab_item.clone()), true, false, None, window, cx);
2406                });
2407
2408                (active_pane, terminal, terminal_view, tab_item)
2409            })
2410            .unwrap();
2411
2412        cx.run_until_parked();
2413
2414        window_handle
2415            .update(cx, |multi_workspace, window, cx| {
2416                let workspace = multi_workspace.workspace().clone();
2417                let terminal_view_index =
2418                    active_pane.read(cx).index_for_item(&terminal_view).unwrap();
2419                let dragged_tab_index = active_pane.read(cx).index_for_item(&tab_item).unwrap();
2420
2421                assert!(
2422                    workspace.read(cx).pane_for(&terminal_view).is_some(),
2423                    "terminal view not registered with workspace after run_until_parked"
2424                );
2425
2426                // Dragging an external file should write its path to the terminal
2427                let external_paths = ExternalPaths(vec![first_path.clone()].into());
2428                assert_drop_writes_to_terminal(
2429                    &active_pane,
2430                    terminal_view_index,
2431                    &terminal,
2432                    &external_paths,
2433                    &expected_drop_text(std::slice::from_ref(&first_path)),
2434                    window,
2435                    cx,
2436                );
2437
2438                // Dragging a tab should write the path of the tab's item to the terminal
2439                let dragged_tab = DraggedTab {
2440                    pane: active_pane.clone(),
2441                    item: Box::new(tab_item.clone()),
2442                    ix: dragged_tab_index,
2443                    detail: 0,
2444                    is_active: false,
2445                };
2446                assert_drop_writes_to_terminal(
2447                    &active_pane,
2448                    terminal_view_index,
2449                    &terminal,
2450                    &dragged_tab,
2451                    &expected_drop_text(std::slice::from_ref(&second_path)),
2452                    window,
2453                    cx,
2454                );
2455
2456                // Dragging multiple selections should write both paths to the terminal
2457                let dragged_selection = DraggedSelection {
2458                    active_selection: SelectedEntry {
2459                        worktree_id,
2460                        entry_id: first_entry.id,
2461                    },
2462                    marked_selections: Arc::from([
2463                        SelectedEntry {
2464                            worktree_id,
2465                            entry_id: first_entry.id,
2466                        },
2467                        SelectedEntry {
2468                            worktree_id,
2469                            entry_id: second_entry.id,
2470                        },
2471                    ]),
2472                };
2473                assert_drop_writes_to_terminal(
2474                    &active_pane,
2475                    terminal_view_index,
2476                    &terminal,
2477                    &dragged_selection,
2478                    &expected_drop_text(&[first_path.clone(), second_path.clone()]),
2479                    window,
2480                    cx,
2481                );
2482
2483                // Dropping a project entry should write the entry's path to the terminal
2484                let dropped_entry_id = first_entry.id;
2485                assert_drop_writes_to_terminal(
2486                    &active_pane,
2487                    terminal_view_index,
2488                    &terminal,
2489                    &dropped_entry_id,
2490                    &expected_drop_text(&[first_path]),
2491                    window,
2492                    cx,
2493                );
2494            })
2495            .unwrap();
2496    }
2497
2498    // Terminal rename tests
2499
2500    #[gpui::test]
2501    async fn test_custom_title_initially_none(cx: &mut TestAppContext) {
2502        cx.executor().allow_parking();
2503
2504        let (project, workspace) = init_test(cx).await;
2505
2506        let terminal = project
2507            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2508            .await
2509            .unwrap();
2510
2511        let terminal_view = cx
2512            .add_window(|window, cx| {
2513                TerminalView::new(
2514                    terminal,
2515                    workspace.downgrade(),
2516                    None,
2517                    project.downgrade(),
2518                    window,
2519                    cx,
2520                )
2521            })
2522            .root(cx)
2523            .unwrap();
2524
2525        terminal_view.update(cx, |view, _cx| {
2526            assert!(view.custom_title().is_none());
2527        });
2528    }
2529
2530    #[gpui::test]
2531    async fn test_set_custom_title(cx: &mut TestAppContext) {
2532        cx.executor().allow_parking();
2533
2534        let (project, workspace) = init_test(cx).await;
2535
2536        let terminal = project
2537            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2538            .await
2539            .unwrap();
2540
2541        let terminal_view = cx
2542            .add_window(|window, cx| {
2543                TerminalView::new(
2544                    terminal,
2545                    workspace.downgrade(),
2546                    None,
2547                    project.downgrade(),
2548                    window,
2549                    cx,
2550                )
2551            })
2552            .root(cx)
2553            .unwrap();
2554
2555        terminal_view.update(cx, |view, cx| {
2556            view.set_custom_title(Some("frontend".to_string()), cx);
2557            assert_eq!(view.custom_title(), Some("frontend"));
2558        });
2559    }
2560
2561    #[gpui::test]
2562    async fn test_set_custom_title_empty_becomes_none(cx: &mut TestAppContext) {
2563        cx.executor().allow_parking();
2564
2565        let (project, workspace) = init_test(cx).await;
2566
2567        let terminal = project
2568            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2569            .await
2570            .unwrap();
2571
2572        let terminal_view = cx
2573            .add_window(|window, cx| {
2574                TerminalView::new(
2575                    terminal,
2576                    workspace.downgrade(),
2577                    None,
2578                    project.downgrade(),
2579                    window,
2580                    cx,
2581                )
2582            })
2583            .root(cx)
2584            .unwrap();
2585
2586        terminal_view.update(cx, |view, cx| {
2587            view.set_custom_title(Some("test".to_string()), cx);
2588            assert_eq!(view.custom_title(), Some("test"));
2589
2590            view.set_custom_title(Some("".to_string()), cx);
2591            assert!(view.custom_title().is_none());
2592
2593            view.set_custom_title(Some("  ".to_string()), cx);
2594            assert!(view.custom_title().is_none());
2595        });
2596    }
2597
2598    #[gpui::test]
2599    async fn test_custom_title_marks_needs_serialize(cx: &mut TestAppContext) {
2600        cx.executor().allow_parking();
2601
2602        let (project, workspace) = init_test(cx).await;
2603
2604        let terminal = project
2605            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2606            .await
2607            .unwrap();
2608
2609        let terminal_view = cx
2610            .add_window(|window, cx| {
2611                TerminalView::new(
2612                    terminal,
2613                    workspace.downgrade(),
2614                    None,
2615                    project.downgrade(),
2616                    window,
2617                    cx,
2618                )
2619            })
2620            .root(cx)
2621            .unwrap();
2622
2623        terminal_view.update(cx, |view, cx| {
2624            view.needs_serialize = false;
2625            view.set_custom_title(Some("new_label".to_string()), cx);
2626            assert!(view.needs_serialize);
2627        });
2628    }
2629
2630    #[gpui::test]
2631    async fn test_tab_content_uses_custom_title(cx: &mut TestAppContext) {
2632        cx.executor().allow_parking();
2633
2634        let (project, workspace) = init_test(cx).await;
2635
2636        let terminal = project
2637            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2638            .await
2639            .unwrap();
2640
2641        let terminal_view = cx
2642            .add_window(|window, cx| {
2643                TerminalView::new(
2644                    terminal,
2645                    workspace.downgrade(),
2646                    None,
2647                    project.downgrade(),
2648                    window,
2649                    cx,
2650                )
2651            })
2652            .root(cx)
2653            .unwrap();
2654
2655        terminal_view.update(cx, |view, cx| {
2656            view.set_custom_title(Some("my-server".to_string()), cx);
2657            let text = view.tab_content_text(0, cx);
2658            assert_eq!(text.as_ref(), "my-server");
2659        });
2660
2661        terminal_view.update(cx, |view, cx| {
2662            view.set_custom_title(None, cx);
2663            let text = view.tab_content_text(0, cx);
2664            assert_ne!(text.as_ref(), "my-server");
2665        });
2666    }
2667
2668    #[gpui::test]
2669    async fn test_tab_content_shows_terminal_title_when_custom_title_directly_set_empty(
2670        cx: &mut TestAppContext,
2671    ) {
2672        cx.executor().allow_parking();
2673
2674        let (project, workspace) = init_test(cx).await;
2675
2676        let terminal = project
2677            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2678            .await
2679            .unwrap();
2680
2681        let terminal_view = cx
2682            .add_window(|window, cx| {
2683                TerminalView::new(
2684                    terminal,
2685                    workspace.downgrade(),
2686                    None,
2687                    project.downgrade(),
2688                    window,
2689                    cx,
2690                )
2691            })
2692            .root(cx)
2693            .unwrap();
2694
2695        terminal_view.update(cx, |view, cx| {
2696            view.custom_title = Some("".to_string());
2697            let text = view.tab_content_text(0, cx);
2698            assert!(
2699                !text.is_empty(),
2700                "Tab should show terminal title, not empty string; got: '{}'",
2701                text
2702            );
2703        });
2704
2705        terminal_view.update(cx, |view, cx| {
2706            view.custom_title = Some("   ".to_string());
2707            let text = view.tab_content_text(0, cx);
2708            assert!(
2709                !text.is_empty() && text.as_ref() != "   ",
2710                "Tab should show terminal title, not whitespace; got: '{}'",
2711                text
2712            );
2713        });
2714    }
2715}