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