terminal_view.rs

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