terminal_view.rs

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