terminal_view.rs

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