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