terminal_view.rs

   1mod persistence;
   2pub mod terminal_element;
   3pub mod terminal_panel;
   4
   5use crate::{persistence::TERMINAL_DB, terminal_element::TerminalElement};
   6use anyhow::Context;
   7use context_menu::{ContextMenu, ContextMenuItem};
   8use dirs::home_dir;
   9use editor::{scroll::autoscroll::Autoscroll, Editor};
  10use gpui::{
  11    actions,
  12    elements::{AnchorCorner, ChildView, Flex, Label, ParentElement, Stack},
  13    geometry::vector::Vector2F,
  14    impl_actions,
  15    keymap_matcher::{KeymapContext, Keystroke},
  16    platform::{KeyDownEvent, ModifiersChangedEvent},
  17    AnyElement, AnyViewHandle, AppContext, Element, Entity, ModelHandle, Task, View, ViewContext,
  18    ViewHandle, WeakViewHandle,
  19};
  20use language::Bias;
  21use project::{LocalWorktree, Project};
  22use serde::Deserialize;
  23use smallvec::{smallvec, SmallVec};
  24use smol::Timer;
  25use std::{
  26    borrow::Cow,
  27    ops::RangeInclusive,
  28    path::{Path, PathBuf},
  29    time::Duration,
  30};
  31use terminal::{
  32    alacritty_terminal::{
  33        index::Point,
  34        term::{search::RegexSearch, TermMode},
  35    },
  36    Event, MaybeNavigationTarget, Terminal, TerminalBlink, WorkingDirectory,
  37};
  38use util::{paths::PathLikeWithPosition, ResultExt};
  39use workspace::{
  40    item::{BreadcrumbText, Item, ItemEvent},
  41    notifications::NotifyResultExt,
  42    pane, register_deserializable_item,
  43    searchable::{SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
  44    NewCenterTerminal, Pane, ToolbarItemLocation, Workspace, WorkspaceId,
  45};
  46
  47pub use terminal::TerminalSettings;
  48
  49const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  50
  51///Event to transmit the scroll from the element to the view
  52#[derive(Clone, Debug, PartialEq)]
  53pub struct ScrollTerminal(pub i32);
  54
  55#[derive(Clone, Default, Deserialize, PartialEq)]
  56pub struct SendText(String);
  57
  58#[derive(Clone, Default, Deserialize, PartialEq)]
  59pub struct SendKeystroke(String);
  60
  61actions!(
  62    terminal,
  63    [Clear, Copy, Paste, ShowCharacterPalette, SearchTest]
  64);
  65
  66impl_actions!(terminal, [SendText, SendKeystroke]);
  67
  68pub fn init(cx: &mut AppContext) {
  69    terminal_panel::init(cx);
  70    terminal::init(cx);
  71
  72    register_deserializable_item::<TerminalView>(cx);
  73
  74    cx.add_action(TerminalView::deploy);
  75
  76    //Useful terminal views
  77    cx.add_action(TerminalView::send_text);
  78    cx.add_action(TerminalView::send_keystroke);
  79    cx.add_action(TerminalView::copy);
  80    cx.add_action(TerminalView::paste);
  81    cx.add_action(TerminalView::clear);
  82    cx.add_action(TerminalView::show_character_palette);
  83}
  84
  85///A terminal view, maintains the PTY's file handles and communicates with the terminal
  86pub struct TerminalView {
  87    terminal: ModelHandle<Terminal>,
  88    has_new_content: bool,
  89    //Currently using iTerm bell, show bell emoji in tab until input is received
  90    has_bell: bool,
  91    context_menu: ViewHandle<ContextMenu>,
  92    blink_state: bool,
  93    blinking_on: bool,
  94    blinking_paused: bool,
  95    blink_epoch: usize,
  96    can_navigate_to_selected_word: bool,
  97    workspace_id: WorkspaceId,
  98}
  99
 100impl Entity for TerminalView {
 101    type Event = Event;
 102}
 103
 104impl TerminalView {
 105    ///Create a new Terminal in the current working directory or the user's home directory
 106    pub fn deploy(
 107        workspace: &mut Workspace,
 108        _: &NewCenterTerminal,
 109        cx: &mut ViewContext<Workspace>,
 110    ) {
 111        let strategy = settings::get::<TerminalSettings>(cx);
 112        let working_directory =
 113            get_working_directory(workspace, cx, strategy.working_directory.clone());
 114
 115        let window_id = cx.window_id();
 116        let terminal = workspace
 117            .project()
 118            .update(cx, |project, cx| {
 119                project.create_terminal(working_directory, window_id, cx)
 120            })
 121            .notify_err(workspace, cx);
 122
 123        if let Some(terminal) = terminal {
 124            let view = cx.add_view(|cx| {
 125                TerminalView::new(
 126                    terminal,
 127                    workspace.weak_handle(),
 128                    workspace.database_id(),
 129                    cx,
 130                )
 131            });
 132            workspace.add_item(Box::new(view), cx)
 133        }
 134    }
 135
 136    pub fn new(
 137        terminal: ModelHandle<Terminal>,
 138        workspace: WeakViewHandle<Workspace>,
 139        workspace_id: WorkspaceId,
 140        cx: &mut ViewContext<Self>,
 141    ) -> Self {
 142        let view_id = cx.view_id();
 143        cx.observe(&terminal, |_, _, cx| cx.notify()).detach();
 144        cx.subscribe(&terminal, move |this, _, event, cx| match event {
 145            Event::Wakeup => {
 146                if !cx.is_self_focused() {
 147                    this.has_new_content = true;
 148                }
 149                cx.notify();
 150                cx.emit(Event::Wakeup);
 151            }
 152            Event::Bell => {
 153                this.has_bell = true;
 154                cx.emit(Event::Wakeup);
 155            }
 156            Event::BlinkChanged => this.blinking_on = !this.blinking_on,
 157            Event::TitleChanged => {
 158                if let Some(foreground_info) = &this.terminal().read(cx).foreground_process_info {
 159                    let cwd = foreground_info.cwd.clone();
 160
 161                    let item_id = cx.view_id();
 162                    let workspace_id = this.workspace_id;
 163                    cx.background()
 164                        .spawn(async move {
 165                            TERMINAL_DB
 166                                .save_working_directory(item_id, workspace_id, cwd)
 167                                .await
 168                                .log_err();
 169                        })
 170                        .detach();
 171                }
 172            }
 173            Event::NewNavigationTarget(maybe_navigation_target) => {
 174                this.can_navigate_to_selected_word = match maybe_navigation_target {
 175                    MaybeNavigationTarget::Url(_) => true,
 176                    MaybeNavigationTarget::PathLike(maybe_path) => {
 177                        !possible_open_targets(&workspace, maybe_path, cx).is_empty()
 178                    }
 179                }
 180            }
 181            Event::Open(maybe_navigation_target) => match maybe_navigation_target {
 182                MaybeNavigationTarget::Url(url) => cx.platform().open_url(url),
 183                MaybeNavigationTarget::PathLike(maybe_path) => {
 184                    if !this.can_navigate_to_selected_word {
 185                        return;
 186                    }
 187                    let potential_abs_paths = possible_open_targets(&workspace, maybe_path, cx);
 188                    if let Some(path) = potential_abs_paths.into_iter().next() {
 189                        let visible = path.path_like.is_dir();
 190                        let task_workspace = workspace.clone();
 191                        cx.spawn(|_, mut cx| async move {
 192                            let opened_item = task_workspace
 193                                .update(&mut cx, |workspace, cx| {
 194                                    workspace.open_abs_path(path.path_like, visible, cx)
 195                                })
 196                                .context("workspace update")?
 197                                .await
 198                                .context("workspace update")?;
 199                            if let Some(row) = path.row {
 200                                let col = path.column.unwrap_or(0);
 201                                if let Some(active_editor) = opened_item.downcast::<Editor>() {
 202                                    active_editor
 203                                        .downgrade()
 204                                        .update(&mut cx, |editor, cx| {
 205                                            let snapshot = editor.snapshot(cx).display_snapshot;
 206                                            let point = snapshot.buffer_snapshot.clip_point(
 207                                                language::Point::new(
 208                                                    row.saturating_sub(1),
 209                                                    col.saturating_sub(1),
 210                                                ),
 211                                                Bias::Left,
 212                                            );
 213                                            editor.change_selections(
 214                                                Some(Autoscroll::center()),
 215                                                cx,
 216                                                |s| s.select_ranges([point..point]),
 217                                            );
 218                                        })
 219                                        .log_err();
 220                                }
 221                            }
 222                            anyhow::Ok(())
 223                        })
 224                        .detach_and_log_err(cx);
 225                    }
 226                }
 227            },
 228            _ => cx.emit(event.clone()),
 229        })
 230        .detach();
 231
 232        Self {
 233            terminal,
 234            has_new_content: true,
 235            has_bell: false,
 236            context_menu: cx.add_view(|cx| ContextMenu::new(view_id, cx)),
 237            blink_state: true,
 238            blinking_on: false,
 239            blinking_paused: false,
 240            blink_epoch: 0,
 241            can_navigate_to_selected_word: false,
 242            workspace_id,
 243        }
 244    }
 245
 246    pub fn model(&self) -> &ModelHandle<Terminal> {
 247        &self.terminal
 248    }
 249
 250    pub fn has_new_content(&self) -> bool {
 251        self.has_new_content
 252    }
 253
 254    pub fn has_bell(&self) -> bool {
 255        self.has_bell
 256    }
 257
 258    pub fn clear_bel(&mut self, cx: &mut ViewContext<TerminalView>) {
 259        self.has_bell = false;
 260        cx.emit(Event::Wakeup);
 261    }
 262
 263    pub fn deploy_context_menu(&mut self, position: Vector2F, cx: &mut ViewContext<Self>) {
 264        let menu_entries = vec![
 265            ContextMenuItem::action("Clear", Clear),
 266            ContextMenuItem::action("Close", pane::CloseActiveItem),
 267        ];
 268
 269        self.context_menu.update(cx, |menu, cx| {
 270            menu.show(position, AnchorCorner::TopLeft, menu_entries, cx)
 271        });
 272
 273        cx.notify();
 274    }
 275
 276    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 277        if !self
 278            .terminal
 279            .read(cx)
 280            .last_content
 281            .mode
 282            .contains(TermMode::ALT_SCREEN)
 283        {
 284            cx.show_character_palette();
 285        } else {
 286            self.terminal.update(cx, |term, cx| {
 287                term.try_keystroke(
 288                    &Keystroke::parse("ctrl-cmd-space").unwrap(),
 289                    settings::get::<TerminalSettings>(cx).option_as_meta,
 290                )
 291            });
 292        }
 293    }
 294
 295    fn clear(&mut self, _: &Clear, cx: &mut ViewContext<Self>) {
 296        self.terminal.update(cx, |term, _| term.clear());
 297        cx.notify();
 298    }
 299
 300    pub fn should_show_cursor(&self, focused: bool, cx: &mut gpui::ViewContext<Self>) -> bool {
 301        //Don't blink the cursor when not focused, blinking is disabled, or paused
 302        if !focused
 303            || !self.blinking_on
 304            || self.blinking_paused
 305            || self
 306                .terminal
 307                .read(cx)
 308                .last_content
 309                .mode
 310                .contains(TermMode::ALT_SCREEN)
 311        {
 312            return true;
 313        }
 314
 315        match settings::get::<TerminalSettings>(cx).blinking {
 316            //If the user requested to never blink, don't blink it.
 317            TerminalBlink::Off => true,
 318            //If the terminal is controlling it, check terminal mode
 319            TerminalBlink::TerminalControlled | TerminalBlink::On => self.blink_state,
 320        }
 321    }
 322
 323    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
 324        if epoch == self.blink_epoch && !self.blinking_paused {
 325            self.blink_state = !self.blink_state;
 326            cx.notify();
 327
 328            let epoch = self.next_blink_epoch();
 329            cx.spawn(|this, mut cx| async move {
 330                Timer::after(CURSOR_BLINK_INTERVAL).await;
 331                this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx))
 332                    .log_err();
 333            })
 334            .detach();
 335        }
 336    }
 337
 338    pub fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
 339        self.blink_state = true;
 340        cx.notify();
 341
 342        let epoch = self.next_blink_epoch();
 343        cx.spawn(|this, mut cx| async move {
 344            Timer::after(CURSOR_BLINK_INTERVAL).await;
 345            this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
 346                .ok();
 347        })
 348        .detach();
 349    }
 350
 351    pub fn find_matches(
 352        &mut self,
 353        query: project::search::SearchQuery,
 354        cx: &mut ViewContext<Self>,
 355    ) -> Task<Vec<RangeInclusive<Point>>> {
 356        let searcher = regex_search_for_query(query);
 357
 358        if let Some(searcher) = searcher {
 359            self.terminal
 360                .update(cx, |term, cx| term.find_matches(searcher, cx))
 361        } else {
 362            cx.background().spawn(async { Vec::new() })
 363        }
 364    }
 365
 366    pub fn terminal(&self) -> &ModelHandle<Terminal> {
 367        &self.terminal
 368    }
 369
 370    fn next_blink_epoch(&mut self) -> usize {
 371        self.blink_epoch += 1;
 372        self.blink_epoch
 373    }
 374
 375    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
 376        if epoch == self.blink_epoch {
 377            self.blinking_paused = false;
 378            self.blink_cursors(epoch, cx);
 379        }
 380    }
 381
 382    ///Attempt to paste the clipboard into the terminal
 383    fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 384        self.terminal.update(cx, |term, _| term.copy())
 385    }
 386
 387    ///Attempt to paste the clipboard into the terminal
 388    fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 389        if let Some(item) = cx.read_from_clipboard() {
 390            self.terminal
 391                .update(cx, |terminal, _cx| terminal.paste(item.text()));
 392        }
 393    }
 394
 395    fn send_text(&mut self, text: &SendText, cx: &mut ViewContext<Self>) {
 396        self.clear_bel(cx);
 397        self.terminal.update(cx, |term, _| {
 398            term.input(text.0.to_string());
 399        });
 400    }
 401
 402    fn send_keystroke(&mut self, text: &SendKeystroke, cx: &mut ViewContext<Self>) {
 403        if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
 404            self.clear_bel(cx);
 405            self.terminal.update(cx, |term, cx| {
 406                term.try_keystroke(
 407                    &keystroke,
 408                    settings::get::<TerminalSettings>(cx).option_as_meta,
 409                );
 410            });
 411        }
 412    }
 413}
 414
 415fn possible_open_targets(
 416    workspace: &WeakViewHandle<Workspace>,
 417    maybe_path: &String,
 418    cx: &mut ViewContext<'_, '_, TerminalView>,
 419) -> Vec<PathLikeWithPosition<PathBuf>> {
 420    let path_like = PathLikeWithPosition::parse_str(maybe_path.as_str(), |path_str| {
 421        Ok::<_, std::convert::Infallible>(Path::new(path_str).to_path_buf())
 422    })
 423    .expect("infallible");
 424    let maybe_path = path_like.path_like;
 425    let potential_abs_paths = if maybe_path.is_absolute() {
 426        vec![maybe_path]
 427    } else if let Some(workspace) = workspace.upgrade(cx) {
 428        workspace.update(cx, |workspace, cx| {
 429            workspace
 430                .worktrees(cx)
 431                .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
 432                .collect()
 433        })
 434    } else {
 435        Vec::new()
 436    };
 437
 438    potential_abs_paths
 439        .into_iter()
 440        .filter(|path| path.exists())
 441        .map(|path| PathLikeWithPosition {
 442            path_like: path,
 443            row: path_like.row,
 444            column: path_like.column,
 445        })
 446        .collect()
 447}
 448
 449pub fn regex_search_for_query(query: project::search::SearchQuery) -> Option<RegexSearch> {
 450    let searcher = match query {
 451        project::search::SearchQuery::Text { query, .. } => RegexSearch::new(&query),
 452        project::search::SearchQuery::Regex { query, .. } => RegexSearch::new(&query),
 453    };
 454    searcher.ok()
 455}
 456
 457impl View for TerminalView {
 458    fn ui_name() -> &'static str {
 459        "Terminal"
 460    }
 461
 462    fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> AnyElement<Self> {
 463        let terminal_handle = self.terminal.clone().downgrade();
 464
 465        let self_id = cx.view_id();
 466        let focused = cx
 467            .focused_view_id()
 468            .filter(|view_id| *view_id == self_id)
 469            .is_some();
 470
 471        Stack::new()
 472            .with_child(
 473                TerminalElement::new(
 474                    terminal_handle,
 475                    focused,
 476                    self.should_show_cursor(focused, cx),
 477                    self.can_navigate_to_selected_word,
 478                )
 479                .contained(),
 480            )
 481            .with_child(ChildView::new(&self.context_menu, cx))
 482            .into_any()
 483    }
 484
 485    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
 486        self.has_new_content = false;
 487        self.terminal.read(cx).focus_in();
 488        self.blink_cursors(self.blink_epoch, cx);
 489        cx.notify();
 490    }
 491
 492    fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
 493        self.terminal.update(cx, |terminal, _| {
 494            terminal.focus_out();
 495        });
 496        cx.notify();
 497    }
 498
 499    fn modifiers_changed(
 500        &mut self,
 501        event: &ModifiersChangedEvent,
 502        cx: &mut ViewContext<Self>,
 503    ) -> bool {
 504        let handled = self
 505            .terminal()
 506            .update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
 507        if handled {
 508            cx.notify();
 509        }
 510        handled
 511    }
 512
 513    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) -> bool {
 514        self.clear_bel(cx);
 515        self.pause_cursor_blinking(cx);
 516
 517        self.terminal.update(cx, |term, cx| {
 518            term.try_keystroke(
 519                &event.keystroke,
 520                settings::get::<TerminalSettings>(cx).option_as_meta,
 521            )
 522        })
 523    }
 524
 525    //IME stuff
 526    fn selected_text_range(&self, cx: &AppContext) -> Option<std::ops::Range<usize>> {
 527        if self
 528            .terminal
 529            .read(cx)
 530            .last_content
 531            .mode
 532            .contains(TermMode::ALT_SCREEN)
 533        {
 534            None
 535        } else {
 536            Some(0..0)
 537        }
 538    }
 539
 540    fn replace_text_in_range(
 541        &mut self,
 542        _: Option<std::ops::Range<usize>>,
 543        text: &str,
 544        cx: &mut ViewContext<Self>,
 545    ) {
 546        self.terminal.update(cx, |terminal, _| {
 547            terminal.input(text.into());
 548        });
 549    }
 550
 551    fn update_keymap_context(&self, keymap: &mut KeymapContext, cx: &gpui::AppContext) {
 552        Self::reset_to_default_keymap_context(keymap);
 553
 554        let mode = self.terminal.read(cx).last_content.mode;
 555        keymap.add_key(
 556            "screen",
 557            if mode.contains(TermMode::ALT_SCREEN) {
 558                "alt"
 559            } else {
 560                "normal"
 561            },
 562        );
 563
 564        if mode.contains(TermMode::APP_CURSOR) {
 565            keymap.add_identifier("DECCKM");
 566        }
 567        if mode.contains(TermMode::APP_KEYPAD) {
 568            keymap.add_identifier("DECPAM");
 569        } else {
 570            keymap.add_identifier("DECPNM");
 571        }
 572        if mode.contains(TermMode::SHOW_CURSOR) {
 573            keymap.add_identifier("DECTCEM");
 574        }
 575        if mode.contains(TermMode::LINE_WRAP) {
 576            keymap.add_identifier("DECAWM");
 577        }
 578        if mode.contains(TermMode::ORIGIN) {
 579            keymap.add_identifier("DECOM");
 580        }
 581        if mode.contains(TermMode::INSERT) {
 582            keymap.add_identifier("IRM");
 583        }
 584        //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 585        if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 586            keymap.add_identifier("LNM");
 587        }
 588        if mode.contains(TermMode::FOCUS_IN_OUT) {
 589            keymap.add_identifier("report_focus");
 590        }
 591        if mode.contains(TermMode::ALTERNATE_SCROLL) {
 592            keymap.add_identifier("alternate_scroll");
 593        }
 594        if mode.contains(TermMode::BRACKETED_PASTE) {
 595            keymap.add_identifier("bracketed_paste");
 596        }
 597        if mode.intersects(TermMode::MOUSE_MODE) {
 598            keymap.add_identifier("any_mouse_reporting");
 599        }
 600        {
 601            let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 602                "click"
 603            } else if mode.contains(TermMode::MOUSE_DRAG) {
 604                "drag"
 605            } else if mode.contains(TermMode::MOUSE_MOTION) {
 606                "motion"
 607            } else {
 608                "off"
 609            };
 610            keymap.add_key("mouse_reporting", mouse_reporting);
 611        }
 612        {
 613            let format = if mode.contains(TermMode::SGR_MOUSE) {
 614                "sgr"
 615            } else if mode.contains(TermMode::UTF8_MOUSE) {
 616                "utf8"
 617            } else {
 618                "normal"
 619            };
 620            keymap.add_key("mouse_format", format);
 621        }
 622    }
 623}
 624
 625impl Item for TerminalView {
 626    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<Cow<str>> {
 627        Some(self.terminal().read(cx).title().into())
 628    }
 629
 630    fn tab_content<T: View>(
 631        &self,
 632        _detail: Option<usize>,
 633        tab_theme: &theme::Tab,
 634        cx: &gpui::AppContext,
 635    ) -> AnyElement<T> {
 636        let title = self.terminal().read(cx).title();
 637
 638        Flex::row()
 639            .with_child(
 640                gpui::elements::Svg::new("icons/terminal_12.svg")
 641                    .with_color(tab_theme.label.text.color)
 642                    .constrained()
 643                    .with_width(tab_theme.type_icon_width)
 644                    .aligned()
 645                    .contained()
 646                    .with_margin_right(tab_theme.spacing),
 647            )
 648            .with_child(Label::new(title, tab_theme.label.clone()).aligned())
 649            .into_any()
 650    }
 651
 652    fn clone_on_split(
 653        &self,
 654        _workspace_id: WorkspaceId,
 655        _cx: &mut ViewContext<Self>,
 656    ) -> Option<Self> {
 657        //From what I can tell, there's no  way to tell the current working
 658        //Directory of the terminal from outside the shell. There might be
 659        //solutions to this, but they are non-trivial and require more IPC
 660
 661        // Some(TerminalContainer::new(
 662        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 663        //     workspace_id,
 664        //     cx,
 665        // ))
 666
 667        // TODO
 668        None
 669    }
 670
 671    fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
 672        self.has_bell()
 673    }
 674
 675    fn has_conflict(&self, _cx: &AppContext) -> bool {
 676        false
 677    }
 678
 679    fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 680        Some(Box::new(handle.clone()))
 681    }
 682
 683    fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
 684        match event {
 685            Event::BreadcrumbsChanged => smallvec![ItemEvent::UpdateBreadcrumbs],
 686            Event::TitleChanged | Event::Wakeup => smallvec![ItemEvent::UpdateTab],
 687            Event::CloseTerminal => smallvec![ItemEvent::CloseItem],
 688            _ => smallvec![],
 689        }
 690    }
 691
 692    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 693        ToolbarItemLocation::PrimaryLeft { flex: None }
 694    }
 695
 696    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 697        Some(vec![BreadcrumbText {
 698            text: self.terminal().read(cx).breadcrumb_text.clone(),
 699            highlights: None,
 700        }])
 701    }
 702
 703    fn serialized_item_kind() -> Option<&'static str> {
 704        Some("Terminal")
 705    }
 706
 707    fn deserialize(
 708        project: ModelHandle<Project>,
 709        workspace: WeakViewHandle<Workspace>,
 710        workspace_id: workspace::WorkspaceId,
 711        item_id: workspace::ItemId,
 712        cx: &mut ViewContext<Pane>,
 713    ) -> Task<anyhow::Result<ViewHandle<Self>>> {
 714        let window_id = cx.window_id();
 715        cx.spawn(|pane, mut cx| async move {
 716            let cwd = TERMINAL_DB
 717                .get_working_directory(item_id, workspace_id)
 718                .log_err()
 719                .flatten()
 720                .or_else(|| {
 721                    cx.read(|cx| {
 722                        let strategy = settings::get::<TerminalSettings>(cx)
 723                            .working_directory
 724                            .clone();
 725                        workspace
 726                            .upgrade(cx)
 727                            .map(|workspace| {
 728                                get_working_directory(workspace.read(cx), cx, strategy)
 729                            })
 730                            .flatten()
 731                    })
 732                });
 733
 734            let terminal = project.update(&mut cx, |project, cx| {
 735                project.create_terminal(cwd, window_id, cx)
 736            })?;
 737            Ok(pane.update(&mut cx, |_, cx| {
 738                cx.add_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 739            })?)
 740        })
 741    }
 742
 743    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 744        cx.background()
 745            .spawn(TERMINAL_DB.update_workspace_id(
 746                workspace.database_id(),
 747                self.workspace_id,
 748                cx.view_id(),
 749            ))
 750            .detach();
 751        self.workspace_id = workspace.database_id();
 752    }
 753}
 754
 755impl SearchableItem for TerminalView {
 756    type Match = RangeInclusive<Point>;
 757
 758    fn supported_options() -> SearchOptions {
 759        SearchOptions {
 760            case: false,
 761            word: false,
 762            regex: false,
 763        }
 764    }
 765
 766    /// Convert events raised by this item into search-relevant events (if applicable)
 767    fn to_search_event(
 768        &mut self,
 769        event: &Self::Event,
 770        _: &mut ViewContext<Self>,
 771    ) -> Option<SearchEvent> {
 772        match event {
 773            Event::Wakeup => Some(SearchEvent::MatchesInvalidated),
 774            Event::SelectionsChanged => Some(SearchEvent::ActiveMatchChanged),
 775            _ => None,
 776        }
 777    }
 778
 779    /// Clear stored matches
 780    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 781        self.terminal().update(cx, |term, _| term.matches.clear())
 782    }
 783
 784    /// Store matches returned from find_matches somewhere for rendering
 785    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 786        self.terminal().update(cx, |term, _| term.matches = matches)
 787    }
 788
 789    /// Return the selection content to pre-load into this search
 790    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 791        self.terminal()
 792            .read(cx)
 793            .last_content
 794            .selection_text
 795            .clone()
 796            .unwrap_or_default()
 797    }
 798
 799    /// Focus match at given index into the Vec of matches
 800    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 801        self.terminal()
 802            .update(cx, |term, _| term.activate_match(index));
 803        cx.notify();
 804    }
 805
 806    /// Add selections for all matches given.
 807    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 808        self.terminal()
 809            .update(cx, |term, _| term.select_matches(matches));
 810        cx.notify();
 811    }
 812
 813    /// Get all of the matches for this query, should be done on the background
 814    fn find_matches(
 815        &mut self,
 816        query: project::search::SearchQuery,
 817        cx: &mut ViewContext<Self>,
 818    ) -> Task<Vec<Self::Match>> {
 819        if let Some(searcher) = regex_search_for_query(query) {
 820            self.terminal()
 821                .update(cx, |term, cx| term.find_matches(searcher, cx))
 822        } else {
 823            Task::ready(vec![])
 824        }
 825    }
 826
 827    /// Reports back to the search toolbar what the active match should be (the selection)
 828    fn active_match_index(
 829        &mut self,
 830        matches: Vec<Self::Match>,
 831        cx: &mut ViewContext<Self>,
 832    ) -> Option<usize> {
 833        // Selection head might have a value if there's a selection that isn't
 834        // associated with a match. Therefore, if there are no matches, we should
 835        // report None, no matter the state of the terminal
 836        let res = if matches.len() > 0 {
 837            if let Some(selection_head) = self.terminal().read(cx).selection_head {
 838                // If selection head is contained in a match. Return that match
 839                if let Some(ix) = matches
 840                    .iter()
 841                    .enumerate()
 842                    .find(|(_, search_match)| {
 843                        search_match.contains(&selection_head)
 844                            || search_match.start() > &selection_head
 845                    })
 846                    .map(|(ix, _)| ix)
 847                {
 848                    Some(ix)
 849                } else {
 850                    // If no selection after selection head, return the last match
 851                    Some(matches.len().saturating_sub(1))
 852                }
 853            } else {
 854                // Matches found but no active selection, return the first last one (closest to cursor)
 855                Some(matches.len().saturating_sub(1))
 856            }
 857        } else {
 858            None
 859        };
 860
 861        res
 862    }
 863}
 864
 865///Get's the working directory for the given workspace, respecting the user's settings.
 866pub fn get_working_directory(
 867    workspace: &Workspace,
 868    cx: &AppContext,
 869    strategy: WorkingDirectory,
 870) -> Option<PathBuf> {
 871    let res = match strategy {
 872        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
 873            .or_else(|| first_project_directory(workspace, cx)),
 874        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
 875        WorkingDirectory::AlwaysHome => None,
 876        WorkingDirectory::Always { directory } => {
 877            shellexpand::full(&directory) //TODO handle this better
 878                .ok()
 879                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
 880                .filter(|dir| dir.is_dir())
 881        }
 882    };
 883    res.or_else(home_dir)
 884}
 885
 886///Get's the first project's home directory, or the home directory
 887fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 888    workspace
 889        .worktrees(cx)
 890        .next()
 891        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 892        .and_then(get_path_from_wt)
 893}
 894
 895///Gets the intuitively correct working directory from the given workspace
 896///If there is an active entry for this project, returns that entry's worktree root.
 897///If there's no active entry but there is a worktree, returns that worktrees root.
 898///If either of these roots are files, or if there are any other query failures,
 899///  returns the user's home directory
 900fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 901    let project = workspace.project().read(cx);
 902
 903    project
 904        .active_entry()
 905        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
 906        .or_else(|| workspace.worktrees(cx).next())
 907        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 908        .and_then(get_path_from_wt)
 909}
 910
 911fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
 912    wt.root_entry()
 913        .filter(|re| re.is_dir())
 914        .map(|_| wt.abs_path().to_path_buf())
 915}
 916
 917#[cfg(test)]
 918mod tests {
 919    use super::*;
 920    use gpui::TestAppContext;
 921    use project::{Entry, Project, ProjectPath, Worktree};
 922    use std::path::Path;
 923    use workspace::AppState;
 924
 925    // Working directory calculation tests
 926
 927    // No Worktrees in project -> home_dir()
 928    #[gpui::test]
 929    async fn no_worktree(cx: &mut TestAppContext) {
 930        let (project, workspace) = init_test(cx).await;
 931        cx.read(|cx| {
 932            let workspace = workspace.read(cx);
 933            let active_entry = project.read(cx).active_entry();
 934
 935            //Make sure environment is as expected
 936            assert!(active_entry.is_none());
 937            assert!(workspace.worktrees(cx).next().is_none());
 938
 939            let res = current_project_directory(workspace, cx);
 940            assert_eq!(res, None);
 941            let res = first_project_directory(workspace, cx);
 942            assert_eq!(res, None);
 943        });
 944    }
 945
 946    // No active entry, but a worktree, worktree is a file -> home_dir()
 947    #[gpui::test]
 948    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
 949        let (project, workspace) = init_test(cx).await;
 950
 951        create_file_wt(project.clone(), "/root.txt", cx).await;
 952        cx.read(|cx| {
 953            let workspace = workspace.read(cx);
 954            let active_entry = project.read(cx).active_entry();
 955
 956            //Make sure environment is as expected
 957            assert!(active_entry.is_none());
 958            assert!(workspace.worktrees(cx).next().is_some());
 959
 960            let res = current_project_directory(workspace, cx);
 961            assert_eq!(res, None);
 962            let res = first_project_directory(workspace, cx);
 963            assert_eq!(res, None);
 964        });
 965    }
 966
 967    // No active entry, but a worktree, worktree is a folder -> worktree_folder
 968    #[gpui::test]
 969    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
 970        let (project, workspace) = init_test(cx).await;
 971
 972        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
 973        cx.update(|cx| {
 974            let workspace = workspace.read(cx);
 975            let active_entry = project.read(cx).active_entry();
 976
 977            assert!(active_entry.is_none());
 978            assert!(workspace.worktrees(cx).next().is_some());
 979
 980            let res = current_project_directory(workspace, cx);
 981            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
 982            let res = first_project_directory(workspace, cx);
 983            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
 984        });
 985    }
 986
 987    // Active entry with a work tree, worktree is a file -> home_dir()
 988    #[gpui::test]
 989    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
 990        let (project, workspace) = init_test(cx).await;
 991
 992        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
 993        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
 994        insert_active_entry_for(wt2, entry2, project.clone(), cx);
 995
 996        cx.update(|cx| {
 997            let workspace = workspace.read(cx);
 998            let active_entry = project.read(cx).active_entry();
 999
1000            assert!(active_entry.is_some());
1001
1002            let res = current_project_directory(workspace, cx);
1003            assert_eq!(res, None);
1004            let res = first_project_directory(workspace, cx);
1005            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1006        });
1007    }
1008
1009    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1010    #[gpui::test]
1011    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1012        let (project, workspace) = init_test(cx).await;
1013
1014        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1015        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1016        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1017
1018        cx.update(|cx| {
1019            let workspace = workspace.read(cx);
1020            let active_entry = project.read(cx).active_entry();
1021
1022            assert!(active_entry.is_some());
1023
1024            let res = current_project_directory(workspace, cx);
1025            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1026            let res = first_project_directory(workspace, cx);
1027            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1028        });
1029    }
1030
1031    /// Creates a worktree with 1 file: /root.txt
1032    pub async fn init_test(
1033        cx: &mut TestAppContext,
1034    ) -> (ModelHandle<Project>, ViewHandle<Workspace>) {
1035        let params = cx.update(AppState::test);
1036        cx.update(|cx| {
1037            theme::init((), cx);
1038            Project::init_settings(cx);
1039            language::init(cx);
1040        });
1041
1042        let project = Project::test(params.fs.clone(), [], cx).await;
1043        let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
1044
1045        (project, workspace)
1046    }
1047
1048    /// Creates a worktree with 1 folder: /root{suffix}/
1049    async fn create_folder_wt(
1050        project: ModelHandle<Project>,
1051        path: impl AsRef<Path>,
1052        cx: &mut TestAppContext,
1053    ) -> (ModelHandle<Worktree>, Entry) {
1054        create_wt(project, true, path, cx).await
1055    }
1056
1057    /// Creates a worktree with 1 file: /root{suffix}.txt
1058    async fn create_file_wt(
1059        project: ModelHandle<Project>,
1060        path: impl AsRef<Path>,
1061        cx: &mut TestAppContext,
1062    ) -> (ModelHandle<Worktree>, Entry) {
1063        create_wt(project, false, path, cx).await
1064    }
1065
1066    async fn create_wt(
1067        project: ModelHandle<Project>,
1068        is_dir: bool,
1069        path: impl AsRef<Path>,
1070        cx: &mut TestAppContext,
1071    ) -> (ModelHandle<Worktree>, Entry) {
1072        let (wt, _) = project
1073            .update(cx, |project, cx| {
1074                project.find_or_create_local_worktree(path, true, cx)
1075            })
1076            .await
1077            .unwrap();
1078
1079        let entry = cx
1080            .update(|cx| {
1081                wt.update(cx, |wt, cx| {
1082                    wt.as_local()
1083                        .unwrap()
1084                        .create_entry(Path::new(""), is_dir, cx)
1085                })
1086            })
1087            .await
1088            .unwrap();
1089
1090        (wt, entry)
1091    }
1092
1093    pub fn insert_active_entry_for(
1094        wt: ModelHandle<Worktree>,
1095        entry: Entry,
1096        project: ModelHandle<Project>,
1097        cx: &mut TestAppContext,
1098    ) {
1099        cx.update(|cx| {
1100            let p = ProjectPath {
1101                worktree_id: wt.read(cx).id(),
1102                path: entry.path,
1103            };
1104            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1105        });
1106    }
1107}