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::{search::SearchQuery, 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    sync::Arc,
  30    time::Duration,
  31};
  32use terminal::{
  33    alacritty_terminal::{
  34        index::Point,
  35        term::{search::RegexSearch, TermMode},
  36    },
  37    terminal_settings::{TerminalBlink, TerminalSettings, WorkingDirectory},
  38    Event, MaybeNavigationTarget, Terminal,
  39};
  40use util::{paths::PathLikeWithPosition, ResultExt};
  41use workspace::{
  42    item::{BreadcrumbText, Item, ItemEvent},
  43    notifications::NotifyResultExt,
  44    pane, register_deserializable_item,
  45    searchable::{SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
  46    NewCenterTerminal, Pane, ToolbarItemLocation, Workspace, WorkspaceId,
  47};
  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(
 288                "Close",
 289                pane::CloseActiveItem {
 290                    save_behavior: None,
 291                },
 292            ),
 293        ];
 294
 295        self.context_menu.update(cx, |menu, cx| {
 296            menu.show(position, AnchorCorner::TopLeft, menu_entries, cx)
 297        });
 298
 299        cx.notify();
 300    }
 301
 302    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 303        if !self
 304            .terminal
 305            .read(cx)
 306            .last_content
 307            .mode
 308            .contains(TermMode::ALT_SCREEN)
 309        {
 310            cx.show_character_palette();
 311        } else {
 312            self.terminal.update(cx, |term, cx| {
 313                term.try_keystroke(
 314                    &Keystroke::parse("ctrl-cmd-space").unwrap(),
 315                    settings::get::<TerminalSettings>(cx).option_as_meta,
 316                )
 317            });
 318        }
 319    }
 320
 321    fn select_all(&mut self, _: &editor::SelectAll, cx: &mut ViewContext<Self>) {
 322        self.terminal.update(cx, |term, _| term.select_all());
 323        cx.notify();
 324    }
 325
 326    fn clear(&mut self, _: &Clear, cx: &mut ViewContext<Self>) {
 327        self.terminal.update(cx, |term, _| term.clear());
 328        cx.notify();
 329    }
 330
 331    pub fn should_show_cursor(&self, focused: bool, cx: &mut gpui::ViewContext<Self>) -> bool {
 332        //Don't blink the cursor when not focused, blinking is disabled, or paused
 333        if !focused
 334            || !self.blinking_on
 335            || self.blinking_paused
 336            || self
 337                .terminal
 338                .read(cx)
 339                .last_content
 340                .mode
 341                .contains(TermMode::ALT_SCREEN)
 342        {
 343            return true;
 344        }
 345
 346        match settings::get::<TerminalSettings>(cx).blinking {
 347            //If the user requested to never blink, don't blink it.
 348            TerminalBlink::Off => true,
 349            //If the terminal is controlling it, check terminal mode
 350            TerminalBlink::TerminalControlled | TerminalBlink::On => self.blink_state,
 351        }
 352    }
 353
 354    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
 355        if epoch == self.blink_epoch && !self.blinking_paused {
 356            self.blink_state = !self.blink_state;
 357            cx.notify();
 358
 359            let epoch = self.next_blink_epoch();
 360            cx.spawn(|this, mut cx| async move {
 361                Timer::after(CURSOR_BLINK_INTERVAL).await;
 362                this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx))
 363                    .log_err();
 364            })
 365            .detach();
 366        }
 367    }
 368
 369    pub fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
 370        self.blink_state = true;
 371        cx.notify();
 372
 373        let epoch = self.next_blink_epoch();
 374        cx.spawn(|this, mut cx| async move {
 375            Timer::after(CURSOR_BLINK_INTERVAL).await;
 376            this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
 377                .ok();
 378        })
 379        .detach();
 380    }
 381
 382    pub fn find_matches(
 383        &mut self,
 384        query: Arc<project::search::SearchQuery>,
 385        cx: &mut ViewContext<Self>,
 386    ) -> Task<Vec<RangeInclusive<Point>>> {
 387        let searcher = regex_search_for_query(&query);
 388
 389        if let Some(searcher) = searcher {
 390            self.terminal
 391                .update(cx, |term, cx| term.find_matches(searcher, cx))
 392        } else {
 393            cx.background().spawn(async { Vec::new() })
 394        }
 395    }
 396
 397    pub fn terminal(&self) -> &ModelHandle<Terminal> {
 398        &self.terminal
 399    }
 400
 401    fn next_blink_epoch(&mut self) -> usize {
 402        self.blink_epoch += 1;
 403        self.blink_epoch
 404    }
 405
 406    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
 407        if epoch == self.blink_epoch {
 408            self.blinking_paused = false;
 409            self.blink_cursors(epoch, cx);
 410        }
 411    }
 412
 413    ///Attempt to paste the clipboard into the terminal
 414    fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 415        self.terminal.update(cx, |term, _| term.copy())
 416    }
 417
 418    ///Attempt to paste the clipboard into the terminal
 419    fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 420        if let Some(item) = cx.read_from_clipboard() {
 421            self.terminal
 422                .update(cx, |terminal, _cx| terminal.paste(item.text()));
 423        }
 424    }
 425
 426    fn send_text(&mut self, text: &SendText, cx: &mut ViewContext<Self>) {
 427        self.clear_bel(cx);
 428        self.terminal.update(cx, |term, _| {
 429            term.input(text.0.to_string());
 430        });
 431    }
 432
 433    fn send_keystroke(&mut self, text: &SendKeystroke, cx: &mut ViewContext<Self>) {
 434        if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
 435            self.clear_bel(cx);
 436            self.terminal.update(cx, |term, cx| {
 437                term.try_keystroke(
 438                    &keystroke,
 439                    settings::get::<TerminalSettings>(cx).option_as_meta,
 440                );
 441            });
 442        }
 443    }
 444}
 445
 446fn possible_open_targets(
 447    workspace: &WeakViewHandle<Workspace>,
 448    maybe_path: &String,
 449    cx: &mut ViewContext<'_, '_, TerminalView>,
 450) -> Vec<PathLikeWithPosition<PathBuf>> {
 451    let path_like = PathLikeWithPosition::parse_str(maybe_path.as_str(), |path_str| {
 452        Ok::<_, std::convert::Infallible>(Path::new(path_str).to_path_buf())
 453    })
 454    .expect("infallible");
 455    let maybe_path = path_like.path_like;
 456    let potential_abs_paths = if maybe_path.is_absolute() {
 457        vec![maybe_path]
 458    } else if maybe_path.starts_with("~") {
 459        if let Some(abs_path) = maybe_path
 460            .strip_prefix("~")
 461            .ok()
 462            .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
 463        {
 464            vec![abs_path]
 465        } else {
 466            Vec::new()
 467        }
 468    } else if let Some(workspace) = workspace.upgrade(cx) {
 469        workspace.update(cx, |workspace, cx| {
 470            workspace
 471                .worktrees(cx)
 472                .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
 473                .collect()
 474        })
 475    } else {
 476        Vec::new()
 477    };
 478
 479    potential_abs_paths
 480        .into_iter()
 481        .filter(|path| path.exists())
 482        .map(|path| PathLikeWithPosition {
 483            path_like: path,
 484            row: path_like.row,
 485            column: path_like.column,
 486        })
 487        .collect()
 488}
 489
 490pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
 491    let query = query.as_str();
 492    let searcher = RegexSearch::new(&query);
 493    searcher.ok()
 494}
 495
 496impl View for TerminalView {
 497    fn ui_name() -> &'static str {
 498        "Terminal"
 499    }
 500
 501    fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> AnyElement<Self> {
 502        let terminal_handle = self.terminal.clone().downgrade();
 503
 504        let self_id = cx.view_id();
 505        let focused = cx
 506            .focused_view_id()
 507            .filter(|view_id| *view_id == self_id)
 508            .is_some();
 509
 510        Stack::new()
 511            .with_child(
 512                TerminalElement::new(
 513                    terminal_handle,
 514                    focused,
 515                    self.should_show_cursor(focused, cx),
 516                    self.can_navigate_to_selected_word,
 517                )
 518                .contained(),
 519            )
 520            .with_child(ChildView::new(&self.context_menu, cx))
 521            .into_any()
 522    }
 523
 524    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
 525        self.has_new_content = false;
 526        self.terminal.read(cx).focus_in();
 527        self.blink_cursors(self.blink_epoch, cx);
 528        cx.notify();
 529    }
 530
 531    fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
 532        self.terminal.update(cx, |terminal, _| {
 533            terminal.focus_out();
 534        });
 535        cx.notify();
 536    }
 537
 538    fn modifiers_changed(
 539        &mut self,
 540        event: &ModifiersChangedEvent,
 541        cx: &mut ViewContext<Self>,
 542    ) -> bool {
 543        let handled = self
 544            .terminal()
 545            .update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
 546        if handled {
 547            cx.notify();
 548        }
 549        handled
 550    }
 551
 552    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) -> bool {
 553        self.clear_bel(cx);
 554        self.pause_cursor_blinking(cx);
 555
 556        self.terminal.update(cx, |term, cx| {
 557            term.try_keystroke(
 558                &event.keystroke,
 559                settings::get::<TerminalSettings>(cx).option_as_meta,
 560            )
 561        })
 562    }
 563
 564    //IME stuff
 565    fn selected_text_range(&self, cx: &AppContext) -> Option<std::ops::Range<usize>> {
 566        if self
 567            .terminal
 568            .read(cx)
 569            .last_content
 570            .mode
 571            .contains(TermMode::ALT_SCREEN)
 572        {
 573            None
 574        } else {
 575            Some(0..0)
 576        }
 577    }
 578
 579    fn replace_text_in_range(
 580        &mut self,
 581        _: Option<std::ops::Range<usize>>,
 582        text: &str,
 583        cx: &mut ViewContext<Self>,
 584    ) {
 585        self.terminal.update(cx, |terminal, _| {
 586            terminal.input(text.into());
 587        });
 588    }
 589
 590    fn update_keymap_context(&self, keymap: &mut KeymapContext, cx: &gpui::AppContext) {
 591        Self::reset_to_default_keymap_context(keymap);
 592
 593        let mode = self.terminal.read(cx).last_content.mode;
 594        keymap.add_key(
 595            "screen",
 596            if mode.contains(TermMode::ALT_SCREEN) {
 597                "alt"
 598            } else {
 599                "normal"
 600            },
 601        );
 602
 603        if mode.contains(TermMode::APP_CURSOR) {
 604            keymap.add_identifier("DECCKM");
 605        }
 606        if mode.contains(TermMode::APP_KEYPAD) {
 607            keymap.add_identifier("DECPAM");
 608        } else {
 609            keymap.add_identifier("DECPNM");
 610        }
 611        if mode.contains(TermMode::SHOW_CURSOR) {
 612            keymap.add_identifier("DECTCEM");
 613        }
 614        if mode.contains(TermMode::LINE_WRAP) {
 615            keymap.add_identifier("DECAWM");
 616        }
 617        if mode.contains(TermMode::ORIGIN) {
 618            keymap.add_identifier("DECOM");
 619        }
 620        if mode.contains(TermMode::INSERT) {
 621            keymap.add_identifier("IRM");
 622        }
 623        //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 624        if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 625            keymap.add_identifier("LNM");
 626        }
 627        if mode.contains(TermMode::FOCUS_IN_OUT) {
 628            keymap.add_identifier("report_focus");
 629        }
 630        if mode.contains(TermMode::ALTERNATE_SCROLL) {
 631            keymap.add_identifier("alternate_scroll");
 632        }
 633        if mode.contains(TermMode::BRACKETED_PASTE) {
 634            keymap.add_identifier("bracketed_paste");
 635        }
 636        if mode.intersects(TermMode::MOUSE_MODE) {
 637            keymap.add_identifier("any_mouse_reporting");
 638        }
 639        {
 640            let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 641                "click"
 642            } else if mode.contains(TermMode::MOUSE_DRAG) {
 643                "drag"
 644            } else if mode.contains(TermMode::MOUSE_MOTION) {
 645                "motion"
 646            } else {
 647                "off"
 648            };
 649            keymap.add_key("mouse_reporting", mouse_reporting);
 650        }
 651        {
 652            let format = if mode.contains(TermMode::SGR_MOUSE) {
 653                "sgr"
 654            } else if mode.contains(TermMode::UTF8_MOUSE) {
 655                "utf8"
 656            } else {
 657                "normal"
 658            };
 659            keymap.add_key("mouse_format", format);
 660        }
 661    }
 662}
 663
 664impl Item for TerminalView {
 665    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<Cow<str>> {
 666        Some(self.terminal().read(cx).title().into())
 667    }
 668
 669    fn tab_content<T: 'static>(
 670        &self,
 671        _detail: Option<usize>,
 672        tab_theme: &theme::Tab,
 673        cx: &gpui::AppContext,
 674    ) -> AnyElement<T> {
 675        let title = self.terminal().read(cx).title();
 676
 677        Flex::row()
 678            .with_child(
 679                gpui::elements::Svg::new("icons/terminal.svg")
 680                    .with_color(tab_theme.label.text.color)
 681                    .constrained()
 682                    .with_width(tab_theme.type_icon_width)
 683                    .aligned()
 684                    .contained()
 685                    .with_margin_right(tab_theme.spacing),
 686            )
 687            .with_child(Label::new(title, tab_theme.label.clone()).aligned())
 688            .into_any()
 689    }
 690
 691    fn clone_on_split(
 692        &self,
 693        _workspace_id: WorkspaceId,
 694        _cx: &mut ViewContext<Self>,
 695    ) -> Option<Self> {
 696        //From what I can tell, there's no  way to tell the current working
 697        //Directory of the terminal from outside the shell. There might be
 698        //solutions to this, but they are non-trivial and require more IPC
 699
 700        // Some(TerminalContainer::new(
 701        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 702        //     workspace_id,
 703        //     cx,
 704        // ))
 705
 706        // TODO
 707        None
 708    }
 709
 710    fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
 711        self.has_bell()
 712    }
 713
 714    fn has_conflict(&self, _cx: &AppContext) -> bool {
 715        false
 716    }
 717
 718    fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 719        Some(Box::new(handle.clone()))
 720    }
 721
 722    fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
 723        match event {
 724            Event::BreadcrumbsChanged => smallvec![ItemEvent::UpdateBreadcrumbs],
 725            Event::TitleChanged | Event::Wakeup => smallvec![ItemEvent::UpdateTab],
 726            Event::CloseTerminal => smallvec![ItemEvent::CloseItem],
 727            _ => smallvec![],
 728        }
 729    }
 730
 731    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 732        ToolbarItemLocation::PrimaryLeft { flex: None }
 733    }
 734
 735    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 736        Some(vec![BreadcrumbText {
 737            text: self.terminal().read(cx).breadcrumb_text.clone(),
 738            highlights: None,
 739        }])
 740    }
 741
 742    fn serialized_item_kind() -> Option<&'static str> {
 743        Some("Terminal")
 744    }
 745
 746    fn deserialize(
 747        project: ModelHandle<Project>,
 748        workspace: WeakViewHandle<Workspace>,
 749        workspace_id: workspace::WorkspaceId,
 750        item_id: workspace::ItemId,
 751        cx: &mut ViewContext<Pane>,
 752    ) -> Task<anyhow::Result<ViewHandle<Self>>> {
 753        let window = cx.window();
 754        cx.spawn(|pane, mut cx| async move {
 755            let cwd = TERMINAL_DB
 756                .get_working_directory(item_id, workspace_id)
 757                .log_err()
 758                .flatten()
 759                .or_else(|| {
 760                    cx.read(|cx| {
 761                        let strategy = settings::get::<TerminalSettings>(cx)
 762                            .working_directory
 763                            .clone();
 764                        workspace
 765                            .upgrade(cx)
 766                            .map(|workspace| {
 767                                get_working_directory(workspace.read(cx), cx, strategy)
 768                            })
 769                            .flatten()
 770                    })
 771                });
 772
 773            let terminal = project.update(&mut cx, |project, cx| {
 774                project.create_terminal(cwd, window, cx)
 775            })?;
 776            Ok(pane.update(&mut cx, |_, cx| {
 777                cx.add_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 778            })?)
 779        })
 780    }
 781
 782    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 783        cx.background()
 784            .spawn(TERMINAL_DB.update_workspace_id(
 785                workspace.database_id(),
 786                self.workspace_id,
 787                cx.view_id(),
 788            ))
 789            .detach();
 790        self.workspace_id = workspace.database_id();
 791    }
 792}
 793
 794impl SearchableItem for TerminalView {
 795    type Match = RangeInclusive<Point>;
 796
 797    fn supported_options() -> SearchOptions {
 798        SearchOptions {
 799            case: false,
 800            word: false,
 801            regex: false,
 802            replacement: false,
 803        }
 804    }
 805
 806    /// Convert events raised by this item into search-relevant events (if applicable)
 807    fn to_search_event(
 808        &mut self,
 809        event: &Self::Event,
 810        _: &mut ViewContext<Self>,
 811    ) -> Option<SearchEvent> {
 812        match event {
 813            Event::Wakeup => Some(SearchEvent::MatchesInvalidated),
 814            Event::SelectionsChanged => Some(SearchEvent::ActiveMatchChanged),
 815            _ => None,
 816        }
 817    }
 818
 819    /// Clear stored matches
 820    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 821        self.terminal().update(cx, |term, _| term.matches.clear())
 822    }
 823
 824    /// Store matches returned from find_matches somewhere for rendering
 825    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 826        self.terminal().update(cx, |term, _| term.matches = matches)
 827    }
 828
 829    /// Return the selection content to pre-load into this search
 830    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 831        self.terminal()
 832            .read(cx)
 833            .last_content
 834            .selection_text
 835            .clone()
 836            .unwrap_or_default()
 837    }
 838
 839    /// Focus match at given index into the Vec of matches
 840    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 841        self.terminal()
 842            .update(cx, |term, _| term.activate_match(index));
 843        cx.notify();
 844    }
 845
 846    /// Add selections for all matches given.
 847    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 848        self.terminal()
 849            .update(cx, |term, _| term.select_matches(matches));
 850        cx.notify();
 851    }
 852
 853    /// Get all of the matches for this query, should be done on the background
 854    fn find_matches(
 855        &mut self,
 856        query: Arc<project::search::SearchQuery>,
 857        cx: &mut ViewContext<Self>,
 858    ) -> Task<Vec<Self::Match>> {
 859        if let Some(searcher) = regex_search_for_query(&query) {
 860            self.terminal()
 861                .update(cx, |term, cx| term.find_matches(searcher, cx))
 862        } else {
 863            Task::ready(vec![])
 864        }
 865    }
 866
 867    /// Reports back to the search toolbar what the active match should be (the selection)
 868    fn active_match_index(
 869        &mut self,
 870        matches: Vec<Self::Match>,
 871        cx: &mut ViewContext<Self>,
 872    ) -> Option<usize> {
 873        // Selection head might have a value if there's a selection that isn't
 874        // associated with a match. Therefore, if there are no matches, we should
 875        // report None, no matter the state of the terminal
 876        let res = if matches.len() > 0 {
 877            if let Some(selection_head) = self.terminal().read(cx).selection_head {
 878                // If selection head is contained in a match. Return that match
 879                if let Some(ix) = matches
 880                    .iter()
 881                    .enumerate()
 882                    .find(|(_, search_match)| {
 883                        search_match.contains(&selection_head)
 884                            || search_match.start() > &selection_head
 885                    })
 886                    .map(|(ix, _)| ix)
 887                {
 888                    Some(ix)
 889                } else {
 890                    // If no selection after selection head, return the last match
 891                    Some(matches.len().saturating_sub(1))
 892                }
 893            } else {
 894                // Matches found but no active selection, return the first last one (closest to cursor)
 895                Some(matches.len().saturating_sub(1))
 896            }
 897        } else {
 898            None
 899        };
 900
 901        res
 902    }
 903    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
 904        // Replacement is not supported in terminal view, so this is a no-op.
 905    }
 906}
 907
 908///Get's the working directory for the given workspace, respecting the user's settings.
 909pub fn get_working_directory(
 910    workspace: &Workspace,
 911    cx: &AppContext,
 912    strategy: WorkingDirectory,
 913) -> Option<PathBuf> {
 914    let res = match strategy {
 915        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
 916            .or_else(|| first_project_directory(workspace, cx)),
 917        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
 918        WorkingDirectory::AlwaysHome => None,
 919        WorkingDirectory::Always { directory } => {
 920            shellexpand::full(&directory) //TODO handle this better
 921                .ok()
 922                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
 923                .filter(|dir| dir.is_dir())
 924        }
 925    };
 926    res.or_else(home_dir)
 927}
 928
 929///Get's the first project's home directory, or the home directory
 930fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 931    workspace
 932        .worktrees(cx)
 933        .next()
 934        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 935        .and_then(get_path_from_wt)
 936}
 937
 938///Gets the intuitively correct working directory from the given workspace
 939///If there is an active entry for this project, returns that entry's worktree root.
 940///If there's no active entry but there is a worktree, returns that worktrees root.
 941///If either of these roots are files, or if there are any other query failures,
 942///  returns the user's home directory
 943fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 944    let project = workspace.project().read(cx);
 945
 946    project
 947        .active_entry()
 948        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
 949        .or_else(|| workspace.worktrees(cx).next())
 950        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 951        .and_then(get_path_from_wt)
 952}
 953
 954fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
 955    wt.root_entry()
 956        .filter(|re| re.is_dir())
 957        .map(|_| wt.abs_path().to_path_buf())
 958}
 959
 960#[cfg(test)]
 961mod tests {
 962    use super::*;
 963    use gpui::TestAppContext;
 964    use project::{Entry, Project, ProjectPath, Worktree};
 965    use std::path::Path;
 966    use workspace::AppState;
 967
 968    // Working directory calculation tests
 969
 970    // No Worktrees in project -> home_dir()
 971    #[gpui::test]
 972    async fn no_worktree(cx: &mut TestAppContext) {
 973        let (project, workspace) = init_test(cx).await;
 974        cx.read(|cx| {
 975            let workspace = workspace.read(cx);
 976            let active_entry = project.read(cx).active_entry();
 977
 978            //Make sure environment is as expected
 979            assert!(active_entry.is_none());
 980            assert!(workspace.worktrees(cx).next().is_none());
 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, None);
 986        });
 987    }
 988
 989    // No active entry, but a worktree, worktree is a file -> home_dir()
 990    #[gpui::test]
 991    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
 992        let (project, workspace) = init_test(cx).await;
 993
 994        create_file_wt(project.clone(), "/root.txt", cx).await;
 995        cx.read(|cx| {
 996            let workspace = workspace.read(cx);
 997            let active_entry = project.read(cx).active_entry();
 998
 999            //Make sure environment is as expected
1000            assert!(active_entry.is_none());
1001            assert!(workspace.worktrees(cx).next().is_some());
1002
1003            let res = current_project_directory(workspace, cx);
1004            assert_eq!(res, None);
1005            let res = first_project_directory(workspace, cx);
1006            assert_eq!(res, None);
1007        });
1008    }
1009
1010    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1011    #[gpui::test]
1012    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1013        let (project, workspace) = init_test(cx).await;
1014
1015        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1016        cx.update(|cx| {
1017            let workspace = workspace.read(cx);
1018            let active_entry = project.read(cx).active_entry();
1019
1020            assert!(active_entry.is_none());
1021            assert!(workspace.worktrees(cx).next().is_some());
1022
1023            let res = current_project_directory(workspace, cx);
1024            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1025            let res = first_project_directory(workspace, cx);
1026            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1027        });
1028    }
1029
1030    // Active entry with a work tree, worktree is a file -> home_dir()
1031    #[gpui::test]
1032    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1033        let (project, workspace) = init_test(cx).await;
1034
1035        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1036        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1037        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1038
1039        cx.update(|cx| {
1040            let workspace = workspace.read(cx);
1041            let active_entry = project.read(cx).active_entry();
1042
1043            assert!(active_entry.is_some());
1044
1045            let res = current_project_directory(workspace, cx);
1046            assert_eq!(res, None);
1047            let res = first_project_directory(workspace, cx);
1048            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1049        });
1050    }
1051
1052    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1053    #[gpui::test]
1054    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1055        let (project, workspace) = init_test(cx).await;
1056
1057        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1058        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1059        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1060
1061        cx.update(|cx| {
1062            let workspace = workspace.read(cx);
1063            let active_entry = project.read(cx).active_entry();
1064
1065            assert!(active_entry.is_some());
1066
1067            let res = current_project_directory(workspace, cx);
1068            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1069            let res = first_project_directory(workspace, cx);
1070            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1071        });
1072    }
1073
1074    /// Creates a worktree with 1 file: /root.txt
1075    pub async fn init_test(
1076        cx: &mut TestAppContext,
1077    ) -> (ModelHandle<Project>, ViewHandle<Workspace>) {
1078        let params = cx.update(AppState::test);
1079        cx.update(|cx| {
1080            theme::init((), cx);
1081            Project::init_settings(cx);
1082            language::init(cx);
1083        });
1084
1085        let project = Project::test(params.fs.clone(), [], cx).await;
1086        let workspace = cx
1087            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1088            .root(cx);
1089
1090        (project, workspace)
1091    }
1092
1093    /// Creates a worktree with 1 folder: /root{suffix}/
1094    async fn create_folder_wt(
1095        project: ModelHandle<Project>,
1096        path: impl AsRef<Path>,
1097        cx: &mut TestAppContext,
1098    ) -> (ModelHandle<Worktree>, Entry) {
1099        create_wt(project, true, path, cx).await
1100    }
1101
1102    /// Creates a worktree with 1 file: /root{suffix}.txt
1103    async fn create_file_wt(
1104        project: ModelHandle<Project>,
1105        path: impl AsRef<Path>,
1106        cx: &mut TestAppContext,
1107    ) -> (ModelHandle<Worktree>, Entry) {
1108        create_wt(project, false, path, cx).await
1109    }
1110
1111    async fn create_wt(
1112        project: ModelHandle<Project>,
1113        is_dir: bool,
1114        path: impl AsRef<Path>,
1115        cx: &mut TestAppContext,
1116    ) -> (ModelHandle<Worktree>, Entry) {
1117        let (wt, _) = project
1118            .update(cx, |project, cx| {
1119                project.find_or_create_local_worktree(path, true, cx)
1120            })
1121            .await
1122            .unwrap();
1123
1124        let entry = cx
1125            .update(|cx| {
1126                wt.update(cx, |wt, cx| {
1127                    wt.as_local()
1128                        .unwrap()
1129                        .create_entry(Path::new(""), is_dir, cx)
1130                })
1131            })
1132            .await
1133            .unwrap();
1134
1135        (wt, entry)
1136    }
1137
1138    pub fn insert_active_entry_for(
1139        wt: ModelHandle<Worktree>,
1140        entry: Entry,
1141        project: ModelHandle<Project>,
1142        cx: &mut TestAppContext,
1143    ) {
1144        cx.update(|cx| {
1145            let p = ProjectPath {
1146                worktree_id: wt.read(cx).id(),
1147                path: entry.path,
1148            };
1149            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1150        });
1151    }
1152}