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