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