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