terminal_view.rs

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