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