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 util::{paths::PathLikeWithPosition, ResultExt};
  29use workspace::{
  30    item::{BreadcrumbText, Item, ItemEvent},
  31    notifications::NotifyResultExt,
  32    register_deserializable_item,
  33    searchable::{SearchEvent, SearchOptions, SearchableItem},
  34    ui::{ContextMenu, Icon, IconElement, Label},
  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
  63actions!(Clear, Copy, Paste, ShowCharacterPalette, SearchTest);
  64
  65pub fn init(cx: &mut AppContext) {
  66    terminal_panel::init(cx);
  67    terminal::init(cx);
  68
  69    register_deserializable_item::<TerminalView>(cx);
  70
  71    cx.observe_new_views(
  72        |workspace: &mut Workspace, cx: &mut ViewContext<Workspace>| {
  73            workspace.register_action(TerminalView::deploy);
  74        },
  75    )
  76    .detach();
  77}
  78
  79///A terminal view, maintains the PTY's file handles and communicates with the terminal
  80pub struct TerminalView {
  81    terminal: Model<Terminal>,
  82    focus_handle: FocusHandle,
  83    has_new_content: bool,
  84    //Currently using iTerm bell, show bell emoji in tab until input is received
  85    has_bell: bool,
  86    context_menu: Option<View<ContextMenu>>,
  87    blink_state: bool,
  88    blinking_on: bool,
  89    blinking_paused: bool,
  90    blink_epoch: usize,
  91    can_navigate_to_selected_word: bool,
  92    workspace_id: WorkspaceId,
  93}
  94
  95impl EventEmitter<Event> for TerminalView {}
  96impl EventEmitter<ItemEvent> for TerminalView {}
  97impl EventEmitter<SearchEvent> for TerminalView {}
  98
  99impl FocusableView for TerminalView {
 100    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
 101        self.focus_handle.clone()
 102    }
 103}
 104
 105impl TerminalView {
 106    ///Create a new Terminal in the current working directory or the user's home directory
 107    pub fn deploy(
 108        workspace: &mut Workspace,
 109        _: &NewCenterTerminal,
 110        cx: &mut ViewContext<Workspace>,
 111    ) {
 112        let strategy = TerminalSettings::get_global(cx);
 113        let working_directory =
 114            get_working_directory(workspace, cx, strategy.working_directory.clone());
 115
 116        let window = cx.window_handle();
 117        let terminal = workspace
 118            .project()
 119            .update(cx, |project, cx| {
 120                project.create_terminal(working_directory, window, cx)
 121            })
 122            .notify_err(workspace, cx);
 123
 124        if let Some(terminal) = terminal {
 125            let view = cx.build_view(|cx| {
 126                TerminalView::new(
 127                    terminal,
 128                    workspace.weak_handle(),
 129                    workspace.database_id(),
 130                    cx,
 131                )
 132            });
 133            workspace.add_item(Box::new(view), cx)
 134        }
 135    }
 136
 137    pub fn new(
 138        terminal: Model<Terminal>,
 139        workspace: WeakView<Workspace>,
 140        workspace_id: WorkspaceId,
 141        cx: &mut ViewContext<Self>,
 142    ) -> Self {
 143        let view_id = cx.entity_id();
 144        cx.observe(&terminal, |_, _, cx| cx.notify()).detach();
 145        cx.subscribe(&terminal, move |this, _, event, cx| match event {
 146            Event::Wakeup => {
 147                if !this.focus_handle.is_focused(cx) {
 148                    this.has_new_content = true;
 149                }
 150                cx.notify();
 151                cx.emit(Event::Wakeup);
 152                cx.emit(ItemEvent::UpdateTab);
 153                cx.emit(SearchEvent::MatchesInvalidated);
 154            }
 155
 156            Event::Bell => {
 157                this.has_bell = true;
 158                cx.emit(Event::Wakeup);
 159            }
 160
 161            Event::BlinkChanged => this.blinking_on = !this.blinking_on,
 162
 163            Event::TitleChanged => {
 164                cx.emit(ItemEvent::UpdateTab);
 165                if let Some(foreground_info) = &this.terminal().read(cx).foreground_process_info {
 166                    let cwd = foreground_info.cwd.clone();
 167
 168                    let item_id = cx.entity_id();
 169                    let workspace_id = this.workspace_id;
 170                    cx.background_executor()
 171                        .spawn(async move {
 172                            TERMINAL_DB
 173                                .save_working_directory(item_id.as_u64(), workspace_id, cwd)
 174                                .await
 175                                .log_err();
 176                        })
 177                        .detach();
 178                }
 179            }
 180
 181            Event::NewNavigationTarget(maybe_navigation_target) => {
 182                this.can_navigate_to_selected_word = match maybe_navigation_target {
 183                    Some(MaybeNavigationTarget::Url(_)) => true,
 184                    Some(MaybeNavigationTarget::PathLike(maybe_path)) => {
 185                        !possible_open_targets(&workspace, maybe_path, cx).is_empty()
 186                    }
 187                    None => false,
 188                }
 189            }
 190
 191            Event::Open(maybe_navigation_target) => match maybe_navigation_target {
 192                MaybeNavigationTarget::Url(url) => cx.open_url(url),
 193
 194                MaybeNavigationTarget::PathLike(maybe_path) => {
 195                    if !this.can_navigate_to_selected_word {
 196                        return;
 197                    }
 198                    let potential_abs_paths = possible_open_targets(&workspace, maybe_path, cx);
 199                    if let Some(path) = potential_abs_paths.into_iter().next() {
 200                        let is_dir = path.path_like.is_dir();
 201                        let task_workspace = workspace.clone();
 202                        cx.spawn(|_, mut cx| async move {
 203                            let opened_items = task_workspace
 204                                .update(&mut cx, |workspace, cx| {
 205                                    workspace.open_paths(vec![path.path_like], is_dir, cx)
 206                                })
 207                                .context("workspace update")?
 208                                .await;
 209                            anyhow::ensure!(
 210                                opened_items.len() == 1,
 211                                "For a single path open, expected single opened item"
 212                            );
 213                            let opened_item = opened_items
 214                                .into_iter()
 215                                .next()
 216                                .unwrap()
 217                                .transpose()
 218                                .context("path open")?;
 219                            if is_dir {
 220                                task_workspace.update(&mut cx, |workspace, cx| {
 221                                    workspace.project().update(cx, |_, cx| {
 222                                        cx.emit(project::Event::ActivateProjectPanel);
 223                                    })
 224                                })?;
 225                            } else {
 226                                if let Some(row) = path.row {
 227                                    let col = path.column.unwrap_or(0);
 228                                    if let Some(active_editor) =
 229                                        opened_item.and_then(|item| item.downcast::<Editor>())
 230                                    {
 231                                        active_editor
 232                                            .downgrade()
 233                                            .update(&mut cx, |editor, cx| {
 234                                                let snapshot = editor.snapshot(cx).display_snapshot;
 235                                                let point = snapshot.buffer_snapshot.clip_point(
 236                                                    language::Point::new(
 237                                                        row.saturating_sub(1),
 238                                                        col.saturating_sub(1),
 239                                                    ),
 240                                                    Bias::Left,
 241                                                );
 242                                                editor.change_selections(
 243                                                    Some(Autoscroll::center()),
 244                                                    cx,
 245                                                    |s| s.select_ranges([point..point]),
 246                                                );
 247                                            })
 248                                            .log_err();
 249                                    }
 250                                }
 251                            }
 252                            anyhow::Ok(())
 253                        })
 254                        .detach_and_log_err(cx);
 255                    }
 256                }
 257            },
 258            Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
 259            Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
 260            Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
 261        })
 262        .detach();
 263
 264        Self {
 265            terminal,
 266            has_new_content: true,
 267            has_bell: false,
 268            focus_handle: cx.focus_handle(),
 269            context_menu: None,
 270            blink_state: true,
 271            blinking_on: false,
 272            blinking_paused: false,
 273            blink_epoch: 0,
 274            can_navigate_to_selected_word: false,
 275            workspace_id,
 276        }
 277    }
 278
 279    pub fn model(&self) -> &Model<Terminal> {
 280        &self.terminal
 281    }
 282
 283    pub fn has_new_content(&self) -> bool {
 284        self.has_new_content
 285    }
 286
 287    pub fn has_bell(&self) -> bool {
 288        self.has_bell
 289    }
 290
 291    pub fn clear_bel(&mut self, cx: &mut ViewContext<TerminalView>) {
 292        self.has_bell = false;
 293        cx.emit(Event::Wakeup);
 294    }
 295
 296    pub fn deploy_context_menu(
 297        &mut self,
 298        position: gpui::Point<Pixels>,
 299        cx: &mut ViewContext<Self>,
 300    ) {
 301        self.context_menu = Some(ContextMenu::build(cx, |menu, _| {
 302            menu.action("Clear", Box::new(Clear))
 303                .action("Close", Box::new(CloseActiveItem { save_intent: None }))
 304        }));
 305        dbg!(&position);
 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            .relative()
 542            .child(
 543                div()
 544                    .z_index(0)
 545                    .absolute()
 546                    .on_key_down(cx.listener(Self::key_down))
 547                    .on_action(cx.listener(TerminalView::send_text))
 548                    .on_action(cx.listener(TerminalView::send_keystroke))
 549                    .on_action(cx.listener(TerminalView::copy))
 550                    .on_action(cx.listener(TerminalView::paste))
 551                    .on_action(cx.listener(TerminalView::clear))
 552                    .on_action(cx.listener(TerminalView::show_character_palette))
 553                    .on_action(cx.listener(TerminalView::select_all))
 554                    // todo!()
 555                    .child(
 556                        "TERMINAL HERE", //     TerminalElement::new(
 557                                         //     terminal_handle,
 558                                         //     focused,
 559                                         //     self.should_show_cursor(focused, cx),
 560                                         //     self.can_navigate_to_selected_word,
 561                                         // )
 562                    )
 563                    .on_mouse_down(
 564                        MouseButton::Right,
 565                        cx.listener(|this, event: &MouseDownEvent, cx| {
 566                            this.deploy_context_menu(event.position, cx);
 567                            cx.notify();
 568                        }),
 569                    ),
 570            )
 571            .children(
 572                self.context_menu
 573                    .clone()
 574                    .map(|context_menu| div().z_index(1).absolute().child(context_menu)),
 575            )
 576            .track_focus(&self.focus_handle)
 577            .on_focus_in(cx.listener(Self::focus_in))
 578            .on_focus_out(cx.listener(Self::focus_out))
 579    }
 580}
 581
 582// impl View for TerminalView {
 583//todo!()
 584// fn modifiers_changed(
 585//     &mut self,
 586//     event: &ModifiersChangedEvent,
 587//     cx: &mut ViewContext<Self>,
 588// ) -> bool {
 589//     let handled = self
 590//         .terminal()
 591//         .update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
 592//     if handled {
 593//         cx.notify();
 594//     }
 595//     handled
 596// }
 597// }
 598
 599// todo!()
 600// fn update_keymap_context(&self, keymap: &mut KeymapContext, cx: &gpui::AppContext) {
 601//     Self::reset_to_default_keymap_context(keymap);
 602
 603//     let mode = self.terminal.read(cx).last_content.mode;
 604//     keymap.add_key(
 605//         "screen",
 606//         if mode.contains(TermMode::ALT_SCREEN) {
 607//             "alt"
 608//         } else {
 609//             "normal"
 610//         },
 611//     );
 612
 613//     if mode.contains(TermMode::APP_CURSOR) {
 614//         keymap.add_identifier("DECCKM");
 615//     }
 616//     if mode.contains(TermMode::APP_KEYPAD) {
 617//         keymap.add_identifier("DECPAM");
 618//     } else {
 619//         keymap.add_identifier("DECPNM");
 620//     }
 621//     if mode.contains(TermMode::SHOW_CURSOR) {
 622//         keymap.add_identifier("DECTCEM");
 623//     }
 624//     if mode.contains(TermMode::LINE_WRAP) {
 625//         keymap.add_identifier("DECAWM");
 626//     }
 627//     if mode.contains(TermMode::ORIGIN) {
 628//         keymap.add_identifier("DECOM");
 629//     }
 630//     if mode.contains(TermMode::INSERT) {
 631//         keymap.add_identifier("IRM");
 632//     }
 633//     //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 634//     if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 635//         keymap.add_identifier("LNM");
 636//     }
 637//     if mode.contains(TermMode::FOCUS_IN_OUT) {
 638//         keymap.add_identifier("report_focus");
 639//     }
 640//     if mode.contains(TermMode::ALTERNATE_SCROLL) {
 641//         keymap.add_identifier("alternate_scroll");
 642//     }
 643//     if mode.contains(TermMode::BRACKETED_PASTE) {
 644//         keymap.add_identifier("bracketed_paste");
 645//     }
 646//     if mode.intersects(TermMode::MOUSE_MODE) {
 647//         keymap.add_identifier("any_mouse_reporting");
 648//     }
 649//     {
 650//         let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 651//             "click"
 652//         } else if mode.contains(TermMode::MOUSE_DRAG) {
 653//             "drag"
 654//         } else if mode.contains(TermMode::MOUSE_MOTION) {
 655//             "motion"
 656//         } else {
 657//             "off"
 658//         };
 659//         keymap.add_key("mouse_reporting", mouse_reporting);
 660//     }
 661//     {
 662//         let format = if mode.contains(TermMode::SGR_MOUSE) {
 663//             "sgr"
 664//         } else if mode.contains(TermMode::UTF8_MOUSE) {
 665//             "utf8"
 666//         } else {
 667//             "normal"
 668//         };
 669//         keymap.add_key("mouse_format", format);
 670//     }
 671// }
 672
 673impl InputHandler for TerminalView {
 674    fn text_for_range(
 675        &mut self,
 676        range: std::ops::Range<usize>,
 677        cx: &mut ViewContext<Self>,
 678    ) -> Option<String> {
 679        todo!()
 680    }
 681
 682    fn selected_text_range(
 683        &mut self,
 684        cx: &mut ViewContext<Self>,
 685    ) -> Option<std::ops::Range<usize>> {
 686        if self
 687            .terminal
 688            .read(cx)
 689            .last_content
 690            .mode
 691            .contains(TermMode::ALT_SCREEN)
 692        {
 693            None
 694        } else {
 695            Some(0..0)
 696        }
 697    }
 698
 699    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<std::ops::Range<usize>> {
 700        todo!()
 701    }
 702
 703    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
 704        todo!()
 705    }
 706
 707    fn replace_text_in_range(
 708        &mut self,
 709        _: Option<std::ops::Range<usize>>,
 710        text: &str,
 711        cx: &mut ViewContext<Self>,
 712    ) {
 713        self.terminal.update(cx, |terminal, _| {
 714            terminal.input(text.into());
 715        });
 716    }
 717
 718    fn replace_and_mark_text_in_range(
 719        &mut self,
 720        range: Option<std::ops::Range<usize>>,
 721        new_text: &str,
 722        new_selected_range: Option<std::ops::Range<usize>>,
 723        cx: &mut ViewContext<Self>,
 724    ) {
 725        todo!()
 726    }
 727
 728    fn bounds_for_range(
 729        &mut self,
 730        range_utf16: std::ops::Range<usize>,
 731        element_bounds: gpui::Bounds<Pixels>,
 732        cx: &mut ViewContext<Self>,
 733    ) -> Option<gpui::Bounds<Pixels>> {
 734        todo!()
 735    }
 736}
 737
 738impl Item for TerminalView {
 739    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 740        Some(self.terminal().read(cx).title().into())
 741    }
 742
 743    fn tab_content(&self, _detail: Option<usize>, cx: &WindowContext) -> AnyElement {
 744        let title = self.terminal().read(cx).title();
 745
 746        div()
 747            .child(IconElement::new(Icon::Terminal))
 748            .child(Label::new(title))
 749            .into_any()
 750    }
 751
 752    fn clone_on_split(
 753        &self,
 754        _workspace_id: WorkspaceId,
 755        _cx: &mut ViewContext<Self>,
 756    ) -> Option<View<Self>> {
 757        //From what I can tell, there's no  way to tell the current working
 758        //Directory of the terminal from outside the shell. There might be
 759        //solutions to this, but they are non-trivial and require more IPC
 760
 761        // Some(TerminalContainer::new(
 762        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 763        //     workspace_id,
 764        //     cx,
 765        // ))
 766
 767        // TODO
 768        None
 769    }
 770
 771    fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
 772        self.has_bell()
 773    }
 774
 775    fn has_conflict(&self, _cx: &AppContext) -> bool {
 776        false
 777    }
 778
 779    // todo!()
 780    // fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 781    //     Some(Box::new(handle.clone()))
 782    // }
 783
 784    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 785        ToolbarItemLocation::PrimaryLeft
 786    }
 787
 788    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 789        Some(vec![BreadcrumbText {
 790            text: self.terminal().read(cx).breadcrumb_text.clone(),
 791            highlights: None,
 792        }])
 793    }
 794
 795    fn serialized_item_kind() -> Option<&'static str> {
 796        Some("Terminal")
 797    }
 798
 799    fn deserialize(
 800        project: Model<Project>,
 801        workspace: WeakView<Workspace>,
 802        workspace_id: workspace::WorkspaceId,
 803        item_id: workspace::ItemId,
 804        cx: &mut ViewContext<Pane>,
 805    ) -> Task<anyhow::Result<View<Self>>> {
 806        let window = cx.window_handle();
 807        cx.spawn(|pane, mut cx| async move {
 808            let cwd = None;
 809            // todo!()
 810            // TERMINAL_DB
 811            // .get_working_directory(item_id, workspace_id)
 812            // .log_err()
 813            // .flatten()
 814            // .or_else(|| {
 815            //     cx.read(|cx| {
 816            //         let strategy = TerminalSettings::get_global(cx).working_directory.clone();
 817            //         workspace
 818            //             .upgrade()
 819            //             .map(|workspace| {
 820            //                 get_working_directory(workspace.read(cx), cx, strategy)
 821            //             })
 822            //             .flatten()
 823            //     })
 824            // });
 825
 826            let terminal = project.update(&mut cx, |project, cx| {
 827                project.create_terminal(cwd, window, cx)
 828            })??;
 829            pane.update(&mut cx, |_, cx| {
 830                cx.build_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 831            })
 832        })
 833    }
 834
 835    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 836        // todo!()
 837        // cx.background()
 838        //     .spawn(TERMINAL_DB.update_workspace_id(
 839        //         workspace.database_id(),
 840        //         self.workspace_id,
 841        //         cx.view_id(),
 842        //     ))
 843        //     .detach();
 844        self.workspace_id = workspace.database_id();
 845    }
 846}
 847
 848impl SearchableItem for TerminalView {
 849    type Match = RangeInclusive<Point>;
 850
 851    fn supported_options() -> SearchOptions {
 852        SearchOptions {
 853            case: false,
 854            word: false,
 855            regex: false,
 856            replacement: false,
 857        }
 858    }
 859
 860    /// Clear stored matches
 861    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 862        self.terminal().update(cx, |term, _| term.matches.clear())
 863    }
 864
 865    /// Store matches returned from find_matches somewhere for rendering
 866    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 867        self.terminal().update(cx, |term, _| term.matches = matches)
 868    }
 869
 870    /// Return the selection content to pre-load into this search
 871    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 872        self.terminal()
 873            .read(cx)
 874            .last_content
 875            .selection_text
 876            .clone()
 877            .unwrap_or_default()
 878    }
 879
 880    /// Focus match at given index into the Vec of matches
 881    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 882        self.terminal()
 883            .update(cx, |term, _| term.activate_match(index));
 884        cx.notify();
 885    }
 886
 887    /// Add selections for all matches given.
 888    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 889        self.terminal()
 890            .update(cx, |term, _| term.select_matches(matches));
 891        cx.notify();
 892    }
 893
 894    /// Get all of the matches for this query, should be done on the background
 895    fn find_matches(
 896        &mut self,
 897        query: Arc<project::search::SearchQuery>,
 898        cx: &mut ViewContext<Self>,
 899    ) -> Task<Vec<Self::Match>> {
 900        if let Some(searcher) = regex_search_for_query(&query) {
 901            self.terminal()
 902                .update(cx, |term, cx| term.find_matches(searcher, cx))
 903        } else {
 904            Task::ready(vec![])
 905        }
 906    }
 907
 908    /// Reports back to the search toolbar what the active match should be (the selection)
 909    fn active_match_index(
 910        &mut self,
 911        matches: Vec<Self::Match>,
 912        cx: &mut ViewContext<Self>,
 913    ) -> Option<usize> {
 914        // Selection head might have a value if there's a selection that isn't
 915        // associated with a match. Therefore, if there are no matches, we should
 916        // report None, no matter the state of the terminal
 917        let res = if matches.len() > 0 {
 918            if let Some(selection_head) = self.terminal().read(cx).selection_head {
 919                // If selection head is contained in a match. Return that match
 920                if let Some(ix) = matches
 921                    .iter()
 922                    .enumerate()
 923                    .find(|(_, search_match)| {
 924                        search_match.contains(&selection_head)
 925                            || search_match.start() > &selection_head
 926                    })
 927                    .map(|(ix, _)| ix)
 928                {
 929                    Some(ix)
 930                } else {
 931                    // If no selection after selection head, return the last match
 932                    Some(matches.len().saturating_sub(1))
 933                }
 934            } else {
 935                // Matches found but no active selection, return the first last one (closest to cursor)
 936                Some(matches.len().saturating_sub(1))
 937            }
 938        } else {
 939            None
 940        };
 941
 942        res
 943    }
 944    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
 945        // Replacement is not supported in terminal view, so this is a no-op.
 946    }
 947}
 948
 949///Get's the working directory for the given workspace, respecting the user's settings.
 950pub fn get_working_directory(
 951    workspace: &Workspace,
 952    cx: &AppContext,
 953    strategy: WorkingDirectory,
 954) -> Option<PathBuf> {
 955    let res = match strategy {
 956        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
 957            .or_else(|| first_project_directory(workspace, cx)),
 958        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
 959        WorkingDirectory::AlwaysHome => None,
 960        WorkingDirectory::Always { directory } => {
 961            shellexpand::full(&directory) //TODO handle this better
 962                .ok()
 963                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
 964                .filter(|dir| dir.is_dir())
 965        }
 966    };
 967    res.or_else(home_dir)
 968}
 969
 970///Get's the first project's home directory, or the home directory
 971fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 972    workspace
 973        .worktrees(cx)
 974        .next()
 975        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 976        .and_then(get_path_from_wt)
 977}
 978
 979///Gets the intuitively correct working directory from the given workspace
 980///If there is an active entry for this project, returns that entry's worktree root.
 981///If there's no active entry but there is a worktree, returns that worktrees root.
 982///If either of these roots are files, or if there are any other query failures,
 983///  returns the user's home directory
 984fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 985    let project = workspace.project().read(cx);
 986
 987    project
 988        .active_entry()
 989        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
 990        .or_else(|| workspace.worktrees(cx).next())
 991        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 992        .and_then(get_path_from_wt)
 993}
 994
 995fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
 996    wt.root_entry()
 997        .filter(|re| re.is_dir())
 998        .map(|_| wt.abs_path().to_path_buf())
 999}
1000
1001#[cfg(test)]
1002mod tests {
1003    use super::*;
1004    use gpui::TestAppContext;
1005    use project::{Entry, Project, ProjectPath, Worktree};
1006    use std::path::Path;
1007    use workspace::AppState;
1008
1009    // Working directory calculation tests
1010
1011    // No Worktrees in project -> home_dir()
1012    #[gpui::test]
1013    async fn no_worktree(cx: &mut TestAppContext) {
1014        let (project, workspace) = init_test(cx).await;
1015        cx.read(|cx| {
1016            let workspace = workspace.read(cx);
1017            let active_entry = project.read(cx).active_entry();
1018
1019            //Make sure environment is as expected
1020            assert!(active_entry.is_none());
1021            assert!(workspace.worktrees(cx).next().is_none());
1022
1023            let res = current_project_directory(workspace, cx);
1024            assert_eq!(res, None);
1025            let res = first_project_directory(workspace, cx);
1026            assert_eq!(res, None);
1027        });
1028    }
1029
1030    // No active entry, but a worktree, worktree is a file -> home_dir()
1031    #[gpui::test]
1032    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1033        let (project, workspace) = init_test(cx).await;
1034
1035        create_file_wt(project.clone(), "/root.txt", cx).await;
1036        cx.read(|cx| {
1037            let workspace = workspace.read(cx);
1038            let active_entry = project.read(cx).active_entry();
1039
1040            //Make sure environment is as expected
1041            assert!(active_entry.is_none());
1042            assert!(workspace.worktrees(cx).next().is_some());
1043
1044            let res = current_project_directory(workspace, cx);
1045            assert_eq!(res, None);
1046            let res = first_project_directory(workspace, cx);
1047            assert_eq!(res, None);
1048        });
1049    }
1050
1051    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1052    #[gpui::test]
1053    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1054        let (project, workspace) = init_test(cx).await;
1055
1056        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1057        cx.update(|cx| {
1058            let workspace = workspace.read(cx);
1059            let active_entry = project.read(cx).active_entry();
1060
1061            assert!(active_entry.is_none());
1062            assert!(workspace.worktrees(cx).next().is_some());
1063
1064            let res = current_project_directory(workspace, cx);
1065            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1066            let res = first_project_directory(workspace, cx);
1067            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1068        });
1069    }
1070
1071    // Active entry with a work tree, worktree is a file -> home_dir()
1072    #[gpui::test]
1073    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1074        let (project, workspace) = init_test(cx).await;
1075
1076        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1077        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1078        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1079
1080        cx.update(|cx| {
1081            let workspace = workspace.read(cx);
1082            let active_entry = project.read(cx).active_entry();
1083
1084            assert!(active_entry.is_some());
1085
1086            let res = current_project_directory(workspace, cx);
1087            assert_eq!(res, None);
1088            let res = first_project_directory(workspace, cx);
1089            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1090        });
1091    }
1092
1093    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1094    #[gpui::test]
1095    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1096        let (project, workspace) = init_test(cx).await;
1097
1098        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1099        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1100        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1101
1102        cx.update(|cx| {
1103            let workspace = workspace.read(cx);
1104            let active_entry = project.read(cx).active_entry();
1105
1106            assert!(active_entry.is_some());
1107
1108            let res = current_project_directory(workspace, cx);
1109            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1110            let res = first_project_directory(workspace, cx);
1111            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1112        });
1113    }
1114
1115    /// Creates a worktree with 1 file: /root.txt
1116    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1117        let params = cx.update(AppState::test);
1118        cx.update(|cx| {
1119            theme::init(theme::LoadThemes::JustBase, cx);
1120            Project::init_settings(cx);
1121            language::init(cx);
1122        });
1123
1124        let project = Project::test(params.fs.clone(), [], cx).await;
1125        let workspace = cx
1126            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1127            .root_view(cx)
1128            .unwrap();
1129
1130        (project, workspace)
1131    }
1132
1133    /// Creates a worktree with 1 folder: /root{suffix}/
1134    async fn create_folder_wt(
1135        project: Model<Project>,
1136        path: impl AsRef<Path>,
1137        cx: &mut TestAppContext,
1138    ) -> (Model<Worktree>, Entry) {
1139        create_wt(project, true, path, cx).await
1140    }
1141
1142    /// Creates a worktree with 1 file: /root{suffix}.txt
1143    async fn create_file_wt(
1144        project: Model<Project>,
1145        path: impl AsRef<Path>,
1146        cx: &mut TestAppContext,
1147    ) -> (Model<Worktree>, Entry) {
1148        create_wt(project, false, path, cx).await
1149    }
1150
1151    async fn create_wt(
1152        project: Model<Project>,
1153        is_dir: bool,
1154        path: impl AsRef<Path>,
1155        cx: &mut TestAppContext,
1156    ) -> (Model<Worktree>, Entry) {
1157        let (wt, _) = project
1158            .update(cx, |project, cx| {
1159                project.find_or_create_local_worktree(path, true, cx)
1160            })
1161            .await
1162            .unwrap();
1163
1164        let entry = cx
1165            .update(|cx| {
1166                wt.update(cx, |wt, cx| {
1167                    wt.as_local()
1168                        .unwrap()
1169                        .create_entry(Path::new(""), is_dir, cx)
1170                })
1171            })
1172            .await
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}