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, cx| {
 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    type Event = ItemEvent;
 740
 741    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 742        Some(self.terminal().read(cx).title().into())
 743    }
 744
 745    fn tab_content(&self, _detail: Option<usize>, cx: &WindowContext) -> AnyElement {
 746        let title = self.terminal().read(cx).title();
 747
 748        div()
 749            .child(IconElement::new(Icon::Terminal))
 750            .child(Label::new(title))
 751            .into_any()
 752    }
 753
 754    fn clone_on_split(
 755        &self,
 756        _workspace_id: WorkspaceId,
 757        _cx: &mut ViewContext<Self>,
 758    ) -> Option<View<Self>> {
 759        //From what I can tell, there's no  way to tell the current working
 760        //Directory of the terminal from outside the shell. There might be
 761        //solutions to this, but they are non-trivial and require more IPC
 762
 763        // Some(TerminalContainer::new(
 764        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 765        //     workspace_id,
 766        //     cx,
 767        // ))
 768
 769        // TODO
 770        None
 771    }
 772
 773    fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
 774        self.has_bell()
 775    }
 776
 777    fn has_conflict(&self, _cx: &AppContext) -> bool {
 778        false
 779    }
 780
 781    // todo!()
 782    // fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 783    //     Some(Box::new(handle.clone()))
 784    // }
 785
 786    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 787        ToolbarItemLocation::PrimaryLeft
 788    }
 789
 790    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 791        Some(vec![BreadcrumbText {
 792            text: self.terminal().read(cx).breadcrumb_text.clone(),
 793            highlights: None,
 794        }])
 795    }
 796
 797    fn serialized_item_kind() -> Option<&'static str> {
 798        Some("Terminal")
 799    }
 800
 801    fn deserialize(
 802        project: Model<Project>,
 803        workspace: WeakView<Workspace>,
 804        workspace_id: workspace::WorkspaceId,
 805        item_id: workspace::ItemId,
 806        cx: &mut ViewContext<Pane>,
 807    ) -> Task<anyhow::Result<View<Self>>> {
 808        let window = cx.window_handle();
 809        cx.spawn(|pane, mut cx| async move {
 810            let cwd = None;
 811            // todo!()
 812            // TERMINAL_DB
 813            // .get_working_directory(item_id, workspace_id)
 814            // .log_err()
 815            // .flatten()
 816            // .or_else(|| {
 817            //     cx.read(|cx| {
 818            //         let strategy = TerminalSettings::get_global(cx).working_directory.clone();
 819            //         workspace
 820            //             .upgrade()
 821            //             .map(|workspace| {
 822            //                 get_working_directory(workspace.read(cx), cx, strategy)
 823            //             })
 824            //             .flatten()
 825            //     })
 826            // });
 827
 828            let terminal = project.update(&mut cx, |project, cx| {
 829                project.create_terminal(cwd, window, cx)
 830            })??;
 831            pane.update(&mut cx, |_, cx| {
 832                cx.build_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 833            })
 834        })
 835    }
 836
 837    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 838        // todo!()
 839        // cx.background()
 840        //     .spawn(TERMINAL_DB.update_workspace_id(
 841        //         workspace.database_id(),
 842        //         self.workspace_id,
 843        //         cx.view_id(),
 844        //     ))
 845        //     .detach();
 846        self.workspace_id = workspace.database_id();
 847    }
 848
 849    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 850        f(*event)
 851    }
 852}
 853
 854impl SearchableItem for TerminalView {
 855    type Match = RangeInclusive<Point>;
 856
 857    fn supported_options() -> SearchOptions {
 858        SearchOptions {
 859            case: false,
 860            word: false,
 861            regex: false,
 862            replacement: false,
 863        }
 864    }
 865
 866    /// Clear stored matches
 867    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 868        self.terminal().update(cx, |term, _| term.matches.clear())
 869    }
 870
 871    /// Store matches returned from find_matches somewhere for rendering
 872    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 873        self.terminal().update(cx, |term, _| term.matches = matches)
 874    }
 875
 876    /// Return the selection content to pre-load into this search
 877    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 878        self.terminal()
 879            .read(cx)
 880            .last_content
 881            .selection_text
 882            .clone()
 883            .unwrap_or_default()
 884    }
 885
 886    /// Focus match at given index into the Vec of matches
 887    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 888        self.terminal()
 889            .update(cx, |term, _| term.activate_match(index));
 890        cx.notify();
 891    }
 892
 893    /// Add selections for all matches given.
 894    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 895        self.terminal()
 896            .update(cx, |term, _| term.select_matches(matches));
 897        cx.notify();
 898    }
 899
 900    /// Get all of the matches for this query, should be done on the background
 901    fn find_matches(
 902        &mut self,
 903        query: Arc<project::search::SearchQuery>,
 904        cx: &mut ViewContext<Self>,
 905    ) -> Task<Vec<Self::Match>> {
 906        if let Some(searcher) = regex_search_for_query(&query) {
 907            self.terminal()
 908                .update(cx, |term, cx| term.find_matches(searcher, cx))
 909        } else {
 910            Task::ready(vec![])
 911        }
 912    }
 913
 914    /// Reports back to the search toolbar what the active match should be (the selection)
 915    fn active_match_index(
 916        &mut self,
 917        matches: Vec<Self::Match>,
 918        cx: &mut ViewContext<Self>,
 919    ) -> Option<usize> {
 920        // Selection head might have a value if there's a selection that isn't
 921        // associated with a match. Therefore, if there are no matches, we should
 922        // report None, no matter the state of the terminal
 923        let res = if matches.len() > 0 {
 924            if let Some(selection_head) = self.terminal().read(cx).selection_head {
 925                // If selection head is contained in a match. Return that match
 926                if let Some(ix) = matches
 927                    .iter()
 928                    .enumerate()
 929                    .find(|(_, search_match)| {
 930                        search_match.contains(&selection_head)
 931                            || search_match.start() > &selection_head
 932                    })
 933                    .map(|(ix, _)| ix)
 934                {
 935                    Some(ix)
 936                } else {
 937                    // If no selection after selection head, return the last match
 938                    Some(matches.len().saturating_sub(1))
 939                }
 940            } else {
 941                // Matches found but no active selection, return the first last one (closest to cursor)
 942                Some(matches.len().saturating_sub(1))
 943            }
 944        } else {
 945            None
 946        };
 947
 948        res
 949    }
 950    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
 951        // Replacement is not supported in terminal view, so this is a no-op.
 952    }
 953}
 954
 955///Get's the working directory for the given workspace, respecting the user's settings.
 956pub fn get_working_directory(
 957    workspace: &Workspace,
 958    cx: &AppContext,
 959    strategy: WorkingDirectory,
 960) -> Option<PathBuf> {
 961    let res = match strategy {
 962        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
 963            .or_else(|| first_project_directory(workspace, cx)),
 964        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
 965        WorkingDirectory::AlwaysHome => None,
 966        WorkingDirectory::Always { directory } => {
 967            shellexpand::full(&directory) //TODO handle this better
 968                .ok()
 969                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
 970                .filter(|dir| dir.is_dir())
 971        }
 972    };
 973    res.or_else(home_dir)
 974}
 975
 976///Get's the first project's home directory, or the home directory
 977fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 978    workspace
 979        .worktrees(cx)
 980        .next()
 981        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 982        .and_then(get_path_from_wt)
 983}
 984
 985///Gets the intuitively correct working directory from the given workspace
 986///If there is an active entry for this project, returns that entry's worktree root.
 987///If there's no active entry but there is a worktree, returns that worktrees root.
 988///If either of these roots are files, or if there are any other query failures,
 989///  returns the user's home directory
 990fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
 991    let project = workspace.project().read(cx);
 992
 993    project
 994        .active_entry()
 995        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
 996        .or_else(|| workspace.worktrees(cx).next())
 997        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
 998        .and_then(get_path_from_wt)
 999}
1000
1001fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
1002    wt.root_entry()
1003        .filter(|re| re.is_dir())
1004        .map(|_| wt.abs_path().to_path_buf())
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009    use super::*;
1010    use gpui::TestAppContext;
1011    use project::{Entry, Project, ProjectPath, Worktree};
1012    use std::path::Path;
1013    use workspace::AppState;
1014
1015    // Working directory calculation tests
1016
1017    // No Worktrees in project -> home_dir()
1018    #[gpui::test]
1019    async fn no_worktree(cx: &mut TestAppContext) {
1020        let (project, workspace) = init_test(cx).await;
1021        cx.read(|cx| {
1022            let workspace = workspace.read(cx);
1023            let active_entry = project.read(cx).active_entry();
1024
1025            //Make sure environment is as expected
1026            assert!(active_entry.is_none());
1027            assert!(workspace.worktrees(cx).next().is_none());
1028
1029            let res = current_project_directory(workspace, cx);
1030            assert_eq!(res, None);
1031            let res = first_project_directory(workspace, cx);
1032            assert_eq!(res, None);
1033        });
1034    }
1035
1036    // No active entry, but a worktree, worktree is a file -> home_dir()
1037    #[gpui::test]
1038    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1039        let (project, workspace) = init_test(cx).await;
1040
1041        create_file_wt(project.clone(), "/root.txt", cx).await;
1042        cx.read(|cx| {
1043            let workspace = workspace.read(cx);
1044            let active_entry = project.read(cx).active_entry();
1045
1046            //Make sure environment is as expected
1047            assert!(active_entry.is_none());
1048            assert!(workspace.worktrees(cx).next().is_some());
1049
1050            let res = current_project_directory(workspace, cx);
1051            assert_eq!(res, None);
1052            let res = first_project_directory(workspace, cx);
1053            assert_eq!(res, None);
1054        });
1055    }
1056
1057    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1058    #[gpui::test]
1059    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1060        let (project, workspace) = init_test(cx).await;
1061
1062        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1063        cx.update(|cx| {
1064            let workspace = workspace.read(cx);
1065            let active_entry = project.read(cx).active_entry();
1066
1067            assert!(active_entry.is_none());
1068            assert!(workspace.worktrees(cx).next().is_some());
1069
1070            let res = current_project_directory(workspace, cx);
1071            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1072            let res = first_project_directory(workspace, cx);
1073            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1074        });
1075    }
1076
1077    // Active entry with a work tree, worktree is a file -> home_dir()
1078    #[gpui::test]
1079    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1080        let (project, workspace) = init_test(cx).await;
1081
1082        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1083        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1084        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1085
1086        cx.update(|cx| {
1087            let workspace = workspace.read(cx);
1088            let active_entry = project.read(cx).active_entry();
1089
1090            assert!(active_entry.is_some());
1091
1092            let res = current_project_directory(workspace, cx);
1093            assert_eq!(res, None);
1094            let res = first_project_directory(workspace, cx);
1095            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1096        });
1097    }
1098
1099    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1100    #[gpui::test]
1101    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1102        let (project, workspace) = init_test(cx).await;
1103
1104        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1105        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1106        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1107
1108        cx.update(|cx| {
1109            let workspace = workspace.read(cx);
1110            let active_entry = project.read(cx).active_entry();
1111
1112            assert!(active_entry.is_some());
1113
1114            let res = current_project_directory(workspace, cx);
1115            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1116            let res = first_project_directory(workspace, cx);
1117            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1118        });
1119    }
1120
1121    /// Creates a worktree with 1 file: /root.txt
1122    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1123        let params = cx.update(AppState::test);
1124        cx.update(|cx| {
1125            theme::init(theme::LoadThemes::JustBase, cx);
1126            Project::init_settings(cx);
1127            language::init(cx);
1128        });
1129
1130        let project = Project::test(params.fs.clone(), [], cx).await;
1131        let workspace = cx
1132            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1133            .root_view(cx)
1134            .unwrap();
1135
1136        (project, workspace)
1137    }
1138
1139    /// Creates a worktree with 1 folder: /root{suffix}/
1140    async fn create_folder_wt(
1141        project: Model<Project>,
1142        path: impl AsRef<Path>,
1143        cx: &mut TestAppContext,
1144    ) -> (Model<Worktree>, Entry) {
1145        create_wt(project, true, path, cx).await
1146    }
1147
1148    /// Creates a worktree with 1 file: /root{suffix}.txt
1149    async fn create_file_wt(
1150        project: Model<Project>,
1151        path: impl AsRef<Path>,
1152        cx: &mut TestAppContext,
1153    ) -> (Model<Worktree>, Entry) {
1154        create_wt(project, false, path, cx).await
1155    }
1156
1157    async fn create_wt(
1158        project: Model<Project>,
1159        is_dir: bool,
1160        path: impl AsRef<Path>,
1161        cx: &mut TestAppContext,
1162    ) -> (Model<Worktree>, Entry) {
1163        let (wt, _) = project
1164            .update(cx, |project, cx| {
1165                project.find_or_create_local_worktree(path, true, cx)
1166            })
1167            .await
1168            .unwrap();
1169
1170        let entry = cx
1171            .update(|cx| {
1172                wt.update(cx, |wt, cx| {
1173                    wt.as_local()
1174                        .unwrap()
1175                        .create_entry(Path::new(""), is_dir, cx)
1176                })
1177            })
1178            .await
1179            .unwrap()
1180            .unwrap();
1181
1182        (wt, entry)
1183    }
1184
1185    pub fn insert_active_entry_for(
1186        wt: Model<Worktree>,
1187        entry: Entry,
1188        project: Model<Project>,
1189        cx: &mut TestAppContext,
1190    ) {
1191        cx.update(|cx| {
1192            let p = ProjectPath {
1193                worktree_id: wt.read(cx).id(),
1194                path: entry.path,
1195            };
1196            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1197        });
1198    }
1199}