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