terminal_view.rs

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