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, TabContentParams},
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 self.terminal.update(cx, |term, cx| {
233 term.try_keystroke(
234 &Keystroke::parse("ctrl-cmd-space").unwrap(),
235 TerminalSettings::get_global(cx).option_as_meta,
236 )
237 });
238 } else {
239 cx.show_character_palette();
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(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
787 let terminal = self.terminal().read(cx);
788 let title = terminal.title(true);
789 let icon = match terminal.task() {
790 Some(terminal_task) => match &terminal_task.status {
791 TaskStatus::Unknown => IconName::ExclamationTriangle,
792 TaskStatus::Running => IconName::Play,
793 TaskStatus::Completed { success } => {
794 if *success {
795 IconName::Check
796 } else {
797 IconName::XCircle
798 }
799 }
800 },
801 None => IconName::Terminal,
802 };
803 h_flex()
804 .gap_2()
805 .child(Icon::new(icon))
806 .child(Label::new(title).color(if params.selected {
807 Color::Default
808 } else {
809 Color::Muted
810 }))
811 .into_any()
812 }
813
814 fn telemetry_event_text(&self) -> Option<&'static str> {
815 None
816 }
817
818 fn clone_on_split(
819 &self,
820 _workspace_id: WorkspaceId,
821 _cx: &mut ViewContext<Self>,
822 ) -> Option<View<Self>> {
823 //From what I can tell, there's no way to tell the current working
824 //Directory of the terminal from outside the shell. There might be
825 //solutions to this, but they are non-trivial and require more IPC
826
827 // Some(TerminalContainer::new(
828 // Err(anyhow::anyhow!("failed to instantiate terminal")),
829 // workspace_id,
830 // cx,
831 // ))
832
833 // TODO
834 None
835 }
836
837 fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
838 match self.terminal.read(cx).task() {
839 Some(task) => task.status == TaskStatus::Running,
840 None => self.has_bell(),
841 }
842 }
843
844 fn has_conflict(&self, _cx: &AppContext) -> bool {
845 false
846 }
847
848 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
849 Some(Box::new(handle.clone()))
850 }
851
852 fn breadcrumb_location(&self) -> ToolbarItemLocation {
853 if self.show_title {
854 ToolbarItemLocation::PrimaryLeft
855 } else {
856 ToolbarItemLocation::Hidden
857 }
858 }
859
860 fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
861 Some(vec![BreadcrumbText {
862 text: self.terminal().read(cx).breadcrumb_text.clone(),
863 highlights: None,
864 }])
865 }
866
867 fn serialized_item_kind() -> Option<&'static str> {
868 Some("Terminal")
869 }
870
871 fn deserialize(
872 project: Model<Project>,
873 workspace: WeakView<Workspace>,
874 workspace_id: workspace::WorkspaceId,
875 item_id: workspace::ItemId,
876 cx: &mut ViewContext<Pane>,
877 ) -> Task<anyhow::Result<View<Self>>> {
878 let window = cx.window_handle();
879 cx.spawn(|pane, mut cx| async move {
880 let cwd = TERMINAL_DB
881 .get_working_directory(item_id, workspace_id)
882 .log_err()
883 .flatten()
884 .or_else(|| {
885 cx.update(|cx| {
886 let strategy = TerminalSettings::get_global(cx).working_directory.clone();
887 workspace.upgrade().and_then(|workspace| {
888 get_working_directory(workspace.read(cx), cx, strategy)
889 })
890 })
891 .ok()
892 .flatten()
893 })
894 .filter(|cwd| !cwd.as_os_str().is_empty());
895
896 let terminal = project.update(&mut cx, |project, cx| {
897 project.create_terminal(cwd, None, window, cx)
898 })??;
899 pane.update(&mut cx, |_, cx| {
900 cx.new_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
901 })
902 })
903 }
904
905 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
906 if self.terminal().read(cx).task().is_none() {
907 cx.background_executor()
908 .spawn(TERMINAL_DB.update_workspace_id(
909 workspace.database_id(),
910 self.workspace_id,
911 cx.entity_id().as_u64(),
912 ))
913 .detach();
914 self.workspace_id = workspace.database_id();
915 }
916 }
917
918 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
919 f(*event)
920 }
921}
922
923impl SearchableItem for TerminalView {
924 type Match = RangeInclusive<Point>;
925
926 fn supported_options() -> SearchOptions {
927 SearchOptions {
928 case: false,
929 word: false,
930 regex: true,
931 replacement: false,
932 }
933 }
934
935 /// Clear stored matches
936 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
937 self.terminal().update(cx, |term, _| term.matches.clear())
938 }
939
940 /// Store matches returned from find_matches somewhere for rendering
941 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
942 self.terminal()
943 .update(cx, |term, _| term.matches = matches.to_vec())
944 }
945
946 /// Returns the selection content to pre-load into this search
947 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
948 self.terminal()
949 .read(cx)
950 .last_content
951 .selection_text
952 .clone()
953 .unwrap_or_default()
954 }
955
956 /// Focus match at given index into the Vec of matches
957 fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
958 self.terminal()
959 .update(cx, |term, _| term.activate_match(index));
960 cx.notify();
961 }
962
963 /// Add selections for all matches given.
964 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
965 self.terminal()
966 .update(cx, |term, _| term.select_matches(matches));
967 cx.notify();
968 }
969
970 /// Get all of the matches for this query, should be done on the background
971 fn find_matches(
972 &mut self,
973 query: Arc<SearchQuery>,
974 cx: &mut ViewContext<Self>,
975 ) -> Task<Vec<Self::Match>> {
976 let searcher = match &*query {
977 SearchQuery::Text { .. } => regex_search_for_query(
978 &(SearchQuery::text(
979 regex_to_literal(&query.as_str()),
980 query.whole_word(),
981 query.case_sensitive(),
982 query.include_ignored(),
983 query.files_to_include().to_vec(),
984 query.files_to_exclude().to_vec(),
985 )
986 .unwrap()),
987 ),
988 SearchQuery::Regex { .. } => regex_search_for_query(&query),
989 };
990
991 if let Some(s) = searcher {
992 self.terminal()
993 .update(cx, |term, cx| term.find_matches(s, cx))
994 } else {
995 Task::ready(vec![])
996 }
997 }
998
999 /// Reports back to the search toolbar what the active match should be (the selection)
1000 fn active_match_index(
1001 &mut self,
1002 matches: &[Self::Match],
1003 cx: &mut ViewContext<Self>,
1004 ) -> Option<usize> {
1005 // Selection head might have a value if there's a selection that isn't
1006 // associated with a match. Therefore, if there are no matches, we should
1007 // report None, no matter the state of the terminal
1008 let res = if matches.len() > 0 {
1009 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1010 // If selection head is contained in a match. Return that match
1011 if let Some(ix) = matches
1012 .iter()
1013 .enumerate()
1014 .find(|(_, search_match)| {
1015 search_match.contains(&selection_head)
1016 || search_match.start() > &selection_head
1017 })
1018 .map(|(ix, _)| ix)
1019 {
1020 Some(ix)
1021 } else {
1022 // If no selection after selection head, return the last match
1023 Some(matches.len().saturating_sub(1))
1024 }
1025 } else {
1026 // Matches found but no active selection, return the first last one (closest to cursor)
1027 Some(matches.len().saturating_sub(1))
1028 }
1029 } else {
1030 None
1031 };
1032
1033 res
1034 }
1035 fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1036 // Replacement is not supported in terminal view, so this is a no-op.
1037 }
1038}
1039
1040///Gets the working directory for the given workspace, respecting the user's settings.
1041pub fn get_working_directory(
1042 workspace: &Workspace,
1043 cx: &AppContext,
1044 strategy: WorkingDirectory,
1045) -> Option<PathBuf> {
1046 let res = match strategy {
1047 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
1048 .or_else(|| first_project_directory(workspace, cx)),
1049 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1050 WorkingDirectory::AlwaysHome => None,
1051 WorkingDirectory::Always { directory } => {
1052 shellexpand::full(&directory) //TODO handle this better
1053 .ok()
1054 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1055 .filter(|dir| dir.is_dir())
1056 }
1057 };
1058 res.or_else(home_dir)
1059}
1060
1061///Gets the first project's home directory, or the home directory
1062fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1063 workspace
1064 .worktrees(cx)
1065 .next()
1066 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
1067 .and_then(get_path_from_wt)
1068}
1069
1070///Gets the intuitively correct working directory from the given workspace
1071///If there is an active entry for this project, returns that entry's worktree root.
1072///If there's no active entry but there is a worktree, returns that worktrees root.
1073///If either of these roots are files, or if there are any other query failures,
1074/// returns the user's home directory
1075fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1076 let project = workspace.project().read(cx);
1077
1078 project
1079 .active_entry()
1080 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
1081 .or_else(|| workspace.worktrees(cx).next())
1082 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
1083 .and_then(get_path_from_wt)
1084}
1085
1086fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
1087 wt.root_entry()
1088 .filter(|re| re.is_dir())
1089 .map(|_| wt.abs_path().to_path_buf())
1090}
1091
1092#[cfg(test)]
1093mod tests {
1094 use super::*;
1095 use gpui::TestAppContext;
1096 use project::{Entry, Project, ProjectPath, Worktree};
1097 use std::path::Path;
1098 use workspace::AppState;
1099
1100 // Working directory calculation tests
1101
1102 // No Worktrees in project -> home_dir()
1103 #[gpui::test]
1104 async fn no_worktree(cx: &mut TestAppContext) {
1105 let (project, workspace) = init_test(cx).await;
1106 cx.read(|cx| {
1107 let workspace = workspace.read(cx);
1108 let active_entry = project.read(cx).active_entry();
1109
1110 //Make sure environment is as expected
1111 assert!(active_entry.is_none());
1112 assert!(workspace.worktrees(cx).next().is_none());
1113
1114 let res = current_project_directory(workspace, cx);
1115 assert_eq!(res, None);
1116 let res = first_project_directory(workspace, cx);
1117 assert_eq!(res, None);
1118 });
1119 }
1120
1121 // No active entry, but a worktree, worktree is a file -> home_dir()
1122 #[gpui::test]
1123 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1124 let (project, workspace) = init_test(cx).await;
1125
1126 create_file_wt(project.clone(), "/root.txt", cx).await;
1127 cx.read(|cx| {
1128 let workspace = workspace.read(cx);
1129 let active_entry = project.read(cx).active_entry();
1130
1131 //Make sure environment is as expected
1132 assert!(active_entry.is_none());
1133 assert!(workspace.worktrees(cx).next().is_some());
1134
1135 let res = current_project_directory(workspace, cx);
1136 assert_eq!(res, None);
1137 let res = first_project_directory(workspace, cx);
1138 assert_eq!(res, None);
1139 });
1140 }
1141
1142 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1143 #[gpui::test]
1144 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1145 let (project, workspace) = init_test(cx).await;
1146
1147 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1148 cx.update(|cx| {
1149 let workspace = workspace.read(cx);
1150 let active_entry = project.read(cx).active_entry();
1151
1152 assert!(active_entry.is_none());
1153 assert!(workspace.worktrees(cx).next().is_some());
1154
1155 let res = current_project_directory(workspace, cx);
1156 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1157 let res = first_project_directory(workspace, cx);
1158 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1159 });
1160 }
1161
1162 // Active entry with a work tree, worktree is a file -> home_dir()
1163 #[gpui::test]
1164 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1165 let (project, workspace) = init_test(cx).await;
1166
1167 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1168 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1169 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1170
1171 cx.update(|cx| {
1172 let workspace = workspace.read(cx);
1173 let active_entry = project.read(cx).active_entry();
1174
1175 assert!(active_entry.is_some());
1176
1177 let res = current_project_directory(workspace, cx);
1178 assert_eq!(res, None);
1179 let res = first_project_directory(workspace, cx);
1180 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1181 });
1182 }
1183
1184 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1185 #[gpui::test]
1186 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1187 let (project, workspace) = init_test(cx).await;
1188
1189 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1190 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1191 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1192
1193 cx.update(|cx| {
1194 let workspace = workspace.read(cx);
1195 let active_entry = project.read(cx).active_entry();
1196
1197 assert!(active_entry.is_some());
1198
1199 let res = current_project_directory(workspace, cx);
1200 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1201 let res = first_project_directory(workspace, cx);
1202 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1203 });
1204 }
1205
1206 /// Creates a worktree with 1 file: /root.txt
1207 pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1208 let params = cx.update(AppState::test);
1209 cx.update(|cx| {
1210 theme::init(theme::LoadThemes::JustBase, cx);
1211 Project::init_settings(cx);
1212 language::init(cx);
1213 });
1214
1215 let project = Project::test(params.fs.clone(), [], cx).await;
1216 let workspace = cx
1217 .add_window(|cx| Workspace::test_new(project.clone(), cx))
1218 .root_view(cx)
1219 .unwrap();
1220
1221 (project, workspace)
1222 }
1223
1224 /// Creates a worktree with 1 folder: /root{suffix}/
1225 async fn create_folder_wt(
1226 project: Model<Project>,
1227 path: impl AsRef<Path>,
1228 cx: &mut TestAppContext,
1229 ) -> (Model<Worktree>, Entry) {
1230 create_wt(project, true, path, cx).await
1231 }
1232
1233 /// Creates a worktree with 1 file: /root{suffix}.txt
1234 async fn create_file_wt(
1235 project: Model<Project>,
1236 path: impl AsRef<Path>,
1237 cx: &mut TestAppContext,
1238 ) -> (Model<Worktree>, Entry) {
1239 create_wt(project, false, path, cx).await
1240 }
1241
1242 async fn create_wt(
1243 project: Model<Project>,
1244 is_dir: bool,
1245 path: impl AsRef<Path>,
1246 cx: &mut TestAppContext,
1247 ) -> (Model<Worktree>, Entry) {
1248 let (wt, _) = project
1249 .update(cx, |project, cx| {
1250 project.find_or_create_local_worktree(path, true, cx)
1251 })
1252 .await
1253 .unwrap();
1254
1255 let entry = cx
1256 .update(|cx| {
1257 wt.update(cx, |wt, cx| {
1258 wt.as_local()
1259 .unwrap()
1260 .create_entry(Path::new(""), is_dir, cx)
1261 })
1262 })
1263 .await
1264 .unwrap()
1265 .unwrap();
1266
1267 (wt, entry)
1268 }
1269
1270 pub fn insert_active_entry_for(
1271 wt: Model<Worktree>,
1272 entry: Entry,
1273 project: Model<Project>,
1274 cx: &mut TestAppContext,
1275 ) {
1276 cx.update(|cx| {
1277 let p = ProjectPath {
1278 worktree_id: wt.read(cx).id(),
1279 path: entry.path,
1280 };
1281 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1282 });
1283 }
1284
1285 #[test]
1286 fn escapes_only_special_characters() {
1287 assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1288 }
1289
1290 #[test]
1291 fn empty_string_stays_empty() {
1292 assert_eq!(regex_to_literal(""), "".to_string());
1293 }
1294}