terminal_view.rs

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