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