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