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