1mod persistence;
2pub mod terminal_element;
3pub mod terminal_panel;
4mod terminal_path_like_target;
5pub mod terminal_scrollbar;
6mod terminal_slash_command;
7
8use assistant_slash_command::SlashCommandRegistry;
9use editor::{EditorSettings, actions::SelectAll, blink_manager::BlinkManager};
10use gpui::{
11 Action, AnyElement, App, ClipboardEntry, DismissEvent, Entity, EventEmitter, FocusHandle,
12 Focusable, KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render,
13 ScrollWheelEvent, Styled, Subscription, Task, WeakEntity, actions, anchored, deferred, div,
14};
15use persistence::TERMINAL_DB;
16use project::{Project, search::SearchQuery};
17use schemars::JsonSchema;
18use task::TaskId;
19use terminal::{
20 Clear, Copy, Event, HoveredWord, MaybeNavigationTarget, Paste, ScrollLineDown, ScrollLineUp,
21 ScrollPageDown, ScrollPageUp, ScrollToBottom, ScrollToTop, ShowCharacterPalette, TaskState,
22 TaskStatus, Terminal, TerminalBounds, ToggleViMode,
23 alacritty_terminal::{
24 index::Point,
25 term::{TermMode, point_to_viewport, search::RegexSearch},
26 },
27 terminal_settings::{CursorShape, TerminalSettings},
28};
29use terminal_element::TerminalElement;
30use terminal_panel::TerminalPanel;
31use terminal_path_like_target::{hover_path_like_target, open_path_like_target};
32use terminal_scrollbar::TerminalScrollHandle;
33use terminal_slash_command::TerminalSlashCommand;
34use ui::{
35 ContextMenu, Divider, ScrollAxes, Scrollbars, Tooltip, WithScrollbar,
36 prelude::*,
37 scrollbars::{self, GlobalSetting, ScrollbarVisibility},
38};
39use util::ResultExt;
40use workspace::{
41 CloseActiveItem, NewCenterTerminal, NewTerminal, ToolbarItemLocation, Workspace, WorkspaceId,
42 delete_unloaded_items,
43 item::{
44 BreadcrumbText, Item, ItemEvent, SerializableItem, TabContentParams, TabTooltipContent,
45 },
46 register_serializable_item,
47 searchable::{Direction, SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
48};
49
50use serde::Deserialize;
51use settings::{Settings, SettingsStore, TerminalBlink, WorkingDirectory};
52use zed_actions::assistant::InlineAssist;
53
54use std::{
55 cmp,
56 ops::{Range, RangeInclusive},
57 path::{Path, PathBuf},
58 rc::Rc,
59 sync::Arc,
60 time::Duration,
61};
62
63struct ImeState {
64 marked_text: String,
65 marked_range_utf16: Option<Range<usize>>,
66}
67
68const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
69
70/// Event to transmit the scroll from the element to the view
71#[derive(Clone, Debug, PartialEq)]
72pub struct ScrollTerminal(pub i32);
73
74/// Sends the specified text directly to the terminal.
75#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
76#[action(namespace = terminal)]
77pub struct SendText(String);
78
79/// Sends a keystroke sequence to the terminal.
80#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
81#[action(namespace = terminal)]
82pub struct SendKeystroke(String);
83
84actions!(
85 terminal,
86 [
87 /// Reruns the last executed task in the terminal.
88 RerunTask
89 ]
90);
91
92pub fn init(cx: &mut App) {
93 assistant_slash_command::init(cx);
94 terminal_panel::init(cx);
95
96 register_serializable_item::<TerminalView>(cx);
97
98 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
99 workspace.register_action(TerminalView::deploy);
100 })
101 .detach();
102 SlashCommandRegistry::global(cx).register_command(TerminalSlashCommand, true);
103}
104
105pub struct BlockProperties {
106 pub height: u8,
107 pub render: Box<dyn Send + Fn(&mut BlockContext) -> AnyElement>,
108}
109
110pub struct BlockContext<'a, 'b> {
111 pub window: &'a mut Window,
112 pub context: &'b mut App,
113 pub dimensions: TerminalBounds,
114}
115
116///A terminal view, maintains the PTY's file handles and communicates with the terminal
117pub struct TerminalView {
118 terminal: Entity<Terminal>,
119 workspace: WeakEntity<Workspace>,
120 project: WeakEntity<Project>,
121 focus_handle: FocusHandle,
122 //Currently using iTerm bell, show bell emoji in tab until input is received
123 has_bell: bool,
124 context_menu: Option<(Entity<ContextMenu>, gpui::Point<Pixels>, Subscription)>,
125 cursor_shape: CursorShape,
126 blink_manager: Entity<BlinkManager>,
127 mode: TerminalMode,
128 blinking_terminal_enabled: bool,
129 cwd_serialized: bool,
130 hover: Option<HoverTarget>,
131 hover_tooltip_update: Task<()>,
132 workspace_id: Option<WorkspaceId>,
133 show_breadcrumbs: bool,
134 block_below_cursor: Option<Rc<BlockProperties>>,
135 scroll_top: Pixels,
136 scroll_handle: TerminalScrollHandle,
137 ime_state: Option<ImeState>,
138 _subscriptions: Vec<Subscription>,
139 _terminal_subscriptions: Vec<Subscription>,
140}
141
142#[derive(Default, Clone)]
143pub enum TerminalMode {
144 #[default]
145 Standalone,
146 Embedded {
147 max_lines_when_unfocused: Option<usize>,
148 },
149}
150
151#[derive(Clone)]
152pub enum ContentMode {
153 Scrollable,
154 Inline {
155 displayed_lines: usize,
156 total_lines: usize,
157 },
158}
159
160impl ContentMode {
161 pub fn is_limited(&self) -> bool {
162 match self {
163 ContentMode::Scrollable => false,
164 ContentMode::Inline {
165 displayed_lines,
166 total_lines,
167 } => displayed_lines < total_lines,
168 }
169 }
170
171 pub fn is_scrollable(&self) -> bool {
172 matches!(self, ContentMode::Scrollable)
173 }
174}
175
176#[derive(Debug)]
177#[cfg_attr(test, derive(Clone, Eq, PartialEq))]
178struct HoverTarget {
179 tooltip: String,
180 hovered_word: HoveredWord,
181}
182
183impl EventEmitter<Event> for TerminalView {}
184impl EventEmitter<ItemEvent> for TerminalView {}
185impl EventEmitter<SearchEvent> for TerminalView {}
186
187impl Focusable for TerminalView {
188 fn focus_handle(&self, _cx: &App) -> FocusHandle {
189 self.focus_handle.clone()
190 }
191}
192
193impl TerminalView {
194 ///Create a new Terminal in the current working directory or the user's home directory
195 pub fn deploy(
196 workspace: &mut Workspace,
197 _: &NewCenterTerminal,
198 window: &mut Window,
199 cx: &mut Context<Workspace>,
200 ) {
201 let working_directory = default_working_directory(workspace, cx);
202 TerminalPanel::add_center_terminal(workspace, window, cx, |project, cx| {
203 project.create_terminal_shell(working_directory, cx)
204 })
205 .detach_and_log_err(cx);
206 }
207
208 pub fn new(
209 terminal: Entity<Terminal>,
210 workspace: WeakEntity<Workspace>,
211 workspace_id: Option<WorkspaceId>,
212 project: WeakEntity<Project>,
213 window: &mut Window,
214 cx: &mut Context<Self>,
215 ) -> Self {
216 let workspace_handle = workspace.clone();
217 let terminal_subscriptions =
218 subscribe_for_terminal_events(&terminal, workspace, window, cx);
219
220 let focus_handle = cx.focus_handle();
221 let focus_in = cx.on_focus_in(&focus_handle, window, |terminal_view, window, cx| {
222 terminal_view.focus_in(window, cx);
223 });
224 let focus_out = cx.on_focus_out(
225 &focus_handle,
226 window,
227 |terminal_view, _event, window, cx| {
228 terminal_view.focus_out(window, cx);
229 },
230 );
231 let cursor_shape = TerminalSettings::get_global(cx).cursor_shape;
232
233 let scroll_handle = TerminalScrollHandle::new(terminal.read(cx));
234
235 let blink_manager = cx.new(|cx| {
236 BlinkManager::new(
237 CURSOR_BLINK_INTERVAL,
238 |cx| {
239 !matches!(
240 TerminalSettings::get_global(cx).blinking,
241 TerminalBlink::Off
242 )
243 },
244 cx,
245 )
246 });
247
248 let _subscriptions = vec![
249 focus_in,
250 focus_out,
251 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
252 cx.observe_global::<SettingsStore>(Self::settings_changed),
253 ];
254 Self {
255 terminal,
256 workspace: workspace_handle,
257 project,
258 has_bell: false,
259 focus_handle,
260 context_menu: None,
261 cursor_shape,
262 blink_manager,
263 blinking_terminal_enabled: false,
264 hover: None,
265 hover_tooltip_update: Task::ready(()),
266 mode: TerminalMode::Standalone,
267 workspace_id,
268 show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
269 block_below_cursor: None,
270 scroll_top: Pixels::ZERO,
271 scroll_handle,
272 cwd_serialized: false,
273 ime_state: None,
274 _subscriptions,
275 _terminal_subscriptions: terminal_subscriptions,
276 }
277 }
278
279 /// Enable 'embedded' mode where the terminal displays the full content with an optional limit of lines.
280 pub fn set_embedded_mode(
281 &mut self,
282 max_lines_when_unfocused: Option<usize>,
283 cx: &mut Context<Self>,
284 ) {
285 self.mode = TerminalMode::Embedded {
286 max_lines_when_unfocused,
287 };
288 cx.notify();
289 }
290
291 const MAX_EMBEDDED_LINES: usize = 1_000;
292
293 /// Returns the current `ContentMode` depending on the set `TerminalMode` and the current number of lines
294 ///
295 /// Note: Even in embedded mode, the terminal will fallback to scrollable when its content exceeds `MAX_EMBEDDED_LINES`
296 pub fn content_mode(&self, window: &Window, cx: &App) -> ContentMode {
297 match &self.mode {
298 TerminalMode::Standalone => ContentMode::Scrollable,
299 TerminalMode::Embedded {
300 max_lines_when_unfocused,
301 } => {
302 let total_lines = self.terminal.read(cx).total_lines();
303
304 if total_lines > Self::MAX_EMBEDDED_LINES {
305 ContentMode::Scrollable
306 } else {
307 let mut displayed_lines = total_lines;
308
309 if !self.focus_handle.is_focused(window)
310 && let Some(max_lines) = max_lines_when_unfocused
311 {
312 displayed_lines = displayed_lines.min(*max_lines)
313 }
314
315 ContentMode::Inline {
316 displayed_lines,
317 total_lines,
318 }
319 }
320 }
321 }
322 }
323
324 /// Sets the marked (pre-edit) text from the IME.
325 pub(crate) fn set_marked_text(
326 &mut self,
327 text: String,
328 range: Option<Range<usize>>,
329 cx: &mut Context<Self>,
330 ) {
331 self.ime_state = Some(ImeState {
332 marked_text: text,
333 marked_range_utf16: range,
334 });
335 cx.notify();
336 }
337
338 /// Gets the current marked range (UTF-16).
339 pub(crate) fn marked_text_range(&self) -> Option<Range<usize>> {
340 self.ime_state
341 .as_ref()
342 .and_then(|state| state.marked_range_utf16.clone())
343 }
344
345 /// Clears the marked (pre-edit) text state.
346 pub(crate) fn clear_marked_text(&mut self, cx: &mut Context<Self>) {
347 if self.ime_state.is_some() {
348 self.ime_state = None;
349 cx.notify();
350 }
351 }
352
353 /// Commits (sends) the given text to the PTY. Called by InputHandler::replace_text_in_range.
354 pub(crate) fn commit_text(&mut self, text: &str, cx: &mut Context<Self>) {
355 if !text.is_empty() {
356 self.terminal.update(cx, |term, _| {
357 term.input(text.to_string().into_bytes());
358 });
359 }
360 }
361
362 pub(crate) fn terminal_bounds(&self, cx: &App) -> TerminalBounds {
363 self.terminal.read(cx).last_content().terminal_bounds
364 }
365
366 pub fn entity(&self) -> &Entity<Terminal> {
367 &self.terminal
368 }
369
370 pub fn has_bell(&self) -> bool {
371 self.has_bell
372 }
373
374 pub fn clear_bell(&mut self, cx: &mut Context<TerminalView>) {
375 self.has_bell = false;
376 cx.emit(Event::Wakeup);
377 }
378
379 pub fn deploy_context_menu(
380 &mut self,
381 position: gpui::Point<Pixels>,
382 window: &mut Window,
383 cx: &mut Context<Self>,
384 ) {
385 let assistant_enabled = self
386 .workspace
387 .upgrade()
388 .and_then(|workspace| workspace.read(cx).panel::<TerminalPanel>(cx))
389 .is_some_and(|terminal_panel| terminal_panel.read(cx).assistant_enabled());
390 let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
391 menu.context(self.focus_handle.clone())
392 .action("New Terminal", Box::new(NewTerminal))
393 .separator()
394 .action("Copy", Box::new(Copy))
395 .action("Paste", Box::new(Paste))
396 .action("Select All", Box::new(SelectAll))
397 .action("Clear", Box::new(Clear))
398 .when(assistant_enabled, |menu| {
399 menu.separator()
400 .action("Inline Assist", Box::new(InlineAssist::default()))
401 })
402 .separator()
403 .action(
404 "Close Terminal Tab",
405 Box::new(CloseActiveItem {
406 save_intent: None,
407 close_pinned: true,
408 }),
409 )
410 });
411
412 window.focus(&context_menu.focus_handle(cx), cx);
413 let subscription = cx.subscribe_in(
414 &context_menu,
415 window,
416 |this, _, _: &DismissEvent, window, cx| {
417 if this.context_menu.as_ref().is_some_and(|context_menu| {
418 context_menu.0.focus_handle(cx).contains_focused(window, cx)
419 }) {
420 cx.focus_self(window);
421 }
422 this.context_menu.take();
423 cx.notify();
424 },
425 );
426
427 self.context_menu = Some((context_menu, position, subscription));
428 }
429
430 fn settings_changed(&mut self, cx: &mut Context<Self>) {
431 let settings = TerminalSettings::get_global(cx);
432 let breadcrumb_visibility_changed = self.show_breadcrumbs != settings.toolbar.breadcrumbs;
433 self.show_breadcrumbs = settings.toolbar.breadcrumbs;
434
435 let should_blink = match settings.blinking {
436 TerminalBlink::Off => false,
437 TerminalBlink::On => true,
438 TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
439 };
440 let new_cursor_shape = settings.cursor_shape;
441 let old_cursor_shape = self.cursor_shape;
442 if old_cursor_shape != new_cursor_shape {
443 self.cursor_shape = new_cursor_shape;
444 self.terminal.update(cx, |term, _| {
445 term.set_cursor_shape(self.cursor_shape);
446 });
447 }
448
449 self.blink_manager.update(
450 cx,
451 if should_blink {
452 BlinkManager::enable
453 } else {
454 BlinkManager::disable
455 },
456 );
457
458 if breadcrumb_visibility_changed {
459 cx.emit(ItemEvent::UpdateBreadcrumbs);
460 }
461 cx.notify();
462 }
463
464 fn show_character_palette(
465 &mut self,
466 _: &ShowCharacterPalette,
467 window: &mut Window,
468 cx: &mut Context<Self>,
469 ) {
470 if self
471 .terminal
472 .read(cx)
473 .last_content
474 .mode
475 .contains(TermMode::ALT_SCREEN)
476 {
477 self.terminal.update(cx, |term, cx| {
478 term.try_keystroke(
479 &Keystroke::parse("ctrl-cmd-space").unwrap(),
480 TerminalSettings::get_global(cx).option_as_meta,
481 )
482 });
483 } else {
484 window.show_character_palette();
485 }
486 }
487
488 fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
489 self.terminal.update(cx, |term, _| term.select_all());
490 cx.notify();
491 }
492
493 fn rerun_task(&mut self, _: &RerunTask, window: &mut Window, cx: &mut Context<Self>) {
494 let task = self
495 .terminal
496 .read(cx)
497 .task()
498 .map(|task| terminal_rerun_override(&task.spawned_task.id))
499 .unwrap_or_default();
500 window.dispatch_action(Box::new(task), cx);
501 }
502
503 fn clear(&mut self, _: &Clear, _: &mut Window, cx: &mut Context<Self>) {
504 self.scroll_top = px(0.);
505 self.terminal.update(cx, |term, _| term.clear());
506 cx.notify();
507 }
508
509 fn max_scroll_top(&self, cx: &App) -> Pixels {
510 let terminal = self.terminal.read(cx);
511
512 let Some(block) = self.block_below_cursor.as_ref() else {
513 return Pixels::ZERO;
514 };
515
516 let line_height = terminal.last_content().terminal_bounds.line_height;
517 let viewport_lines = terminal.viewport_lines();
518 let cursor = point_to_viewport(
519 terminal.last_content.display_offset,
520 terminal.last_content.cursor.point,
521 )
522 .unwrap_or_default();
523 let max_scroll_top_in_lines =
524 (block.height as usize).saturating_sub(viewport_lines.saturating_sub(cursor.line + 1));
525
526 max_scroll_top_in_lines as f32 * line_height
527 }
528
529 fn scroll_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
530 let terminal_content = self.terminal.read(cx).last_content();
531
532 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
533 let line_height = terminal_content.terminal_bounds.line_height;
534 let y_delta = event.delta.pixel_delta(line_height).y;
535 if y_delta < Pixels::ZERO || self.scroll_top > Pixels::ZERO {
536 self.scroll_top = cmp::max(
537 Pixels::ZERO,
538 cmp::min(self.scroll_top - y_delta, self.max_scroll_top(cx)),
539 );
540 cx.notify();
541 return;
542 }
543 }
544 self.terminal.update(cx, |term, cx| {
545 term.scroll_wheel(
546 event,
547 TerminalSettings::get_global(cx).scroll_multiplier.max(0.01),
548 )
549 });
550 }
551
552 fn scroll_line_up(&mut self, _: &ScrollLineUp, _: &mut Window, cx: &mut Context<Self>) {
553 let terminal_content = self.terminal.read(cx).last_content();
554 if self.block_below_cursor.is_some()
555 && terminal_content.display_offset == 0
556 && self.scroll_top > Pixels::ZERO
557 {
558 let line_height = terminal_content.terminal_bounds.line_height;
559 self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
560 return;
561 }
562
563 self.terminal.update(cx, |term, _| term.scroll_line_up());
564 cx.notify();
565 }
566
567 fn scroll_line_down(&mut self, _: &ScrollLineDown, _: &mut Window, cx: &mut Context<Self>) {
568 let terminal_content = self.terminal.read(cx).last_content();
569 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
570 let max_scroll_top = self.max_scroll_top(cx);
571 if self.scroll_top < max_scroll_top {
572 let line_height = terminal_content.terminal_bounds.line_height;
573 self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
574 }
575 return;
576 }
577
578 self.terminal.update(cx, |term, _| term.scroll_line_down());
579 cx.notify();
580 }
581
582 fn scroll_page_up(&mut self, _: &ScrollPageUp, _: &mut Window, cx: &mut Context<Self>) {
583 if self.scroll_top == Pixels::ZERO {
584 self.terminal.update(cx, |term, _| term.scroll_page_up());
585 } else {
586 let line_height = self
587 .terminal
588 .read(cx)
589 .last_content
590 .terminal_bounds
591 .line_height();
592 let visible_block_lines = (self.scroll_top / line_height) as usize;
593 let viewport_lines = self.terminal.read(cx).viewport_lines();
594 let visible_content_lines = viewport_lines - visible_block_lines;
595
596 if visible_block_lines >= viewport_lines {
597 self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
598 } else {
599 self.scroll_top = px(0.);
600 self.terminal
601 .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
602 }
603 }
604 cx.notify();
605 }
606
607 fn scroll_page_down(&mut self, _: &ScrollPageDown, _: &mut Window, cx: &mut Context<Self>) {
608 self.terminal.update(cx, |term, _| term.scroll_page_down());
609 let terminal = self.terminal.read(cx);
610 if terminal.last_content().display_offset < terminal.viewport_lines() {
611 self.scroll_top = self.max_scroll_top(cx);
612 }
613 cx.notify();
614 }
615
616 fn scroll_to_top(&mut self, _: &ScrollToTop, _: &mut Window, cx: &mut Context<Self>) {
617 self.terminal.update(cx, |term, _| term.scroll_to_top());
618 cx.notify();
619 }
620
621 fn scroll_to_bottom(&mut self, _: &ScrollToBottom, _: &mut Window, cx: &mut Context<Self>) {
622 self.terminal.update(cx, |term, _| term.scroll_to_bottom());
623 if self.block_below_cursor.is_some() {
624 self.scroll_top = self.max_scroll_top(cx);
625 }
626 cx.notify();
627 }
628
629 fn toggle_vi_mode(&mut self, _: &ToggleViMode, _: &mut Window, cx: &mut Context<Self>) {
630 self.terminal.update(cx, |term, _| term.toggle_vi_mode());
631 cx.notify();
632 }
633
634 pub fn should_show_cursor(&self, focused: bool, cx: &mut Context<Self>) -> bool {
635 // Always show cursor when not focused or in special modes
636 if !focused
637 || self
638 .terminal
639 .read(cx)
640 .last_content
641 .mode
642 .contains(TermMode::ALT_SCREEN)
643 {
644 return true;
645 }
646
647 // When focused, check blinking settings and blink manager state
648 match TerminalSettings::get_global(cx).blinking {
649 TerminalBlink::Off => true,
650 TerminalBlink::TerminalControlled => {
651 !self.blinking_terminal_enabled || self.blink_manager.read(cx).visible()
652 }
653 TerminalBlink::On => self.blink_manager.read(cx).visible(),
654 }
655 }
656
657 pub fn pause_cursor_blinking(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
658 self.blink_manager.update(cx, BlinkManager::pause_blinking);
659 }
660
661 pub fn terminal(&self) -> &Entity<Terminal> {
662 &self.terminal
663 }
664
665 pub fn set_block_below_cursor(
666 &mut self,
667 block: BlockProperties,
668 window: &mut Window,
669 cx: &mut Context<Self>,
670 ) {
671 self.block_below_cursor = Some(Rc::new(block));
672 self.scroll_to_bottom(&ScrollToBottom, window, cx);
673 cx.notify();
674 }
675
676 pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
677 self.block_below_cursor = None;
678 self.scroll_top = Pixels::ZERO;
679 cx.notify();
680 }
681
682 ///Attempt to paste the clipboard into the terminal
683 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
684 self.terminal.update(cx, |term, _| term.copy(None));
685 cx.notify();
686 }
687
688 ///Attempt to paste the clipboard into the terminal
689 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
690 let Some(clipboard) = cx.read_from_clipboard() else {
691 return;
692 };
693
694 if clipboard.entries().iter().any(|entry| match entry {
695 ClipboardEntry::Image(image) => !image.bytes.is_empty(),
696 _ => false,
697 }) {
698 self.forward_ctrl_v(cx);
699 return;
700 }
701
702 if let Some(text) = clipboard.text() {
703 self.terminal
704 .update(cx, |terminal, _cx| terminal.paste(&text));
705 }
706 }
707
708 /// Emits a raw Ctrl+V so TUI agents can read the OS clipboard directly
709 /// and attach images using their native workflows.
710 fn forward_ctrl_v(&self, cx: &mut Context<Self>) {
711 self.terminal.update(cx, |term, _| {
712 term.input(vec![0x16]);
713 });
714 }
715
716 fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
717 self.clear_bell(cx);
718 self.terminal.update(cx, |term, _| {
719 term.input(text.0.to_string().into_bytes());
720 });
721 }
722
723 fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
724 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
725 self.clear_bell(cx);
726 self.terminal.update(cx, |term, cx| {
727 let processed =
728 term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
729 if processed && term.vi_mode_enabled() {
730 cx.notify();
731 }
732 processed
733 });
734 }
735 }
736
737 fn dispatch_context(&self, cx: &App) -> KeyContext {
738 let mut dispatch_context = KeyContext::new_with_defaults();
739 dispatch_context.add("Terminal");
740
741 if self.terminal.read(cx).vi_mode_enabled() {
742 dispatch_context.add("vi_mode");
743 }
744
745 let mode = self.terminal.read(cx).last_content.mode;
746 dispatch_context.set(
747 "screen",
748 if mode.contains(TermMode::ALT_SCREEN) {
749 "alt"
750 } else {
751 "normal"
752 },
753 );
754
755 if mode.contains(TermMode::APP_CURSOR) {
756 dispatch_context.add("DECCKM");
757 }
758 if mode.contains(TermMode::APP_KEYPAD) {
759 dispatch_context.add("DECPAM");
760 } else {
761 dispatch_context.add("DECPNM");
762 }
763 if mode.contains(TermMode::SHOW_CURSOR) {
764 dispatch_context.add("DECTCEM");
765 }
766 if mode.contains(TermMode::LINE_WRAP) {
767 dispatch_context.add("DECAWM");
768 }
769 if mode.contains(TermMode::ORIGIN) {
770 dispatch_context.add("DECOM");
771 }
772 if mode.contains(TermMode::INSERT) {
773 dispatch_context.add("IRM");
774 }
775 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
776 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
777 dispatch_context.add("LNM");
778 }
779 if mode.contains(TermMode::FOCUS_IN_OUT) {
780 dispatch_context.add("report_focus");
781 }
782 if mode.contains(TermMode::ALTERNATE_SCROLL) {
783 dispatch_context.add("alternate_scroll");
784 }
785 if mode.contains(TermMode::BRACKETED_PASTE) {
786 dispatch_context.add("bracketed_paste");
787 }
788 if mode.intersects(TermMode::MOUSE_MODE) {
789 dispatch_context.add("any_mouse_reporting");
790 }
791 {
792 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
793 "click"
794 } else if mode.contains(TermMode::MOUSE_DRAG) {
795 "drag"
796 } else if mode.contains(TermMode::MOUSE_MOTION) {
797 "motion"
798 } else {
799 "off"
800 };
801 dispatch_context.set("mouse_reporting", mouse_reporting);
802 }
803 {
804 let format = if mode.contains(TermMode::SGR_MOUSE) {
805 "sgr"
806 } else if mode.contains(TermMode::UTF8_MOUSE) {
807 "utf8"
808 } else {
809 "normal"
810 };
811 dispatch_context.set("mouse_format", format);
812 };
813
814 if self.terminal.read(cx).last_content.selection.is_some() {
815 dispatch_context.add("selection");
816 }
817
818 dispatch_context
819 }
820
821 fn set_terminal(
822 &mut self,
823 terminal: Entity<Terminal>,
824 window: &mut Window,
825 cx: &mut Context<TerminalView>,
826 ) {
827 self._terminal_subscriptions =
828 subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
829 self.terminal = terminal;
830 }
831
832 fn rerun_button(task: &TaskState) -> Option<IconButton> {
833 if !task.spawned_task.show_rerun {
834 return None;
835 }
836
837 let task_id = task.spawned_task.id.clone();
838 Some(
839 IconButton::new("rerun-icon", IconName::Rerun)
840 .icon_size(IconSize::Small)
841 .size(ButtonSize::Compact)
842 .icon_color(Color::Default)
843 .shape(ui::IconButtonShape::Square)
844 .tooltip(move |_window, cx| Tooltip::for_action("Rerun task", &RerunTask, cx))
845 .on_click(move |_, window, cx| {
846 window.dispatch_action(Box::new(terminal_rerun_override(&task_id)), cx);
847 }),
848 )
849 }
850}
851
852fn terminal_rerun_override(task: &TaskId) -> zed_actions::Rerun {
853 zed_actions::Rerun {
854 task_id: Some(task.0.clone()),
855 allow_concurrent_runs: Some(true),
856 use_new_terminal: Some(false),
857 reevaluate_context: false,
858 }
859}
860
861fn subscribe_for_terminal_events(
862 terminal: &Entity<Terminal>,
863 workspace: WeakEntity<Workspace>,
864 window: &mut Window,
865 cx: &mut Context<TerminalView>,
866) -> Vec<Subscription> {
867 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
868 let mut previous_cwd = None;
869 let terminal_events_subscription = cx.subscribe_in(
870 terminal,
871 window,
872 move |terminal_view, terminal, event, window, cx| {
873 let current_cwd = terminal.read(cx).working_directory();
874 if current_cwd != previous_cwd {
875 previous_cwd = current_cwd;
876 terminal_view.cwd_serialized = false;
877 }
878
879 match event {
880 Event::Wakeup => {
881 cx.notify();
882 cx.emit(Event::Wakeup);
883 cx.emit(ItemEvent::UpdateTab);
884 cx.emit(SearchEvent::MatchesInvalidated);
885 }
886
887 Event::Bell => {
888 terminal_view.has_bell = true;
889 cx.emit(Event::Wakeup);
890 }
891
892 Event::BlinkChanged(blinking) => {
893 terminal_view.blinking_terminal_enabled = *blinking;
894
895 // If in terminal-controlled mode and focused, update blink manager
896 if matches!(
897 TerminalSettings::get_global(cx).blinking,
898 TerminalBlink::TerminalControlled
899 ) && terminal_view.focus_handle.is_focused(window)
900 {
901 terminal_view.blink_manager.update(cx, |manager, cx| {
902 if *blinking {
903 manager.enable(cx);
904 } else {
905 manager.disable(cx);
906 }
907 });
908 }
909 }
910
911 Event::TitleChanged => {
912 cx.emit(ItemEvent::UpdateTab);
913 }
914
915 Event::NewNavigationTarget(maybe_navigation_target) => {
916 match maybe_navigation_target
917 .as_ref()
918 .zip(terminal.read(cx).last_content.last_hovered_word.as_ref())
919 {
920 Some((MaybeNavigationTarget::Url(url), hovered_word)) => {
921 if Some(hovered_word)
922 != terminal_view
923 .hover
924 .as_ref()
925 .map(|hover| &hover.hovered_word)
926 {
927 terminal_view.hover = Some(HoverTarget {
928 tooltip: url.clone(),
929 hovered_word: hovered_word.clone(),
930 });
931 terminal_view.hover_tooltip_update = Task::ready(());
932 cx.notify();
933 }
934 }
935 Some((MaybeNavigationTarget::PathLike(path_like_target), hovered_word)) => {
936 if Some(hovered_word)
937 != terminal_view
938 .hover
939 .as_ref()
940 .map(|hover| &hover.hovered_word)
941 {
942 terminal_view.hover = None;
943 terminal_view.hover_tooltip_update = hover_path_like_target(
944 &workspace,
945 hovered_word.clone(),
946 path_like_target,
947 cx,
948 );
949 cx.notify();
950 }
951 }
952 None => {
953 terminal_view.hover = None;
954 terminal_view.hover_tooltip_update = Task::ready(());
955 cx.notify();
956 }
957 }
958 }
959
960 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
961 MaybeNavigationTarget::Url(url) => cx.open_url(url),
962 MaybeNavigationTarget::PathLike(path_like_target) => open_path_like_target(
963 &workspace,
964 terminal_view,
965 path_like_target,
966 window,
967 cx,
968 ),
969 },
970 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
971 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
972 Event::SelectionsChanged => {
973 window.invalidate_character_coordinates();
974 cx.emit(SearchEvent::ActiveMatchChanged)
975 }
976 }
977 },
978 );
979 vec![terminal_subscription, terminal_events_subscription]
980}
981
982fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
983 let str = query.as_str();
984 if query.is_regex() {
985 if str == "." {
986 return None;
987 }
988 RegexSearch::new(str).ok()
989 } else {
990 RegexSearch::new(®ex::escape(str)).ok()
991 }
992}
993
994struct TerminalScrollbarSettingsWrapper;
995
996impl GlobalSetting for TerminalScrollbarSettingsWrapper {
997 fn get_value(_cx: &App) -> &Self {
998 &Self
999 }
1000}
1001
1002impl ScrollbarVisibility for TerminalScrollbarSettingsWrapper {
1003 fn visibility(&self, cx: &App) -> scrollbars::ShowScrollbar {
1004 TerminalSettings::get_global(cx)
1005 .scrollbar
1006 .show
1007 .map(Into::into)
1008 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
1009 }
1010}
1011
1012impl TerminalView {
1013 fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1014 self.clear_bell(cx);
1015 self.pause_cursor_blinking(window, cx);
1016
1017 self.terminal.update(cx, |term, cx| {
1018 let handled = term.try_keystroke(
1019 &event.keystroke,
1020 TerminalSettings::get_global(cx).option_as_meta,
1021 );
1022 if handled {
1023 cx.stop_propagation();
1024 }
1025 });
1026 }
1027
1028 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1029 self.terminal.update(cx, |terminal, _| {
1030 terminal.set_cursor_shape(self.cursor_shape);
1031 terminal.focus_in();
1032 });
1033
1034 let should_blink = match TerminalSettings::get_global(cx).blinking {
1035 TerminalBlink::Off => false,
1036 TerminalBlink::On => true,
1037 TerminalBlink::TerminalControlled => self.blinking_terminal_enabled,
1038 };
1039
1040 if should_blink {
1041 self.blink_manager.update(cx, BlinkManager::enable);
1042 }
1043
1044 window.invalidate_character_coordinates();
1045 cx.notify();
1046 }
1047
1048 fn focus_out(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1049 self.blink_manager.update(cx, BlinkManager::disable);
1050 self.terminal.update(cx, |terminal, _| {
1051 terminal.focus_out();
1052 terminal.set_cursor_shape(CursorShape::Hollow);
1053 });
1054 cx.notify();
1055 }
1056}
1057
1058impl Render for TerminalView {
1059 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1060 // TODO: this should be moved out of render
1061 self.scroll_handle.update(self.terminal.read(cx));
1062
1063 if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
1064 self.terminal.update(cx, |term, _| {
1065 let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
1066 match delta.cmp(&0) {
1067 std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
1068 std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
1069 std::cmp::Ordering::Equal => {}
1070 }
1071 });
1072 }
1073
1074 let terminal_handle = self.terminal.clone();
1075 let terminal_view_handle = cx.entity();
1076
1077 let focused = self.focus_handle.is_focused(window);
1078
1079 div()
1080 .id("terminal-view")
1081 .size_full()
1082 .relative()
1083 .track_focus(&self.focus_handle(cx))
1084 .key_context(self.dispatch_context(cx))
1085 .on_action(cx.listener(TerminalView::send_text))
1086 .on_action(cx.listener(TerminalView::send_keystroke))
1087 .on_action(cx.listener(TerminalView::copy))
1088 .on_action(cx.listener(TerminalView::paste))
1089 .on_action(cx.listener(TerminalView::clear))
1090 .on_action(cx.listener(TerminalView::scroll_line_up))
1091 .on_action(cx.listener(TerminalView::scroll_line_down))
1092 .on_action(cx.listener(TerminalView::scroll_page_up))
1093 .on_action(cx.listener(TerminalView::scroll_page_down))
1094 .on_action(cx.listener(TerminalView::scroll_to_top))
1095 .on_action(cx.listener(TerminalView::scroll_to_bottom))
1096 .on_action(cx.listener(TerminalView::toggle_vi_mode))
1097 .on_action(cx.listener(TerminalView::show_character_palette))
1098 .on_action(cx.listener(TerminalView::select_all))
1099 .on_action(cx.listener(TerminalView::rerun_task))
1100 .on_key_down(cx.listener(Self::key_down))
1101 .on_mouse_down(
1102 MouseButton::Right,
1103 cx.listener(|this, event: &MouseDownEvent, window, cx| {
1104 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1105 if this.terminal.read(cx).last_content.selection.is_none() {
1106 this.terminal.update(cx, |terminal, _| {
1107 terminal.select_word_at_event_position(event);
1108 });
1109 };
1110 this.deploy_context_menu(event.position, window, cx);
1111 cx.notify();
1112 }
1113 }),
1114 )
1115 .child(
1116 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1117 div()
1118 .id("terminal-view-container")
1119 .size_full()
1120 .bg(cx.theme().colors().editor_background)
1121 .child(TerminalElement::new(
1122 terminal_handle,
1123 terminal_view_handle,
1124 self.workspace.clone(),
1125 self.focus_handle.clone(),
1126 focused,
1127 self.should_show_cursor(focused, cx),
1128 self.block_below_cursor.clone(),
1129 self.mode.clone(),
1130 ))
1131 .when(self.content_mode(window, cx).is_scrollable(), |div| {
1132 div.custom_scrollbars(
1133 Scrollbars::for_settings::<TerminalScrollbarSettingsWrapper>()
1134 .show_along(ScrollAxes::Vertical)
1135 .with_track_along(
1136 ScrollAxes::Vertical,
1137 cx.theme().colors().editor_background,
1138 )
1139 .tracked_scroll_handle(&self.scroll_handle),
1140 window,
1141 cx,
1142 )
1143 }),
1144 )
1145 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1146 deferred(
1147 anchored()
1148 .position(*position)
1149 .anchor(gpui::Corner::TopLeft)
1150 .child(menu.clone()),
1151 )
1152 .with_priority(1)
1153 }))
1154 }
1155}
1156
1157impl Item for TerminalView {
1158 type Event = ItemEvent;
1159
1160 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1161 Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
1162 let terminal = self.terminal().read(cx);
1163 let title = terminal.title(false);
1164 let pid = terminal.pid_getter()?.fallback_pid();
1165
1166 move |_, _| {
1167 v_flex()
1168 .gap_1()
1169 .child(Label::new(title.clone()))
1170 .child(h_flex().flex_grow().child(Divider::horizontal()))
1171 .child(
1172 Label::new(format!("Process ID (PID): {}", pid))
1173 .color(Color::Muted)
1174 .size(LabelSize::Small),
1175 )
1176 .into_any_element()
1177 }
1178 }))))
1179 }
1180
1181 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1182 let terminal = self.terminal().read(cx);
1183 let title = terminal.title(true);
1184
1185 let (icon, icon_color, rerun_button) = match terminal.task() {
1186 Some(terminal_task) => match &terminal_task.status {
1187 TaskStatus::Running => (
1188 IconName::PlayFilled,
1189 Color::Disabled,
1190 TerminalView::rerun_button(terminal_task),
1191 ),
1192 TaskStatus::Unknown => (
1193 IconName::Warning,
1194 Color::Warning,
1195 TerminalView::rerun_button(terminal_task),
1196 ),
1197 TaskStatus::Completed { success } => {
1198 let rerun_button = TerminalView::rerun_button(terminal_task);
1199
1200 if *success {
1201 (IconName::Check, Color::Success, rerun_button)
1202 } else {
1203 (IconName::XCircle, Color::Error, rerun_button)
1204 }
1205 }
1206 },
1207 None => (IconName::Terminal, Color::Muted, None),
1208 };
1209
1210 h_flex()
1211 .gap_1()
1212 .group("term-tab-icon")
1213 .child(
1214 h_flex()
1215 .group("term-tab-icon")
1216 .child(
1217 div()
1218 .when(rerun_button.is_some(), |this| {
1219 this.hover(|style| style.invisible().w_0())
1220 })
1221 .child(Icon::new(icon).color(icon_color)),
1222 )
1223 .when_some(rerun_button, |this, rerun_button| {
1224 this.child(
1225 div()
1226 .absolute()
1227 .visible_on_hover("term-tab-icon")
1228 .child(rerun_button),
1229 )
1230 }),
1231 )
1232 .child(Label::new(title).color(params.text_color()))
1233 .into_any()
1234 }
1235
1236 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
1237 let terminal = self.terminal().read(cx);
1238 terminal.title(detail == 0).into()
1239 }
1240
1241 fn telemetry_event_text(&self) -> Option<&'static str> {
1242 None
1243 }
1244
1245 fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
1246 workspace::item::ItemBufferKind::Singleton
1247 }
1248
1249 fn can_split(&self) -> bool {
1250 true
1251 }
1252
1253 fn clone_on_split(
1254 &self,
1255 workspace_id: Option<WorkspaceId>,
1256 window: &mut Window,
1257 cx: &mut Context<Self>,
1258 ) -> Task<Option<Entity<Self>>> {
1259 let Ok(terminal) = self.project.update(cx, |project, cx| {
1260 let cwd = project
1261 .active_project_directory(cx)
1262 .map(|it| it.to_path_buf());
1263 project.clone_terminal(self.terminal(), cx, cwd)
1264 }) else {
1265 return Task::ready(None);
1266 };
1267 cx.spawn_in(window, async move |this, cx| {
1268 let terminal = terminal.await.log_err()?;
1269 this.update_in(cx, |this, window, cx| {
1270 cx.new(|cx| {
1271 TerminalView::new(
1272 terminal,
1273 this.workspace.clone(),
1274 workspace_id,
1275 this.project.clone(),
1276 window,
1277 cx,
1278 )
1279 })
1280 })
1281 .ok()
1282 })
1283 }
1284
1285 fn is_dirty(&self, cx: &gpui::App) -> bool {
1286 match self.terminal.read(cx).task() {
1287 Some(task) => task.status == TaskStatus::Running,
1288 None => self.has_bell(),
1289 }
1290 }
1291
1292 fn has_conflict(&self, _cx: &App) -> bool {
1293 false
1294 }
1295
1296 fn can_save_as(&self, _cx: &App) -> bool {
1297 false
1298 }
1299
1300 fn as_searchable(
1301 &self,
1302 handle: &Entity<Self>,
1303 _: &App,
1304 ) -> Option<Box<dyn SearchableItemHandle>> {
1305 Some(Box::new(handle.clone()))
1306 }
1307
1308 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1309 if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1310 ToolbarItemLocation::PrimaryLeft
1311 } else {
1312 ToolbarItemLocation::Hidden
1313 }
1314 }
1315
1316 fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1317 Some(vec![BreadcrumbText {
1318 text: self.terminal().read(cx).breadcrumb_text.clone(),
1319 highlights: None,
1320 font: None,
1321 }])
1322 }
1323
1324 fn added_to_workspace(
1325 &mut self,
1326 workspace: &mut Workspace,
1327 _: &mut Window,
1328 cx: &mut Context<Self>,
1329 ) {
1330 if self.terminal().read(cx).task().is_none() {
1331 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1332 log::debug!(
1333 "Updating workspace id for the terminal, old: {old_id:?}, new: {new_id:?}",
1334 );
1335 cx.background_spawn(TERMINAL_DB.update_workspace_id(
1336 new_id,
1337 old_id,
1338 cx.entity_id().as_u64(),
1339 ))
1340 .detach();
1341 }
1342 self.workspace_id = workspace.database_id();
1343 }
1344 }
1345
1346 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1347 f(*event)
1348 }
1349}
1350
1351impl SerializableItem for TerminalView {
1352 fn serialized_item_kind() -> &'static str {
1353 "Terminal"
1354 }
1355
1356 fn cleanup(
1357 workspace_id: WorkspaceId,
1358 alive_items: Vec<workspace::ItemId>,
1359 _window: &mut Window,
1360 cx: &mut App,
1361 ) -> Task<anyhow::Result<()>> {
1362 delete_unloaded_items(alive_items, workspace_id, "terminals", &TERMINAL_DB, cx)
1363 }
1364
1365 fn serialize(
1366 &mut self,
1367 _workspace: &mut Workspace,
1368 item_id: workspace::ItemId,
1369 _closing: bool,
1370 _: &mut Window,
1371 cx: &mut Context<Self>,
1372 ) -> Option<Task<anyhow::Result<()>>> {
1373 let terminal = self.terminal().read(cx);
1374 if terminal.task().is_some() {
1375 return None;
1376 }
1377
1378 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1379 self.cwd_serialized = true;
1380 Some(cx.background_spawn(async move {
1381 TERMINAL_DB
1382 .save_working_directory(item_id, workspace_id, cwd)
1383 .await
1384 }))
1385 } else {
1386 None
1387 }
1388 }
1389
1390 fn should_serialize(&self, _: &Self::Event) -> bool {
1391 !self.cwd_serialized
1392 }
1393
1394 fn deserialize(
1395 project: Entity<Project>,
1396 workspace: WeakEntity<Workspace>,
1397 workspace_id: workspace::WorkspaceId,
1398 item_id: workspace::ItemId,
1399 window: &mut Window,
1400 cx: &mut App,
1401 ) -> Task<anyhow::Result<Entity<Self>>> {
1402 window.spawn(cx, async move |cx| {
1403 let cwd = cx
1404 .update(|_window, cx| {
1405 let from_db = TERMINAL_DB
1406 .get_working_directory(item_id, workspace_id)
1407 .log_err()
1408 .flatten();
1409 if from_db
1410 .as_ref()
1411 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1412 {
1413 from_db
1414 } else {
1415 workspace
1416 .upgrade()
1417 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1418 }
1419 })
1420 .ok()
1421 .flatten();
1422
1423 let terminal = project
1424 .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
1425 .await?;
1426 cx.update(|window, cx| {
1427 cx.new(|cx| {
1428 TerminalView::new(
1429 terminal,
1430 workspace,
1431 Some(workspace_id),
1432 project.downgrade(),
1433 window,
1434 cx,
1435 )
1436 })
1437 })
1438 })
1439 }
1440}
1441
1442impl SearchableItem for TerminalView {
1443 type Match = RangeInclusive<Point>;
1444
1445 fn supported_options(&self) -> SearchOptions {
1446 SearchOptions {
1447 case: false,
1448 word: false,
1449 regex: true,
1450 replacement: false,
1451 selection: false,
1452 find_in_results: false,
1453 }
1454 }
1455
1456 /// Clear stored matches
1457 fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1458 self.terminal().update(cx, |term, _| term.matches.clear())
1459 }
1460
1461 /// Store matches returned from find_matches somewhere for rendering
1462 fn update_matches(
1463 &mut self,
1464 matches: &[Self::Match],
1465 _active_match_index: Option<usize>,
1466 _window: &mut Window,
1467 cx: &mut Context<Self>,
1468 ) {
1469 self.terminal()
1470 .update(cx, |term, _| term.matches = matches.to_vec())
1471 }
1472
1473 /// Returns the selection content to pre-load into this search
1474 fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1475 self.terminal()
1476 .read(cx)
1477 .last_content
1478 .selection_text
1479 .clone()
1480 .unwrap_or_default()
1481 }
1482
1483 /// Focus match at given index into the Vec of matches
1484 fn activate_match(
1485 &mut self,
1486 index: usize,
1487 _: &[Self::Match],
1488 _window: &mut Window,
1489 cx: &mut Context<Self>,
1490 ) {
1491 self.terminal()
1492 .update(cx, |term, _| term.activate_match(index));
1493 cx.notify();
1494 }
1495
1496 /// Add selections for all matches given.
1497 fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1498 self.terminal()
1499 .update(cx, |term, _| term.select_matches(matches));
1500 cx.notify();
1501 }
1502
1503 /// Get all of the matches for this query, should be done on the background
1504 fn find_matches(
1505 &mut self,
1506 query: Arc<SearchQuery>,
1507 _: &mut Window,
1508 cx: &mut Context<Self>,
1509 ) -> Task<Vec<Self::Match>> {
1510 if let Some(s) = regex_search_for_query(&query) {
1511 self.terminal()
1512 .update(cx, |term, cx| term.find_matches(s, cx))
1513 } else {
1514 Task::ready(vec![])
1515 }
1516 }
1517
1518 /// Reports back to the search toolbar what the active match should be (the selection)
1519 fn active_match_index(
1520 &mut self,
1521 direction: Direction,
1522 matches: &[Self::Match],
1523 _: &mut Window,
1524 cx: &mut Context<Self>,
1525 ) -> Option<usize> {
1526 // Selection head might have a value if there's a selection that isn't
1527 // associated with a match. Therefore, if there are no matches, we should
1528 // report None, no matter the state of the terminal
1529
1530 if !matches.is_empty() {
1531 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1532 // If selection head is contained in a match. Return that match
1533 match direction {
1534 Direction::Prev => {
1535 // If no selection before selection head, return the first match
1536 Some(
1537 matches
1538 .iter()
1539 .enumerate()
1540 .rev()
1541 .find(|(_, search_match)| {
1542 search_match.contains(&selection_head)
1543 || search_match.start() < &selection_head
1544 })
1545 .map(|(ix, _)| ix)
1546 .unwrap_or(0),
1547 )
1548 }
1549 Direction::Next => {
1550 // If no selection after selection head, return the last match
1551 Some(
1552 matches
1553 .iter()
1554 .enumerate()
1555 .find(|(_, search_match)| {
1556 search_match.contains(&selection_head)
1557 || search_match.start() > &selection_head
1558 })
1559 .map(|(ix, _)| ix)
1560 .unwrap_or(matches.len().saturating_sub(1)),
1561 )
1562 }
1563 }
1564 } else {
1565 // Matches found but no active selection, return the first last one (closest to cursor)
1566 Some(matches.len().saturating_sub(1))
1567 }
1568 } else {
1569 None
1570 }
1571 }
1572 fn replace(
1573 &mut self,
1574 _: &Self::Match,
1575 _: &SearchQuery,
1576 _window: &mut Window,
1577 _: &mut Context<Self>,
1578 ) {
1579 // Replacement is not supported in terminal view, so this is a no-op.
1580 }
1581}
1582
1583///Gets the working directory for the given workspace, respecting the user's settings.
1584/// None implies "~" on whichever machine we end up on.
1585pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1586 match &TerminalSettings::get_global(cx).working_directory {
1587 WorkingDirectory::CurrentProjectDirectory => workspace
1588 .project()
1589 .read(cx)
1590 .active_project_directory(cx)
1591 .as_deref()
1592 .map(Path::to_path_buf)
1593 .or_else(|| first_project_directory(workspace, cx)),
1594 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1595 WorkingDirectory::AlwaysHome => None,
1596 WorkingDirectory::Always { directory } => {
1597 shellexpand::full(&directory) //TODO handle this better
1598 .ok()
1599 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1600 .filter(|dir| dir.is_dir())
1601 }
1602 }
1603}
1604///Gets the first project's home directory, or the home directory
1605fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1606 let worktree = workspace.worktrees(cx).next()?.read(cx);
1607 let worktree_path = worktree.abs_path();
1608 if worktree.root_entry()?.is_dir() {
1609 Some(worktree_path.to_path_buf())
1610 } else {
1611 // If worktree is a file, return its parent directory
1612 worktree_path.parent().map(|p| p.to_path_buf())
1613 }
1614}
1615
1616#[cfg(test)]
1617mod tests {
1618 use super::*;
1619 use gpui::TestAppContext;
1620 use project::{Entry, Project, ProjectPath, Worktree};
1621 use std::path::Path;
1622 use util::rel_path::RelPath;
1623 use workspace::AppState;
1624
1625 // Working directory calculation tests
1626
1627 // No Worktrees in project -> home_dir()
1628 #[gpui::test]
1629 async fn no_worktree(cx: &mut TestAppContext) {
1630 let (project, workspace) = init_test(cx).await;
1631 cx.read(|cx| {
1632 let workspace = workspace.read(cx);
1633 let active_entry = project.read(cx).active_entry();
1634
1635 //Make sure environment is as expected
1636 assert!(active_entry.is_none());
1637 assert!(workspace.worktrees(cx).next().is_none());
1638
1639 let res = default_working_directory(workspace, cx);
1640 assert_eq!(res, None);
1641 let res = first_project_directory(workspace, cx);
1642 assert_eq!(res, None);
1643 });
1644 }
1645
1646 // No active entry, but a worktree, worktree is a file -> parent directory
1647 #[gpui::test]
1648 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1649 let (project, workspace) = init_test(cx).await;
1650
1651 create_file_wt(project.clone(), "/root.txt", cx).await;
1652 cx.read(|cx| {
1653 let workspace = workspace.read(cx);
1654 let active_entry = project.read(cx).active_entry();
1655
1656 //Make sure environment is as expected
1657 assert!(active_entry.is_none());
1658 assert!(workspace.worktrees(cx).next().is_some());
1659
1660 let res = default_working_directory(workspace, cx);
1661 assert_eq!(res, Some(Path::new("/").to_path_buf()));
1662 let res = first_project_directory(workspace, cx);
1663 assert_eq!(res, Some(Path::new("/").to_path_buf()));
1664 });
1665 }
1666
1667 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1668 #[gpui::test]
1669 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1670 let (project, workspace) = init_test(cx).await;
1671
1672 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1673 cx.update(|cx| {
1674 let workspace = workspace.read(cx);
1675 let active_entry = project.read(cx).active_entry();
1676
1677 assert!(active_entry.is_none());
1678 assert!(workspace.worktrees(cx).next().is_some());
1679
1680 let res = default_working_directory(workspace, cx);
1681 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1682 let res = first_project_directory(workspace, cx);
1683 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1684 });
1685 }
1686
1687 // Active entry with a work tree, worktree is a file -> worktree_folder()
1688 #[gpui::test]
1689 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1690 let (project, workspace) = init_test(cx).await;
1691
1692 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1693 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1694 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1695
1696 cx.update(|cx| {
1697 let workspace = workspace.read(cx);
1698 let active_entry = project.read(cx).active_entry();
1699
1700 assert!(active_entry.is_some());
1701
1702 let res = default_working_directory(workspace, cx);
1703 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1704 let res = first_project_directory(workspace, cx);
1705 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1706 });
1707 }
1708
1709 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1710 #[gpui::test]
1711 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1712 let (project, workspace) = init_test(cx).await;
1713
1714 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1715 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1716 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1717
1718 cx.update(|cx| {
1719 let workspace = workspace.read(cx);
1720 let active_entry = project.read(cx).active_entry();
1721
1722 assert!(active_entry.is_some());
1723
1724 let res = default_working_directory(workspace, cx);
1725 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1726 let res = first_project_directory(workspace, cx);
1727 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1728 });
1729 }
1730
1731 /// Creates a worktree with 1 file: /root.txt
1732 pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
1733 let params = cx.update(AppState::test);
1734 cx.update(|cx| {
1735 theme::init(theme::LoadThemes::JustBase, cx);
1736 });
1737
1738 let project = Project::test(params.fs.clone(), [], cx).await;
1739 let workspace = cx
1740 .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
1741 .root(cx)
1742 .unwrap();
1743
1744 (project, workspace)
1745 }
1746
1747 /// Creates a worktree with 1 folder: /root{suffix}/
1748 async fn create_folder_wt(
1749 project: Entity<Project>,
1750 path: impl AsRef<Path>,
1751 cx: &mut TestAppContext,
1752 ) -> (Entity<Worktree>, Entry) {
1753 create_wt(project, true, path, cx).await
1754 }
1755
1756 /// Creates a worktree with 1 file: /root{suffix}.txt
1757 async fn create_file_wt(
1758 project: Entity<Project>,
1759 path: impl AsRef<Path>,
1760 cx: &mut TestAppContext,
1761 ) -> (Entity<Worktree>, Entry) {
1762 create_wt(project, false, path, cx).await
1763 }
1764
1765 async fn create_wt(
1766 project: Entity<Project>,
1767 is_dir: bool,
1768 path: impl AsRef<Path>,
1769 cx: &mut TestAppContext,
1770 ) -> (Entity<Worktree>, Entry) {
1771 let (wt, _) = project
1772 .update(cx, |project, cx| {
1773 project.find_or_create_worktree(path, true, cx)
1774 })
1775 .await
1776 .unwrap();
1777
1778 let entry = cx
1779 .update(|cx| {
1780 wt.update(cx, |wt, cx| {
1781 wt.create_entry(RelPath::empty().into(), is_dir, None, cx)
1782 })
1783 })
1784 .await
1785 .unwrap()
1786 .into_included()
1787 .unwrap();
1788
1789 (wt, entry)
1790 }
1791
1792 pub fn insert_active_entry_for(
1793 wt: Entity<Worktree>,
1794 entry: Entry,
1795 project: Entity<Project>,
1796 cx: &mut TestAppContext,
1797 ) {
1798 cx.update(|cx| {
1799 let p = ProjectPath {
1800 worktree_id: wt.read(cx).id(),
1801 path: entry.path,
1802 };
1803 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1804 });
1805 }
1806}