1#![allow(unused_variables)]
2//todo!(remove)
3
4mod persistence;
5pub mod terminal_element;
6pub mod terminal_panel;
7
8// todo!()
9// use crate::terminal_element::TerminalElement;
10use editor::{scroll::autoscroll::Autoscroll, Editor};
11use gpui::{
12 div, impl_actions, overlay, AnyElement, AppContext, DismissEvent, Div, EventEmitter,
13 FocusEvent, FocusHandle, Focusable, FocusableElement, FocusableView, KeyContext, KeyDownEvent,
14 Keystroke, Model, MouseButton, MouseDownEvent, Pixels, Render, Styled, Subscription, Task,
15 View, VisualContext, WeakView,
16};
17use language::Bias;
18use persistence::TERMINAL_DB;
19use project::{search::SearchQuery, LocalWorktree, Project};
20use terminal::{
21 alacritty_terminal::{
22 index::Point,
23 term::{search::RegexSearch, TermMode},
24 },
25 terminal_settings::{TerminalBlink, TerminalSettings, WorkingDirectory},
26 Clear, Copy, Event, MaybeNavigationTarget, Paste, ShowCharacterPalette, Terminal,
27};
28use terminal_element::TerminalElement;
29use ui::{h_stack, prelude::*, ContextMenu, Icon, IconElement, Label};
30use util::{paths::PathLikeWithPosition, ResultExt};
31use workspace::{
32 item::{BreadcrumbText, Item, ItemEvent},
33 notifications::NotifyResultExt,
34 register_deserializable_item,
35 searchable::{SearchEvent, SearchOptions, SearchableItem},
36 CloseActiveItem, NewCenterTerminal, Pane, ToolbarItemLocation, Workspace, WorkspaceId,
37};
38
39use anyhow::Context;
40use dirs::home_dir;
41use serde::Deserialize;
42use settings::Settings;
43use smol::Timer;
44
45use std::{
46 ops::RangeInclusive,
47 path::{Path, PathBuf},
48 sync::Arc,
49 time::Duration,
50};
51
52const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
53
54///Event to transmit the scroll from the element to the view
55#[derive(Clone, Debug, PartialEq)]
56pub struct ScrollTerminal(pub i32);
57
58#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
59pub struct SendText(String);
60
61#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
62pub struct SendKeystroke(String);
63
64impl_actions!(terminal_view, [SendText, SendKeystroke]);
65
66pub fn init(cx: &mut AppContext) {
67 terminal_panel::init(cx);
68 terminal::init(cx);
69
70 register_deserializable_item::<TerminalView>(cx);
71
72 cx.observe_new_views(
73 |workspace: &mut Workspace, cx: &mut ViewContext<Workspace>| {
74 workspace.register_action(TerminalView::deploy);
75 },
76 )
77 .detach();
78}
79
80///A terminal view, maintains the PTY's file handles and communicates with the terminal
81pub struct TerminalView {
82 terminal: Model<Terminal>,
83 focus_handle: FocusHandle,
84 has_new_content: bool,
85 //Currently using iTerm bell, show bell emoji in tab until input is received
86 has_bell: bool,
87 context_menu: Option<(View<ContextMenu>, gpui::Point<Pixels>, Subscription)>,
88 blink_state: bool,
89 blinking_on: bool,
90 blinking_paused: bool,
91 blink_epoch: usize,
92 can_navigate_to_selected_word: bool,
93 workspace_id: WorkspaceId,
94 _subscriptions: Vec<Subscription>,
95}
96
97impl EventEmitter<Event> for TerminalView {}
98impl EventEmitter<ItemEvent> for TerminalView {}
99impl EventEmitter<SearchEvent> for TerminalView {}
100
101impl FocusableView for TerminalView {
102 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
103 self.focus_handle.clone()
104 }
105}
106
107impl TerminalView {
108 ///Create a new Terminal in the current working directory or the user's home directory
109 pub fn deploy(
110 workspace: &mut Workspace,
111 _: &NewCenterTerminal,
112 cx: &mut ViewContext<Workspace>,
113 ) {
114 let strategy = TerminalSettings::get_global(cx);
115 let working_directory =
116 get_working_directory(workspace, cx, strategy.working_directory.clone());
117
118 let window = cx.window_handle();
119 let terminal = workspace
120 .project()
121 .update(cx, |project, cx| {
122 project.create_terminal(working_directory, window, cx)
123 })
124 .notify_err(workspace, cx);
125
126 if let Some(terminal) = terminal {
127 let view = cx.build_view(|cx| {
128 TerminalView::new(
129 terminal,
130 workspace.weak_handle(),
131 workspace.database_id(),
132 cx,
133 )
134 });
135 workspace.add_item(Box::new(view), cx)
136 }
137 }
138
139 pub fn new(
140 terminal: Model<Terminal>,
141 workspace: WeakView<Workspace>,
142 workspace_id: WorkspaceId,
143 cx: &mut ViewContext<Self>,
144 ) -> Self {
145 let view_id = cx.entity_id();
146 cx.observe(&terminal, |_, _, cx| cx.notify()).detach();
147 cx.subscribe(&terminal, move |this, _, event, cx| match event {
148 Event::Wakeup => {
149 if !this.focus_handle.is_focused(cx) {
150 this.has_new_content = true;
151 }
152 cx.notify();
153 cx.emit(Event::Wakeup);
154 cx.emit(ItemEvent::UpdateTab);
155 cx.emit(SearchEvent::MatchesInvalidated);
156 }
157
158 Event::Bell => {
159 this.has_bell = true;
160 cx.emit(Event::Wakeup);
161 }
162
163 Event::BlinkChanged => this.blinking_on = !this.blinking_on,
164
165 Event::TitleChanged => {
166 cx.emit(ItemEvent::UpdateTab);
167 if let Some(foreground_info) = &this.terminal().read(cx).foreground_process_info {
168 let cwd = foreground_info.cwd.clone();
169
170 let item_id = cx.entity_id();
171 let workspace_id = this.workspace_id;
172 cx.background_executor()
173 .spawn(async move {
174 TERMINAL_DB
175 .save_working_directory(item_id.as_u64(), workspace_id, cwd)
176 .await
177 .log_err();
178 })
179 .detach();
180 }
181 }
182
183 Event::NewNavigationTarget(maybe_navigation_target) => {
184 this.can_navigate_to_selected_word = match maybe_navigation_target {
185 Some(MaybeNavigationTarget::Url(_)) => true,
186 Some(MaybeNavigationTarget::PathLike(maybe_path)) => {
187 !possible_open_targets(&workspace, maybe_path, cx).is_empty()
188 }
189 None => false,
190 }
191 }
192
193 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
194 MaybeNavigationTarget::Url(url) => cx.open_url(url),
195
196 MaybeNavigationTarget::PathLike(maybe_path) => {
197 if !this.can_navigate_to_selected_word {
198 return;
199 }
200 let potential_abs_paths = possible_open_targets(&workspace, maybe_path, cx);
201 if let Some(path) = potential_abs_paths.into_iter().next() {
202 let is_dir = path.path_like.is_dir();
203 let task_workspace = workspace.clone();
204 cx.spawn(|_, mut cx| async move {
205 let opened_items = task_workspace
206 .update(&mut cx, |workspace, cx| {
207 workspace.open_paths(vec![path.path_like], is_dir, cx)
208 })
209 .context("workspace update")?
210 .await;
211 anyhow::ensure!(
212 opened_items.len() == 1,
213 "For a single path open, expected single opened item"
214 );
215 let opened_item = opened_items
216 .into_iter()
217 .next()
218 .unwrap()
219 .transpose()
220 .context("path open")?;
221 if is_dir {
222 task_workspace.update(&mut cx, |workspace, cx| {
223 workspace.project().update(cx, |_, cx| {
224 cx.emit(project::Event::ActivateProjectPanel);
225 })
226 })?;
227 } else {
228 if let Some(row) = path.row {
229 let col = path.column.unwrap_or(0);
230 if let Some(active_editor) =
231 opened_item.and_then(|item| item.downcast::<Editor>())
232 {
233 active_editor
234 .downgrade()
235 .update(&mut cx, |editor, cx| {
236 let snapshot = editor.snapshot(cx).display_snapshot;
237 let point = snapshot.buffer_snapshot.clip_point(
238 language::Point::new(
239 row.saturating_sub(1),
240 col.saturating_sub(1),
241 ),
242 Bias::Left,
243 );
244 editor.change_selections(
245 Some(Autoscroll::center()),
246 cx,
247 |s| s.select_ranges([point..point]),
248 );
249 })
250 .log_err();
251 }
252 }
253 }
254 anyhow::Ok(())
255 })
256 .detach_and_log_err(cx);
257 }
258 }
259 },
260 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
261 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
262 Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
263 })
264 .detach();
265
266 let focus = cx.focus_handle();
267 // let focus_in = cx.on_focus_in(&focus, |this, cx| {
268 // this.has_new_content = false;
269 // this.terminal.read(cx).focus_in();
270 // this.blink_cursors(this.blink_epoch, cx);
271 // cx.notify();
272 // });
273 // let focus_out = cx.on_focus_out(&focus, |this, cx| {
274 // this.terminal.update(cx, |terminal, _| {
275 // terminal.focus_out();
276 // });
277 // cx.notify();
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, cx| {
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, event: &FocusEvent, 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, event: &FocusEvent, 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 type Element = Focusable<Div>;
634
635 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
636 let terminal_handle = self.terminal.clone();
637
638 let self_id = cx.entity_id();
639 let focused = self.focus_handle.is_focused(cx);
640
641 div()
642 .size_full()
643 .relative()
644 .track_focus(&self.focus_handle)
645 .key_context(self.dispatch_context(cx))
646 .on_action(cx.listener(TerminalView::send_text))
647 .on_action(cx.listener(TerminalView::send_keystroke))
648 .on_action(cx.listener(TerminalView::copy))
649 .on_action(cx.listener(TerminalView::paste))
650 .on_action(cx.listener(TerminalView::clear))
651 .on_action(cx.listener(TerminalView::show_character_palette))
652 .on_action(cx.listener(TerminalView::select_all))
653 .on_focus_in(cx.listener(Self::focus_in))
654 .on_focus_out(cx.listener(Self::focus_out))
655 .on_key_down(cx.listener(Self::key_down))
656 .on_mouse_down(
657 MouseButton::Right,
658 cx.listener(|this, event: &MouseDownEvent, cx| {
659 this.deploy_context_menu(event.position, cx);
660 cx.notify();
661 }),
662 )
663 .child(
664 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
665 div().size_full().child(TerminalElement::new(
666 terminal_handle,
667 self.focus_handle.clone(),
668 focused,
669 self.should_show_cursor(focused, cx),
670 self.can_navigate_to_selected_word,
671 )),
672 )
673 .children(self.context_menu.as_ref().map(|(menu, positon, _)| {
674 overlay()
675 .position(*positon)
676 .anchor(gpui::AnchorCorner::TopLeft)
677 .child(menu.clone())
678 }))
679 }
680}
681
682impl Item for TerminalView {
683 type Event = ItemEvent;
684
685 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
686 Some(self.terminal().read(cx).title().into())
687 }
688
689 fn tab_content(
690 &self,
691 _detail: Option<usize>,
692 selected: bool,
693 cx: &WindowContext,
694 ) -> AnyElement {
695 let title = self.terminal().read(cx).title();
696
697 h_stack()
698 .gap_2()
699 .child(IconElement::new(Icon::Terminal))
700 .child(Label::new(title).color(if selected {
701 Color::Default
702 } else {
703 Color::Muted
704 }))
705 .into_any()
706 }
707
708 fn clone_on_split(
709 &self,
710 _workspace_id: WorkspaceId,
711 _cx: &mut ViewContext<Self>,
712 ) -> Option<View<Self>> {
713 //From what I can tell, there's no way to tell the current working
714 //Directory of the terminal from outside the shell. There might be
715 //solutions to this, but they are non-trivial and require more IPC
716
717 // Some(TerminalContainer::new(
718 // Err(anyhow::anyhow!("failed to instantiate terminal")),
719 // workspace_id,
720 // cx,
721 // ))
722
723 // TODO
724 None
725 }
726
727 fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
728 self.has_bell()
729 }
730
731 fn has_conflict(&self, _cx: &AppContext) -> bool {
732 false
733 }
734
735 // todo!(search)
736 // fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
737 // Some(Box::new(handle.clone()))
738 // }
739
740 fn breadcrumb_location(&self) -> ToolbarItemLocation {
741 ToolbarItemLocation::PrimaryLeft
742 }
743
744 fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
745 Some(vec![BreadcrumbText {
746 text: self.terminal().read(cx).breadcrumb_text.clone(),
747 highlights: None,
748 }])
749 }
750
751 fn serialized_item_kind() -> Option<&'static str> {
752 Some("Terminal")
753 }
754
755 fn deserialize(
756 project: Model<Project>,
757 workspace: WeakView<Workspace>,
758 workspace_id: workspace::WorkspaceId,
759 item_id: workspace::ItemId,
760 cx: &mut ViewContext<Pane>,
761 ) -> Task<anyhow::Result<View<Self>>> {
762 let window = cx.window_handle();
763 cx.spawn(|pane, mut cx| async move {
764 let cwd = None;
765 TERMINAL_DB
766 .get_working_directory(item_id, workspace_id)
767 .log_err()
768 .flatten()
769 .or_else(|| {
770 cx.update(|_, cx| {
771 let strategy = TerminalSettings::get_global(cx).working_directory.clone();
772 workspace
773 .upgrade()
774 .map(|workspace| {
775 get_working_directory(workspace.read(cx), cx, strategy)
776 })
777 .flatten()
778 })
779 .ok()
780 .flatten()
781 });
782
783 let terminal = project.update(&mut cx, |project, cx| {
784 project.create_terminal(cwd, window, cx)
785 })??;
786 pane.update(&mut cx, |_, cx| {
787 cx.build_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
788 })
789 })
790 }
791
792 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
793 cx.background_executor()
794 .spawn(TERMINAL_DB.update_workspace_id(
795 workspace.database_id(),
796 self.workspace_id,
797 cx.entity_id().as_u64(),
798 ))
799 .detach();
800 self.workspace_id = workspace.database_id();
801 }
802
803 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
804 f(*event)
805 }
806}
807
808impl SearchableItem for TerminalView {
809 type Match = RangeInclusive<Point>;
810
811 fn supported_options() -> SearchOptions {
812 SearchOptions {
813 case: false,
814 word: false,
815 regex: false,
816 replacement: false,
817 }
818 }
819
820 /// Clear stored matches
821 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
822 self.terminal().update(cx, |term, _| term.matches.clear())
823 }
824
825 /// Store matches returned from find_matches somewhere for rendering
826 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
827 self.terminal().update(cx, |term, _| term.matches = matches)
828 }
829
830 /// Return the selection content to pre-load into this search
831 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
832 self.terminal()
833 .read(cx)
834 .last_content
835 .selection_text
836 .clone()
837 .unwrap_or_default()
838 }
839
840 /// Focus match at given index into the Vec of matches
841 fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
842 self.terminal()
843 .update(cx, |term, _| term.activate_match(index));
844 cx.notify();
845 }
846
847 /// Add selections for all matches given.
848 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
849 self.terminal()
850 .update(cx, |term, _| term.select_matches(matches));
851 cx.notify();
852 }
853
854 /// Get all of the matches for this query, should be done on the background
855 fn find_matches(
856 &mut self,
857 query: Arc<project::search::SearchQuery>,
858 cx: &mut ViewContext<Self>,
859 ) -> Task<Vec<Self::Match>> {
860 if let Some(searcher) = regex_search_for_query(&query) {
861 self.terminal()
862 .update(cx, |term, cx| term.find_matches(searcher, cx))
863 } else {
864 Task::ready(vec![])
865 }
866 }
867
868 /// Reports back to the search toolbar what the active match should be (the selection)
869 fn active_match_index(
870 &mut self,
871 matches: Vec<Self::Match>,
872 cx: &mut ViewContext<Self>,
873 ) -> Option<usize> {
874 // Selection head might have a value if there's a selection that isn't
875 // associated with a match. Therefore, if there are no matches, we should
876 // report None, no matter the state of the terminal
877 let res = if matches.len() > 0 {
878 if let Some(selection_head) = self.terminal().read(cx).selection_head {
879 // If selection head is contained in a match. Return that match
880 if let Some(ix) = matches
881 .iter()
882 .enumerate()
883 .find(|(_, search_match)| {
884 search_match.contains(&selection_head)
885 || search_match.start() > &selection_head
886 })
887 .map(|(ix, _)| ix)
888 {
889 Some(ix)
890 } else {
891 // If no selection after selection head, return the last match
892 Some(matches.len().saturating_sub(1))
893 }
894 } else {
895 // Matches found but no active selection, return the first last one (closest to cursor)
896 Some(matches.len().saturating_sub(1))
897 }
898 } else {
899 None
900 };
901
902 res
903 }
904 fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
905 // Replacement is not supported in terminal view, so this is a no-op.
906 }
907}
908
909///Get's the working directory for the given workspace, respecting the user's settings.
910pub fn get_working_directory(
911 workspace: &Workspace,
912 cx: &AppContext,
913 strategy: WorkingDirectory,
914) -> Option<PathBuf> {
915 let res = match strategy {
916 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
917 .or_else(|| first_project_directory(workspace, cx)),
918 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
919 WorkingDirectory::AlwaysHome => None,
920 WorkingDirectory::Always { directory } => {
921 shellexpand::full(&directory) //TODO handle this better
922 .ok()
923 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
924 .filter(|dir| dir.is_dir())
925 }
926 };
927 res.or_else(home_dir)
928}
929
930///Get's the first project's home directory, or the home directory
931fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
932 workspace
933 .worktrees(cx)
934 .next()
935 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
936 .and_then(get_path_from_wt)
937}
938
939///Gets the intuitively correct working directory from the given workspace
940///If there is an active entry for this project, returns that entry's worktree root.
941///If there's no active entry but there is a worktree, returns that worktrees root.
942///If either of these roots are files, or if there are any other query failures,
943/// returns the user's home directory
944fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
945 let project = workspace.project().read(cx);
946
947 project
948 .active_entry()
949 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
950 .or_else(|| workspace.worktrees(cx).next())
951 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
952 .and_then(get_path_from_wt)
953}
954
955fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
956 wt.root_entry()
957 .filter(|re| re.is_dir())
958 .map(|_| wt.abs_path().to_path_buf())
959}
960
961#[cfg(test)]
962mod tests {
963 use super::*;
964 use gpui::TestAppContext;
965 use project::{Entry, Project, ProjectPath, Worktree};
966 use std::path::Path;
967 use workspace::AppState;
968
969 // Working directory calculation tests
970
971 // No Worktrees in project -> home_dir()
972 #[gpui::test]
973 async fn no_worktree(cx: &mut TestAppContext) {
974 let (project, workspace) = init_test(cx).await;
975 cx.read(|cx| {
976 let workspace = workspace.read(cx);
977 let active_entry = project.read(cx).active_entry();
978
979 //Make sure environment is as expected
980 assert!(active_entry.is_none());
981 assert!(workspace.worktrees(cx).next().is_none());
982
983 let res = current_project_directory(workspace, cx);
984 assert_eq!(res, None);
985 let res = first_project_directory(workspace, cx);
986 assert_eq!(res, None);
987 });
988 }
989
990 // No active entry, but a worktree, worktree is a file -> home_dir()
991 #[gpui::test]
992 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
993 let (project, workspace) = init_test(cx).await;
994
995 create_file_wt(project.clone(), "/root.txt", cx).await;
996 cx.read(|cx| {
997 let workspace = workspace.read(cx);
998 let active_entry = project.read(cx).active_entry();
999
1000 //Make sure environment is as expected
1001 assert!(active_entry.is_none());
1002 assert!(workspace.worktrees(cx).next().is_some());
1003
1004 let res = current_project_directory(workspace, cx);
1005 assert_eq!(res, None);
1006 let res = first_project_directory(workspace, cx);
1007 assert_eq!(res, None);
1008 });
1009 }
1010
1011 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1012 #[gpui::test]
1013 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1014 let (project, workspace) = init_test(cx).await;
1015
1016 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1017 cx.update(|cx| {
1018 let workspace = workspace.read(cx);
1019 let active_entry = project.read(cx).active_entry();
1020
1021 assert!(active_entry.is_none());
1022 assert!(workspace.worktrees(cx).next().is_some());
1023
1024 let res = current_project_directory(workspace, cx);
1025 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1026 let res = first_project_directory(workspace, cx);
1027 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1028 });
1029 }
1030
1031 // Active entry with a work tree, worktree is a file -> home_dir()
1032 #[gpui::test]
1033 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1034 let (project, workspace) = init_test(cx).await;
1035
1036 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1037 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1038 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1039
1040 cx.update(|cx| {
1041 let workspace = workspace.read(cx);
1042 let active_entry = project.read(cx).active_entry();
1043
1044 assert!(active_entry.is_some());
1045
1046 let res = current_project_directory(workspace, cx);
1047 assert_eq!(res, None);
1048 let res = first_project_directory(workspace, cx);
1049 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1050 });
1051 }
1052
1053 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1054 #[gpui::test]
1055 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1056 let (project, workspace) = init_test(cx).await;
1057
1058 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1059 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1060 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1061
1062 cx.update(|cx| {
1063 let workspace = workspace.read(cx);
1064 let active_entry = project.read(cx).active_entry();
1065
1066 assert!(active_entry.is_some());
1067
1068 let res = current_project_directory(workspace, cx);
1069 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1070 let res = first_project_directory(workspace, cx);
1071 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1072 });
1073 }
1074
1075 /// Creates a worktree with 1 file: /root.txt
1076 pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1077 let params = cx.update(AppState::test);
1078 cx.update(|cx| {
1079 theme::init(theme::LoadThemes::JustBase, cx);
1080 Project::init_settings(cx);
1081 language::init(cx);
1082 });
1083
1084 let project = Project::test(params.fs.clone(), [], cx).await;
1085 let workspace = cx
1086 .add_window(|cx| Workspace::test_new(project.clone(), cx))
1087 .root_view(cx)
1088 .unwrap();
1089
1090 (project, workspace)
1091 }
1092
1093 /// Creates a worktree with 1 folder: /root{suffix}/
1094 async fn create_folder_wt(
1095 project: Model<Project>,
1096 path: impl AsRef<Path>,
1097 cx: &mut TestAppContext,
1098 ) -> (Model<Worktree>, Entry) {
1099 create_wt(project, true, path, cx).await
1100 }
1101
1102 /// Creates a worktree with 1 file: /root{suffix}.txt
1103 async fn create_file_wt(
1104 project: Model<Project>,
1105 path: impl AsRef<Path>,
1106 cx: &mut TestAppContext,
1107 ) -> (Model<Worktree>, Entry) {
1108 create_wt(project, false, path, cx).await
1109 }
1110
1111 async fn create_wt(
1112 project: Model<Project>,
1113 is_dir: bool,
1114 path: impl AsRef<Path>,
1115 cx: &mut TestAppContext,
1116 ) -> (Model<Worktree>, Entry) {
1117 let (wt, _) = project
1118 .update(cx, |project, cx| {
1119 project.find_or_create_local_worktree(path, true, cx)
1120 })
1121 .await
1122 .unwrap();
1123
1124 let entry = cx
1125 .update(|cx| {
1126 wt.update(cx, |wt, cx| {
1127 wt.as_local()
1128 .unwrap()
1129 .create_entry(Path::new(""), is_dir, cx)
1130 })
1131 })
1132 .await
1133 .unwrap()
1134 .unwrap();
1135
1136 (wt, entry)
1137 }
1138
1139 pub fn insert_active_entry_for(
1140 wt: Model<Worktree>,
1141 entry: Entry,
1142 project: Model<Project>,
1143 cx: &mut TestAppContext,
1144 ) {
1145 cx.update(|cx| {
1146 let p = ProjectPath {
1147 worktree_id: wt.read(cx).id(),
1148 path: entry.path,
1149 };
1150 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1151 });
1152 }
1153}