terminal_view.rs

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