1mod persistence;
2pub mod terminal_button;
3pub mod terminal_element;
4
5use std::{
6 borrow::Cow,
7 ops::RangeInclusive,
8 path::{Path, PathBuf},
9 time::Duration,
10};
11
12use context_menu::{ContextMenu, ContextMenuItem};
13use dirs::home_dir;
14use gpui::{
15 actions,
16 elements::{AnchorCorner, ChildView, Flex, Label, ParentElement, Stack},
17 geometry::vector::Vector2F,
18 impl_actions, impl_internal_actions,
19 keymap_matcher::{KeymapContext, Keystroke},
20 platform::KeyDownEvent,
21 AnyElement, AnyViewHandle, AppContext, Element, Entity, ModelHandle, Task, View, ViewContext,
22 ViewHandle, WeakViewHandle,
23};
24use project::{LocalWorktree, Project};
25use serde::Deserialize;
26use settings::{Settings, TerminalBlink, WorkingDirectory};
27use smallvec::{smallvec, SmallVec};
28use smol::Timer;
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| {
279 let this = this.downgrade();
280 async move {
281 Timer::after(CURSOR_BLINK_INTERVAL).await;
282 if let Some(this) = this.upgrade(&cx) {
283 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx))
284 .log_err();
285 }
286 }
287 })
288 .detach();
289 }
290 }
291
292 pub fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
293 self.blink_state = true;
294 cx.notify();
295
296 let epoch = self.next_blink_epoch();
297 cx.spawn(|this, mut cx| {
298 let this = this.downgrade();
299 async move {
300 Timer::after(CURSOR_BLINK_INTERVAL).await;
301 if let Some(this) = this.upgrade(&cx) {
302 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
303 .log_err();
304 }
305 }
306 })
307 .detach();
308 }
309
310 pub fn find_matches(
311 &mut self,
312 query: project::search::SearchQuery,
313 cx: &mut ViewContext<Self>,
314 ) -> Task<Vec<RangeInclusive<Point>>> {
315 let searcher = regex_search_for_query(query);
316
317 if let Some(searcher) = searcher {
318 self.terminal
319 .update(cx, |term, cx| term.find_matches(searcher, cx))
320 } else {
321 cx.background().spawn(async { Vec::new() })
322 }
323 }
324
325 pub fn terminal(&self) -> &ModelHandle<Terminal> {
326 &self.terminal
327 }
328
329 fn next_blink_epoch(&mut self) -> usize {
330 self.blink_epoch += 1;
331 self.blink_epoch
332 }
333
334 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
335 if epoch == self.blink_epoch {
336 self.blinking_paused = false;
337 self.blink_cursors(epoch, cx);
338 }
339 }
340
341 ///Attempt to paste the clipboard into the terminal
342 fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
343 self.terminal.update(cx, |term, _| term.copy())
344 }
345
346 ///Attempt to paste the clipboard into the terminal
347 fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
348 if let Some(item) = cx.read_from_clipboard() {
349 self.terminal
350 .update(cx, |terminal, _cx| terminal.paste(item.text()));
351 }
352 }
353
354 fn send_text(&mut self, text: &SendText, cx: &mut ViewContext<Self>) {
355 self.clear_bel(cx);
356 self.terminal.update(cx, |term, _| {
357 term.input(text.0.to_string());
358 });
359 }
360
361 fn send_keystroke(&mut self, text: &SendKeystroke, cx: &mut ViewContext<Self>) {
362 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
363 self.clear_bel(cx);
364 self.terminal.update(cx, |term, cx| {
365 term.try_keystroke(
366 &keystroke,
367 cx.global::<Settings>()
368 .terminal_overrides
369 .option_as_meta
370 .unwrap_or(false),
371 );
372 });
373 }
374 }
375}
376
377pub fn regex_search_for_query(query: project::search::SearchQuery) -> Option<RegexSearch> {
378 let searcher = match query {
379 project::search::SearchQuery::Text { query, .. } => RegexSearch::new(&query),
380 project::search::SearchQuery::Regex { query, .. } => RegexSearch::new(&query),
381 };
382 searcher.ok()
383}
384
385impl View for TerminalView {
386 fn ui_name() -> &'static str {
387 "Terminal"
388 }
389
390 fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> AnyElement<Self> {
391 let terminal_handle = self.terminal.clone().downgrade();
392
393 let self_id = cx.view_id();
394 let focused = cx
395 .focused_view_id()
396 .filter(|view_id| *view_id == self_id)
397 .is_some();
398
399 Stack::new()
400 .with_child(
401 TerminalElement::new(
402 terminal_handle,
403 focused,
404 self.should_show_cursor(focused, cx),
405 )
406 .contained(),
407 )
408 .with_child(ChildView::new(&self.context_menu, cx))
409 .into_any()
410 }
411
412 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
413 self.has_new_content = false;
414 self.terminal.read(cx).focus_in();
415 self.blink_cursors(self.blink_epoch, cx);
416 cx.notify();
417 }
418
419 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
420 self.terminal.update(cx, |terminal, _| {
421 terminal.focus_out();
422 });
423 cx.notify();
424 }
425
426 fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) -> bool {
427 self.clear_bel(cx);
428 self.pause_cursor_blinking(cx);
429
430 self.terminal.update(cx, |term, cx| {
431 term.try_keystroke(
432 &event.keystroke,
433 cx.global::<Settings>()
434 .terminal_overrides
435 .option_as_meta
436 .unwrap_or(false),
437 )
438 })
439 }
440
441 //IME stuff
442 fn selected_text_range(&self, cx: &AppContext) -> Option<std::ops::Range<usize>> {
443 if self
444 .terminal
445 .read(cx)
446 .last_content
447 .mode
448 .contains(TermMode::ALT_SCREEN)
449 {
450 None
451 } else {
452 Some(0..0)
453 }
454 }
455
456 fn replace_text_in_range(
457 &mut self,
458 _: Option<std::ops::Range<usize>>,
459 text: &str,
460 cx: &mut ViewContext<Self>,
461 ) {
462 self.terminal.update(cx, |terminal, _| {
463 terminal.input(text.into());
464 });
465 }
466
467 fn keymap_context(&self, cx: &gpui::AppContext) -> KeymapContext {
468 let mut context = Self::default_keymap_context();
469
470 let mode = self.terminal.read(cx).last_content.mode;
471 context.add_key(
472 "screen",
473 if mode.contains(TermMode::ALT_SCREEN) {
474 "alt"
475 } else {
476 "normal"
477 },
478 );
479
480 if mode.contains(TermMode::APP_CURSOR) {
481 context.add_identifier("DECCKM");
482 }
483 if mode.contains(TermMode::APP_KEYPAD) {
484 context.add_identifier("DECPAM");
485 } else {
486 context.add_identifier("DECPNM");
487 }
488 if mode.contains(TermMode::SHOW_CURSOR) {
489 context.add_identifier("DECTCEM");
490 }
491 if mode.contains(TermMode::LINE_WRAP) {
492 context.add_identifier("DECAWM");
493 }
494 if mode.contains(TermMode::ORIGIN) {
495 context.add_identifier("DECOM");
496 }
497 if mode.contains(TermMode::INSERT) {
498 context.add_identifier("IRM");
499 }
500 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
501 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
502 context.add_identifier("LNM");
503 }
504 if mode.contains(TermMode::FOCUS_IN_OUT) {
505 context.add_identifier("report_focus");
506 }
507 if mode.contains(TermMode::ALTERNATE_SCROLL) {
508 context.add_identifier("alternate_scroll");
509 }
510 if mode.contains(TermMode::BRACKETED_PASTE) {
511 context.add_identifier("bracketed_paste");
512 }
513 if mode.intersects(TermMode::MOUSE_MODE) {
514 context.add_identifier("any_mouse_reporting");
515 }
516 {
517 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
518 "click"
519 } else if mode.contains(TermMode::MOUSE_DRAG) {
520 "drag"
521 } else if mode.contains(TermMode::MOUSE_MOTION) {
522 "motion"
523 } else {
524 "off"
525 };
526 context.add_key("mouse_reporting", mouse_reporting);
527 }
528 {
529 let format = if mode.contains(TermMode::SGR_MOUSE) {
530 "sgr"
531 } else if mode.contains(TermMode::UTF8_MOUSE) {
532 "utf8"
533 } else {
534 "normal"
535 };
536 context.add_key("mouse_format", format);
537 }
538 context
539 }
540}
541
542impl Item for TerminalView {
543 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<Cow<str>> {
544 Some(self.terminal().read(cx).title().into())
545 }
546
547 fn tab_content<T: View>(
548 &self,
549 _detail: Option<usize>,
550 tab_theme: &theme::Tab,
551 cx: &gpui::AppContext,
552 ) -> AnyElement<T> {
553 let title = self.terminal().read(cx).title();
554
555 Flex::row()
556 .with_child(
557 gpui::elements::Svg::new("icons/terminal_12.svg")
558 .with_color(tab_theme.label.text.color)
559 .constrained()
560 .with_width(tab_theme.type_icon_width)
561 .aligned()
562 .contained()
563 .with_margin_right(tab_theme.spacing),
564 )
565 .with_child(Label::new(title, tab_theme.label.clone()).aligned())
566 .into_any()
567 }
568
569 fn clone_on_split(
570 &self,
571 _workspace_id: WorkspaceId,
572 _cx: &mut ViewContext<Self>,
573 ) -> Option<Self> {
574 //From what I can tell, there's no way to tell the current working
575 //Directory of the terminal from outside the shell. There might be
576 //solutions to this, but they are non-trivial and require more IPC
577
578 // Some(TerminalContainer::new(
579 // Err(anyhow::anyhow!("failed to instantiate terminal")),
580 // workspace_id,
581 // cx,
582 // ))
583
584 // TODO
585 None
586 }
587
588 fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
589 self.has_bell()
590 }
591
592 fn has_conflict(&self, _cx: &AppContext) -> bool {
593 false
594 }
595
596 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
597 Some(Box::new(handle.clone()))
598 }
599
600 fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
601 match event {
602 Event::BreadcrumbsChanged => smallvec![ItemEvent::UpdateBreadcrumbs],
603 Event::TitleChanged | Event::Wakeup => smallvec![ItemEvent::UpdateTab],
604 Event::CloseTerminal => smallvec![ItemEvent::CloseItem],
605 _ => smallvec![],
606 }
607 }
608
609 fn breadcrumb_location(&self) -> ToolbarItemLocation {
610 ToolbarItemLocation::PrimaryLeft { flex: None }
611 }
612
613 fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
614 Some(vec![BreadcrumbText {
615 text: self.terminal().read(cx).breadcrumb_text.clone(),
616 highlights: None,
617 }])
618 }
619
620 fn serialized_item_kind() -> Option<&'static str> {
621 Some("Terminal")
622 }
623
624 fn deserialize(
625 project: ModelHandle<Project>,
626 workspace: WeakViewHandle<Workspace>,
627 workspace_id: workspace::WorkspaceId,
628 item_id: workspace::ItemId,
629 cx: &mut ViewContext<Pane>,
630 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
631 let window_id = cx.window_id();
632 cx.spawn(|pane, mut cx| async move {
633 let cwd = TERMINAL_DB
634 .get_working_directory(item_id, workspace_id)
635 .log_err()
636 .flatten()
637 .or_else(|| {
638 cx.read(|cx| {
639 let strategy = cx.global::<Settings>().terminal_strategy();
640 workspace
641 .upgrade(cx)
642 .map(|workspace| {
643 get_working_directory(workspace.read(cx), cx, strategy)
644 })
645 .flatten()
646 })
647 });
648
649 cx.update(|cx| {
650 let terminal = project.update(cx, |project, cx| {
651 project.create_terminal(cwd, window_id, cx)
652 })?;
653
654 Ok(cx.add_view(&pane, |cx| TerminalView::new(terminal, workspace_id, cx)))
655 })
656 })
657 }
658
659 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
660 cx.background()
661 .spawn(TERMINAL_DB.update_workspace_id(
662 workspace.database_id(),
663 self.workspace_id,
664 cx.view_id(),
665 ))
666 .detach();
667 self.workspace_id = workspace.database_id();
668 }
669}
670
671impl SearchableItem for TerminalView {
672 type Match = RangeInclusive<Point>;
673
674 fn supported_options() -> SearchOptions {
675 SearchOptions {
676 case: false,
677 word: false,
678 regex: false,
679 }
680 }
681
682 /// Convert events raised by this item into search-relevant events (if applicable)
683 fn to_search_event(event: &Self::Event) -> Option<SearchEvent> {
684 match event {
685 Event::Wakeup => Some(SearchEvent::MatchesInvalidated),
686 Event::SelectionsChanged => Some(SearchEvent::ActiveMatchChanged),
687 _ => None,
688 }
689 }
690
691 /// Clear stored matches
692 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
693 self.terminal().update(cx, |term, _| term.matches.clear())
694 }
695
696 /// Store matches returned from find_matches somewhere for rendering
697 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
698 self.terminal().update(cx, |term, _| term.matches = matches)
699 }
700
701 /// Return the selection content to pre-load into this search
702 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
703 self.terminal()
704 .read(cx)
705 .last_content
706 .selection_text
707 .clone()
708 .unwrap_or_default()
709 }
710
711 /// Focus match at given index into the Vec of matches
712 fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
713 self.terminal()
714 .update(cx, |term, _| term.activate_match(index));
715 cx.notify();
716 }
717
718 /// Get all of the matches for this query, should be done on the background
719 fn find_matches(
720 &mut self,
721 query: project::search::SearchQuery,
722 cx: &mut ViewContext<Self>,
723 ) -> Task<Vec<Self::Match>> {
724 if let Some(searcher) = regex_search_for_query(query) {
725 self.terminal()
726 .update(cx, |term, cx| term.find_matches(searcher, cx))
727 } else {
728 Task::ready(vec![])
729 }
730 }
731
732 /// Reports back to the search toolbar what the active match should be (the selection)
733 fn active_match_index(
734 &mut self,
735 matches: Vec<Self::Match>,
736 cx: &mut ViewContext<Self>,
737 ) -> Option<usize> {
738 // Selection head might have a value if there's a selection that isn't
739 // associated with a match. Therefore, if there are no matches, we should
740 // report None, no matter the state of the terminal
741 let res = if matches.len() > 0 {
742 if let Some(selection_head) = self.terminal().read(cx).selection_head {
743 // If selection head is contained in a match. Return that match
744 if let Some(ix) = matches
745 .iter()
746 .enumerate()
747 .find(|(_, search_match)| {
748 search_match.contains(&selection_head)
749 || search_match.start() > &selection_head
750 })
751 .map(|(ix, _)| ix)
752 {
753 Some(ix)
754 } else {
755 // If no selection after selection head, return the last match
756 Some(matches.len().saturating_sub(1))
757 }
758 } else {
759 // Matches found but no active selection, return the first last one (closest to cursor)
760 Some(matches.len().saturating_sub(1))
761 }
762 } else {
763 None
764 };
765
766 res
767 }
768}
769
770///Get's the working directory for the given workspace, respecting the user's settings.
771pub fn get_working_directory(
772 workspace: &Workspace,
773 cx: &AppContext,
774 strategy: WorkingDirectory,
775) -> Option<PathBuf> {
776 let res = match strategy {
777 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
778 .or_else(|| first_project_directory(workspace, cx)),
779 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
780 WorkingDirectory::AlwaysHome => None,
781 WorkingDirectory::Always { directory } => {
782 shellexpand::full(&directory) //TODO handle this better
783 .ok()
784 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
785 .filter(|dir| dir.is_dir())
786 }
787 };
788 res.or_else(home_dir)
789}
790
791///Get's the first project's home directory, or the home directory
792fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
793 workspace
794 .worktrees(cx)
795 .next()
796 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
797 .and_then(get_path_from_wt)
798}
799
800///Gets the intuitively correct working directory from the given workspace
801///If there is an active entry for this project, returns that entry's worktree root.
802///If there's no active entry but there is a worktree, returns that worktrees root.
803///If either of these roots are files, or if there are any other query failures,
804/// returns the user's home directory
805fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
806 let project = workspace.project().read(cx);
807
808 project
809 .active_entry()
810 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
811 .or_else(|| workspace.worktrees(cx).next())
812 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
813 .and_then(get_path_from_wt)
814}
815
816fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
817 wt.root_entry()
818 .filter(|re| re.is_dir())
819 .map(|_| wt.abs_path().to_path_buf())
820}
821
822#[cfg(test)]
823mod tests {
824
825 use super::*;
826 use gpui::TestAppContext;
827 use project::{Entry, Project, ProjectPath, Worktree};
828 use workspace::AppState;
829
830 use std::path::Path;
831
832 ///Working directory calculation tests
833
834 ///No Worktrees in project -> home_dir()
835 #[gpui::test]
836 async fn no_worktree(cx: &mut TestAppContext) {
837 //Setup variables
838 let (project, workspace) = blank_workspace(cx).await;
839 //Test
840 cx.read(|cx| {
841 let workspace = workspace.read(cx);
842 let active_entry = project.read(cx).active_entry();
843
844 //Make sure enviroment is as expeted
845 assert!(active_entry.is_none());
846 assert!(workspace.worktrees(cx).next().is_none());
847
848 let res = current_project_directory(workspace, cx);
849 assert_eq!(res, None);
850 let res = first_project_directory(workspace, cx);
851 assert_eq!(res, None);
852 });
853 }
854
855 ///No active entry, but a worktree, worktree is a file -> home_dir()
856 #[gpui::test]
857 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
858 //Setup variables
859
860 let (project, workspace) = blank_workspace(cx).await;
861 create_file_wt(project.clone(), "/root.txt", cx).await;
862
863 cx.read(|cx| {
864 let workspace = workspace.read(cx);
865 let active_entry = project.read(cx).active_entry();
866
867 //Make sure enviroment is as expeted
868 assert!(active_entry.is_none());
869 assert!(workspace.worktrees(cx).next().is_some());
870
871 let res = current_project_directory(workspace, cx);
872 assert_eq!(res, None);
873 let res = first_project_directory(workspace, cx);
874 assert_eq!(res, None);
875 });
876 }
877
878 //No active entry, but a worktree, worktree is a folder -> worktree_folder
879 #[gpui::test]
880 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
881 //Setup variables
882 let (project, workspace) = blank_workspace(cx).await;
883 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
884
885 //Test
886 cx.update(|cx| {
887 let workspace = workspace.read(cx);
888 let active_entry = project.read(cx).active_entry();
889
890 assert!(active_entry.is_none());
891 assert!(workspace.worktrees(cx).next().is_some());
892
893 let res = current_project_directory(workspace, cx);
894 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
895 let res = first_project_directory(workspace, cx);
896 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
897 });
898 }
899
900 //Active entry with a work tree, worktree is a file -> home_dir()
901 #[gpui::test]
902 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
903 //Setup variables
904
905 let (project, workspace) = blank_workspace(cx).await;
906 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
907 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
908 insert_active_entry_for(wt2, entry2, project.clone(), cx);
909
910 //Test
911 cx.update(|cx| {
912 let workspace = workspace.read(cx);
913 let active_entry = project.read(cx).active_entry();
914
915 assert!(active_entry.is_some());
916
917 let res = current_project_directory(workspace, cx);
918 assert_eq!(res, None);
919 let res = first_project_directory(workspace, cx);
920 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
921 });
922 }
923
924 //Active entry, with a worktree, worktree is a folder -> worktree_folder
925 #[gpui::test]
926 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
927 //Setup variables
928 let (project, workspace) = blank_workspace(cx).await;
929 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
930 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
931 insert_active_entry_for(wt2, entry2, project.clone(), cx);
932
933 //Test
934 cx.update(|cx| {
935 let workspace = workspace.read(cx);
936 let active_entry = project.read(cx).active_entry();
937
938 assert!(active_entry.is_some());
939
940 let res = current_project_directory(workspace, cx);
941 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
942 let res = first_project_directory(workspace, cx);
943 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
944 });
945 }
946
947 ///Creates a worktree with 1 file: /root.txt
948 pub async fn blank_workspace(
949 cx: &mut TestAppContext,
950 ) -> (ModelHandle<Project>, ViewHandle<Workspace>) {
951 let params = cx.update(AppState::test);
952
953 let project = Project::test(params.fs.clone(), [], cx).await;
954 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
955
956 (project, workspace)
957 }
958
959 ///Creates a worktree with 1 folder: /root{suffix}/
960 async fn create_folder_wt(
961 project: ModelHandle<Project>,
962 path: impl AsRef<Path>,
963 cx: &mut TestAppContext,
964 ) -> (ModelHandle<Worktree>, Entry) {
965 create_wt(project, true, path, cx).await
966 }
967
968 ///Creates a worktree with 1 file: /root{suffix}.txt
969 async fn create_file_wt(
970 project: ModelHandle<Project>,
971 path: impl AsRef<Path>,
972 cx: &mut TestAppContext,
973 ) -> (ModelHandle<Worktree>, Entry) {
974 create_wt(project, false, path, cx).await
975 }
976
977 async fn create_wt(
978 project: ModelHandle<Project>,
979 is_dir: bool,
980 path: impl AsRef<Path>,
981 cx: &mut TestAppContext,
982 ) -> (ModelHandle<Worktree>, Entry) {
983 let (wt, _) = project
984 .update(cx, |project, cx| {
985 project.find_or_create_local_worktree(path, true, cx)
986 })
987 .await
988 .unwrap();
989
990 let entry = cx
991 .update(|cx| {
992 wt.update(cx, |wt, cx| {
993 wt.as_local()
994 .unwrap()
995 .create_entry(Path::new(""), is_dir, cx)
996 })
997 })
998 .await
999 .unwrap();
1000
1001 (wt, entry)
1002 }
1003
1004 pub fn insert_active_entry_for(
1005 wt: ModelHandle<Worktree>,
1006 entry: Entry,
1007 project: ModelHandle<Project>,
1008 cx: &mut TestAppContext,
1009 ) {
1010 cx.update(|cx| {
1011 let p = ProjectPath {
1012 worktree_id: wt.read(cx).id(),
1013 path: entry.path,
1014 };
1015 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1016 });
1017 }
1018}