terminal_view.rs

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