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 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, TaskStatus, 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(cwd) = terminal.get_cwd() {
459 let item_id = cx.entity_id();
460 let workspace_id = this.workspace_id;
461 cx.background_executor()
462 .spawn(async move {
463 TERMINAL_DB
464 .save_working_directory(item_id.as_u64(), workspace_id, cwd)
465 .await
466 .log_err();
467 })
468 .detach();
469 }
470 }
471 }
472
473 Event::NewNavigationTarget(maybe_navigation_target) => {
474 this.can_navigate_to_selected_word = match maybe_navigation_target {
475 Some(MaybeNavigationTarget::Url(_)) => true,
476 Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
477 if let Ok(fs) = workspace.update(cx, |workspace, cx| {
478 workspace.project().read(cx).fs().clone()
479 }) {
480 let valid_files_to_open_task = possible_open_targets(
481 fs,
482 &workspace,
483 &path_like_target.terminal_dir,
484 &path_like_target.maybe_path,
485 cx,
486 );
487 smol::block_on(valid_files_to_open_task).len() > 0
488 } else {
489 false
490 }
491 }
492 None => false,
493 }
494 }
495
496 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
497 MaybeNavigationTarget::Url(url) => cx.open_url(url),
498
499 MaybeNavigationTarget::PathLike(path_like_target) => {
500 if !this.can_navigate_to_selected_word {
501 return;
502 }
503 let task_workspace = workspace.clone();
504 let Some(fs) = workspace
505 .update(cx, |workspace, cx| {
506 workspace.project().read(cx).fs().clone()
507 })
508 .ok()
509 else {
510 return;
511 };
512
513 let path_like_target = path_like_target.clone();
514 cx.spawn(|terminal_view, mut cx| async move {
515 let valid_files_to_open = terminal_view
516 .update(&mut cx, |_, cx| {
517 possible_open_targets(
518 fs,
519 &task_workspace,
520 &path_like_target.terminal_dir,
521 &path_like_target.maybe_path,
522 cx,
523 )
524 })?
525 .await;
526 let paths_to_open = valid_files_to_open
527 .iter()
528 .map(|(p, _)| p.path_like.clone())
529 .collect();
530 let opened_items = task_workspace
531 .update(&mut cx, |workspace, cx| {
532 workspace.open_paths(
533 paths_to_open,
534 OpenVisible::OnlyDirectories,
535 None,
536 cx,
537 )
538 })
539 .context("workspace update")?
540 .await;
541
542 let mut has_dirs = false;
543 for ((path, metadata), opened_item) in valid_files_to_open
544 .into_iter()
545 .zip(opened_items.into_iter())
546 {
547 if metadata.is_dir {
548 has_dirs = true;
549 } else if let Some(Ok(opened_item)) = opened_item {
550 if let Some(row) = path.row {
551 let col = path.column.unwrap_or(0);
552 if let Some(active_editor) = opened_item.downcast::<Editor>() {
553 active_editor
554 .downgrade()
555 .update(&mut cx, |editor, cx| {
556 let snapshot = editor.snapshot(cx).display_snapshot;
557 let point = snapshot.buffer_snapshot.clip_point(
558 language::Point::new(
559 row.saturating_sub(1),
560 col.saturating_sub(1),
561 ),
562 Bias::Left,
563 );
564 editor.change_selections(
565 Some(Autoscroll::center()),
566 cx,
567 |s| s.select_ranges([point..point]),
568 );
569 })
570 .log_err();
571 }
572 }
573 }
574 }
575
576 if has_dirs {
577 task_workspace.update(&mut cx, |workspace, cx| {
578 workspace.project().update(cx, |_, cx| {
579 cx.emit(project::Event::ActivateProjectPanel);
580 })
581 })?;
582 }
583
584 anyhow::Ok(())
585 })
586 .detach_and_log_err(cx)
587 }
588 },
589 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
590 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
591 Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
592 });
593 vec![terminal_subscription, terminal_events_subscription]
594}
595
596fn possible_open_paths_metadata(
597 fs: Arc<dyn Fs>,
598 row: Option<u32>,
599 column: Option<u32>,
600 potential_paths: HashSet<PathBuf>,
601 cx: &mut ViewContext<TerminalView>,
602) -> Task<Vec<(PathLikeWithPosition<PathBuf>, Metadata)>> {
603 cx.background_executor().spawn(async move {
604 let mut paths_with_metadata = Vec::with_capacity(potential_paths.len());
605
606 let mut fetch_metadata_tasks = potential_paths
607 .into_iter()
608 .map(|potential_path| async {
609 let metadata = fs.metadata(&potential_path).await.ok().flatten();
610 (
611 PathLikeWithPosition {
612 path_like: potential_path,
613 row,
614 column,
615 },
616 metadata,
617 )
618 })
619 .collect::<FuturesUnordered<_>>();
620
621 while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
622 if let Some(metadata) = metadata {
623 paths_with_metadata.push((path, metadata));
624 }
625 }
626
627 paths_with_metadata
628 })
629}
630
631fn possible_open_targets(
632 fs: Arc<dyn Fs>,
633 workspace: &WeakView<Workspace>,
634 cwd: &Option<PathBuf>,
635 maybe_path: &String,
636 cx: &mut ViewContext<TerminalView>,
637) -> Task<Vec<(PathLikeWithPosition<PathBuf>, Metadata)>> {
638 let path_like = PathLikeWithPosition::parse_str(maybe_path.as_str(), |path_str| {
639 Ok::<_, std::convert::Infallible>(Path::new(path_str).to_path_buf())
640 })
641 .expect("infallible");
642 let row = path_like.row;
643 let column = path_like.column;
644 let maybe_path = path_like.path_like;
645 let potential_abs_paths = if maybe_path.is_absolute() {
646 HashSet::from_iter([maybe_path])
647 } else if maybe_path.starts_with("~") {
648 if let Some(abs_path) = maybe_path
649 .strip_prefix("~")
650 .ok()
651 .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
652 {
653 HashSet::from_iter([abs_path])
654 } else {
655 HashSet::default()
656 }
657 } else {
658 // First check cwd and then workspace
659 let mut potential_cwd_and_workspace_paths = HashSet::default();
660 if let Some(cwd) = cwd {
661 potential_cwd_and_workspace_paths.insert(Path::join(cwd, &maybe_path));
662 }
663 if let Some(workspace) = workspace.upgrade() {
664 workspace.update(cx, |workspace, cx| {
665 for potential_worktree_path in workspace
666 .worktrees(cx)
667 .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
668 {
669 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
670 }
671 });
672 }
673 potential_cwd_and_workspace_paths
674 };
675
676 possible_open_paths_metadata(fs, row, column, potential_abs_paths, cx)
677}
678
679fn regex_to_literal(regex: &str) -> String {
680 regex
681 .chars()
682 .flat_map(|c| {
683 if REGEX_SPECIAL_CHARS.contains(&c) {
684 vec!['\\', c]
685 } else {
686 vec![c]
687 }
688 })
689 .collect()
690}
691
692pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
693 let query = query.as_str();
694 if query == "." {
695 return None;
696 }
697 let searcher = RegexSearch::new(&query);
698 searcher.ok()
699}
700
701impl TerminalView {
702 fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) {
703 self.clear_bel(cx);
704 self.pause_cursor_blinking(cx);
705
706 self.terminal.update(cx, |term, cx| {
707 term.try_keystroke(
708 &event.keystroke,
709 TerminalSettings::get_global(cx).option_as_meta,
710 )
711 });
712 }
713
714 fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
715 self.terminal.read(cx).focus_in();
716 self.blink_cursors(self.blink_epoch, cx);
717 cx.notify();
718 }
719
720 fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
721 self.terminal.update(cx, |terminal, _| {
722 terminal.focus_out();
723 });
724 cx.notify();
725 }
726}
727
728impl Render for TerminalView {
729 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
730 let terminal_handle = self.terminal.clone();
731
732 let focused = self.focus_handle.is_focused(cx);
733
734 div()
735 .size_full()
736 .relative()
737 .track_focus(&self.focus_handle)
738 .key_context(self.dispatch_context(cx))
739 .on_action(cx.listener(TerminalView::send_text))
740 .on_action(cx.listener(TerminalView::send_keystroke))
741 .on_action(cx.listener(TerminalView::copy))
742 .on_action(cx.listener(TerminalView::paste))
743 .on_action(cx.listener(TerminalView::clear))
744 .on_action(cx.listener(TerminalView::show_character_palette))
745 .on_action(cx.listener(TerminalView::select_all))
746 .on_key_down(cx.listener(Self::key_down))
747 .on_mouse_down(
748 MouseButton::Right,
749 cx.listener(|this, event: &MouseDownEvent, cx| {
750 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
751 this.deploy_context_menu(event.position, cx);
752 cx.notify();
753 }
754 }),
755 )
756 .child(
757 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
758 div().size_full().child(TerminalElement::new(
759 terminal_handle,
760 self.workspace.clone(),
761 self.focus_handle.clone(),
762 focused,
763 self.should_show_cursor(focused, cx),
764 self.can_navigate_to_selected_word,
765 )),
766 )
767 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
768 deferred(
769 anchored()
770 .position(*position)
771 .anchor(gpui::AnchorCorner::TopLeft)
772 .child(menu.clone()),
773 )
774 .with_priority(1)
775 }))
776 }
777}
778
779impl Item for TerminalView {
780 type Event = ItemEvent;
781
782 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
783 Some(self.terminal().read(cx).title(false).into())
784 }
785
786 fn tab_content(
787 &self,
788 _detail: Option<usize>,
789 selected: bool,
790 cx: &WindowContext,
791 ) -> AnyElement {
792 let terminal = self.terminal().read(cx);
793 let title = terminal.title(true);
794 let icon = match terminal.task() {
795 Some(terminal_task) => match &terminal_task.status {
796 TaskStatus::Unknown => IconName::ExclamationTriangle,
797 TaskStatus::Running => IconName::Play,
798 TaskStatus::Completed { success } => {
799 if *success {
800 IconName::Check
801 } else {
802 IconName::XCircle
803 }
804 }
805 },
806 None => IconName::Terminal,
807 };
808 h_flex()
809 .gap_2()
810 .child(Icon::new(icon))
811 .child(Label::new(title).color(if selected {
812 Color::Default
813 } else {
814 Color::Muted
815 }))
816 .into_any()
817 }
818
819 fn telemetry_event_text(&self) -> Option<&'static str> {
820 None
821 }
822
823 fn clone_on_split(
824 &self,
825 _workspace_id: WorkspaceId,
826 _cx: &mut ViewContext<Self>,
827 ) -> Option<View<Self>> {
828 //From what I can tell, there's no way to tell the current working
829 //Directory of the terminal from outside the shell. There might be
830 //solutions to this, but they are non-trivial and require more IPC
831
832 // Some(TerminalContainer::new(
833 // Err(anyhow::anyhow!("failed to instantiate terminal")),
834 // workspace_id,
835 // cx,
836 // ))
837
838 // TODO
839 None
840 }
841
842 fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
843 match self.terminal.read(cx).task() {
844 Some(task) => task.status == TaskStatus::Running,
845 None => self.has_bell(),
846 }
847 }
848
849 fn has_conflict(&self, _cx: &AppContext) -> bool {
850 false
851 }
852
853 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
854 Some(Box::new(handle.clone()))
855 }
856
857 fn breadcrumb_location(&self) -> ToolbarItemLocation {
858 if self.show_title {
859 ToolbarItemLocation::PrimaryLeft
860 } else {
861 ToolbarItemLocation::Hidden
862 }
863 }
864
865 fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
866 Some(vec![BreadcrumbText {
867 text: self.terminal().read(cx).breadcrumb_text.clone(),
868 highlights: None,
869 font: None,
870 }])
871 }
872
873 fn serialized_item_kind() -> Option<&'static str> {
874 Some("Terminal")
875 }
876
877 fn deserialize(
878 project: Model<Project>,
879 workspace: WeakView<Workspace>,
880 workspace_id: workspace::WorkspaceId,
881 item_id: workspace::ItemId,
882 cx: &mut ViewContext<Pane>,
883 ) -> Task<anyhow::Result<View<Self>>> {
884 let window = cx.window_handle();
885 cx.spawn(|pane, mut cx| async move {
886 let cwd = TERMINAL_DB
887 .get_working_directory(item_id, workspace_id)
888 .log_err()
889 .flatten()
890 .or_else(|| {
891 cx.update(|cx| {
892 let strategy = TerminalSettings::get_global(cx).working_directory.clone();
893 workspace.upgrade().and_then(|workspace| {
894 get_working_directory(workspace.read(cx), cx, strategy)
895 })
896 })
897 .ok()
898 .flatten()
899 })
900 .filter(|cwd| !cwd.as_os_str().is_empty());
901
902 let terminal = project.update(&mut cx, |project, cx| {
903 project.create_terminal(cwd, None, window, cx)
904 })??;
905 pane.update(&mut cx, |_, cx| {
906 cx.new_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
907 })
908 })
909 }
910
911 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
912 if self.terminal().read(cx).task().is_none() {
913 cx.background_executor()
914 .spawn(TERMINAL_DB.update_workspace_id(
915 workspace.database_id(),
916 self.workspace_id,
917 cx.entity_id().as_u64(),
918 ))
919 .detach();
920 self.workspace_id = workspace.database_id();
921 }
922 }
923
924 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
925 f(*event)
926 }
927}
928
929impl SearchableItem for TerminalView {
930 type Match = RangeInclusive<Point>;
931
932 fn supported_options() -> SearchOptions {
933 SearchOptions {
934 case: false,
935 word: false,
936 regex: true,
937 replacement: false,
938 }
939 }
940
941 /// Clear stored matches
942 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
943 self.terminal().update(cx, |term, _| term.matches.clear())
944 }
945
946 /// Store matches returned from find_matches somewhere for rendering
947 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
948 self.terminal()
949 .update(cx, |term, _| term.matches = matches.to_vec())
950 }
951
952 /// Returns the selection content to pre-load into this search
953 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
954 self.terminal()
955 .read(cx)
956 .last_content
957 .selection_text
958 .clone()
959 .unwrap_or_default()
960 }
961
962 /// Focus match at given index into the Vec of matches
963 fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
964 self.terminal()
965 .update(cx, |term, _| term.activate_match(index));
966 cx.notify();
967 }
968
969 /// Add selections for all matches given.
970 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
971 self.terminal()
972 .update(cx, |term, _| term.select_matches(matches));
973 cx.notify();
974 }
975
976 /// Get all of the matches for this query, should be done on the background
977 fn find_matches(
978 &mut self,
979 query: Arc<SearchQuery>,
980 cx: &mut ViewContext<Self>,
981 ) -> Task<Vec<Self::Match>> {
982 let searcher = match &*query {
983 SearchQuery::Text { .. } => regex_search_for_query(
984 &(SearchQuery::text(
985 regex_to_literal(&query.as_str()),
986 query.whole_word(),
987 query.case_sensitive(),
988 query.include_ignored(),
989 query.files_to_include().to_vec(),
990 query.files_to_exclude().to_vec(),
991 )
992 .unwrap()),
993 ),
994 SearchQuery::Regex { .. } => regex_search_for_query(&query),
995 };
996
997 if let Some(s) = searcher {
998 self.terminal()
999 .update(cx, |term, cx| term.find_matches(s, cx))
1000 } else {
1001 Task::ready(vec![])
1002 }
1003 }
1004
1005 /// Reports back to the search toolbar what the active match should be (the selection)
1006 fn active_match_index(
1007 &mut self,
1008 matches: &[Self::Match],
1009 cx: &mut ViewContext<Self>,
1010 ) -> Option<usize> {
1011 // Selection head might have a value if there's a selection that isn't
1012 // associated with a match. Therefore, if there are no matches, we should
1013 // report None, no matter the state of the terminal
1014 let res = if matches.len() > 0 {
1015 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1016 // If selection head is contained in a match. Return that match
1017 if let Some(ix) = matches
1018 .iter()
1019 .enumerate()
1020 .find(|(_, search_match)| {
1021 search_match.contains(&selection_head)
1022 || search_match.start() > &selection_head
1023 })
1024 .map(|(ix, _)| ix)
1025 {
1026 Some(ix)
1027 } else {
1028 // If no selection after selection head, return the last match
1029 Some(matches.len().saturating_sub(1))
1030 }
1031 } else {
1032 // Matches found but no active selection, return the first last one (closest to cursor)
1033 Some(matches.len().saturating_sub(1))
1034 }
1035 } else {
1036 None
1037 };
1038
1039 res
1040 }
1041 fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1042 // Replacement is not supported in terminal view, so this is a no-op.
1043 }
1044}
1045
1046///Gets the working directory for the given workspace, respecting the user's settings.
1047pub fn get_working_directory(
1048 workspace: &Workspace,
1049 cx: &AppContext,
1050 strategy: WorkingDirectory,
1051) -> Option<PathBuf> {
1052 let res = match strategy {
1053 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
1054 .or_else(|| first_project_directory(workspace, cx)),
1055 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1056 WorkingDirectory::AlwaysHome => None,
1057 WorkingDirectory::Always { directory } => {
1058 shellexpand::full(&directory) //TODO handle this better
1059 .ok()
1060 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1061 .filter(|dir| dir.is_dir())
1062 }
1063 };
1064 res.or_else(home_dir)
1065}
1066
1067///Gets the first project's home directory, or the home directory
1068fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1069 workspace
1070 .worktrees(cx)
1071 .next()
1072 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
1073 .and_then(get_path_from_wt)
1074}
1075
1076///Gets the intuitively correct working directory from the given workspace
1077///If there is an active entry for this project, returns that entry's worktree root.
1078///If there's no active entry but there is a worktree, returns that worktrees root.
1079///If either of these roots are files, or if there are any other query failures,
1080/// returns the user's home directory
1081fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1082 let project = workspace.project().read(cx);
1083
1084 project
1085 .active_entry()
1086 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
1087 .or_else(|| workspace.worktrees(cx).next())
1088 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
1089 .and_then(get_path_from_wt)
1090}
1091
1092fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
1093 wt.root_entry()
1094 .filter(|re| re.is_dir())
1095 .map(|_| wt.abs_path().to_path_buf())
1096}
1097
1098#[cfg(test)]
1099mod tests {
1100 use super::*;
1101 use gpui::TestAppContext;
1102 use project::{Entry, Project, ProjectPath, Worktree};
1103 use std::path::Path;
1104 use workspace::AppState;
1105
1106 // Working directory calculation tests
1107
1108 // No Worktrees in project -> home_dir()
1109 #[gpui::test]
1110 async fn no_worktree(cx: &mut TestAppContext) {
1111 let (project, workspace) = init_test(cx).await;
1112 cx.read(|cx| {
1113 let workspace = workspace.read(cx);
1114 let active_entry = project.read(cx).active_entry();
1115
1116 //Make sure environment is as expected
1117 assert!(active_entry.is_none());
1118 assert!(workspace.worktrees(cx).next().is_none());
1119
1120 let res = current_project_directory(workspace, cx);
1121 assert_eq!(res, None);
1122 let res = first_project_directory(workspace, cx);
1123 assert_eq!(res, None);
1124 });
1125 }
1126
1127 // No active entry, but a worktree, worktree is a file -> home_dir()
1128 #[gpui::test]
1129 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1130 let (project, workspace) = init_test(cx).await;
1131
1132 create_file_wt(project.clone(), "/root.txt", cx).await;
1133 cx.read(|cx| {
1134 let workspace = workspace.read(cx);
1135 let active_entry = project.read(cx).active_entry();
1136
1137 //Make sure environment is as expected
1138 assert!(active_entry.is_none());
1139 assert!(workspace.worktrees(cx).next().is_some());
1140
1141 let res = current_project_directory(workspace, cx);
1142 assert_eq!(res, None);
1143 let res = first_project_directory(workspace, cx);
1144 assert_eq!(res, None);
1145 });
1146 }
1147
1148 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1149 #[gpui::test]
1150 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1151 let (project, workspace) = init_test(cx).await;
1152
1153 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1154 cx.update(|cx| {
1155 let workspace = workspace.read(cx);
1156 let active_entry = project.read(cx).active_entry();
1157
1158 assert!(active_entry.is_none());
1159 assert!(workspace.worktrees(cx).next().is_some());
1160
1161 let res = current_project_directory(workspace, cx);
1162 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1163 let res = first_project_directory(workspace, cx);
1164 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1165 });
1166 }
1167
1168 // Active entry with a work tree, worktree is a file -> home_dir()
1169 #[gpui::test]
1170 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1171 let (project, workspace) = init_test(cx).await;
1172
1173 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1174 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1175 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1176
1177 cx.update(|cx| {
1178 let workspace = workspace.read(cx);
1179 let active_entry = project.read(cx).active_entry();
1180
1181 assert!(active_entry.is_some());
1182
1183 let res = current_project_directory(workspace, cx);
1184 assert_eq!(res, None);
1185 let res = first_project_directory(workspace, cx);
1186 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1187 });
1188 }
1189
1190 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1191 #[gpui::test]
1192 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1193 let (project, workspace) = init_test(cx).await;
1194
1195 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1196 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1197 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1198
1199 cx.update(|cx| {
1200 let workspace = workspace.read(cx);
1201 let active_entry = project.read(cx).active_entry();
1202
1203 assert!(active_entry.is_some());
1204
1205 let res = current_project_directory(workspace, cx);
1206 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1207 let res = first_project_directory(workspace, cx);
1208 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1209 });
1210 }
1211
1212 /// Creates a worktree with 1 file: /root.txt
1213 pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1214 let params = cx.update(AppState::test);
1215 cx.update(|cx| {
1216 theme::init(theme::LoadThemes::JustBase, cx);
1217 Project::init_settings(cx);
1218 language::init(cx);
1219 });
1220
1221 let project = Project::test(params.fs.clone(), [], cx).await;
1222 let workspace = cx
1223 .add_window(|cx| Workspace::test_new(project.clone(), cx))
1224 .root_view(cx)
1225 .unwrap();
1226
1227 (project, workspace)
1228 }
1229
1230 /// Creates a worktree with 1 folder: /root{suffix}/
1231 async fn create_folder_wt(
1232 project: Model<Project>,
1233 path: impl AsRef<Path>,
1234 cx: &mut TestAppContext,
1235 ) -> (Model<Worktree>, Entry) {
1236 create_wt(project, true, path, cx).await
1237 }
1238
1239 /// Creates a worktree with 1 file: /root{suffix}.txt
1240 async fn create_file_wt(
1241 project: Model<Project>,
1242 path: impl AsRef<Path>,
1243 cx: &mut TestAppContext,
1244 ) -> (Model<Worktree>, Entry) {
1245 create_wt(project, false, path, cx).await
1246 }
1247
1248 async fn create_wt(
1249 project: Model<Project>,
1250 is_dir: bool,
1251 path: impl AsRef<Path>,
1252 cx: &mut TestAppContext,
1253 ) -> (Model<Worktree>, Entry) {
1254 let (wt, _) = project
1255 .update(cx, |project, cx| {
1256 project.find_or_create_local_worktree(path, true, cx)
1257 })
1258 .await
1259 .unwrap();
1260
1261 let entry = cx
1262 .update(|cx| {
1263 wt.update(cx, |wt, cx| {
1264 wt.as_local()
1265 .unwrap()
1266 .create_entry(Path::new(""), is_dir, cx)
1267 })
1268 })
1269 .await
1270 .unwrap()
1271 .unwrap();
1272
1273 (wt, entry)
1274 }
1275
1276 pub fn insert_active_entry_for(
1277 wt: Model<Worktree>,
1278 entry: Entry,
1279 project: Model<Project>,
1280 cx: &mut TestAppContext,
1281 ) {
1282 cx.update(|cx| {
1283 let p = ProjectPath {
1284 worktree_id: wt.read(cx).id(),
1285 path: entry.path,
1286 };
1287 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1288 });
1289 }
1290
1291 #[test]
1292 fn escapes_only_special_characters() {
1293 assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1294 }
1295
1296 #[test]
1297 fn empty_string_stays_empty() {
1298 assert_eq!(regex_to_literal(""), "".to_string());
1299 }
1300}