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