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