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.terminal.update(cx, |term, _| {
 854            term.input(text.0.to_string().into_bytes());
 855        });
 856    }
 857
 858    fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
 859        if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
 860            self.clear_bell(cx);
 861            self.process_keystroke(&keystroke, cx);
 862        }
 863    }
 864
 865    fn dispatch_context(&self, cx: &App) -> KeyContext {
 866        let mut dispatch_context = KeyContext::new_with_defaults();
 867        dispatch_context.add("Terminal");
 868
 869        if self.terminal.read(cx).vi_mode_enabled() {
 870            dispatch_context.add("vi_mode");
 871        }
 872
 873        let mode = self.terminal.read(cx).last_content.mode;
 874        dispatch_context.set(
 875            "screen",
 876            if mode.contains(TermMode::ALT_SCREEN) {
 877                "alt"
 878            } else {
 879                "normal"
 880            },
 881        );
 882
 883        if mode.contains(TermMode::APP_CURSOR) {
 884            dispatch_context.add("DECCKM");
 885        }
 886        if mode.contains(TermMode::APP_KEYPAD) {
 887            dispatch_context.add("DECPAM");
 888        } else {
 889            dispatch_context.add("DECPNM");
 890        }
 891        if mode.contains(TermMode::SHOW_CURSOR) {
 892            dispatch_context.add("DECTCEM");
 893        }
 894        if mode.contains(TermMode::LINE_WRAP) {
 895            dispatch_context.add("DECAWM");
 896        }
 897        if mode.contains(TermMode::ORIGIN) {
 898            dispatch_context.add("DECOM");
 899        }
 900        if mode.contains(TermMode::INSERT) {
 901            dispatch_context.add("IRM");
 902        }
 903        //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 904        if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 905            dispatch_context.add("LNM");
 906        }
 907        if mode.contains(TermMode::FOCUS_IN_OUT) {
 908            dispatch_context.add("report_focus");
 909        }
 910        if mode.contains(TermMode::ALTERNATE_SCROLL) {
 911            dispatch_context.add("alternate_scroll");
 912        }
 913        if mode.contains(TermMode::BRACKETED_PASTE) {
 914            dispatch_context.add("bracketed_paste");
 915        }
 916        if mode.intersects(TermMode::MOUSE_MODE) {
 917            dispatch_context.add("any_mouse_reporting");
 918        }
 919        {
 920            let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 921                "click"
 922            } else if mode.contains(TermMode::MOUSE_DRAG) {
 923                "drag"
 924            } else if mode.contains(TermMode::MOUSE_MOTION) {
 925                "motion"
 926            } else {
 927                "off"
 928            };
 929            dispatch_context.set("mouse_reporting", mouse_reporting);
 930        }
 931        {
 932            let format = if mode.contains(TermMode::SGR_MOUSE) {
 933                "sgr"
 934            } else if mode.contains(TermMode::UTF8_MOUSE) {
 935                "utf8"
 936            } else {
 937                "normal"
 938            };
 939            dispatch_context.set("mouse_format", format);
 940        };
 941
 942        if self.terminal.read(cx).last_content.selection.is_some() {
 943            dispatch_context.add("selection");
 944        }
 945
 946        dispatch_context
 947    }
 948
 949    fn set_terminal(
 950        &mut self,
 951        terminal: Entity<Terminal>,
 952        window: &mut Window,
 953        cx: &mut Context<TerminalView>,
 954    ) {
 955        self._terminal_subscriptions =
 956            subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
 957        self.terminal = terminal;
 958    }
 959
 960    fn rerun_button(task: &TaskState) -> Option<IconButton> {
 961        if !task.spawned_task.show_rerun {
 962            return None;
 963        }
 964
 965        let task_id = task.spawned_task.id.clone();
 966        Some(
 967            IconButton::new("rerun-icon", IconName::Rerun)
 968                .icon_size(IconSize::Small)
 969                .size(ButtonSize::Compact)
 970                .icon_color(Color::Default)
 971                .shape(ui::IconButtonShape::Square)
 972                .tooltip(move |_window, cx| Tooltip::for_action("Rerun task", &RerunTask, cx))
 973                .on_click(move |_, window, cx| {
 974                    window.dispatch_action(Box::new(terminal_rerun_override(&task_id)), cx);
 975                }),
 976        )
 977    }
 978}
 979
 980fn terminal_rerun_override(task: &TaskId) -> zed_actions::Rerun {
 981    zed_actions::Rerun {
 982        task_id: Some(task.0.clone()),
 983        allow_concurrent_runs: Some(true),
 984        use_new_terminal: Some(false),
 985        reevaluate_context: false,
 986    }
 987}
 988
 989fn subscribe_for_terminal_events(
 990    terminal: &Entity<Terminal>,
 991    workspace: WeakEntity<Workspace>,
 992    window: &mut Window,
 993    cx: &mut Context<TerminalView>,
 994) -> Vec<Subscription> {
 995    let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
 996    let mut previous_cwd = None;
 997    let terminal_events_subscription = cx.subscribe_in(
 998        terminal,
 999        window,
1000        move |terminal_view, terminal, event, window, cx| {
1001            let current_cwd = terminal.read(cx).working_directory();
1002            if current_cwd != previous_cwd {
1003                previous_cwd = current_cwd;
1004                terminal_view.needs_serialize = true;
1005            }
1006
1007            match event {
1008                Event::Wakeup => {
1009                    cx.notify();
1010                    cx.emit(Event::Wakeup);
1011                    cx.emit(ItemEvent::UpdateTab);
1012                    cx.emit(SearchEvent::MatchesInvalidated);
1013                }
1014
1015                Event::Bell => {
1016                    terminal_view.has_bell = true;
1017                    cx.emit(Event::Wakeup);
1018                }
1019
1020                Event::BlinkChanged(blinking) => {
1021                    terminal_view.blinking_terminal_enabled = *blinking;
1022
1023                    // If in terminal-controlled mode and focused, update blink manager
1024                    if matches!(
1025                        TerminalSettings::get_global(cx).blinking,
1026                        TerminalBlink::TerminalControlled
1027                    ) && terminal_view.focus_handle.is_focused(window)
1028                    {
1029                        terminal_view.blink_manager.update(cx, |manager, cx| {
1030                            if *blinking {
1031                                manager.enable(cx);
1032                            } else {
1033                                manager.disable(cx);
1034                            }
1035                        });
1036                    }
1037                }
1038
1039                Event::TitleChanged => {
1040                    cx.emit(ItemEvent::UpdateTab);
1041                }
1042
1043                Event::NewNavigationTarget(maybe_navigation_target) => {
1044                    match maybe_navigation_target
1045                        .as_ref()
1046                        .zip(terminal.read(cx).last_content.last_hovered_word.as_ref())
1047                    {
1048                        Some((MaybeNavigationTarget::Url(url), hovered_word)) => {
1049                            if Some(hovered_word)
1050                                != terminal_view
1051                                    .hover
1052                                    .as_ref()
1053                                    .map(|hover| &hover.hovered_word)
1054                            {
1055                                terminal_view.hover = Some(HoverTarget {
1056                                    tooltip: url.clone(),
1057                                    hovered_word: hovered_word.clone(),
1058                                });
1059                                terminal_view.hover_tooltip_update = Task::ready(());
1060                                cx.notify();
1061                            }
1062                        }
1063                        Some((MaybeNavigationTarget::PathLike(path_like_target), hovered_word)) => {
1064                            if Some(hovered_word)
1065                                != terminal_view
1066                                    .hover
1067                                    .as_ref()
1068                                    .map(|hover| &hover.hovered_word)
1069                            {
1070                                terminal_view.hover = None;
1071                                terminal_view.hover_tooltip_update = hover_path_like_target(
1072                                    &workspace,
1073                                    hovered_word.clone(),
1074                                    path_like_target,
1075                                    cx,
1076                                );
1077                                cx.notify();
1078                            }
1079                        }
1080                        None => {
1081                            terminal_view.hover = None;
1082                            terminal_view.hover_tooltip_update = Task::ready(());
1083                            cx.notify();
1084                        }
1085                    }
1086                }
1087
1088                Event::Open(maybe_navigation_target) => match maybe_navigation_target {
1089                    MaybeNavigationTarget::Url(url) => cx.open_url(url),
1090                    MaybeNavigationTarget::PathLike(path_like_target) => open_path_like_target(
1091                        &workspace,
1092                        terminal_view,
1093                        path_like_target,
1094                        window,
1095                        cx,
1096                    ),
1097                },
1098                Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
1099                Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
1100                Event::SelectionsChanged => {
1101                    window.invalidate_character_coordinates();
1102                    cx.emit(SearchEvent::ActiveMatchChanged)
1103                }
1104            }
1105        },
1106    );
1107    vec![terminal_subscription, terminal_events_subscription]
1108}
1109
1110fn regex_search_for_query(query: &SearchQuery) -> Option<RegexSearch> {
1111    let str = query.as_str();
1112    if query.is_regex() {
1113        if str == "." {
1114            return None;
1115        }
1116        RegexSearch::new(str).ok()
1117    } else {
1118        RegexSearch::new(&regex::escape(str)).ok()
1119    }
1120}
1121
1122#[derive(Default)]
1123struct TerminalScrollbarSettingsWrapper;
1124
1125impl ScrollbarVisibility for TerminalScrollbarSettingsWrapper {
1126    fn visibility(&self, cx: &App) -> scrollbars::ShowScrollbar {
1127        TerminalSettings::get_global(cx)
1128            .scrollbar
1129            .show
1130            .map(ui_scrollbar_settings_from_raw)
1131            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
1132    }
1133}
1134
1135impl TerminalView {
1136    /// Attempts to process a keystroke in the terminal. Returns true if handled.
1137    ///
1138    /// In vi mode, explicitly triggers a re-render because vi navigation (like j/k)
1139    /// updates the cursor locally without sending data to the shell, so there's no
1140    /// shell output to automatically trigger a re-render.
1141    fn process_keystroke(&mut self, keystroke: &Keystroke, cx: &mut Context<Self>) -> bool {
1142        let (handled, vi_mode_enabled) = self.terminal.update(cx, |term, cx| {
1143            (
1144                term.try_keystroke(keystroke, TerminalSettings::get_global(cx).option_as_meta),
1145                term.vi_mode_enabled(),
1146            )
1147        });
1148
1149        if handled && vi_mode_enabled {
1150            cx.notify();
1151        }
1152
1153        handled
1154    }
1155
1156    fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1157        self.clear_bell(cx);
1158        self.pause_cursor_blinking(window, cx);
1159
1160        if self.process_keystroke(&event.keystroke, cx) {
1161            cx.stop_propagation();
1162        }
1163    }
1164
1165    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1166        self.terminal.update(cx, |terminal, _| {
1167            terminal.set_cursor_shape(self.cursor_shape);
1168            terminal.focus_in();
1169        });
1170
1171        let should_blink = match TerminalSettings::get_global(cx).blinking {
1172            TerminalBlink::Off => false,
1173            TerminalBlink::On => true,
1174            TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
1175        };
1176
1177        if should_blink {
1178            self.blink_manager.update(cx, BlinkManager::enable);
1179        }
1180
1181        window.invalidate_character_coordinates();
1182        cx.notify();
1183    }
1184
1185    fn focus_out(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1186        self.blink_manager.update(cx, BlinkManager::disable);
1187        self.terminal.update(cx, |terminal, _| {
1188            terminal.focus_out();
1189            terminal.set_cursor_shape(CursorShape::Hollow);
1190        });
1191        cx.notify();
1192    }
1193}
1194
1195impl Render for TerminalView {
1196    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1197        // TODO: this should be moved out of render
1198        self.scroll_handle.update(self.terminal.read(cx));
1199
1200        if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
1201            self.terminal.update(cx, |term, _| {
1202                let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
1203                match delta.cmp(&0) {
1204                    cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
1205                    cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
1206                    cmp::Ordering::Equal => {}
1207                }
1208            });
1209        }
1210
1211        let terminal_handle = self.terminal.clone();
1212        let terminal_view_handle = cx.entity();
1213
1214        let focused = self.focus_handle.is_focused(window);
1215
1216        div()
1217            .id("terminal-view")
1218            .size_full()
1219            .relative()
1220            .track_focus(&self.focus_handle(cx))
1221            .key_context(self.dispatch_context(cx))
1222            .on_action(cx.listener(TerminalView::send_text))
1223            .on_action(cx.listener(TerminalView::send_keystroke))
1224            .on_action(cx.listener(TerminalView::copy))
1225            .on_action(cx.listener(TerminalView::paste))
1226            .on_action(cx.listener(TerminalView::clear))
1227            .on_action(cx.listener(TerminalView::scroll_line_up))
1228            .on_action(cx.listener(TerminalView::scroll_line_down))
1229            .on_action(cx.listener(TerminalView::scroll_page_up))
1230            .on_action(cx.listener(TerminalView::scroll_page_down))
1231            .on_action(cx.listener(TerminalView::scroll_to_top))
1232            .on_action(cx.listener(TerminalView::scroll_to_bottom))
1233            .on_action(cx.listener(TerminalView::toggle_vi_mode))
1234            .on_action(cx.listener(TerminalView::show_character_palette))
1235            .on_action(cx.listener(TerminalView::select_all))
1236            .on_action(cx.listener(TerminalView::rerun_task))
1237            .on_action(cx.listener(TerminalView::rename_terminal))
1238            .on_key_down(cx.listener(Self::key_down))
1239            .on_mouse_down(
1240                MouseButton::Right,
1241                cx.listener(|this, event: &MouseDownEvent, window, cx| {
1242                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1243                        if this.terminal.read(cx).last_content.selection.is_none() {
1244                            this.terminal.update(cx, |terminal, _| {
1245                                terminal.select_word_at_event_position(event);
1246                            });
1247                        };
1248                        this.deploy_context_menu(event.position, window, cx);
1249                        cx.notify();
1250                    }
1251                }),
1252            )
1253            .child(
1254                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1255                div()
1256                    .id("terminal-view-container")
1257                    .size_full()
1258                    .bg(cx.theme().colors().editor_background)
1259                    .child(TerminalElement::new(
1260                        terminal_handle,
1261                        terminal_view_handle,
1262                        self.workspace.clone(),
1263                        self.focus_handle.clone(),
1264                        focused,
1265                        self.should_show_cursor(focused, cx),
1266                        self.block_below_cursor.clone(),
1267                        self.mode.clone(),
1268                    ))
1269                    .when(self.content_mode(window, cx).is_scrollable(), |div| {
1270                        div.custom_scrollbars(
1271                            Scrollbars::for_settings::<TerminalScrollbarSettingsWrapper>()
1272                                .show_along(ScrollAxes::Vertical)
1273                                .with_track_along(
1274                                    ScrollAxes::Vertical,
1275                                    cx.theme().colors().editor_background,
1276                                )
1277                                .tracked_scroll_handle(&self.scroll_handle),
1278                            window,
1279                            cx,
1280                        )
1281                    }),
1282            )
1283            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1284                deferred(
1285                    anchored()
1286                        .position(*position)
1287                        .anchor(gpui::Corner::TopLeft)
1288                        .child(menu.clone()),
1289                )
1290                .with_priority(1)
1291            }))
1292    }
1293}
1294
1295impl Item for TerminalView {
1296    type Event = ItemEvent;
1297
1298    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1299        Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
1300            let terminal = self.terminal().read(cx);
1301            let title = terminal.title(false);
1302            let pid = terminal.pid_getter()?.fallback_pid();
1303
1304            move |_, _| {
1305                v_flex()
1306                    .gap_1()
1307                    .child(Label::new(title.clone()))
1308                    .child(h_flex().flex_grow().child(Divider::horizontal()))
1309                    .child(
1310                        Label::new(format!("Process ID (PID): {}", pid))
1311                            .color(Color::Muted)
1312                            .size(LabelSize::Small),
1313                    )
1314                    .into_any_element()
1315            }
1316        }))))
1317    }
1318
1319    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1320        let terminal = self.terminal().read(cx);
1321        let title = self
1322            .custom_title
1323            .as_ref()
1324            .filter(|title| !title.trim().is_empty())
1325            .cloned()
1326            .unwrap_or_else(|| terminal.title(true));
1327
1328        let (icon, icon_color, rerun_button) = match terminal.task() {
1329            Some(terminal_task) => match &terminal_task.status {
1330                TaskStatus::Running => (
1331                    IconName::PlayFilled,
1332                    Color::Disabled,
1333                    TerminalView::rerun_button(terminal_task),
1334                ),
1335                TaskStatus::Unknown => (
1336                    IconName::Warning,
1337                    Color::Warning,
1338                    TerminalView::rerun_button(terminal_task),
1339                ),
1340                TaskStatus::Completed { success } => {
1341                    let rerun_button = TerminalView::rerun_button(terminal_task);
1342
1343                    if *success {
1344                        (IconName::Check, Color::Success, rerun_button)
1345                    } else {
1346                        (IconName::XCircle, Color::Error, rerun_button)
1347                    }
1348                }
1349            },
1350            None => (IconName::Terminal, Color::Muted, None),
1351        };
1352
1353        let self_handle = self.self_handle.clone();
1354        h_flex()
1355            .gap_1()
1356            .group("term-tab-icon")
1357            .track_focus(&self.focus_handle)
1358            .on_action(move |action: &RenameTerminal, window, cx| {
1359                self_handle
1360                    .update(cx, |this, cx| this.rename_terminal(action, window, cx))
1361                    .ok();
1362            })
1363            .child(
1364                h_flex()
1365                    .group("term-tab-icon")
1366                    .child(
1367                        div()
1368                            .when(rerun_button.is_some(), |this| {
1369                                this.hover(|style| style.invisible().w_0())
1370                            })
1371                            .child(Icon::new(icon).color(icon_color)),
1372                    )
1373                    .when_some(rerun_button, |this, rerun_button| {
1374                        this.child(
1375                            div()
1376                                .absolute()
1377                                .visible_on_hover("term-tab-icon")
1378                                .child(rerun_button),
1379                        )
1380                    }),
1381            )
1382            .child(
1383                div()
1384                    .relative()
1385                    .child(
1386                        Label::new(title)
1387                            .color(params.text_color())
1388                            .when(self.is_renaming(), |this| this.alpha(0.)),
1389                    )
1390                    .when_some(self.rename_editor.clone(), |this, editor| {
1391                        let self_handle = self.self_handle.clone();
1392                        let self_handle_cancel = self.self_handle.clone();
1393                        this.child(
1394                            div()
1395                                .absolute()
1396                                .top_0()
1397                                .left_0()
1398                                .size_full()
1399                                .child(editor)
1400                                .on_action(move |_: &menu::Confirm, window, cx| {
1401                                    self_handle
1402                                        .update(cx, |this, cx| {
1403                                            this.finish_renaming(true, window, cx)
1404                                        })
1405                                        .ok();
1406                                })
1407                                .on_action(move |_: &menu::Cancel, window, cx| {
1408                                    self_handle_cancel
1409                                        .update(cx, |this, cx| {
1410                                            this.finish_renaming(false, window, cx)
1411                                        })
1412                                        .ok();
1413                                }),
1414                        )
1415                    }),
1416            )
1417            .into_any()
1418    }
1419
1420    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
1421        if let Some(custom_title) = self.custom_title.as_ref().filter(|l| !l.trim().is_empty()) {
1422            return custom_title.clone().into();
1423        }
1424        let terminal = self.terminal().read(cx);
1425        terminal.title(detail == 0).into()
1426    }
1427
1428    fn telemetry_event_text(&self) -> Option<&'static str> {
1429        None
1430    }
1431
1432    fn handle_drop(
1433        &self,
1434        active_pane: &Pane,
1435        dropped: &dyn Any,
1436        window: &mut Window,
1437        cx: &mut App,
1438    ) -> bool {
1439        let Some(project) = self.project.upgrade() else {
1440            return false;
1441        };
1442
1443        if let Some(paths) = dropped.downcast_ref::<ExternalPaths>() {
1444            let is_local = project.read(cx).is_local();
1445            if is_local {
1446                self.add_paths_to_terminal(paths.paths(), window, cx);
1447                return true;
1448            }
1449
1450            return false;
1451        } else if let Some(tab) = dropped.downcast_ref::<DraggedTab>() {
1452            let Some(self_handle) = self.self_handle.upgrade() else {
1453                return false;
1454            };
1455
1456            let Some(workspace) = self.workspace.upgrade() else {
1457                return false;
1458            };
1459
1460            let Some(this_pane) = workspace.read(cx).pane_for(&self_handle) else {
1461                return false;
1462            };
1463
1464            let item = if tab.pane == this_pane {
1465                active_pane.item_for_index(tab.ix)
1466            } else {
1467                tab.pane.read(cx).item_for_index(tab.ix)
1468            };
1469
1470            let Some(item) = item else {
1471                return false;
1472            };
1473
1474            if item.downcast::<TerminalView>().is_some() {
1475                let Some(split_direction) = active_pane.drag_split_direction() else {
1476                    return false;
1477                };
1478
1479                let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1480                    return false;
1481                };
1482
1483                if !terminal_panel.read(cx).center.panes().contains(&&this_pane) {
1484                    return false;
1485                }
1486
1487                let source = tab.pane.clone();
1488                let item_id_to_move = item.item_id();
1489                let is_zoomed = {
1490                    let terminal_panel = terminal_panel.read(cx);
1491                    if terminal_panel.active_pane == this_pane {
1492                        active_pane.is_zoomed()
1493                    } else {
1494                        terminal_panel.active_pane.read(cx).is_zoomed()
1495                    }
1496                };
1497
1498                let workspace = workspace.downgrade();
1499                let terminal_panel = terminal_panel.downgrade();
1500                // Defer the split operation to avoid re-entrancy panic.
1501                // The pane may be the one currently being updated, so we cannot
1502                // call mark_positions (via split) synchronously.
1503                window
1504                    .spawn(cx, async move |cx| {
1505                        cx.update(|window, cx| {
1506                            let Ok(new_pane) = terminal_panel.update(cx, |terminal_panel, cx| {
1507                                let new_pane = terminal_panel::new_terminal_pane(
1508                                    workspace, project, is_zoomed, window, cx,
1509                                );
1510                                terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1511                                terminal_panel.center.split(
1512                                    &this_pane,
1513                                    &new_pane,
1514                                    split_direction,
1515                                    cx,
1516                                );
1517                                anyhow::Ok(new_pane)
1518                            }) else {
1519                                return;
1520                            };
1521
1522                            let Some(new_pane) = new_pane.log_err() else {
1523                                return;
1524                            };
1525
1526                            workspace::move_item(
1527                                &source,
1528                                &new_pane,
1529                                item_id_to_move,
1530                                new_pane.read(cx).active_item_index(),
1531                                true,
1532                                window,
1533                                cx,
1534                            );
1535                        })
1536                        .ok();
1537                    })
1538                    .detach();
1539
1540                return true;
1541            } else {
1542                if let Some(project_path) = item.project_path(cx)
1543                    && let Some(path) = project.read(cx).absolute_path(&project_path, cx)
1544                {
1545                    self.add_paths_to_terminal(&[path], window, cx);
1546                    return true;
1547                }
1548            }
1549
1550            return false;
1551        } else if let Some(selection) = dropped.downcast_ref::<DraggedSelection>() {
1552            let project = project.read(cx);
1553            let paths = selection
1554                .items()
1555                .map(|selected_entry| selected_entry.entry_id)
1556                .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1557                .filter_map(|project_path| project.absolute_path(&project_path, cx))
1558                .collect::<Vec<_>>();
1559
1560            if !paths.is_empty() {
1561                self.add_paths_to_terminal(&paths, window, cx);
1562            }
1563
1564            return true;
1565        } else if let Some(&entry_id) = dropped.downcast_ref::<ProjectEntryId>() {
1566            let project = project.read(cx);
1567            if let Some(path) = project
1568                .path_for_entry(entry_id, cx)
1569                .and_then(|project_path| project.absolute_path(&project_path, cx))
1570            {
1571                self.add_paths_to_terminal(&[path], window, cx);
1572            }
1573
1574            return true;
1575        }
1576
1577        false
1578    }
1579
1580    fn tab_extra_context_menu_actions(
1581        &self,
1582        _window: &mut Window,
1583        cx: &mut Context<Self>,
1584    ) -> Vec<(SharedString, Box<dyn gpui::Action>)> {
1585        let terminal = self.terminal.read(cx);
1586        if terminal.task().is_none() {
1587            vec![("Rename".into(), Box::new(RenameTerminal))]
1588        } else {
1589            Vec::new()
1590        }
1591    }
1592
1593    fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
1594        workspace::item::ItemBufferKind::Singleton
1595    }
1596
1597    fn can_split(&self) -> bool {
1598        true
1599    }
1600
1601    fn clone_on_split(
1602        &self,
1603        workspace_id: Option<WorkspaceId>,
1604        window: &mut Window,
1605        cx: &mut Context<Self>,
1606    ) -> Task<Option<Entity<Self>>> {
1607        let Ok(terminal) = self.project.update(cx, |project, cx| {
1608            let cwd = project
1609                .active_project_directory(cx)
1610                .map(|it| it.to_path_buf());
1611            project.clone_terminal(self.terminal(), cx, cwd)
1612        }) else {
1613            return Task::ready(None);
1614        };
1615        cx.spawn_in(window, async move |this, cx| {
1616            let terminal = terminal.await.log_err()?;
1617            this.update_in(cx, |this, window, cx| {
1618                cx.new(|cx| {
1619                    TerminalView::new(
1620                        terminal,
1621                        this.workspace.clone(),
1622                        workspace_id,
1623                        this.project.clone(),
1624                        window,
1625                        cx,
1626                    )
1627                })
1628            })
1629            .ok()
1630        })
1631    }
1632
1633    fn is_dirty(&self, cx: &App) -> bool {
1634        match self.terminal.read(cx).task() {
1635            Some(task) => task.status == TaskStatus::Running,
1636            None => self.has_bell(),
1637        }
1638    }
1639
1640    fn has_conflict(&self, _cx: &App) -> bool {
1641        false
1642    }
1643
1644    fn can_save_as(&self, _cx: &App) -> bool {
1645        false
1646    }
1647
1648    fn as_searchable(
1649        &self,
1650        handle: &Entity<Self>,
1651        _: &App,
1652    ) -> Option<Box<dyn SearchableItemHandle>> {
1653        Some(Box::new(handle.clone()))
1654    }
1655
1656    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1657        if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1658            ToolbarItemLocation::PrimaryLeft
1659        } else {
1660            ToolbarItemLocation::Hidden
1661        }
1662    }
1663
1664    fn breadcrumbs(&self, cx: &App) -> Option<(Vec<HighlightedText>, Option<Font>)> {
1665        Some((
1666            vec![HighlightedText {
1667                text: self.terminal().read(cx).breadcrumb_text.clone().into(),
1668                highlights: vec![],
1669            }],
1670            None,
1671        ))
1672    }
1673
1674    fn added_to_workspace(
1675        &mut self,
1676        workspace: &mut Workspace,
1677        _: &mut Window,
1678        cx: &mut Context<Self>,
1679    ) {
1680        if self.terminal().read(cx).task().is_none() {
1681            if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1682                log::debug!(
1683                    "Updating workspace id for the terminal, old: {old_id:?}, new: {new_id:?}",
1684                );
1685                let db = TerminalDb::global(cx);
1686                let entity_id = cx.entity_id().as_u64();
1687                cx.background_spawn(async move {
1688                    db.update_workspace_id(new_id, old_id, entity_id).await
1689                })
1690                .detach();
1691            }
1692            self.workspace_id = workspace.database_id();
1693        }
1694    }
1695
1696    fn to_item_events(event: &Self::Event, f: &mut dyn FnMut(ItemEvent)) {
1697        f(*event)
1698    }
1699}
1700
1701impl SerializableItem for TerminalView {
1702    fn serialized_item_kind() -> &'static str {
1703        "Terminal"
1704    }
1705
1706    fn cleanup(
1707        workspace_id: WorkspaceId,
1708        alive_items: Vec<workspace::ItemId>,
1709        _window: &mut Window,
1710        cx: &mut App,
1711    ) -> Task<anyhow::Result<()>> {
1712        let db = TerminalDb::global(cx);
1713        delete_unloaded_items(alive_items, workspace_id, "terminals", &db, cx)
1714    }
1715
1716    fn serialize(
1717        &mut self,
1718        _workspace: &mut Workspace,
1719        item_id: workspace::ItemId,
1720        _closing: bool,
1721        _: &mut Window,
1722        cx: &mut Context<Self>,
1723    ) -> Option<Task<anyhow::Result<()>>> {
1724        let terminal = self.terminal().read(cx);
1725        if terminal.task().is_some() {
1726            return None;
1727        }
1728
1729        if !self.needs_serialize {
1730            return None;
1731        }
1732
1733        let workspace_id = self.workspace_id?;
1734        let cwd = terminal.working_directory();
1735        let custom_title = self.custom_title.clone();
1736        self.needs_serialize = false;
1737
1738        let db = TerminalDb::global(cx);
1739        Some(cx.background_spawn(async move {
1740            if let Some(cwd) = cwd {
1741                db.save_working_directory(item_id, workspace_id, cwd)
1742                    .await?;
1743            }
1744            db.save_custom_title(item_id, workspace_id, custom_title)
1745                .await?;
1746            Ok(())
1747        }))
1748    }
1749
1750    fn should_serialize(&self, _: &Self::Event) -> bool {
1751        self.needs_serialize
1752    }
1753
1754    fn deserialize(
1755        project: Entity<Project>,
1756        workspace: WeakEntity<Workspace>,
1757        workspace_id: WorkspaceId,
1758        item_id: workspace::ItemId,
1759        window: &mut Window,
1760        cx: &mut App,
1761    ) -> Task<anyhow::Result<Entity<Self>>> {
1762        window.spawn(cx, async move |cx| {
1763            let (cwd, custom_title) = cx
1764                .update(|_window, cx| {
1765                    let db = TerminalDb::global(cx);
1766                    let from_db = db
1767                        .get_working_directory(item_id, workspace_id)
1768                        .log_err()
1769                        .flatten();
1770                    let cwd = if from_db
1771                        .as_ref()
1772                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1773                    {
1774                        from_db
1775                    } else {
1776                        workspace
1777                            .upgrade()
1778                            .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1779                    };
1780                    let custom_title = db
1781                        .get_custom_title(item_id, workspace_id)
1782                        .log_err()
1783                        .flatten()
1784                        .filter(|title| !title.trim().is_empty());
1785                    (cwd, custom_title)
1786                })
1787                .ok()
1788                .unwrap_or((None, None));
1789
1790            let terminal = project
1791                .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))
1792                .await?;
1793            cx.update(|window, cx| {
1794                cx.new(|cx| {
1795                    let mut view = TerminalView::new(
1796                        terminal,
1797                        workspace,
1798                        Some(workspace_id),
1799                        project.downgrade(),
1800                        window,
1801                        cx,
1802                    );
1803                    if custom_title.is_some() {
1804                        view.custom_title = custom_title;
1805                    }
1806                    view
1807                })
1808            })
1809        })
1810    }
1811}
1812
1813impl SearchableItem for TerminalView {
1814    type Match = RangeInclusive<AlacPoint>;
1815
1816    fn supported_options(&self) -> SearchOptions {
1817        SearchOptions {
1818            case: false,
1819            word: false,
1820            regex: true,
1821            replacement: false,
1822            selection: false,
1823            find_in_results: false,
1824        }
1825    }
1826
1827    /// Clear stored matches
1828    fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1829        self.terminal().update(cx, |term, _| term.matches.clear())
1830    }
1831
1832    /// Store matches returned from find_matches somewhere for rendering
1833    fn update_matches(
1834        &mut self,
1835        matches: &[Self::Match],
1836        _active_match_index: Option<usize>,
1837        _token: SearchToken,
1838        _window: &mut Window,
1839        cx: &mut Context<Self>,
1840    ) {
1841        self.terminal()
1842            .update(cx, |term, _| term.matches = matches.to_vec())
1843    }
1844
1845    /// Returns the selection content to pre-load into this search
1846    fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1847        self.terminal()
1848            .read(cx)
1849            .last_content
1850            .selection_text
1851            .clone()
1852            .unwrap_or_default()
1853    }
1854
1855    /// Focus match at given index into the Vec of matches
1856    fn activate_match(
1857        &mut self,
1858        index: usize,
1859        _: &[Self::Match],
1860        _token: SearchToken,
1861        _window: &mut Window,
1862        cx: &mut Context<Self>,
1863    ) {
1864        self.terminal()
1865            .update(cx, |term, _| term.activate_match(index));
1866        cx.notify();
1867    }
1868
1869    /// Add selections for all matches given.
1870    fn select_matches(
1871        &mut self,
1872        matches: &[Self::Match],
1873        _token: SearchToken,
1874        _: &mut Window,
1875        cx: &mut Context<Self>,
1876    ) {
1877        self.terminal()
1878            .update(cx, |term, _| term.select_matches(matches));
1879        cx.notify();
1880    }
1881
1882    /// Get all of the matches for this query, should be done on the background
1883    fn find_matches(
1884        &mut self,
1885        query: Arc<SearchQuery>,
1886        _: &mut Window,
1887        cx: &mut Context<Self>,
1888    ) -> Task<Vec<Self::Match>> {
1889        if let Some(s) = regex_search_for_query(&query) {
1890            self.terminal()
1891                .update(cx, |term, cx| term.find_matches(s, cx))
1892        } else {
1893            Task::ready(vec![])
1894        }
1895    }
1896
1897    /// Reports back to the search toolbar what the active match should be (the selection)
1898    fn active_match_index(
1899        &mut self,
1900        direction: Direction,
1901        matches: &[Self::Match],
1902        _token: SearchToken,
1903        _: &mut Window,
1904        cx: &mut Context<Self>,
1905    ) -> Option<usize> {
1906        // Selection head might have a value if there's a selection that isn't
1907        // associated with a match. Therefore, if there are no matches, we should
1908        // report None, no matter the state of the terminal
1909
1910        if !matches.is_empty() {
1911            if let Some(selection_head) = self.terminal().read(cx).selection_head {
1912                // If selection head is contained in a match. Return that match
1913                match direction {
1914                    Direction::Prev => {
1915                        // If no selection before selection head, return the first match
1916                        Some(
1917                            matches
1918                                .iter()
1919                                .enumerate()
1920                                .rev()
1921                                .find(|(_, search_match)| {
1922                                    search_match.contains(&selection_head)
1923                                        || search_match.start() < &selection_head
1924                                })
1925                                .map(|(ix, _)| ix)
1926                                .unwrap_or(0),
1927                        )
1928                    }
1929                    Direction::Next => {
1930                        // If no selection after selection head, return the last match
1931                        Some(
1932                            matches
1933                                .iter()
1934                                .enumerate()
1935                                .find(|(_, search_match)| {
1936                                    search_match.contains(&selection_head)
1937                                        || search_match.start() > &selection_head
1938                                })
1939                                .map(|(ix, _)| ix)
1940                                .unwrap_or(matches.len().saturating_sub(1)),
1941                        )
1942                    }
1943                }
1944            } else {
1945                // Matches found but no active selection, return the first last one (closest to cursor)
1946                Some(matches.len().saturating_sub(1))
1947            }
1948        } else {
1949            None
1950        }
1951    }
1952    fn replace(
1953        &mut self,
1954        _: &Self::Match,
1955        _: &SearchQuery,
1956        _token: SearchToken,
1957        _window: &mut Window,
1958        _: &mut Context<Self>,
1959    ) {
1960        // Replacement is not supported in terminal view, so this is a no-op.
1961    }
1962}
1963
1964/// Gets the working directory for the given workspace, respecting the user's settings.
1965/// Falls back to home directory when no project directory is available.
1966pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1967    let directory = match &TerminalSettings::get_global(cx).working_directory {
1968        WorkingDirectory::CurrentFileDirectory => workspace
1969            .project()
1970            .read(cx)
1971            .active_entry_directory(cx)
1972            .or_else(|| current_project_directory(workspace, cx)),
1973        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx),
1974        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1975        WorkingDirectory::AlwaysHome => None,
1976        WorkingDirectory::Always { directory } => shellexpand::full(directory)
1977            .ok()
1978            .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1979            .filter(|dir| dir.is_dir()),
1980    };
1981    directory.or_else(dirs::home_dir)
1982}
1983
1984fn current_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1985    workspace
1986        .project()
1987        .read(cx)
1988        .active_project_directory(cx)
1989        .as_deref()
1990        .map(Path::to_path_buf)
1991        .or_else(|| first_project_directory(workspace, cx))
1992}
1993
1994///Gets the first project's home directory, or the home directory
1995fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1996    let worktree = workspace.worktrees(cx).next()?.read(cx);
1997    let worktree_path = worktree.abs_path();
1998    if worktree.root_entry()?.is_dir() {
1999        Some(worktree_path.to_path_buf())
2000    } else {
2001        // If worktree is a file, return its parent directory
2002        worktree_path.parent().map(|p| p.to_path_buf())
2003    }
2004}
2005
2006#[cfg(test)]
2007mod tests {
2008    use super::*;
2009    use gpui::TestAppContext;
2010    use project::{Entry, Project, ProjectPath, Worktree};
2011    use std::path::{Path, PathBuf};
2012    use util::paths::PathStyle;
2013    use util::rel_path::RelPath;
2014    use workspace::item::test::{TestItem, TestProjectItem};
2015    use workspace::{AppState, MultiWorkspace, SelectedEntry};
2016
2017    fn expected_drop_text(paths: &[PathBuf]) -> String {
2018        let mut text = String::new();
2019        for path in paths {
2020            text.push(' ');
2021            text.push_str(&format!("{path:?}"));
2022        }
2023        text.push(' ');
2024        text
2025    }
2026
2027    fn assert_drop_writes_to_terminal(
2028        pane: &Entity<Pane>,
2029        terminal_view_index: usize,
2030        terminal: &Entity<Terminal>,
2031        dropped: &dyn Any,
2032        expected_text: &str,
2033        window: &mut Window,
2034        cx: &mut Context<MultiWorkspace>,
2035    ) {
2036        let _ = terminal.update(cx, |terminal, _| terminal.take_input_log());
2037
2038        let handled = pane.update(cx, |pane, cx| {
2039            pane.item_for_index(terminal_view_index)
2040                .unwrap()
2041                .handle_drop(pane, dropped, window, cx)
2042        });
2043        assert!(handled, "handle_drop should return true for {:?}", dropped);
2044
2045        let mut input_log = terminal.update(cx, |terminal, _| terminal.take_input_log());
2046        assert_eq!(input_log.len(), 1, "expected exactly one write to terminal");
2047        let written =
2048            String::from_utf8(input_log.remove(0)).expect("terminal write should be valid UTF-8");
2049        assert_eq!(written, expected_text);
2050    }
2051
2052    // Working directory calculation tests
2053
2054    // No Worktrees in project -> home_dir()
2055    #[gpui::test]
2056    async fn no_worktree(cx: &mut TestAppContext) {
2057        let (project, workspace) = init_test(cx).await;
2058        cx.read(|cx| {
2059            let workspace = workspace.read(cx);
2060            let active_entry = project.read(cx).active_entry();
2061
2062            //Make sure environment is as expected
2063            assert!(active_entry.is_none());
2064            assert!(workspace.worktrees(cx).next().is_none());
2065
2066            let res = default_working_directory(workspace, cx);
2067            assert_eq!(res, dirs::home_dir());
2068            let res = first_project_directory(workspace, cx);
2069            assert_eq!(res, None);
2070        });
2071    }
2072
2073    // No active entry, but a worktree, worktree is a file -> parent directory
2074    #[gpui::test]
2075    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
2076        let (project, workspace) = init_test(cx).await;
2077
2078        create_file_wt(project.clone(), "/root.txt", cx).await;
2079        cx.read(|cx| {
2080            let workspace = workspace.read(cx);
2081            let active_entry = project.read(cx).active_entry();
2082
2083            //Make sure environment is as expected
2084            assert!(active_entry.is_none());
2085            assert!(workspace.worktrees(cx).next().is_some());
2086
2087            let res = default_working_directory(workspace, cx);
2088            assert_eq!(res, Some(Path::new("/").to_path_buf()));
2089            let res = first_project_directory(workspace, cx);
2090            assert_eq!(res, Some(Path::new("/").to_path_buf()));
2091        });
2092    }
2093
2094    // No active entry, but a worktree, worktree is a folder -> worktree_folder
2095    #[gpui::test]
2096    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
2097        let (project, workspace) = init_test(cx).await;
2098
2099        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2100        cx.update(|cx| {
2101            let workspace = workspace.read(cx);
2102            let active_entry = project.read(cx).active_entry();
2103
2104            assert!(active_entry.is_none());
2105            assert!(workspace.worktrees(cx).next().is_some());
2106
2107            let res = default_working_directory(workspace, cx);
2108            assert_eq!(res, Some(Path::new("/root/").to_path_buf()));
2109            let res = first_project_directory(workspace, cx);
2110            assert_eq!(res, Some(Path::new("/root/").to_path_buf()));
2111        });
2112    }
2113
2114    // Active entry with a work tree, worktree is a file -> worktree_folder()
2115    #[gpui::test]
2116    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
2117        let (project, workspace) = init_test(cx).await;
2118
2119        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
2120        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
2121        insert_active_entry_for(wt2, entry2, project.clone(), cx);
2122
2123        cx.update(|cx| {
2124            let workspace = workspace.read(cx);
2125            let active_entry = project.read(cx).active_entry();
2126
2127            assert!(active_entry.is_some());
2128
2129            let res = default_working_directory(workspace, cx);
2130            assert_eq!(res, Some(Path::new("/root1/").to_path_buf()));
2131            let res = first_project_directory(workspace, cx);
2132            assert_eq!(res, Some(Path::new("/root1/").to_path_buf()));
2133        });
2134    }
2135
2136    // Active entry, with a worktree, worktree is a folder -> worktree_folder
2137    #[gpui::test]
2138    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
2139        let (project, workspace) = init_test(cx).await;
2140
2141        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
2142        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
2143        insert_active_entry_for(wt2, entry2, project.clone(), cx);
2144
2145        cx.update(|cx| {
2146            let workspace = workspace.read(cx);
2147            let active_entry = project.read(cx).active_entry();
2148
2149            assert!(active_entry.is_some());
2150
2151            let res = default_working_directory(workspace, cx);
2152            assert_eq!(res, Some(Path::new("/root2/").to_path_buf()));
2153            let res = first_project_directory(workspace, cx);
2154            assert_eq!(res, Some(Path::new("/root1/").to_path_buf()));
2155        });
2156    }
2157
2158    // active_entry_directory: No active entry -> returns None (used by CurrentFileDirectory)
2159    #[gpui::test]
2160    async fn active_entry_directory_no_active_entry(cx: &mut TestAppContext) {
2161        let (project, _workspace) = init_test(cx).await;
2162
2163        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2164
2165        cx.update(|cx| {
2166            assert!(project.read(cx).active_entry().is_none());
2167
2168            let res = project.read(cx).active_entry_directory(cx);
2169            assert_eq!(res, None);
2170        });
2171    }
2172
2173    // active_entry_directory: Active entry is file -> returns parent directory (used by CurrentFileDirectory)
2174    #[gpui::test]
2175    async fn active_entry_directory_active_file(cx: &mut TestAppContext) {
2176        let (project, _workspace) = init_test(cx).await;
2177
2178        let (wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2179        let entry = create_file_in_worktree(wt.clone(), "src/main.rs", cx).await;
2180        insert_active_entry_for(wt, entry, project.clone(), cx);
2181
2182        cx.update(|cx| {
2183            let res = project.read(cx).active_entry_directory(cx);
2184            assert_eq!(res, Some(Path::new("/root/src").to_path_buf()));
2185        });
2186    }
2187
2188    // active_entry_directory: Active entry is directory -> returns that directory (used by CurrentFileDirectory)
2189    #[gpui::test]
2190    async fn active_entry_directory_active_dir(cx: &mut TestAppContext) {
2191        let (project, _workspace) = init_test(cx).await;
2192
2193        let (wt, entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2194        insert_active_entry_for(wt, entry, project.clone(), cx);
2195
2196        cx.update(|cx| {
2197            let res = project.read(cx).active_entry_directory(cx);
2198            assert_eq!(res, Some(Path::new("/root/").to_path_buf()));
2199        });
2200    }
2201
2202    /// Creates a worktree with 1 file: /root.txt
2203    pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
2204        let (project, workspace, _) = init_test_with_window(cx).await;
2205        (project, workspace)
2206    }
2207
2208    /// Creates a worktree with 1 file /root.txt and returns the project, workspace, and window handle.
2209    async fn init_test_with_window(
2210        cx: &mut TestAppContext,
2211    ) -> (
2212        Entity<Project>,
2213        Entity<Workspace>,
2214        gpui::WindowHandle<MultiWorkspace>,
2215    ) {
2216        let params = cx.update(AppState::test);
2217        cx.update(|cx| {
2218            theme_settings::init(theme::LoadThemes::JustBase, cx);
2219        });
2220
2221        let project = Project::test(params.fs.clone(), [], cx).await;
2222        let window_handle =
2223            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2224        let workspace = window_handle
2225            .read_with(cx, |mw, _| mw.workspace().clone())
2226            .unwrap();
2227
2228        (project, workspace, window_handle)
2229    }
2230
2231    /// Creates a file in the given worktree and returns its entry.
2232    async fn create_file_in_worktree(
2233        worktree: Entity<Worktree>,
2234        relative_path: impl AsRef<Path>,
2235        cx: &mut TestAppContext,
2236    ) -> Entry {
2237        cx.update(|cx| {
2238            worktree.update(cx, |worktree, cx| {
2239                worktree.create_entry(
2240                    RelPath::new(relative_path.as_ref(), PathStyle::local())
2241                        .unwrap()
2242                        .as_ref()
2243                        .into(),
2244                    false,
2245                    None,
2246                    cx,
2247                )
2248            })
2249        })
2250        .await
2251        .unwrap()
2252        .into_included()
2253        .unwrap()
2254    }
2255
2256    /// Creates a worktree with 1 folder: /root{suffix}/
2257    async fn create_folder_wt(
2258        project: Entity<Project>,
2259        path: impl AsRef<Path>,
2260        cx: &mut TestAppContext,
2261    ) -> (Entity<Worktree>, Entry) {
2262        create_wt(project, true, path, cx).await
2263    }
2264
2265    /// Creates a worktree with 1 file: /root{suffix}.txt
2266    async fn create_file_wt(
2267        project: Entity<Project>,
2268        path: impl AsRef<Path>,
2269        cx: &mut TestAppContext,
2270    ) -> (Entity<Worktree>, Entry) {
2271        create_wt(project, false, path, cx).await
2272    }
2273
2274    async fn create_wt(
2275        project: Entity<Project>,
2276        is_dir: bool,
2277        path: impl AsRef<Path>,
2278        cx: &mut TestAppContext,
2279    ) -> (Entity<Worktree>, Entry) {
2280        let (wt, _) = project
2281            .update(cx, |project, cx| {
2282                project.find_or_create_worktree(path, true, cx)
2283            })
2284            .await
2285            .unwrap();
2286
2287        let entry = cx
2288            .update(|cx| {
2289                wt.update(cx, |wt, cx| {
2290                    wt.create_entry(RelPath::empty().into(), is_dir, None, cx)
2291                })
2292            })
2293            .await
2294            .unwrap()
2295            .into_included()
2296            .unwrap();
2297
2298        (wt, entry)
2299    }
2300
2301    pub fn insert_active_entry_for(
2302        wt: Entity<Worktree>,
2303        entry: Entry,
2304        project: Entity<Project>,
2305        cx: &mut TestAppContext,
2306    ) {
2307        cx.update(|cx| {
2308            let p = ProjectPath {
2309                worktree_id: wt.read(cx).id(),
2310                path: entry.path,
2311            };
2312            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
2313        });
2314    }
2315
2316    // Terminal drag/drop test
2317
2318    #[gpui::test]
2319    async fn test_handle_drop_writes_paths_for_all_drop_types(cx: &mut TestAppContext) {
2320        let (project, _workspace, window_handle) = init_test_with_window(cx).await;
2321
2322        let (worktree, _) = create_folder_wt(project.clone(), "/root/", cx).await;
2323        let first_entry = create_file_in_worktree(worktree.clone(), "first.txt", cx).await;
2324        let second_entry = create_file_in_worktree(worktree.clone(), "second.txt", cx).await;
2325
2326        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
2327        let first_path = project
2328            .read_with(cx, |project, cx| {
2329                project.absolute_path(
2330                    &ProjectPath {
2331                        worktree_id,
2332                        path: first_entry.path.clone(),
2333                    },
2334                    cx,
2335                )
2336            })
2337            .unwrap();
2338        let second_path = project
2339            .read_with(cx, |project, cx| {
2340                project.absolute_path(
2341                    &ProjectPath {
2342                        worktree_id,
2343                        path: second_entry.path.clone(),
2344                    },
2345                    cx,
2346                )
2347            })
2348            .unwrap();
2349
2350        let (active_pane, terminal, terminal_view, tab_item) = window_handle
2351            .update(cx, |multi_workspace, window, cx| {
2352                let workspace = multi_workspace.workspace().clone();
2353                let active_pane = workspace.read(cx).active_pane().clone();
2354
2355                let terminal = cx.new(|cx| {
2356                    terminal::TerminalBuilder::new_display_only(
2357                        CursorShape::default(),
2358                        terminal::terminal_settings::AlternateScroll::On,
2359                        None,
2360                        0,
2361                        cx.background_executor(),
2362                        PathStyle::local(),
2363                    )
2364                    .unwrap()
2365                    .subscribe(cx)
2366                });
2367                let terminal_view = cx.new(|cx| {
2368                    TerminalView::new(
2369                        terminal.clone(),
2370                        workspace.downgrade(),
2371                        None,
2372                        project.downgrade(),
2373                        window,
2374                        cx,
2375                    )
2376                });
2377
2378                active_pane.update(cx, |pane, cx| {
2379                    pane.add_item(
2380                        Box::new(terminal_view.clone()),
2381                        true,
2382                        false,
2383                        None,
2384                        window,
2385                        cx,
2386                    );
2387                });
2388
2389                let tab_project_item = cx.new(|_| TestProjectItem {
2390                    entry_id: Some(second_entry.id),
2391                    project_path: Some(ProjectPath {
2392                        worktree_id,
2393                        path: second_entry.path.clone(),
2394                    }),
2395                    is_dirty: false,
2396                });
2397                let tab_item =
2398                    cx.new(|cx| TestItem::new(cx).with_project_items(&[tab_project_item]));
2399                active_pane.update(cx, |pane, cx| {
2400                    pane.add_item(Box::new(tab_item.clone()), true, false, None, window, cx);
2401                });
2402
2403                (active_pane, terminal, terminal_view, tab_item)
2404            })
2405            .unwrap();
2406
2407        cx.run_until_parked();
2408
2409        window_handle
2410            .update(cx, |multi_workspace, window, cx| {
2411                let workspace = multi_workspace.workspace().clone();
2412                let terminal_view_index =
2413                    active_pane.read(cx).index_for_item(&terminal_view).unwrap();
2414                let dragged_tab_index = active_pane.read(cx).index_for_item(&tab_item).unwrap();
2415
2416                assert!(
2417                    workspace.read(cx).pane_for(&terminal_view).is_some(),
2418                    "terminal view not registered with workspace after run_until_parked"
2419                );
2420
2421                // Dragging an external file should write its path to the terminal
2422                let external_paths = ExternalPaths(vec![first_path.clone()].into());
2423                assert_drop_writes_to_terminal(
2424                    &active_pane,
2425                    terminal_view_index,
2426                    &terminal,
2427                    &external_paths,
2428                    &expected_drop_text(std::slice::from_ref(&first_path)),
2429                    window,
2430                    cx,
2431                );
2432
2433                // Dragging a tab should write the path of the tab's item to the terminal
2434                let dragged_tab = DraggedTab {
2435                    pane: active_pane.clone(),
2436                    item: Box::new(tab_item.clone()),
2437                    ix: dragged_tab_index,
2438                    detail: 0,
2439                    is_active: false,
2440                };
2441                assert_drop_writes_to_terminal(
2442                    &active_pane,
2443                    terminal_view_index,
2444                    &terminal,
2445                    &dragged_tab,
2446                    &expected_drop_text(std::slice::from_ref(&second_path)),
2447                    window,
2448                    cx,
2449                );
2450
2451                // Dragging multiple selections should write both paths to the terminal
2452                let dragged_selection = DraggedSelection {
2453                    active_selection: SelectedEntry {
2454                        worktree_id,
2455                        entry_id: first_entry.id,
2456                    },
2457                    marked_selections: Arc::from([
2458                        SelectedEntry {
2459                            worktree_id,
2460                            entry_id: first_entry.id,
2461                        },
2462                        SelectedEntry {
2463                            worktree_id,
2464                            entry_id: second_entry.id,
2465                        },
2466                    ]),
2467                };
2468                assert_drop_writes_to_terminal(
2469                    &active_pane,
2470                    terminal_view_index,
2471                    &terminal,
2472                    &dragged_selection,
2473                    &expected_drop_text(&[first_path.clone(), second_path.clone()]),
2474                    window,
2475                    cx,
2476                );
2477
2478                // Dropping a project entry should write the entry's path to the terminal
2479                let dropped_entry_id = first_entry.id;
2480                assert_drop_writes_to_terminal(
2481                    &active_pane,
2482                    terminal_view_index,
2483                    &terminal,
2484                    &dropped_entry_id,
2485                    &expected_drop_text(&[first_path]),
2486                    window,
2487                    cx,
2488                );
2489            })
2490            .unwrap();
2491    }
2492
2493    // Terminal rename tests
2494
2495    #[gpui::test]
2496    async fn test_custom_title_initially_none(cx: &mut TestAppContext) {
2497        cx.executor().allow_parking();
2498
2499        let (project, workspace) = init_test(cx).await;
2500
2501        let terminal = project
2502            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2503            .await
2504            .unwrap();
2505
2506        let terminal_view = cx
2507            .add_window(|window, cx| {
2508                TerminalView::new(
2509                    terminal,
2510                    workspace.downgrade(),
2511                    None,
2512                    project.downgrade(),
2513                    window,
2514                    cx,
2515                )
2516            })
2517            .root(cx)
2518            .unwrap();
2519
2520        terminal_view.update(cx, |view, _cx| {
2521            assert!(view.custom_title().is_none());
2522        });
2523    }
2524
2525    #[gpui::test]
2526    async fn test_set_custom_title(cx: &mut TestAppContext) {
2527        cx.executor().allow_parking();
2528
2529        let (project, workspace) = init_test(cx).await;
2530
2531        let terminal = project
2532            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2533            .await
2534            .unwrap();
2535
2536        let terminal_view = cx
2537            .add_window(|window, cx| {
2538                TerminalView::new(
2539                    terminal,
2540                    workspace.downgrade(),
2541                    None,
2542                    project.downgrade(),
2543                    window,
2544                    cx,
2545                )
2546            })
2547            .root(cx)
2548            .unwrap();
2549
2550        terminal_view.update(cx, |view, cx| {
2551            view.set_custom_title(Some("frontend".to_string()), cx);
2552            assert_eq!(view.custom_title(), Some("frontend"));
2553        });
2554    }
2555
2556    #[gpui::test]
2557    async fn test_set_custom_title_empty_becomes_none(cx: &mut TestAppContext) {
2558        cx.executor().allow_parking();
2559
2560        let (project, workspace) = init_test(cx).await;
2561
2562        let terminal = project
2563            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2564            .await
2565            .unwrap();
2566
2567        let terminal_view = cx
2568            .add_window(|window, cx| {
2569                TerminalView::new(
2570                    terminal,
2571                    workspace.downgrade(),
2572                    None,
2573                    project.downgrade(),
2574                    window,
2575                    cx,
2576                )
2577            })
2578            .root(cx)
2579            .unwrap();
2580
2581        terminal_view.update(cx, |view, cx| {
2582            view.set_custom_title(Some("test".to_string()), cx);
2583            assert_eq!(view.custom_title(), Some("test"));
2584
2585            view.set_custom_title(Some("".to_string()), cx);
2586            assert!(view.custom_title().is_none());
2587
2588            view.set_custom_title(Some("  ".to_string()), cx);
2589            assert!(view.custom_title().is_none());
2590        });
2591    }
2592
2593    #[gpui::test]
2594    async fn test_custom_title_marks_needs_serialize(cx: &mut TestAppContext) {
2595        cx.executor().allow_parking();
2596
2597        let (project, workspace) = init_test(cx).await;
2598
2599        let terminal = project
2600            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2601            .await
2602            .unwrap();
2603
2604        let terminal_view = cx
2605            .add_window(|window, cx| {
2606                TerminalView::new(
2607                    terminal,
2608                    workspace.downgrade(),
2609                    None,
2610                    project.downgrade(),
2611                    window,
2612                    cx,
2613                )
2614            })
2615            .root(cx)
2616            .unwrap();
2617
2618        terminal_view.update(cx, |view, cx| {
2619            view.needs_serialize = false;
2620            view.set_custom_title(Some("new_label".to_string()), cx);
2621            assert!(view.needs_serialize);
2622        });
2623    }
2624
2625    #[gpui::test]
2626    async fn test_tab_content_uses_custom_title(cx: &mut TestAppContext) {
2627        cx.executor().allow_parking();
2628
2629        let (project, workspace) = init_test(cx).await;
2630
2631        let terminal = project
2632            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2633            .await
2634            .unwrap();
2635
2636        let terminal_view = cx
2637            .add_window(|window, cx| {
2638                TerminalView::new(
2639                    terminal,
2640                    workspace.downgrade(),
2641                    None,
2642                    project.downgrade(),
2643                    window,
2644                    cx,
2645                )
2646            })
2647            .root(cx)
2648            .unwrap();
2649
2650        terminal_view.update(cx, |view, cx| {
2651            view.set_custom_title(Some("my-server".to_string()), cx);
2652            let text = view.tab_content_text(0, cx);
2653            assert_eq!(text.as_ref(), "my-server");
2654        });
2655
2656        terminal_view.update(cx, |view, cx| {
2657            view.set_custom_title(None, cx);
2658            let text = view.tab_content_text(0, cx);
2659            assert_ne!(text.as_ref(), "my-server");
2660        });
2661    }
2662
2663    #[gpui::test]
2664    async fn test_tab_content_shows_terminal_title_when_custom_title_directly_set_empty(
2665        cx: &mut TestAppContext,
2666    ) {
2667        cx.executor().allow_parking();
2668
2669        let (project, workspace) = init_test(cx).await;
2670
2671        let terminal = project
2672            .update(cx, |project, cx| project.create_terminal_shell(None, cx))
2673            .await
2674            .unwrap();
2675
2676        let terminal_view = cx
2677            .add_window(|window, cx| {
2678                TerminalView::new(
2679                    terminal,
2680                    workspace.downgrade(),
2681                    None,
2682                    project.downgrade(),
2683                    window,
2684                    cx,
2685                )
2686            })
2687            .root(cx)
2688            .unwrap();
2689
2690        terminal_view.update(cx, |view, cx| {
2691            view.custom_title = Some("".to_string());
2692            let text = view.tab_content_text(0, cx);
2693            assert!(
2694                !text.is_empty(),
2695                "Tab should show terminal title, not empty string; got: '{}'",
2696                text
2697            );
2698        });
2699
2700        terminal_view.update(cx, |view, cx| {
2701            view.custom_title = Some("   ".to_string());
2702            let text = view.tab_content_text(0, cx);
2703            assert!(
2704                !text.is_empty() && text.as_ref() != "   ",
2705                "Tab should show terminal title, not whitespace; got: '{}'",
2706                text
2707            );
2708        });
2709    }
2710}