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