terminal_view.rs

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