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