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