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