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