terminal_view.rs

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