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