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