terminal_view.rs

   1mod persistence;
   2pub mod terminal_element;
   3pub mod terminal_panel;
   4
   5// todo!()
   6// use crate::terminal_element::TerminalElement;
   7use editor::{scroll::autoscroll::Autoscroll, Editor};
   8use gpui::{
   9    div, impl_actions, overlay, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle,
  10    FocusableView, KeyContext, KeyDownEvent, Keystroke, Model, MouseButton, MouseDownEvent, Pixels,
  11    Render, Styled, Subscription, Task, View, VisualContext, WeakView,
  12};
  13use language::Bias;
  14use persistence::TERMINAL_DB;
  15use project::{search::SearchQuery, LocalWorktree, Project};
  16use terminal::{
  17    alacritty_terminal::{
  18        index::Point,
  19        term::{search::RegexSearch, TermMode},
  20    },
  21    terminal_settings::{TerminalBlink, TerminalSettings, WorkingDirectory},
  22    Clear, Copy, Event, MaybeNavigationTarget, Paste, ShowCharacterPalette, Terminal,
  23};
  24use terminal_element::TerminalElement;
  25use ui::{h_stack, prelude::*, ContextMenu, Icon, IconElement, Label};
  26use util::{paths::PathLikeWithPosition, ResultExt};
  27use workspace::{
  28    item::{BreadcrumbText, Item, ItemEvent},
  29    notifications::NotifyResultExt,
  30    register_deserializable_item,
  31    searchable::{SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
  32    CloseActiveItem, NewCenterTerminal, Pane, ToolbarItemLocation, Workspace, WorkspaceId,
  33};
  34
  35use anyhow::Context;
  36use dirs::home_dir;
  37use serde::Deserialize;
  38use settings::Settings;
  39use smol::Timer;
  40
  41use std::{
  42    ops::RangeInclusive,
  43    path::{Path, PathBuf},
  44    sync::Arc,
  45    time::Duration,
  46};
  47
  48const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  49
  50///Event to transmit the scroll from the element to the view
  51#[derive(Clone, Debug, PartialEq)]
  52pub struct ScrollTerminal(pub i32);
  53
  54#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
  55pub struct SendText(String);
  56
  57#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
  58pub struct SendKeystroke(String);
  59
  60impl_actions!(terminal_view, [SendText, SendKeystroke]);
  61
  62pub fn init(cx: &mut AppContext) {
  63    terminal_panel::init(cx);
  64    terminal::init(cx);
  65
  66    register_deserializable_item::<TerminalView>(cx);
  67
  68    cx.observe_new_views(|workspace: &mut Workspace, _| {
  69        workspace.register_action(TerminalView::deploy);
  70    })
  71    .detach();
  72}
  73
  74///A terminal view, maintains the PTY's file handles and communicates with the terminal
  75pub struct TerminalView {
  76    terminal: Model<Terminal>,
  77    focus_handle: FocusHandle,
  78    has_new_content: bool,
  79    //Currently using iTerm bell, show bell emoji in tab until input is received
  80    has_bell: bool,
  81    context_menu: Option<(View<ContextMenu>, gpui::Point<Pixels>, Subscription)>,
  82    blink_state: bool,
  83    blinking_on: bool,
  84    blinking_paused: bool,
  85    blink_epoch: usize,
  86    can_navigate_to_selected_word: bool,
  87    workspace_id: WorkspaceId,
  88    _subscriptions: Vec<Subscription>,
  89}
  90
  91impl EventEmitter<Event> for TerminalView {}
  92impl EventEmitter<ItemEvent> for TerminalView {}
  93impl EventEmitter<SearchEvent> for TerminalView {}
  94
  95impl FocusableView for TerminalView {
  96    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
  97        self.focus_handle.clone()
  98    }
  99}
 100
 101impl TerminalView {
 102    ///Create a new Terminal in the current working directory or the user's home directory
 103    pub fn deploy(
 104        workspace: &mut Workspace,
 105        _: &NewCenterTerminal,
 106        cx: &mut ViewContext<Workspace>,
 107    ) {
 108        let strategy = TerminalSettings::get_global(cx);
 109        let working_directory =
 110            get_working_directory(workspace, cx, strategy.working_directory.clone());
 111
 112        let window = cx.window_handle();
 113        let terminal = workspace
 114            .project()
 115            .update(cx, |project, cx| {
 116                project.create_terminal(working_directory, window, cx)
 117            })
 118            .notify_err(workspace, cx);
 119
 120        if let Some(terminal) = terminal {
 121            let view = cx.new_view(|cx| {
 122                TerminalView::new(
 123                    terminal,
 124                    workspace.weak_handle(),
 125                    workspace.database_id(),
 126                    cx,
 127                )
 128            });
 129            workspace.add_item(Box::new(view), cx)
 130        }
 131    }
 132
 133    pub fn new(
 134        terminal: Model<Terminal>,
 135        workspace: WeakView<Workspace>,
 136        workspace_id: WorkspaceId,
 137        cx: &mut ViewContext<Self>,
 138    ) -> Self {
 139        cx.observe(&terminal, |_, _, cx| cx.notify()).detach();
 140        cx.subscribe(&terminal, move |this, _, event, cx| match event {
 141            Event::Wakeup => {
 142                if !this.focus_handle.is_focused(cx) {
 143                    this.has_new_content = true;
 144                }
 145                cx.notify();
 146                cx.emit(Event::Wakeup);
 147                cx.emit(ItemEvent::UpdateTab);
 148                cx.emit(SearchEvent::MatchesInvalidated);
 149            }
 150
 151            Event::Bell => {
 152                this.has_bell = true;
 153                cx.emit(Event::Wakeup);
 154            }
 155
 156            Event::BlinkChanged => this.blinking_on = !this.blinking_on,
 157
 158            Event::TitleChanged => {
 159                cx.emit(ItemEvent::UpdateTab);
 160                if let Some(foreground_info) = &this.terminal().read(cx).foreground_process_info {
 161                    let cwd = foreground_info.cwd.clone();
 162
 163                    let item_id = cx.entity_id();
 164                    let workspace_id = this.workspace_id;
 165                    cx.background_executor()
 166                        .spawn(async move {
 167                            TERMINAL_DB
 168                                .save_working_directory(item_id.as_u64(), workspace_id, cwd)
 169                                .await
 170                                .log_err();
 171                        })
 172                        .detach();
 173                }
 174            }
 175
 176            Event::NewNavigationTarget(maybe_navigation_target) => {
 177                this.can_navigate_to_selected_word = match maybe_navigation_target {
 178                    Some(MaybeNavigationTarget::Url(_)) => true,
 179                    Some(MaybeNavigationTarget::PathLike(maybe_path)) => {
 180                        !possible_open_targets(&workspace, maybe_path, cx).is_empty()
 181                    }
 182                    None => false,
 183                }
 184            }
 185
 186            Event::Open(maybe_navigation_target) => match maybe_navigation_target {
 187                MaybeNavigationTarget::Url(url) => cx.open_url(url),
 188
 189                MaybeNavigationTarget::PathLike(maybe_path) => {
 190                    if !this.can_navigate_to_selected_word {
 191                        return;
 192                    }
 193                    let potential_abs_paths = possible_open_targets(&workspace, maybe_path, cx);
 194                    if let Some(path) = potential_abs_paths.into_iter().next() {
 195                        let is_dir = path.path_like.is_dir();
 196                        let task_workspace = workspace.clone();
 197                        cx.spawn(|_, mut cx| async move {
 198                            let opened_items = task_workspace
 199                                .update(&mut cx, |workspace, cx| {
 200                                    workspace.open_paths(vec![path.path_like], is_dir, cx)
 201                                })
 202                                .context("workspace update")?
 203                                .await;
 204                            anyhow::ensure!(
 205                                opened_items.len() == 1,
 206                                "For a single path open, expected single opened item"
 207                            );
 208                            let opened_item = opened_items
 209                                .into_iter()
 210                                .next()
 211                                .unwrap()
 212                                .transpose()
 213                                .context("path open")?;
 214                            if is_dir {
 215                                task_workspace.update(&mut cx, |workspace, cx| {
 216                                    workspace.project().update(cx, |_, cx| {
 217                                        cx.emit(project::Event::ActivateProjectPanel);
 218                                    })
 219                                })?;
 220                            } else {
 221                                if let Some(row) = path.row {
 222                                    let col = path.column.unwrap_or(0);
 223                                    if let Some(active_editor) =
 224                                        opened_item.and_then(|item| item.downcast::<Editor>())
 225                                    {
 226                                        active_editor
 227                                            .downgrade()
 228                                            .update(&mut cx, |editor, cx| {
 229                                                let snapshot = editor.snapshot(cx).display_snapshot;
 230                                                let point = snapshot.buffer_snapshot.clip_point(
 231                                                    language::Point::new(
 232                                                        row.saturating_sub(1),
 233                                                        col.saturating_sub(1),
 234                                                    ),
 235                                                    Bias::Left,
 236                                                );
 237                                                editor.change_selections(
 238                                                    Some(Autoscroll::center()),
 239                                                    cx,
 240                                                    |s| s.select_ranges([point..point]),
 241                                                );
 242                                            })
 243                                            .log_err();
 244                                    }
 245                                }
 246                            }
 247                            anyhow::Ok(())
 248                        })
 249                        .detach_and_log_err(cx);
 250                    }
 251                }
 252            },
 253            Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
 254            Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
 255            Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
 256        })
 257        .detach();
 258
 259        let focus_handle = cx.focus_handle();
 260        let focus_in = cx.on_focus_in(&focus_handle, |terminal_view, cx| {
 261            terminal_view.focus_in(cx);
 262        });
 263        let focus_out = cx.on_focus_out(&focus_handle, |terminal_view, cx| {
 264            terminal_view.focus_out(cx);
 265        });
 266
 267        Self {
 268            terminal,
 269            has_new_content: true,
 270            has_bell: false,
 271            focus_handle: cx.focus_handle(),
 272            context_menu: None,
 273            blink_state: true,
 274            blinking_on: false,
 275            blinking_paused: false,
 276            blink_epoch: 0,
 277            can_navigate_to_selected_word: false,
 278            workspace_id,
 279            _subscriptions: vec![focus_in, focus_out],
 280        }
 281    }
 282
 283    pub fn model(&self) -> &Model<Terminal> {
 284        &self.terminal
 285    }
 286
 287    pub fn has_new_content(&self) -> bool {
 288        self.has_new_content
 289    }
 290
 291    pub fn has_bell(&self) -> bool {
 292        self.has_bell
 293    }
 294
 295    pub fn clear_bel(&mut self, cx: &mut ViewContext<TerminalView>) {
 296        self.has_bell = false;
 297        cx.emit(Event::Wakeup);
 298    }
 299
 300    pub fn deploy_context_menu(
 301        &mut self,
 302        position: gpui::Point<Pixels>,
 303        cx: &mut ViewContext<Self>,
 304    ) {
 305        let context_menu = ContextMenu::build(cx, |menu, _| {
 306            menu.action("Clear", Box::new(Clear))
 307                .action("Close", Box::new(CloseActiveItem { save_intent: None }))
 308        });
 309
 310        cx.focus_view(&context_menu);
 311        let subscription =
 312            cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
 313                if this.context_menu.as_ref().is_some_and(|context_menu| {
 314                    context_menu.0.focus_handle(cx).contains_focused(cx)
 315                }) {
 316                    cx.focus_self();
 317                }
 318                this.context_menu.take();
 319                cx.notify();
 320            });
 321
 322        self.context_menu = Some((context_menu, position, subscription));
 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, 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, 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    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 621        let terminal_handle = self.terminal.clone();
 622
 623        let focused = self.focus_handle.is_focused(cx);
 624
 625        div()
 626            .size_full()
 627            .relative()
 628            .track_focus(&self.focus_handle)
 629            .key_context(self.dispatch_context(cx))
 630            .on_action(cx.listener(TerminalView::send_text))
 631            .on_action(cx.listener(TerminalView::send_keystroke))
 632            .on_action(cx.listener(TerminalView::copy))
 633            .on_action(cx.listener(TerminalView::paste))
 634            .on_action(cx.listener(TerminalView::clear))
 635            .on_action(cx.listener(TerminalView::show_character_palette))
 636            .on_action(cx.listener(TerminalView::select_all))
 637            .on_key_down(cx.listener(Self::key_down))
 638            .on_mouse_down(
 639                MouseButton::Right,
 640                cx.listener(|this, event: &MouseDownEvent, cx| {
 641                    this.deploy_context_menu(event.position, cx);
 642                    cx.notify();
 643                }),
 644            )
 645            .child(
 646                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
 647                div().size_full().child(TerminalElement::new(
 648                    terminal_handle,
 649                    self.focus_handle.clone(),
 650                    focused,
 651                    self.should_show_cursor(focused, cx),
 652                    self.can_navigate_to_selected_word,
 653                )),
 654            )
 655            .children(self.context_menu.as_ref().map(|(menu, positon, _)| {
 656                overlay()
 657                    .position(*positon)
 658                    .anchor(gpui::AnchorCorner::TopLeft)
 659                    .child(menu.clone())
 660            }))
 661    }
 662}
 663
 664impl Item for TerminalView {
 665    type Event = ItemEvent;
 666
 667    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 668        Some(self.terminal().read(cx).title().into())
 669    }
 670
 671    fn tab_content(
 672        &self,
 673        _detail: Option<usize>,
 674        selected: bool,
 675        cx: &WindowContext,
 676    ) -> AnyElement {
 677        let title = self.terminal().read(cx).title();
 678
 679        h_stack()
 680            .gap_2()
 681            .child(IconElement::new(Icon::Terminal))
 682            .child(Label::new(title).color(if selected {
 683                Color::Default
 684            } else {
 685                Color::Muted
 686            }))
 687            .into_any()
 688    }
 689
 690    fn clone_on_split(
 691        &self,
 692        _workspace_id: WorkspaceId,
 693        _cx: &mut ViewContext<Self>,
 694    ) -> Option<View<Self>> {
 695        //From what I can tell, there's no  way to tell the current working
 696        //Directory of the terminal from outside the shell. There might be
 697        //solutions to this, but they are non-trivial and require more IPC
 698
 699        // Some(TerminalContainer::new(
 700        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 701        //     workspace_id,
 702        //     cx,
 703        // ))
 704
 705        // TODO
 706        None
 707    }
 708
 709    fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
 710        self.has_bell()
 711    }
 712
 713    fn has_conflict(&self, _cx: &AppContext) -> bool {
 714        false
 715    }
 716
 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 = TERMINAL_DB
 746                .get_working_directory(item_id, workspace_id)
 747                .log_err()
 748                .flatten()
 749                .or_else(|| {
 750                    cx.update(|_, cx| {
 751                        let strategy = TerminalSettings::get_global(cx).working_directory.clone();
 752                        workspace
 753                            .upgrade()
 754                            .map(|workspace| {
 755                                get_working_directory(workspace.read(cx), cx, strategy)
 756                            })
 757                            .flatten()
 758                    })
 759                    .ok()
 760                    .flatten()
 761                });
 762
 763            let terminal = project.update(&mut cx, |project, cx| {
 764                project.create_terminal(cwd, window, cx)
 765            })??;
 766            pane.update(&mut cx, |_, cx| {
 767                cx.new_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 768            })
 769        })
 770    }
 771
 772    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 773        cx.background_executor()
 774            .spawn(TERMINAL_DB.update_workspace_id(
 775                workspace.database_id(),
 776                self.workspace_id,
 777                cx.entity_id().as_u64(),
 778            ))
 779            .detach();
 780        self.workspace_id = workspace.database_id();
 781    }
 782
 783    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 784        f(*event)
 785    }
 786}
 787
 788impl SearchableItem for TerminalView {
 789    type Match = RangeInclusive<Point>;
 790
 791    fn supported_options() -> SearchOptions {
 792        SearchOptions {
 793            case: false,
 794            word: false,
 795            regex: false,
 796            replacement: false,
 797        }
 798    }
 799
 800    /// Clear stored matches
 801    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 802        self.terminal().update(cx, |term, _| term.matches.clear())
 803    }
 804
 805    /// Store matches returned from find_matches somewhere for rendering
 806    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 807        self.terminal().update(cx, |term, _| term.matches = matches)
 808    }
 809
 810    /// Return the selection content to pre-load into this search
 811    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 812        self.terminal()
 813            .read(cx)
 814            .last_content
 815            .selection_text
 816            .clone()
 817            .unwrap_or_default()
 818    }
 819
 820    /// Focus match at given index into the Vec of matches
 821    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 822        self.terminal()
 823            .update(cx, |term, _| term.activate_match(index));
 824        cx.notify();
 825    }
 826
 827    /// Add selections for all matches given.
 828    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 829        self.terminal()
 830            .update(cx, |term, _| term.select_matches(matches));
 831        cx.notify();
 832    }
 833
 834    /// Get all of the matches for this query, should be done on the background
 835    fn find_matches(
 836        &mut self,
 837        query: Arc<project::search::SearchQuery>,
 838        cx: &mut ViewContext<Self>,
 839    ) -> Task<Vec<Self::Match>> {
 840        if let Some(searcher) = regex_search_for_query(&query) {
 841            self.terminal()
 842                .update(cx, |term, cx| term.find_matches(searcher, cx))
 843        } else {
 844            Task::ready(vec![])
 845        }
 846    }
 847
 848    /// Reports back to the search toolbar what the active match should be (the selection)
 849    fn active_match_index(
 850        &mut self,
 851        matches: Vec<Self::Match>,
 852        cx: &mut ViewContext<Self>,
 853    ) -> Option<usize> {
 854        // Selection head might have a value if there's a selection that isn't
 855        // associated with a match. Therefore, if there are no matches, we should
 856        // report None, no matter the state of the terminal
 857        let res = if matches.len() > 0 {
 858            if let Some(selection_head) = self.terminal().read(cx).selection_head {
 859                // If selection head is contained in a match. Return that match
 860                if let Some(ix) = matches
 861                    .iter()
 862                    .enumerate()
 863                    .find(|(_, search_match)| {
 864                        search_match.contains(&selection_head)
 865                            || search_match.start() > &selection_head
 866                    })
 867                    .map(|(ix, _)| ix)
 868                {
 869                    Some(ix)
 870                } else {
 871                    // If no selection after selection head, return the last match
 872                    Some(matches.len().saturating_sub(1))
 873                }
 874            } else {
 875                // Matches found but no active selection, return the first last one (closest to cursor)
 876                Some(matches.len().saturating_sub(1))
 877            }
 878        } else {
 879            None
 880        };
 881
 882        res
 883    }
 884    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
 885        // Replacement is not supported in terminal view, so this is a no-op.
 886    }
 887}
 888
 889///Get's the working directory for the given workspace, respecting the user's settings.
 890pub fn get_working_directory(
 891    workspace: &Workspace,
 892    cx: &AppContext,
 893    strategy: WorkingDirectory,
 894) -> Option<PathBuf> {
 895    let res = match strategy {
 896        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
 897            .or_else(|| first_project_directory(workspace, cx)),
 898        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
 899        WorkingDirectory::AlwaysHome => None,
 900        WorkingDirectory::Always { directory } => {
 901            shellexpand::full(&directory) //TODO handle this better
 902                .ok()
 903                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
 904                .filter(|dir| dir.is_dir())
 905        }
 906    };
 907    res.or_else(home_dir)
 908}
 909
 910///Get's the first project's home directory, or the home directory
 911fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 912    workspace
 913        .worktrees(cx)
 914        .next()
 915        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 916        .and_then(get_path_from_wt)
 917}
 918
 919///Gets the intuitively correct working directory from the given workspace
 920///If there is an active entry for this project, returns that entry's worktree root.
 921///If there's no active entry but there is a worktree, returns that worktrees root.
 922///If either of these roots are files, or if there are any other query failures,
 923///  returns the user's home directory
 924fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 925    let project = workspace.project().read(cx);
 926
 927    project
 928        .active_entry()
 929        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
 930        .or_else(|| workspace.worktrees(cx).next())
 931        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 932        .and_then(get_path_from_wt)
 933}
 934
 935fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
 936    wt.root_entry()
 937        .filter(|re| re.is_dir())
 938        .map(|_| wt.abs_path().to_path_buf())
 939}
 940
 941#[cfg(test)]
 942mod tests {
 943    use super::*;
 944    use gpui::TestAppContext;
 945    use project::{Entry, Project, ProjectPath, Worktree};
 946    use std::path::Path;
 947    use workspace::AppState;
 948
 949    // Working directory calculation tests
 950
 951    // No Worktrees in project -> home_dir()
 952    #[gpui::test]
 953    async fn no_worktree(cx: &mut TestAppContext) {
 954        let (project, workspace) = init_test(cx).await;
 955        cx.read(|cx| {
 956            let workspace = workspace.read(cx);
 957            let active_entry = project.read(cx).active_entry();
 958
 959            //Make sure environment is as expected
 960            assert!(active_entry.is_none());
 961            assert!(workspace.worktrees(cx).next().is_none());
 962
 963            let res = current_project_directory(workspace, cx);
 964            assert_eq!(res, None);
 965            let res = first_project_directory(workspace, cx);
 966            assert_eq!(res, None);
 967        });
 968    }
 969
 970    // No active entry, but a worktree, worktree is a file -> home_dir()
 971    #[gpui::test]
 972    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
 973        let (project, workspace) = init_test(cx).await;
 974
 975        create_file_wt(project.clone(), "/root.txt", cx).await;
 976        cx.read(|cx| {
 977            let workspace = workspace.read(cx);
 978            let active_entry = project.read(cx).active_entry();
 979
 980            //Make sure environment is as expected
 981            assert!(active_entry.is_none());
 982            assert!(workspace.worktrees(cx).next().is_some());
 983
 984            let res = current_project_directory(workspace, cx);
 985            assert_eq!(res, None);
 986            let res = first_project_directory(workspace, cx);
 987            assert_eq!(res, None);
 988        });
 989    }
 990
 991    // No active entry, but a worktree, worktree is a folder -> worktree_folder
 992    #[gpui::test]
 993    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
 994        let (project, workspace) = init_test(cx).await;
 995
 996        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
 997        cx.update(|cx| {
 998            let workspace = workspace.read(cx);
 999            let active_entry = project.read(cx).active_entry();
1000
1001            assert!(active_entry.is_none());
1002            assert!(workspace.worktrees(cx).next().is_some());
1003
1004            let res = current_project_directory(workspace, cx);
1005            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1006            let res = first_project_directory(workspace, cx);
1007            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1008        });
1009    }
1010
1011    // Active entry with a work tree, worktree is a file -> home_dir()
1012    #[gpui::test]
1013    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1014        let (project, workspace) = init_test(cx).await;
1015
1016        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1017        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1018        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1019
1020        cx.update(|cx| {
1021            let workspace = workspace.read(cx);
1022            let active_entry = project.read(cx).active_entry();
1023
1024            assert!(active_entry.is_some());
1025
1026            let res = current_project_directory(workspace, cx);
1027            assert_eq!(res, None);
1028            let res = first_project_directory(workspace, cx);
1029            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1030        });
1031    }
1032
1033    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1034    #[gpui::test]
1035    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1036        let (project, workspace) = init_test(cx).await;
1037
1038        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1039        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1040        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1041
1042        cx.update(|cx| {
1043            let workspace = workspace.read(cx);
1044            let active_entry = project.read(cx).active_entry();
1045
1046            assert!(active_entry.is_some());
1047
1048            let res = current_project_directory(workspace, cx);
1049            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1050            let res = first_project_directory(workspace, cx);
1051            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1052        });
1053    }
1054
1055    /// Creates a worktree with 1 file: /root.txt
1056    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1057        let params = cx.update(AppState::test);
1058        cx.update(|cx| {
1059            theme::init(theme::LoadThemes::JustBase, cx);
1060            Project::init_settings(cx);
1061            language::init(cx);
1062        });
1063
1064        let project = Project::test(params.fs.clone(), [], cx).await;
1065        let workspace = cx
1066            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1067            .root_view(cx)
1068            .unwrap();
1069
1070        (project, workspace)
1071    }
1072
1073    /// Creates a worktree with 1 folder: /root{suffix}/
1074    async fn create_folder_wt(
1075        project: Model<Project>,
1076        path: impl AsRef<Path>,
1077        cx: &mut TestAppContext,
1078    ) -> (Model<Worktree>, Entry) {
1079        create_wt(project, true, path, cx).await
1080    }
1081
1082    /// Creates a worktree with 1 file: /root{suffix}.txt
1083    async fn create_file_wt(
1084        project: Model<Project>,
1085        path: impl AsRef<Path>,
1086        cx: &mut TestAppContext,
1087    ) -> (Model<Worktree>, Entry) {
1088        create_wt(project, false, path, cx).await
1089    }
1090
1091    async fn create_wt(
1092        project: Model<Project>,
1093        is_dir: bool,
1094        path: impl AsRef<Path>,
1095        cx: &mut TestAppContext,
1096    ) -> (Model<Worktree>, Entry) {
1097        let (wt, _) = project
1098            .update(cx, |project, cx| {
1099                project.find_or_create_local_worktree(path, true, cx)
1100            })
1101            .await
1102            .unwrap();
1103
1104        let entry = cx
1105            .update(|cx| {
1106                wt.update(cx, |wt, cx| {
1107                    wt.as_local()
1108                        .unwrap()
1109                        .create_entry(Path::new(""), is_dir, cx)
1110                })
1111            })
1112            .await
1113            .unwrap()
1114            .unwrap();
1115
1116        (wt, entry)
1117    }
1118
1119    pub fn insert_active_entry_for(
1120        wt: Model<Worktree>,
1121        entry: Entry,
1122        project: Model<Project>,
1123        cx: &mut TestAppContext,
1124    ) {
1125        cx.update(|cx| {
1126            let p = ProjectPath {
1127                worktree_id: wt.read(cx).id(),
1128                path: entry.path,
1129            };
1130            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1131        });
1132    }
1133}