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