terminal_view.rs

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