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 .ok();
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(
651 &mut self,
652 event: &Self::Event,
653 _: &mut ViewContext<Self>,
654 ) -> Option<SearchEvent> {
655 match event {
656 Event::Wakeup => Some(SearchEvent::MatchesInvalidated),
657 Event::SelectionsChanged => Some(SearchEvent::ActiveMatchChanged),
658 _ => None,
659 }
660 }
661
662 /// Clear stored matches
663 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
664 self.terminal().update(cx, |term, _| term.matches.clear())
665 }
666
667 /// Store matches returned from find_matches somewhere for rendering
668 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
669 self.terminal().update(cx, |term, _| term.matches = matches)
670 }
671
672 /// Return the selection content to pre-load into this search
673 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
674 self.terminal()
675 .read(cx)
676 .last_content
677 .selection_text
678 .clone()
679 .unwrap_or_default()
680 }
681
682 /// Focus match at given index into the Vec of matches
683 fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
684 self.terminal()
685 .update(cx, |term, _| term.activate_match(index));
686 cx.notify();
687 }
688
689 /// Add selections for all matches given.
690 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
691 self.terminal()
692 .update(cx, |term, _| term.select_matches(matches));
693 cx.notify();
694 }
695
696 /// Get all of the matches for this query, should be done on the background
697 fn find_matches(
698 &mut self,
699 query: project::search::SearchQuery,
700 cx: &mut ViewContext<Self>,
701 ) -> Task<Vec<Self::Match>> {
702 if let Some(searcher) = regex_search_for_query(query) {
703 self.terminal()
704 .update(cx, |term, cx| term.find_matches(searcher, cx))
705 } else {
706 Task::ready(vec![])
707 }
708 }
709
710 /// Reports back to the search toolbar what the active match should be (the selection)
711 fn active_match_index(
712 &mut self,
713 matches: Vec<Self::Match>,
714 cx: &mut ViewContext<Self>,
715 ) -> Option<usize> {
716 // Selection head might have a value if there's a selection that isn't
717 // associated with a match. Therefore, if there are no matches, we should
718 // report None, no matter the state of the terminal
719 let res = if matches.len() > 0 {
720 if let Some(selection_head) = self.terminal().read(cx).selection_head {
721 // If selection head is contained in a match. Return that match
722 if let Some(ix) = matches
723 .iter()
724 .enumerate()
725 .find(|(_, search_match)| {
726 search_match.contains(&selection_head)
727 || search_match.start() > &selection_head
728 })
729 .map(|(ix, _)| ix)
730 {
731 Some(ix)
732 } else {
733 // If no selection after selection head, return the last match
734 Some(matches.len().saturating_sub(1))
735 }
736 } else {
737 // Matches found but no active selection, return the first last one (closest to cursor)
738 Some(matches.len().saturating_sub(1))
739 }
740 } else {
741 None
742 };
743
744 res
745 }
746}
747
748///Get's the working directory for the given workspace, respecting the user's settings.
749pub fn get_working_directory(
750 workspace: &Workspace,
751 cx: &AppContext,
752 strategy: WorkingDirectory,
753) -> Option<PathBuf> {
754 let res = match strategy {
755 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
756 .or_else(|| first_project_directory(workspace, cx)),
757 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
758 WorkingDirectory::AlwaysHome => None,
759 WorkingDirectory::Always { directory } => {
760 shellexpand::full(&directory) //TODO handle this better
761 .ok()
762 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
763 .filter(|dir| dir.is_dir())
764 }
765 };
766 res.or_else(home_dir)
767}
768
769///Get's the first project's home directory, or the home directory
770fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
771 workspace
772 .worktrees(cx)
773 .next()
774 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
775 .and_then(get_path_from_wt)
776}
777
778///Gets the intuitively correct working directory from the given workspace
779///If there is an active entry for this project, returns that entry's worktree root.
780///If there's no active entry but there is a worktree, returns that worktrees root.
781///If either of these roots are files, or if there are any other query failures,
782/// returns the user's home directory
783fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
784 let project = workspace.project().read(cx);
785
786 project
787 .active_entry()
788 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
789 .or_else(|| workspace.worktrees(cx).next())
790 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
791 .and_then(get_path_from_wt)
792}
793
794fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
795 wt.root_entry()
796 .filter(|re| re.is_dir())
797 .map(|_| wt.abs_path().to_path_buf())
798}
799
800#[cfg(test)]
801mod tests {
802 use super::*;
803 use gpui::TestAppContext;
804 use project::{Entry, Project, ProjectPath, Worktree};
805 use std::path::Path;
806 use workspace::AppState;
807
808 // Working directory calculation tests
809
810 // No Worktrees in project -> home_dir()
811 #[gpui::test]
812 async fn no_worktree(cx: &mut TestAppContext) {
813 let (project, workspace) = init_test(cx).await;
814 cx.read(|cx| {
815 let workspace = workspace.read(cx);
816 let active_entry = project.read(cx).active_entry();
817
818 //Make sure environment is as expected
819 assert!(active_entry.is_none());
820 assert!(workspace.worktrees(cx).next().is_none());
821
822 let res = current_project_directory(workspace, cx);
823 assert_eq!(res, None);
824 let res = first_project_directory(workspace, cx);
825 assert_eq!(res, None);
826 });
827 }
828
829 // No active entry, but a worktree, worktree is a file -> home_dir()
830 #[gpui::test]
831 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
832 let (project, workspace) = init_test(cx).await;
833
834 create_file_wt(project.clone(), "/root.txt", cx).await;
835 cx.read(|cx| {
836 let workspace = workspace.read(cx);
837 let active_entry = project.read(cx).active_entry();
838
839 //Make sure environment is as expected
840 assert!(active_entry.is_none());
841 assert!(workspace.worktrees(cx).next().is_some());
842
843 let res = current_project_directory(workspace, cx);
844 assert_eq!(res, None);
845 let res = first_project_directory(workspace, cx);
846 assert_eq!(res, None);
847 });
848 }
849
850 // No active entry, but a worktree, worktree is a folder -> worktree_folder
851 #[gpui::test]
852 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
853 let (project, workspace) = init_test(cx).await;
854
855 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
856 cx.update(|cx| {
857 let workspace = workspace.read(cx);
858 let active_entry = project.read(cx).active_entry();
859
860 assert!(active_entry.is_none());
861 assert!(workspace.worktrees(cx).next().is_some());
862
863 let res = current_project_directory(workspace, cx);
864 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
865 let res = first_project_directory(workspace, cx);
866 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
867 });
868 }
869
870 // Active entry with a work tree, worktree is a file -> home_dir()
871 #[gpui::test]
872 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
873 let (project, workspace) = init_test(cx).await;
874
875 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
876 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
877 insert_active_entry_for(wt2, entry2, project.clone(), cx);
878
879 cx.update(|cx| {
880 let workspace = workspace.read(cx);
881 let active_entry = project.read(cx).active_entry();
882
883 assert!(active_entry.is_some());
884
885 let res = current_project_directory(workspace, cx);
886 assert_eq!(res, None);
887 let res = first_project_directory(workspace, cx);
888 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
889 });
890 }
891
892 // Active entry, with a worktree, worktree is a folder -> worktree_folder
893 #[gpui::test]
894 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
895 let (project, workspace) = init_test(cx).await;
896
897 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
898 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
899 insert_active_entry_for(wt2, entry2, project.clone(), cx);
900
901 cx.update(|cx| {
902 let workspace = workspace.read(cx);
903 let active_entry = project.read(cx).active_entry();
904
905 assert!(active_entry.is_some());
906
907 let res = current_project_directory(workspace, cx);
908 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
909 let res = first_project_directory(workspace, cx);
910 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
911 });
912 }
913
914 /// Creates a worktree with 1 file: /root.txt
915 pub async fn init_test(
916 cx: &mut TestAppContext,
917 ) -> (ModelHandle<Project>, ViewHandle<Workspace>) {
918 let params = cx.update(AppState::test);
919 cx.update(|cx| {
920 theme::init((), cx);
921 Project::init_settings(cx);
922 language::init(cx);
923 });
924
925 let project = Project::test(params.fs.clone(), [], cx).await;
926 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
927
928 (project, workspace)
929 }
930
931 /// Creates a worktree with 1 folder: /root{suffix}/
932 async fn create_folder_wt(
933 project: ModelHandle<Project>,
934 path: impl AsRef<Path>,
935 cx: &mut TestAppContext,
936 ) -> (ModelHandle<Worktree>, Entry) {
937 create_wt(project, true, path, cx).await
938 }
939
940 /// Creates a worktree with 1 file: /root{suffix}.txt
941 async fn create_file_wt(
942 project: ModelHandle<Project>,
943 path: impl AsRef<Path>,
944 cx: &mut TestAppContext,
945 ) -> (ModelHandle<Worktree>, Entry) {
946 create_wt(project, false, path, cx).await
947 }
948
949 async fn create_wt(
950 project: ModelHandle<Project>,
951 is_dir: bool,
952 path: impl AsRef<Path>,
953 cx: &mut TestAppContext,
954 ) -> (ModelHandle<Worktree>, Entry) {
955 let (wt, _) = project
956 .update(cx, |project, cx| {
957 project.find_or_create_local_worktree(path, true, cx)
958 })
959 .await
960 .unwrap();
961
962 let entry = cx
963 .update(|cx| {
964 wt.update(cx, |wt, cx| {
965 wt.as_local()
966 .unwrap()
967 .create_entry(Path::new(""), is_dir, cx)
968 })
969 })
970 .await
971 .unwrap();
972
973 (wt, entry)
974 }
975
976 pub fn insert_active_entry_for(
977 wt: ModelHandle<Worktree>,
978 entry: Entry,
979 project: ModelHandle<Project>,
980 cx: &mut TestAppContext,
981 ) {
982 cx.update(|cx| {
983 let p = ProjectPath {
984 worktree_id: wt.read(cx).id(),
985 path: entry.path,
986 };
987 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
988 });
989 }
990}