terminal_view.rs

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