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