terminal_view.rs

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