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