terminal_view.rs

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