terminal_view.rs

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