terminal_view.rs

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