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::{search::SearchQuery, 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 sync::Arc,
30 time::Duration,
31};
32use terminal::{
33 alacritty_terminal::{
34 index::Point,
35 term::{search::RegexSearch, TermMode},
36 },
37 terminal_settings::{TerminalBlink, TerminalSettings, WorkingDirectory},
38 Event, MaybeNavigationTarget, Terminal,
39};
40use util::{paths::PathLikeWithPosition, ResultExt};
41use workspace::{
42 item::{BreadcrumbText, Item, ItemEvent},
43 notifications::NotifyResultExt,
44 pane, register_deserializable_item,
45 searchable::{SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
46 NewCenterTerminal, Pane, ToolbarItemLocation, Workspace, WorkspaceId,
47};
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 { save_intent: None }),
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: Arc<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 replacement: false,
798 }
799 }
800
801 /// Convert events raised by this item into search-relevant events (if applicable)
802 fn to_search_event(
803 &mut self,
804 event: &Self::Event,
805 _: &mut ViewContext<Self>,
806 ) -> Option<SearchEvent> {
807 match event {
808 Event::Wakeup => Some(SearchEvent::MatchesInvalidated),
809 Event::SelectionsChanged => Some(SearchEvent::ActiveMatchChanged),
810 _ => None,
811 }
812 }
813
814 /// Clear stored matches
815 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
816 self.terminal().update(cx, |term, _| term.matches.clear())
817 }
818
819 /// Store matches returned from find_matches somewhere for rendering
820 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
821 self.terminal().update(cx, |term, _| term.matches = matches)
822 }
823
824 /// Return the selection content to pre-load into this search
825 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
826 self.terminal()
827 .read(cx)
828 .last_content
829 .selection_text
830 .clone()
831 .unwrap_or_default()
832 }
833
834 /// Focus match at given index into the Vec of matches
835 fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
836 self.terminal()
837 .update(cx, |term, _| term.activate_match(index));
838 cx.notify();
839 }
840
841 /// Add selections for all matches given.
842 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
843 self.terminal()
844 .update(cx, |term, _| term.select_matches(matches));
845 cx.notify();
846 }
847
848 /// Get all of the matches for this query, should be done on the background
849 fn find_matches(
850 &mut self,
851 query: Arc<project::search::SearchQuery>,
852 cx: &mut ViewContext<Self>,
853 ) -> Task<Vec<Self::Match>> {
854 if let Some(searcher) = regex_search_for_query(&query) {
855 self.terminal()
856 .update(cx, |term, cx| term.find_matches(searcher, cx))
857 } else {
858 Task::ready(vec![])
859 }
860 }
861
862 /// Reports back to the search toolbar what the active match should be (the selection)
863 fn active_match_index(
864 &mut self,
865 matches: Vec<Self::Match>,
866 cx: &mut ViewContext<Self>,
867 ) -> Option<usize> {
868 // Selection head might have a value if there's a selection that isn't
869 // associated with a match. Therefore, if there are no matches, we should
870 // report None, no matter the state of the terminal
871 let res = if matches.len() > 0 {
872 if let Some(selection_head) = self.terminal().read(cx).selection_head {
873 // If selection head is contained in a match. Return that match
874 if let Some(ix) = matches
875 .iter()
876 .enumerate()
877 .find(|(_, search_match)| {
878 search_match.contains(&selection_head)
879 || search_match.start() > &selection_head
880 })
881 .map(|(ix, _)| ix)
882 {
883 Some(ix)
884 } else {
885 // If no selection after selection head, return the last match
886 Some(matches.len().saturating_sub(1))
887 }
888 } else {
889 // Matches found but no active selection, return the first last one (closest to cursor)
890 Some(matches.len().saturating_sub(1))
891 }
892 } else {
893 None
894 };
895
896 res
897 }
898 fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
899 // Replacement is not supported in terminal view, so this is a no-op.
900 }
901}
902
903///Get's the working directory for the given workspace, respecting the user's settings.
904pub fn get_working_directory(
905 workspace: &Workspace,
906 cx: &AppContext,
907 strategy: WorkingDirectory,
908) -> Option<PathBuf> {
909 let res = match strategy {
910 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
911 .or_else(|| first_project_directory(workspace, cx)),
912 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
913 WorkingDirectory::AlwaysHome => None,
914 WorkingDirectory::Always { directory } => {
915 shellexpand::full(&directory) //TODO handle this better
916 .ok()
917 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
918 .filter(|dir| dir.is_dir())
919 }
920 };
921 res.or_else(home_dir)
922}
923
924///Get's the first project's home directory, or the home directory
925fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
926 workspace
927 .worktrees(cx)
928 .next()
929 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
930 .and_then(get_path_from_wt)
931}
932
933///Gets the intuitively correct working directory from the given workspace
934///If there is an active entry for this project, returns that entry's worktree root.
935///If there's no active entry but there is a worktree, returns that worktrees root.
936///If either of these roots are files, or if there are any other query failures,
937/// returns the user's home directory
938fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
939 let project = workspace.project().read(cx);
940
941 project
942 .active_entry()
943 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
944 .or_else(|| workspace.worktrees(cx).next())
945 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
946 .and_then(get_path_from_wt)
947}
948
949fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
950 wt.root_entry()
951 .filter(|re| re.is_dir())
952 .map(|_| wt.abs_path().to_path_buf())
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958 use gpui::TestAppContext;
959 use project::{Entry, Project, ProjectPath, Worktree};
960 use std::path::Path;
961 use workspace::AppState;
962
963 // Working directory calculation tests
964
965 // No Worktrees in project -> home_dir()
966 #[gpui::test]
967 async fn no_worktree(cx: &mut TestAppContext) {
968 let (project, workspace) = init_test(cx).await;
969 cx.read(|cx| {
970 let workspace = workspace.read(cx);
971 let active_entry = project.read(cx).active_entry();
972
973 //Make sure environment is as expected
974 assert!(active_entry.is_none());
975 assert!(workspace.worktrees(cx).next().is_none());
976
977 let res = current_project_directory(workspace, cx);
978 assert_eq!(res, None);
979 let res = first_project_directory(workspace, cx);
980 assert_eq!(res, None);
981 });
982 }
983
984 // No active entry, but a worktree, worktree is a file -> home_dir()
985 #[gpui::test]
986 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
987 let (project, workspace) = init_test(cx).await;
988
989 create_file_wt(project.clone(), "/root.txt", cx).await;
990 cx.read(|cx| {
991 let workspace = workspace.read(cx);
992 let active_entry = project.read(cx).active_entry();
993
994 //Make sure environment is as expected
995 assert!(active_entry.is_none());
996 assert!(workspace.worktrees(cx).next().is_some());
997
998 let res = current_project_directory(workspace, cx);
999 assert_eq!(res, None);
1000 let res = first_project_directory(workspace, cx);
1001 assert_eq!(res, None);
1002 });
1003 }
1004
1005 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1006 #[gpui::test]
1007 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1008 let (project, workspace) = init_test(cx).await;
1009
1010 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1011 cx.update(|cx| {
1012 let workspace = workspace.read(cx);
1013 let active_entry = project.read(cx).active_entry();
1014
1015 assert!(active_entry.is_none());
1016 assert!(workspace.worktrees(cx).next().is_some());
1017
1018 let res = current_project_directory(workspace, cx);
1019 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1020 let res = first_project_directory(workspace, cx);
1021 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1022 });
1023 }
1024
1025 // Active entry with a work tree, worktree is a file -> home_dir()
1026 #[gpui::test]
1027 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1028 let (project, workspace) = init_test(cx).await;
1029
1030 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1031 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1032 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1033
1034 cx.update(|cx| {
1035 let workspace = workspace.read(cx);
1036 let active_entry = project.read(cx).active_entry();
1037
1038 assert!(active_entry.is_some());
1039
1040 let res = current_project_directory(workspace, cx);
1041 assert_eq!(res, None);
1042 let res = first_project_directory(workspace, cx);
1043 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1044 });
1045 }
1046
1047 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1048 #[gpui::test]
1049 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1050 let (project, workspace) = init_test(cx).await;
1051
1052 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1053 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1054 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1055
1056 cx.update(|cx| {
1057 let workspace = workspace.read(cx);
1058 let active_entry = project.read(cx).active_entry();
1059
1060 assert!(active_entry.is_some());
1061
1062 let res = current_project_directory(workspace, cx);
1063 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1064 let res = first_project_directory(workspace, cx);
1065 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1066 });
1067 }
1068
1069 /// Creates a worktree with 1 file: /root.txt
1070 pub async fn init_test(
1071 cx: &mut TestAppContext,
1072 ) -> (ModelHandle<Project>, ViewHandle<Workspace>) {
1073 let params = cx.update(AppState::test);
1074 cx.update(|cx| {
1075 theme::init((), cx);
1076 Project::init_settings(cx);
1077 language::init(cx);
1078 });
1079
1080 let project = Project::test(params.fs.clone(), [], cx).await;
1081 let workspace = cx
1082 .add_window(|cx| Workspace::test_new(project.clone(), cx))
1083 .root(cx);
1084
1085 (project, workspace)
1086 }
1087
1088 /// Creates a worktree with 1 folder: /root{suffix}/
1089 async fn create_folder_wt(
1090 project: ModelHandle<Project>,
1091 path: impl AsRef<Path>,
1092 cx: &mut TestAppContext,
1093 ) -> (ModelHandle<Worktree>, Entry) {
1094 create_wt(project, true, path, cx).await
1095 }
1096
1097 /// Creates a worktree with 1 file: /root{suffix}.txt
1098 async fn create_file_wt(
1099 project: ModelHandle<Project>,
1100 path: impl AsRef<Path>,
1101 cx: &mut TestAppContext,
1102 ) -> (ModelHandle<Worktree>, Entry) {
1103 create_wt(project, false, path, cx).await
1104 }
1105
1106 async fn create_wt(
1107 project: ModelHandle<Project>,
1108 is_dir: bool,
1109 path: impl AsRef<Path>,
1110 cx: &mut TestAppContext,
1111 ) -> (ModelHandle<Worktree>, Entry) {
1112 let (wt, _) = project
1113 .update(cx, |project, cx| {
1114 project.find_or_create_local_worktree(path, true, cx)
1115 })
1116 .await
1117 .unwrap();
1118
1119 let entry = cx
1120 .update(|cx| {
1121 wt.update(cx, |wt, cx| {
1122 wt.as_local()
1123 .unwrap()
1124 .create_entry(Path::new(""), is_dir, cx)
1125 })
1126 })
1127 .await
1128 .unwrap();
1129
1130 (wt, entry)
1131 }
1132
1133 pub fn insert_active_entry_for(
1134 wt: ModelHandle<Worktree>,
1135 entry: Entry,
1136 project: ModelHandle<Project>,
1137 cx: &mut TestAppContext,
1138 ) {
1139 cx.update(|cx| {
1140 let p = ProjectPath {
1141 worktree_id: wt.read(cx).id(),
1142 path: entry.path,
1143 };
1144 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1145 });
1146 }
1147}