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    let searcher = RegexSearch::new(&query);
 604    searcher.ok()
 605}
 606
 607impl TerminalView {
 608    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) {
 609        self.clear_bel(cx);
 610        self.pause_cursor_blinking(cx);
 611
 612        self.terminal.update(cx, |term, cx| {
 613            term.try_keystroke(
 614                &event.keystroke,
 615                TerminalSettings::get_global(cx).option_as_meta,
 616            )
 617        });
 618    }
 619
 620    fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
 621        self.has_new_content = false;
 622        self.terminal.read(cx).focus_in();
 623        self.blink_cursors(self.blink_epoch, cx);
 624        cx.notify();
 625    }
 626
 627    fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
 628        self.terminal.update(cx, |terminal, _| {
 629            terminal.focus_out();
 630        });
 631        cx.notify();
 632    }
 633}
 634
 635impl Render for TerminalView {
 636    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 637        let terminal_handle = self.terminal.clone();
 638
 639        let focused = self.focus_handle.is_focused(cx);
 640
 641        div()
 642            .size_full()
 643            .relative()
 644            .track_focus(&self.focus_handle)
 645            .key_context(self.dispatch_context(cx))
 646            .on_action(cx.listener(TerminalView::send_text))
 647            .on_action(cx.listener(TerminalView::send_keystroke))
 648            .on_action(cx.listener(TerminalView::copy))
 649            .on_action(cx.listener(TerminalView::paste))
 650            .on_action(cx.listener(TerminalView::clear))
 651            .on_action(cx.listener(TerminalView::show_character_palette))
 652            .on_action(cx.listener(TerminalView::select_all))
 653            .on_key_down(cx.listener(Self::key_down))
 654            .on_mouse_down(
 655                MouseButton::Right,
 656                cx.listener(|this, event: &MouseDownEvent, cx| {
 657                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
 658                        this.deploy_context_menu(event.position, cx);
 659                        cx.notify();
 660                    }
 661                }),
 662            )
 663            .child(
 664                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
 665                div().size_full().child(TerminalElement::new(
 666                    terminal_handle,
 667                    self.workspace.clone(),
 668                    self.focus_handle.clone(),
 669                    focused,
 670                    self.should_show_cursor(focused, cx),
 671                    self.can_navigate_to_selected_word,
 672                )),
 673            )
 674            .children(self.context_menu.as_ref().map(|(menu, positon, _)| {
 675                overlay()
 676                    .position(*positon)
 677                    .anchor(gpui::AnchorCorner::TopLeft)
 678                    .child(menu.clone())
 679            }))
 680    }
 681}
 682
 683impl Item for TerminalView {
 684    type Event = ItemEvent;
 685
 686    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 687        Some(self.terminal().read(cx).title(false).into())
 688    }
 689
 690    fn tab_content(
 691        &self,
 692        _detail: Option<usize>,
 693        selected: bool,
 694        cx: &WindowContext,
 695    ) -> AnyElement {
 696        let title = self.terminal().read(cx).title(true);
 697        h_stack()
 698            .gap_2()
 699            .child(Icon::new(IconName::Terminal))
 700            .child(Label::new(title).color(if selected {
 701                Color::Default
 702            } else {
 703                Color::Muted
 704            }))
 705            .into_any()
 706    }
 707
 708    fn clone_on_split(
 709        &self,
 710        _workspace_id: WorkspaceId,
 711        _cx: &mut ViewContext<Self>,
 712    ) -> Option<View<Self>> {
 713        //From what I can tell, there's no  way to tell the current working
 714        //Directory of the terminal from outside the shell. There might be
 715        //solutions to this, but they are non-trivial and require more IPC
 716
 717        // Some(TerminalContainer::new(
 718        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 719        //     workspace_id,
 720        //     cx,
 721        // ))
 722
 723        // TODO
 724        None
 725    }
 726
 727    fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
 728        self.has_bell()
 729    }
 730
 731    fn has_conflict(&self, _cx: &AppContext) -> bool {
 732        false
 733    }
 734
 735    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 736        Some(Box::new(handle.clone()))
 737    }
 738
 739    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 740        ToolbarItemLocation::PrimaryLeft
 741    }
 742
 743    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 744        Some(vec![BreadcrumbText {
 745            text: self.terminal().read(cx).breadcrumb_text.clone(),
 746            highlights: None,
 747        }])
 748    }
 749
 750    fn serialized_item_kind() -> Option<&'static str> {
 751        Some("Terminal")
 752    }
 753
 754    fn deserialize(
 755        project: Model<Project>,
 756        workspace: WeakView<Workspace>,
 757        workspace_id: workspace::WorkspaceId,
 758        item_id: workspace::ItemId,
 759        cx: &mut ViewContext<Pane>,
 760    ) -> Task<anyhow::Result<View<Self>>> {
 761        let window = cx.window_handle();
 762        cx.spawn(|pane, mut cx| async move {
 763            let cwd = TERMINAL_DB
 764                .get_working_directory(item_id, workspace_id)
 765                .log_err()
 766                .flatten()
 767                .or_else(|| {
 768                    cx.update(|_, cx| {
 769                        let strategy = TerminalSettings::get_global(cx).working_directory.clone();
 770                        workspace
 771                            .upgrade()
 772                            .map(|workspace| {
 773                                get_working_directory(workspace.read(cx), cx, strategy)
 774                            })
 775                            .flatten()
 776                    })
 777                    .ok()
 778                    .flatten()
 779                });
 780
 781            let terminal = project.update(&mut cx, |project, cx| {
 782                project.create_terminal(cwd, window, cx)
 783            })??;
 784            pane.update(&mut cx, |_, cx| {
 785                cx.new_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 786            })
 787        })
 788    }
 789
 790    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 791        cx.background_executor()
 792            .spawn(TERMINAL_DB.update_workspace_id(
 793                workspace.database_id(),
 794                self.workspace_id,
 795                cx.entity_id().as_u64(),
 796            ))
 797            .detach();
 798        self.workspace_id = workspace.database_id();
 799    }
 800
 801    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 802        f(*event)
 803    }
 804}
 805
 806impl SearchableItem for TerminalView {
 807    type Match = RangeInclusive<Point>;
 808
 809    fn supported_options() -> SearchOptions {
 810        SearchOptions {
 811            case: false,
 812            word: false,
 813            regex: false,
 814            replacement: false,
 815        }
 816    }
 817
 818    /// Clear stored matches
 819    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 820        self.terminal().update(cx, |term, _| term.matches.clear())
 821    }
 822
 823    /// Store matches returned from find_matches somewhere for rendering
 824    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 825        self.terminal().update(cx, |term, _| term.matches = matches)
 826    }
 827
 828    /// Return the selection content to pre-load into this search
 829    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 830        self.terminal()
 831            .read(cx)
 832            .last_content
 833            .selection_text
 834            .clone()
 835            .unwrap_or_default()
 836    }
 837
 838    /// Focus match at given index into the Vec of matches
 839    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 840        self.terminal()
 841            .update(cx, |term, _| term.activate_match(index));
 842        cx.notify();
 843    }
 844
 845    /// Add selections for all matches given.
 846    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 847        self.terminal()
 848            .update(cx, |term, _| term.select_matches(matches));
 849        cx.notify();
 850    }
 851
 852    /// Get all of the matches for this query, should be done on the background
 853    fn find_matches(
 854        &mut self,
 855        query: Arc<project::search::SearchQuery>,
 856        cx: &mut ViewContext<Self>,
 857    ) -> Task<Vec<Self::Match>> {
 858        if let Some(searcher) = regex_search_for_query(&query) {
 859            self.terminal()
 860                .update(cx, |term, cx| term.find_matches(searcher, cx))
 861        } else {
 862            Task::ready(vec![])
 863        }
 864    }
 865
 866    /// Reports back to the search toolbar what the active match should be (the selection)
 867    fn active_match_index(
 868        &mut self,
 869        matches: Vec<Self::Match>,
 870        cx: &mut ViewContext<Self>,
 871    ) -> Option<usize> {
 872        // Selection head might have a value if there's a selection that isn't
 873        // associated with a match. Therefore, if there are no matches, we should
 874        // report None, no matter the state of the terminal
 875        let res = if matches.len() > 0 {
 876            if let Some(selection_head) = self.terminal().read(cx).selection_head {
 877                // If selection head is contained in a match. Return that match
 878                if let Some(ix) = matches
 879                    .iter()
 880                    .enumerate()
 881                    .find(|(_, search_match)| {
 882                        search_match.contains(&selection_head)
 883                            || search_match.start() > &selection_head
 884                    })
 885                    .map(|(ix, _)| ix)
 886                {
 887                    Some(ix)
 888                } else {
 889                    // If no selection after selection head, return the last match
 890                    Some(matches.len().saturating_sub(1))
 891                }
 892            } else {
 893                // Matches found but no active selection, return the first last one (closest to cursor)
 894                Some(matches.len().saturating_sub(1))
 895            }
 896        } else {
 897            None
 898        };
 899
 900        res
 901    }
 902    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
 903        // Replacement is not supported in terminal view, so this is a no-op.
 904    }
 905}
 906
 907///Get's the working directory for the given workspace, respecting the user's settings.
 908pub fn get_working_directory(
 909    workspace: &Workspace,
 910    cx: &AppContext,
 911    strategy: WorkingDirectory,
 912) -> Option<PathBuf> {
 913    let res = match strategy {
 914        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
 915            .or_else(|| first_project_directory(workspace, cx)),
 916        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
 917        WorkingDirectory::AlwaysHome => None,
 918        WorkingDirectory::Always { directory } => {
 919            shellexpand::full(&directory) //TODO handle this better
 920                .ok()
 921                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
 922                .filter(|dir| dir.is_dir())
 923        }
 924    };
 925    res.or_else(home_dir)
 926}
 927
 928///Get's the first project's home directory, or the home directory
 929fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 930    workspace
 931        .worktrees(cx)
 932        .next()
 933        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 934        .and_then(get_path_from_wt)
 935}
 936
 937///Gets the intuitively correct working directory from the given workspace
 938///If there is an active entry for this project, returns that entry's worktree root.
 939///If there's no active entry but there is a worktree, returns that worktrees root.
 940///If either of these roots are files, or if there are any other query failures,
 941///  returns the user's home directory
 942fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 943    let project = workspace.project().read(cx);
 944
 945    project
 946        .active_entry()
 947        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
 948        .or_else(|| workspace.worktrees(cx).next())
 949        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 950        .and_then(get_path_from_wt)
 951}
 952
 953fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
 954    wt.root_entry()
 955        .filter(|re| re.is_dir())
 956        .map(|_| wt.abs_path().to_path_buf())
 957}
 958
 959#[cfg(test)]
 960mod tests {
 961    use super::*;
 962    use gpui::TestAppContext;
 963    use project::{Entry, Project, ProjectPath, Worktree};
 964    use std::path::Path;
 965    use workspace::AppState;
 966
 967    // Working directory calculation tests
 968
 969    // No Worktrees in project -> home_dir()
 970    #[gpui::test]
 971    async fn no_worktree(cx: &mut TestAppContext) {
 972        let (project, workspace) = init_test(cx).await;
 973        cx.read(|cx| {
 974            let workspace = workspace.read(cx);
 975            let active_entry = project.read(cx).active_entry();
 976
 977            //Make sure environment is as expected
 978            assert!(active_entry.is_none());
 979            assert!(workspace.worktrees(cx).next().is_none());
 980
 981            let res = current_project_directory(workspace, cx);
 982            assert_eq!(res, None);
 983            let res = first_project_directory(workspace, cx);
 984            assert_eq!(res, None);
 985        });
 986    }
 987
 988    // No active entry, but a worktree, worktree is a file -> home_dir()
 989    #[gpui::test]
 990    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
 991        let (project, workspace) = init_test(cx).await;
 992
 993        create_file_wt(project.clone(), "/root.txt", cx).await;
 994        cx.read(|cx| {
 995            let workspace = workspace.read(cx);
 996            let active_entry = project.read(cx).active_entry();
 997
 998            //Make sure environment is as expected
 999            assert!(active_entry.is_none());
1000            assert!(workspace.worktrees(cx).next().is_some());
1001
1002            let res = current_project_directory(workspace, cx);
1003            assert_eq!(res, None);
1004            let res = first_project_directory(workspace, cx);
1005            assert_eq!(res, None);
1006        });
1007    }
1008
1009    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1010    #[gpui::test]
1011    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1012        let (project, workspace) = init_test(cx).await;
1013
1014        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1015        cx.update(|cx| {
1016            let workspace = workspace.read(cx);
1017            let active_entry = project.read(cx).active_entry();
1018
1019            assert!(active_entry.is_none());
1020            assert!(workspace.worktrees(cx).next().is_some());
1021
1022            let res = current_project_directory(workspace, cx);
1023            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1024            let res = first_project_directory(workspace, cx);
1025            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1026        });
1027    }
1028
1029    // Active entry with a work tree, worktree is a file -> home_dir()
1030    #[gpui::test]
1031    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1032        let (project, workspace) = init_test(cx).await;
1033
1034        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1035        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1036        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1037
1038        cx.update(|cx| {
1039            let workspace = workspace.read(cx);
1040            let active_entry = project.read(cx).active_entry();
1041
1042            assert!(active_entry.is_some());
1043
1044            let res = current_project_directory(workspace, cx);
1045            assert_eq!(res, None);
1046            let res = first_project_directory(workspace, cx);
1047            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1048        });
1049    }
1050
1051    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1052    #[gpui::test]
1053    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1054        let (project, workspace) = init_test(cx).await;
1055
1056        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1057        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1058        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1059
1060        cx.update(|cx| {
1061            let workspace = workspace.read(cx);
1062            let active_entry = project.read(cx).active_entry();
1063
1064            assert!(active_entry.is_some());
1065
1066            let res = current_project_directory(workspace, cx);
1067            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1068            let res = first_project_directory(workspace, cx);
1069            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1070        });
1071    }
1072
1073    /// Creates a worktree with 1 file: /root.txt
1074    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1075        let params = cx.update(AppState::test);
1076        cx.update(|cx| {
1077            theme::init(theme::LoadThemes::JustBase, cx);
1078            Project::init_settings(cx);
1079            language::init(cx);
1080        });
1081
1082        let project = Project::test(params.fs.clone(), [], cx).await;
1083        let workspace = cx
1084            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1085            .root_view(cx)
1086            .unwrap();
1087
1088        (project, workspace)
1089    }
1090
1091    /// Creates a worktree with 1 folder: /root{suffix}/
1092    async fn create_folder_wt(
1093        project: Model<Project>,
1094        path: impl AsRef<Path>,
1095        cx: &mut TestAppContext,
1096    ) -> (Model<Worktree>, Entry) {
1097        create_wt(project, true, path, cx).await
1098    }
1099
1100    /// Creates a worktree with 1 file: /root{suffix}.txt
1101    async fn create_file_wt(
1102        project: Model<Project>,
1103        path: impl AsRef<Path>,
1104        cx: &mut TestAppContext,
1105    ) -> (Model<Worktree>, Entry) {
1106        create_wt(project, false, path, cx).await
1107    }
1108
1109    async fn create_wt(
1110        project: Model<Project>,
1111        is_dir: bool,
1112        path: impl AsRef<Path>,
1113        cx: &mut TestAppContext,
1114    ) -> (Model<Worktree>, Entry) {
1115        let (wt, _) = project
1116            .update(cx, |project, cx| {
1117                project.find_or_create_local_worktree(path, true, cx)
1118            })
1119            .await
1120            .unwrap();
1121
1122        let entry = cx
1123            .update(|cx| {
1124                wt.update(cx, |wt, cx| {
1125                    wt.as_local()
1126                        .unwrap()
1127                        .create_entry(Path::new(""), is_dir, cx)
1128                })
1129            })
1130            .await
1131            .unwrap()
1132            .unwrap();
1133
1134        (wt, entry)
1135    }
1136
1137    pub fn insert_active_entry_for(
1138        wt: Model<Worktree>,
1139        entry: Entry,
1140        project: Model<Project>,
1141        cx: &mut TestAppContext,
1142    ) {
1143        cx.update(|cx| {
1144            let p = ProjectPath {
1145                worktree_id: wt.read(cx).id(),
1146                path: entry.path,
1147            };
1148            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1149        });
1150    }
1151}