terminal_view.rs

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