terminal_view.rs

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