terminal_view.rs

   1mod persistence;
   2pub mod terminal_element;
   3pub mod terminal_panel;
   4
   5use editor::{scroll::autoscroll::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_stack, 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::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, positon, _)| {
 678                overlay()
 679                    .position(*positon)
 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_stack()
 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 clone_on_split(
 712        &self,
 713        _workspace_id: WorkspaceId,
 714        _cx: &mut ViewContext<Self>,
 715    ) -> Option<View<Self>> {
 716        //From what I can tell, there's no  way to tell the current working
 717        //Directory of the terminal from outside the shell. There might be
 718        //solutions to this, but they are non-trivial and require more IPC
 719
 720        // Some(TerminalContainer::new(
 721        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 722        //     workspace_id,
 723        //     cx,
 724        // ))
 725
 726        // TODO
 727        None
 728    }
 729
 730    fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
 731        self.has_bell()
 732    }
 733
 734    fn has_conflict(&self, _cx: &AppContext) -> bool {
 735        false
 736    }
 737
 738    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 739        Some(Box::new(handle.clone()))
 740    }
 741
 742    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 743        ToolbarItemLocation::PrimaryLeft
 744    }
 745
 746    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 747        Some(vec![BreadcrumbText {
 748            text: self.terminal().read(cx).breadcrumb_text.clone(),
 749            highlights: None,
 750        }])
 751    }
 752
 753    fn serialized_item_kind() -> Option<&'static str> {
 754        Some("Terminal")
 755    }
 756
 757    fn deserialize(
 758        project: Model<Project>,
 759        workspace: WeakView<Workspace>,
 760        workspace_id: workspace::WorkspaceId,
 761        item_id: workspace::ItemId,
 762        cx: &mut ViewContext<Pane>,
 763    ) -> Task<anyhow::Result<View<Self>>> {
 764        let window = cx.window_handle();
 765        cx.spawn(|pane, mut cx| async move {
 766            let cwd = TERMINAL_DB
 767                .get_working_directory(item_id, workspace_id)
 768                .log_err()
 769                .flatten()
 770                .or_else(|| {
 771                    cx.update(|_, cx| {
 772                        let strategy = TerminalSettings::get_global(cx).working_directory.clone();
 773                        workspace
 774                            .upgrade()
 775                            .map(|workspace| {
 776                                get_working_directory(workspace.read(cx), cx, strategy)
 777                            })
 778                            .flatten()
 779                    })
 780                    .ok()
 781                    .flatten()
 782                });
 783
 784            let terminal = project.update(&mut cx, |project, cx| {
 785                project.create_terminal(cwd, window, cx)
 786            })??;
 787            pane.update(&mut cx, |_, cx| {
 788                cx.new_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 789            })
 790        })
 791    }
 792
 793    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 794        cx.background_executor()
 795            .spawn(TERMINAL_DB.update_workspace_id(
 796                workspace.database_id(),
 797                self.workspace_id,
 798                cx.entity_id().as_u64(),
 799            ))
 800            .detach();
 801        self.workspace_id = workspace.database_id();
 802    }
 803
 804    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 805        f(*event)
 806    }
 807}
 808
 809impl SearchableItem for TerminalView {
 810    type Match = RangeInclusive<Point>;
 811
 812    fn supported_options() -> SearchOptions {
 813        SearchOptions {
 814            case: false,
 815            word: false,
 816            regex: false,
 817            replacement: false,
 818        }
 819    }
 820
 821    /// Clear stored matches
 822    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 823        self.terminal().update(cx, |term, _| term.matches.clear())
 824    }
 825
 826    /// Store matches returned from find_matches somewhere for rendering
 827    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 828        self.terminal().update(cx, |term, _| term.matches = matches)
 829    }
 830
 831    /// Return the selection content to pre-load into this search
 832    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 833        self.terminal()
 834            .read(cx)
 835            .last_content
 836            .selection_text
 837            .clone()
 838            .unwrap_or_default()
 839    }
 840
 841    /// Focus match at given index into the Vec of matches
 842    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 843        self.terminal()
 844            .update(cx, |term, _| term.activate_match(index));
 845        cx.notify();
 846    }
 847
 848    /// Add selections for all matches given.
 849    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 850        self.terminal()
 851            .update(cx, |term, _| term.select_matches(matches));
 852        cx.notify();
 853    }
 854
 855    /// Get all of the matches for this query, should be done on the background
 856    fn find_matches(
 857        &mut self,
 858        query: Arc<project::search::SearchQuery>,
 859        cx: &mut ViewContext<Self>,
 860    ) -> Task<Vec<Self::Match>> {
 861        if let Some(searcher) = regex_search_for_query(&query) {
 862            self.terminal()
 863                .update(cx, |term, cx| term.find_matches(searcher, cx))
 864        } else {
 865            Task::ready(vec![])
 866        }
 867    }
 868
 869    /// Reports back to the search toolbar what the active match should be (the selection)
 870    fn active_match_index(
 871        &mut self,
 872        matches: Vec<Self::Match>,
 873        cx: &mut ViewContext<Self>,
 874    ) -> Option<usize> {
 875        // Selection head might have a value if there's a selection that isn't
 876        // associated with a match. Therefore, if there are no matches, we should
 877        // report None, no matter the state of the terminal
 878        let res = if matches.len() > 0 {
 879            if let Some(selection_head) = self.terminal().read(cx).selection_head {
 880                // If selection head is contained in a match. Return that match
 881                if let Some(ix) = matches
 882                    .iter()
 883                    .enumerate()
 884                    .find(|(_, search_match)| {
 885                        search_match.contains(&selection_head)
 886                            || search_match.start() > &selection_head
 887                    })
 888                    .map(|(ix, _)| ix)
 889                {
 890                    Some(ix)
 891                } else {
 892                    // If no selection after selection head, return the last match
 893                    Some(matches.len().saturating_sub(1))
 894                }
 895            } else {
 896                // Matches found but no active selection, return the first last one (closest to cursor)
 897                Some(matches.len().saturating_sub(1))
 898            }
 899        } else {
 900            None
 901        };
 902
 903        res
 904    }
 905    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
 906        // Replacement is not supported in terminal view, so this is a no-op.
 907    }
 908}
 909
 910///Get's the working directory for the given workspace, respecting the user's settings.
 911pub fn get_working_directory(
 912    workspace: &Workspace,
 913    cx: &AppContext,
 914    strategy: WorkingDirectory,
 915) -> Option<PathBuf> {
 916    let res = match strategy {
 917        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
 918            .or_else(|| first_project_directory(workspace, cx)),
 919        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
 920        WorkingDirectory::AlwaysHome => None,
 921        WorkingDirectory::Always { directory } => {
 922            shellexpand::full(&directory) //TODO handle this better
 923                .ok()
 924                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
 925                .filter(|dir| dir.is_dir())
 926        }
 927    };
 928    res.or_else(home_dir)
 929}
 930
 931///Get's the first project's home directory, or the home directory
 932fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 933    workspace
 934        .worktrees(cx)
 935        .next()
 936        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 937        .and_then(get_path_from_wt)
 938}
 939
 940///Gets the intuitively correct working directory from the given workspace
 941///If there is an active entry for this project, returns that entry's worktree root.
 942///If there's no active entry but there is a worktree, returns that worktrees root.
 943///If either of these roots are files, or if there are any other query failures,
 944///  returns the user's home directory
 945fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 946    let project = workspace.project().read(cx);
 947
 948    project
 949        .active_entry()
 950        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
 951        .or_else(|| workspace.worktrees(cx).next())
 952        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 953        .and_then(get_path_from_wt)
 954}
 955
 956fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
 957    wt.root_entry()
 958        .filter(|re| re.is_dir())
 959        .map(|_| wt.abs_path().to_path_buf())
 960}
 961
 962#[cfg(test)]
 963mod tests {
 964    use super::*;
 965    use gpui::TestAppContext;
 966    use project::{Entry, Project, ProjectPath, Worktree};
 967    use std::path::Path;
 968    use workspace::AppState;
 969
 970    // Working directory calculation tests
 971
 972    // No Worktrees in project -> home_dir()
 973    #[gpui::test]
 974    async fn no_worktree(cx: &mut TestAppContext) {
 975        let (project, workspace) = init_test(cx).await;
 976        cx.read(|cx| {
 977            let workspace = workspace.read(cx);
 978            let active_entry = project.read(cx).active_entry();
 979
 980            //Make sure environment is as expected
 981            assert!(active_entry.is_none());
 982            assert!(workspace.worktrees(cx).next().is_none());
 983
 984            let res = current_project_directory(workspace, cx);
 985            assert_eq!(res, None);
 986            let res = first_project_directory(workspace, cx);
 987            assert_eq!(res, None);
 988        });
 989    }
 990
 991    // No active entry, but a worktree, worktree is a file -> home_dir()
 992    #[gpui::test]
 993    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
 994        let (project, workspace) = init_test(cx).await;
 995
 996        create_file_wt(project.clone(), "/root.txt", cx).await;
 997        cx.read(|cx| {
 998            let workspace = workspace.read(cx);
 999            let active_entry = project.read(cx).active_entry();
1000
1001            //Make sure environment is as expected
1002            assert!(active_entry.is_none());
1003            assert!(workspace.worktrees(cx).next().is_some());
1004
1005            let res = current_project_directory(workspace, cx);
1006            assert_eq!(res, None);
1007            let res = first_project_directory(workspace, cx);
1008            assert_eq!(res, None);
1009        });
1010    }
1011
1012    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1013    #[gpui::test]
1014    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1015        let (project, workspace) = init_test(cx).await;
1016
1017        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1018        cx.update(|cx| {
1019            let workspace = workspace.read(cx);
1020            let active_entry = project.read(cx).active_entry();
1021
1022            assert!(active_entry.is_none());
1023            assert!(workspace.worktrees(cx).next().is_some());
1024
1025            let res = current_project_directory(workspace, cx);
1026            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1027            let res = first_project_directory(workspace, cx);
1028            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1029        });
1030    }
1031
1032    // Active entry with a work tree, worktree is a file -> home_dir()
1033    #[gpui::test]
1034    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1035        let (project, workspace) = init_test(cx).await;
1036
1037        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1038        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1039        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1040
1041        cx.update(|cx| {
1042            let workspace = workspace.read(cx);
1043            let active_entry = project.read(cx).active_entry();
1044
1045            assert!(active_entry.is_some());
1046
1047            let res = current_project_directory(workspace, cx);
1048            assert_eq!(res, None);
1049            let res = first_project_directory(workspace, cx);
1050            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1051        });
1052    }
1053
1054    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1055    #[gpui::test]
1056    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1057        let (project, workspace) = init_test(cx).await;
1058
1059        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1060        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1061        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1062
1063        cx.update(|cx| {
1064            let workspace = workspace.read(cx);
1065            let active_entry = project.read(cx).active_entry();
1066
1067            assert!(active_entry.is_some());
1068
1069            let res = current_project_directory(workspace, cx);
1070            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1071            let res = first_project_directory(workspace, cx);
1072            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1073        });
1074    }
1075
1076    /// Creates a worktree with 1 file: /root.txt
1077    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1078        let params = cx.update(AppState::test);
1079        cx.update(|cx| {
1080            theme::init(theme::LoadThemes::JustBase, 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_view(cx)
1089            .unwrap();
1090
1091        (project, workspace)
1092    }
1093
1094    /// Creates a worktree with 1 folder: /root{suffix}/
1095    async fn create_folder_wt(
1096        project: Model<Project>,
1097        path: impl AsRef<Path>,
1098        cx: &mut TestAppContext,
1099    ) -> (Model<Worktree>, Entry) {
1100        create_wt(project, true, path, cx).await
1101    }
1102
1103    /// Creates a worktree with 1 file: /root{suffix}.txt
1104    async fn create_file_wt(
1105        project: Model<Project>,
1106        path: impl AsRef<Path>,
1107        cx: &mut TestAppContext,
1108    ) -> (Model<Worktree>, Entry) {
1109        create_wt(project, false, path, cx).await
1110    }
1111
1112    async fn create_wt(
1113        project: Model<Project>,
1114        is_dir: bool,
1115        path: impl AsRef<Path>,
1116        cx: &mut TestAppContext,
1117    ) -> (Model<Worktree>, Entry) {
1118        let (wt, _) = project
1119            .update(cx, |project, cx| {
1120                project.find_or_create_local_worktree(path, true, cx)
1121            })
1122            .await
1123            .unwrap();
1124
1125        let entry = cx
1126            .update(|cx| {
1127                wt.update(cx, |wt, cx| {
1128                    wt.as_local()
1129                        .unwrap()
1130                        .create_entry(Path::new(""), is_dir, cx)
1131                })
1132            })
1133            .await
1134            .unwrap()
1135            .unwrap();
1136
1137        (wt, entry)
1138    }
1139
1140    pub fn insert_active_entry_for(
1141        wt: Model<Worktree>,
1142        entry: Entry,
1143        project: Model<Project>,
1144        cx: &mut TestAppContext,
1145    ) {
1146        cx.update(|cx| {
1147            let p = ProjectPath {
1148                worktree_id: wt.read(cx).id(),
1149                path: entry.path,
1150            };
1151            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1152        });
1153    }
1154}