1mod color_contrast;
2mod persistence;
3pub mod terminal_element;
4pub mod terminal_panel;
5pub mod terminal_scrollbar;
6mod terminal_slash_command;
7pub mod terminal_tab_tooltip;
8
9use assistant_slash_command::SlashCommandRegistry;
10use editor::{Editor, EditorSettings, actions::SelectAll, scroll::ScrollbarAutoHide};
11use gpui::{
12 Action, AnyElement, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
13 KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render,
14 ScrollWheelEvent, Stateful, Styled, Subscription, Task, WeakEntity, actions, anchored,
15 deferred, div,
16};
17use itertools::Itertools;
18use persistence::TERMINAL_DB;
19use project::{Entry, Metadata, Project, search::SearchQuery, terminals::TerminalKind};
20use schemars::JsonSchema;
21use task::TaskId;
22use terminal::{
23 Clear, Copy, Event, HoveredWord, MaybeNavigationTarget, Paste, ScrollLineDown, ScrollLineUp,
24 ScrollPageDown, ScrollPageUp, ScrollToBottom, ScrollToTop, ShowCharacterPalette, TaskState,
25 TaskStatus, Terminal, TerminalBounds, ToggleViMode,
26 alacritty_terminal::{
27 index::Point,
28 term::{TermMode, point_to_viewport, search::RegexSearch},
29 },
30 terminal_settings::{self, CursorShape, TerminalBlink, TerminalSettings, WorkingDirectory},
31};
32use terminal_element::TerminalElement;
33use terminal_panel::TerminalPanel;
34use terminal_scrollbar::TerminalScrollHandle;
35use terminal_slash_command::TerminalSlashCommand;
36use terminal_tab_tooltip::TerminalTooltip;
37use ui::{
38 ContextMenu, Icon, IconName, Label, Scrollbar, ScrollbarState, Tooltip, h_flex, prelude::*,
39};
40use util::{ResultExt, debug_panic, paths::PathWithPosition};
41use workspace::{
42 CloseActiveItem, NewCenterTerminal, NewTerminal, OpenOptions, OpenVisible, ToolbarItemLocation,
43 Workspace, WorkspaceId, delete_unloaded_items,
44 item::{
45 BreadcrumbText, Item, ItemEvent, SerializableItem, TabContentParams, TabTooltipContent,
46 },
47 register_serializable_item,
48 searchable::{Direction, SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
49};
50
51use anyhow::Context as _;
52use serde::Deserialize;
53use settings::{Settings, SettingsStore};
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
66const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
67const GIT_DIFF_PATH_PREFIXES: &[&str] = &["a", "b"];
68const TERMINAL_SCROLLBAR_WIDTH: Pixels = px(12.);
69
70/// Event to transmit the scroll from the element to the view
71#[derive(Clone, Debug, PartialEq)]
72pub struct ScrollTerminal(pub i32);
73
74/// Sends the specified text directly to the terminal.
75#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
76#[action(namespace = terminal)]
77pub struct SendText(String);
78
79/// Sends a keystroke sequence to the terminal.
80#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Action)]
81#[action(namespace = terminal)]
82pub struct SendKeystroke(String);
83
84actions!(
85 terminal,
86 [
87 /// Reruns the last executed task in the terminal.
88 RerunTask
89 ]
90);
91
92pub fn init(cx: &mut App) {
93 assistant_slash_command::init(cx);
94 terminal_panel::init(cx);
95 terminal::init(cx);
96
97 register_serializable_item::<TerminalView>(cx);
98
99 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
100 workspace.register_action(TerminalView::deploy);
101 })
102 .detach();
103 SlashCommandRegistry::global(cx).register_command(TerminalSlashCommand, true);
104}
105
106pub struct BlockProperties {
107 pub height: u8,
108 pub render: Box<dyn Send + Fn(&mut BlockContext) -> AnyElement>,
109}
110
111pub struct BlockContext<'a, 'b> {
112 pub window: &'a mut Window,
113 pub context: &'b mut App,
114 pub dimensions: TerminalBounds,
115}
116
117///A terminal view, maintains the PTY's file handles and communicates with the terminal
118pub struct TerminalView {
119 terminal: Entity<Terminal>,
120 workspace: WeakEntity<Workspace>,
121 project: WeakEntity<Project>,
122 focus_handle: FocusHandle,
123 //Currently using iTerm bell, show bell emoji in tab until input is received
124 has_bell: bool,
125 context_menu: Option<(Entity<ContextMenu>, gpui::Point<Pixels>, Subscription)>,
126 cursor_shape: CursorShape,
127 blink_state: bool,
128 mode: TerminalMode,
129 blinking_terminal_enabled: bool,
130 cwd_serialized: bool,
131 blinking_paused: bool,
132 blink_epoch: usize,
133 hover: Option<HoverTarget>,
134 hover_tooltip_update: Task<()>,
135 workspace_id: Option<WorkspaceId>,
136 show_breadcrumbs: bool,
137 block_below_cursor: Option<Rc<BlockProperties>>,
138 scroll_top: Pixels,
139 scrollbar_state: ScrollbarState,
140 scroll_handle: TerminalScrollHandle,
141 show_scrollbar: bool,
142 hide_scrollbar_task: Option<Task<()>>,
143 marked_text: Option<String>,
144 marked_range_utf16: Option<Range<usize>>,
145 _subscriptions: Vec<Subscription>,
146 _terminal_subscriptions: Vec<Subscription>,
147}
148
149#[derive(Default, Clone)]
150pub enum TerminalMode {
151 #[default]
152 Standalone,
153 Embedded {
154 max_lines_when_unfocused: Option<usize>,
155 },
156}
157
158#[derive(Clone)]
159pub enum ContentMode {
160 Scrollable,
161 Inline {
162 displayed_lines: usize,
163 total_lines: usize,
164 },
165}
166
167impl ContentMode {
168 pub fn is_limited(&self) -> bool {
169 match self {
170 ContentMode::Scrollable => false,
171 ContentMode::Inline {
172 displayed_lines,
173 total_lines,
174 } => displayed_lines < total_lines,
175 }
176 }
177
178 pub fn is_scrollable(&self) -> bool {
179 matches!(self, ContentMode::Scrollable)
180 }
181}
182
183#[derive(Debug)]
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(
209 workspace,
210 TerminalKind::Shell(working_directory),
211 window,
212 cx,
213 )
214 .detach_and_log_err(cx);
215 }
216
217 pub fn new(
218 terminal: Entity<Terminal>,
219 workspace: WeakEntity<Workspace>,
220 workspace_id: Option<WorkspaceId>,
221 project: WeakEntity<Project>,
222 window: &mut Window,
223 cx: &mut Context<Self>,
224 ) -> Self {
225 let workspace_handle = workspace.clone();
226 let terminal_subscriptions =
227 subscribe_for_terminal_events(&terminal, workspace, window, cx);
228
229 let focus_handle = cx.focus_handle();
230 let focus_in = cx.on_focus_in(&focus_handle, window, |terminal_view, window, cx| {
231 terminal_view.focus_in(window, cx);
232 });
233 let focus_out = cx.on_focus_out(
234 &focus_handle,
235 window,
236 |terminal_view, _event, window, cx| {
237 terminal_view.focus_out(window, cx);
238 },
239 );
240 let cursor_shape = TerminalSettings::get_global(cx)
241 .cursor_shape
242 .unwrap_or_default();
243
244 let scroll_handle = TerminalScrollHandle::new(terminal.read(cx));
245
246 Self {
247 terminal,
248 workspace: workspace_handle,
249 project,
250 has_bell: false,
251 focus_handle,
252 context_menu: None,
253 cursor_shape,
254 blink_state: true,
255 blinking_terminal_enabled: false,
256 blinking_paused: false,
257 blink_epoch: 0,
258 hover: None,
259 hover_tooltip_update: Task::ready(()),
260 mode: TerminalMode::Standalone,
261 workspace_id,
262 show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
263 block_below_cursor: None,
264 scroll_top: Pixels::ZERO,
265 scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
266 scroll_handle,
267 show_scrollbar: !Self::should_autohide_scrollbar(cx),
268 hide_scrollbar_task: None,
269 cwd_serialized: false,
270 marked_text: None,
271 marked_range_utf16: None,
272 _subscriptions: vec![
273 focus_in,
274 focus_out,
275 cx.observe_global::<SettingsStore>(Self::settings_changed),
276 ],
277 _terminal_subscriptions: terminal_subscriptions,
278 }
279 }
280
281 /// Enable 'embedded' mode where the terminal displays the full content with an optional limit of lines.
282 pub fn set_embedded_mode(
283 &mut self,
284 max_lines_when_unfocused: Option<usize>,
285 cx: &mut Context<Self>,
286 ) {
287 self.mode = TerminalMode::Embedded {
288 max_lines_when_unfocused,
289 };
290 cx.notify();
291 }
292
293 const MAX_EMBEDDED_LINES: usize = 1_000;
294
295 /// Returns the current `ContentMode` depending on the set `TerminalMode` and the current number of lines
296 ///
297 /// Note: Even in embedded mode, the terminal will fallback to scrollable when its content exceeds `MAX_EMBEDDED_LINES`
298 pub fn content_mode(&self, window: &Window, cx: &App) -> ContentMode {
299 match &self.mode {
300 TerminalMode::Standalone => ContentMode::Scrollable,
301 TerminalMode::Embedded {
302 max_lines_when_unfocused,
303 } => {
304 let total_lines = self.terminal.read(cx).total_lines();
305
306 if total_lines > Self::MAX_EMBEDDED_LINES {
307 ContentMode::Scrollable
308 } else {
309 let mut displayed_lines = total_lines;
310
311 if !self.focus_handle.is_focused(window) {
312 if let Some(max_lines) = max_lines_when_unfocused {
313 displayed_lines = displayed_lines.min(*max_lines)
314 }
315 }
316
317 ContentMode::Inline {
318 displayed_lines,
319 total_lines,
320 }
321 }
322 }
323 }
324 }
325
326 /// Sets the marked (pre-edit) text from the IME.
327 pub(crate) fn set_marked_text(
328 &mut self,
329 text: String,
330 range: Range<usize>,
331 cx: &mut Context<Self>,
332 ) {
333 self.marked_text = Some(text);
334 self.marked_range_utf16 = Some(range);
335 cx.notify();
336 }
337
338 /// Gets the current marked range (UTF-16).
339 pub(crate) fn marked_text_range(&self) -> Option<Range<usize>> {
340 self.marked_range_utf16.clone()
341 }
342
343 /// Clears the marked (pre-edit) text state.
344 pub(crate) fn clear_marked_text(&mut self, cx: &mut Context<Self>) {
345 if self.marked_text.is_some() {
346 self.marked_text = None;
347 self.marked_range_utf16 = 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 .map_or(false, |terminal_panel| {
389 terminal_panel.read(cx).assistant_enabled()
390 });
391 let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
392 menu.context(self.focus_handle.clone())
393 .action("New Terminal", Box::new(NewTerminal))
394 .separator()
395 .action("Copy", Box::new(Copy))
396 .action("Paste", Box::new(Paste))
397 .action("Select All", Box::new(SelectAll))
398 .action("Clear", Box::new(Clear))
399 .when(assistant_enabled, |menu| {
400 menu.separator()
401 .action("Inline Assist", Box::new(InlineAssist::default()))
402 })
403 .separator()
404 .action(
405 "Close Terminal Tab",
406 Box::new(CloseActiveItem {
407 save_intent: None,
408 close_pinned: true,
409 }),
410 )
411 });
412
413 window.focus(&context_menu.focus_handle(cx));
414 let subscription = cx.subscribe_in(
415 &context_menu,
416 window,
417 |this, _, _: &DismissEvent, window, cx| {
418 if this.context_menu.as_ref().is_some_and(|context_menu| {
419 context_menu.0.focus_handle(cx).contains_focused(window, cx)
420 }) {
421 cx.focus_self(window);
422 }
423 this.context_menu.take();
424 cx.notify();
425 },
426 );
427
428 self.context_menu = Some((context_menu, position, subscription));
429 }
430
431 fn settings_changed(&mut self, cx: &mut Context<Self>) {
432 let settings = TerminalSettings::get_global(cx);
433 let breadcrumb_visibility_changed = self.show_breadcrumbs != settings.toolbar.breadcrumbs;
434 self.show_breadcrumbs = settings.toolbar.breadcrumbs;
435
436 let new_cursor_shape = settings.cursor_shape.unwrap_or_default();
437 let old_cursor_shape = self.cursor_shape;
438 if old_cursor_shape != new_cursor_shape {
439 self.cursor_shape = new_cursor_shape;
440 self.terminal.update(cx, |term, _| {
441 term.set_cursor_shape(self.cursor_shape);
442 });
443 }
444
445 if breadcrumb_visibility_changed {
446 cx.emit(ItemEvent::UpdateBreadcrumbs);
447 }
448 cx.notify();
449 }
450
451 fn show_character_palette(
452 &mut self,
453 _: &ShowCharacterPalette,
454 window: &mut Window,
455 cx: &mut Context<Self>,
456 ) {
457 if self
458 .terminal
459 .read(cx)
460 .last_content
461 .mode
462 .contains(TermMode::ALT_SCREEN)
463 {
464 self.terminal.update(cx, |term, cx| {
465 term.try_keystroke(
466 &Keystroke::parse("ctrl-cmd-space").unwrap(),
467 TerminalSettings::get_global(cx).option_as_meta,
468 )
469 });
470 } else {
471 window.show_character_palette();
472 }
473 }
474
475 fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
476 self.terminal.update(cx, |term, _| term.select_all());
477 cx.notify();
478 }
479
480 fn rerun_task(&mut self, _: &RerunTask, window: &mut Window, cx: &mut Context<Self>) {
481 let task = self
482 .terminal
483 .read(cx)
484 .task()
485 .map(|task| terminal_rerun_override(&task.id))
486 .unwrap_or_default();
487 window.dispatch_action(Box::new(task), cx);
488 }
489
490 fn clear(&mut self, _: &Clear, _: &mut Window, cx: &mut Context<Self>) {
491 self.scroll_top = px(0.);
492 self.terminal.update(cx, |term, _| term.clear());
493 cx.notify();
494 }
495
496 fn max_scroll_top(&self, cx: &App) -> Pixels {
497 let terminal = self.terminal.read(cx);
498
499 let Some(block) = self.block_below_cursor.as_ref() else {
500 return Pixels::ZERO;
501 };
502
503 let line_height = terminal.last_content().terminal_bounds.line_height;
504 let viewport_lines = terminal.viewport_lines();
505 let cursor = point_to_viewport(
506 terminal.last_content.display_offset,
507 terminal.last_content.cursor.point,
508 )
509 .unwrap_or_default();
510 let max_scroll_top_in_lines =
511 (block.height as usize).saturating_sub(viewport_lines.saturating_sub(cursor.line + 1));
512
513 max_scroll_top_in_lines as f32 * line_height
514 }
515
516 fn scroll_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
517 let terminal_content = self.terminal.read(cx).last_content();
518
519 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
520 let line_height = terminal_content.terminal_bounds.line_height;
521 let y_delta = event.delta.pixel_delta(line_height).y;
522 if y_delta < Pixels::ZERO || self.scroll_top > Pixels::ZERO {
523 self.scroll_top = cmp::max(
524 Pixels::ZERO,
525 cmp::min(self.scroll_top - y_delta, self.max_scroll_top(cx)),
526 );
527 cx.notify();
528 return;
529 }
530 }
531 self.terminal.update(cx, |term, _| term.scroll_wheel(event));
532 }
533
534 fn scroll_line_up(&mut self, _: &ScrollLineUp, _: &mut Window, cx: &mut Context<Self>) {
535 let terminal_content = self.terminal.read(cx).last_content();
536 if self.block_below_cursor.is_some()
537 && terminal_content.display_offset == 0
538 && self.scroll_top > Pixels::ZERO
539 {
540 let line_height = terminal_content.terminal_bounds.line_height;
541 self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
542 return;
543 }
544
545 self.terminal.update(cx, |term, _| term.scroll_line_up());
546 cx.notify();
547 }
548
549 fn scroll_line_down(&mut self, _: &ScrollLineDown, _: &mut Window, cx: &mut Context<Self>) {
550 let terminal_content = self.terminal.read(cx).last_content();
551 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
552 let max_scroll_top = self.max_scroll_top(cx);
553 if self.scroll_top < max_scroll_top {
554 let line_height = terminal_content.terminal_bounds.line_height;
555 self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
556 }
557 return;
558 }
559
560 self.terminal.update(cx, |term, _| term.scroll_line_down());
561 cx.notify();
562 }
563
564 fn scroll_page_up(&mut self, _: &ScrollPageUp, _: &mut Window, cx: &mut Context<Self>) {
565 if self.scroll_top == Pixels::ZERO {
566 self.terminal.update(cx, |term, _| term.scroll_page_up());
567 } else {
568 let line_height = self
569 .terminal
570 .read(cx)
571 .last_content
572 .terminal_bounds
573 .line_height();
574 let visible_block_lines = (self.scroll_top / line_height) as usize;
575 let viewport_lines = self.terminal.read(cx).viewport_lines();
576 let visible_content_lines = viewport_lines - visible_block_lines;
577
578 if visible_block_lines >= viewport_lines {
579 self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
580 } else {
581 self.scroll_top = px(0.);
582 self.terminal
583 .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
584 }
585 }
586 cx.notify();
587 }
588
589 fn scroll_page_down(&mut self, _: &ScrollPageDown, _: &mut Window, cx: &mut Context<Self>) {
590 self.terminal.update(cx, |term, _| term.scroll_page_down());
591 let terminal = self.terminal.read(cx);
592 if terminal.last_content().display_offset < terminal.viewport_lines() {
593 self.scroll_top = self.max_scroll_top(cx);
594 }
595 cx.notify();
596 }
597
598 fn scroll_to_top(&mut self, _: &ScrollToTop, _: &mut Window, cx: &mut Context<Self>) {
599 self.terminal.update(cx, |term, _| term.scroll_to_top());
600 cx.notify();
601 }
602
603 fn scroll_to_bottom(&mut self, _: &ScrollToBottom, _: &mut Window, cx: &mut Context<Self>) {
604 self.terminal.update(cx, |term, _| term.scroll_to_bottom());
605 if self.block_below_cursor.is_some() {
606 self.scroll_top = self.max_scroll_top(cx);
607 }
608 cx.notify();
609 }
610
611 fn toggle_vi_mode(&mut self, _: &ToggleViMode, _: &mut Window, cx: &mut Context<Self>) {
612 self.terminal.update(cx, |term, _| term.toggle_vi_mode());
613 cx.notify();
614 }
615
616 pub fn should_show_cursor(&self, focused: bool, cx: &mut Context<Self>) -> bool {
617 //Don't blink the cursor when not focused, blinking is disabled, or paused
618 if !focused
619 || self.blinking_paused
620 || self
621 .terminal
622 .read(cx)
623 .last_content
624 .mode
625 .contains(TermMode::ALT_SCREEN)
626 {
627 return true;
628 }
629
630 match TerminalSettings::get_global(cx).blinking {
631 //If the user requested to never blink, don't blink it.
632 TerminalBlink::Off => true,
633 //If the terminal is controlling it, check terminal mode
634 TerminalBlink::TerminalControlled => {
635 !self.blinking_terminal_enabled || self.blink_state
636 }
637 TerminalBlink::On => self.blink_state,
638 }
639 }
640
641 fn blink_cursors(&mut self, epoch: usize, window: &mut Window, cx: &mut Context<Self>) {
642 if epoch == self.blink_epoch && !self.blinking_paused {
643 self.blink_state = !self.blink_state;
644 cx.notify();
645
646 let epoch = self.next_blink_epoch();
647 cx.spawn_in(window, async move |this, cx| {
648 Timer::after(CURSOR_BLINK_INTERVAL).await;
649 this.update_in(cx, |this, window, cx| this.blink_cursors(epoch, window, cx))
650 .ok();
651 })
652 .detach();
653 }
654 }
655
656 pub fn pause_cursor_blinking(&mut self, window: &mut Window, cx: &mut Context<Self>) {
657 self.blink_state = true;
658 cx.notify();
659
660 let epoch = self.next_blink_epoch();
661 cx.spawn_in(window, async move |this, cx| {
662 Timer::after(CURSOR_BLINK_INTERVAL).await;
663 this.update_in(cx, |this, window, cx| {
664 this.resume_cursor_blinking(epoch, window, cx)
665 })
666 .ok();
667 })
668 .detach();
669 }
670
671 pub fn terminal(&self) -> &Entity<Terminal> {
672 &self.terminal
673 }
674
675 pub fn set_block_below_cursor(
676 &mut self,
677 block: BlockProperties,
678 window: &mut Window,
679 cx: &mut Context<Self>,
680 ) {
681 self.block_below_cursor = Some(Rc::new(block));
682 self.scroll_to_bottom(&ScrollToBottom, window, cx);
683 cx.notify();
684 }
685
686 pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
687 self.block_below_cursor = None;
688 self.scroll_top = Pixels::ZERO;
689 cx.notify();
690 }
691
692 fn next_blink_epoch(&mut self) -> usize {
693 self.blink_epoch += 1;
694 self.blink_epoch
695 }
696
697 fn resume_cursor_blinking(
698 &mut self,
699 epoch: usize,
700 window: &mut Window,
701 cx: &mut Context<Self>,
702 ) {
703 if epoch == self.blink_epoch {
704 self.blinking_paused = false;
705 self.blink_cursors(epoch, window, cx);
706 }
707 }
708
709 ///Attempt to paste the clipboard into the terminal
710 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
711 self.terminal.update(cx, |term, _| term.copy(None));
712 cx.notify();
713 }
714
715 ///Attempt to paste the clipboard into the terminal
716 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
717 if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
718 self.terminal
719 .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
720 }
721 }
722
723 fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
724 self.clear_bell(cx);
725 self.terminal.update(cx, |term, _| {
726 term.input(text.0.to_string().into_bytes());
727 });
728 }
729
730 fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
731 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
732 self.clear_bell(cx);
733 self.terminal.update(cx, |term, cx| {
734 let processed =
735 term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
736 if processed && term.vi_mode_enabled() {
737 cx.notify();
738 }
739 processed
740 });
741 }
742 }
743
744 fn dispatch_context(&self, cx: &App) -> KeyContext {
745 let mut dispatch_context = KeyContext::new_with_defaults();
746 dispatch_context.add("Terminal");
747
748 if self.terminal.read(cx).vi_mode_enabled() {
749 dispatch_context.add("vi_mode");
750 }
751
752 let mode = self.terminal.read(cx).last_content.mode;
753 dispatch_context.set(
754 "screen",
755 if mode.contains(TermMode::ALT_SCREEN) {
756 "alt"
757 } else {
758 "normal"
759 },
760 );
761
762 if mode.contains(TermMode::APP_CURSOR) {
763 dispatch_context.add("DECCKM");
764 }
765 if mode.contains(TermMode::APP_KEYPAD) {
766 dispatch_context.add("DECPAM");
767 } else {
768 dispatch_context.add("DECPNM");
769 }
770 if mode.contains(TermMode::SHOW_CURSOR) {
771 dispatch_context.add("DECTCEM");
772 }
773 if mode.contains(TermMode::LINE_WRAP) {
774 dispatch_context.add("DECAWM");
775 }
776 if mode.contains(TermMode::ORIGIN) {
777 dispatch_context.add("DECOM");
778 }
779 if mode.contains(TermMode::INSERT) {
780 dispatch_context.add("IRM");
781 }
782 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
783 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
784 dispatch_context.add("LNM");
785 }
786 if mode.contains(TermMode::FOCUS_IN_OUT) {
787 dispatch_context.add("report_focus");
788 }
789 if mode.contains(TermMode::ALTERNATE_SCROLL) {
790 dispatch_context.add("alternate_scroll");
791 }
792 if mode.contains(TermMode::BRACKETED_PASTE) {
793 dispatch_context.add("bracketed_paste");
794 }
795 if mode.intersects(TermMode::MOUSE_MODE) {
796 dispatch_context.add("any_mouse_reporting");
797 }
798 {
799 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
800 "click"
801 } else if mode.contains(TermMode::MOUSE_DRAG) {
802 "drag"
803 } else if mode.contains(TermMode::MOUSE_MOTION) {
804 "motion"
805 } else {
806 "off"
807 };
808 dispatch_context.set("mouse_reporting", mouse_reporting);
809 }
810 {
811 let format = if mode.contains(TermMode::SGR_MOUSE) {
812 "sgr"
813 } else if mode.contains(TermMode::UTF8_MOUSE) {
814 "utf8"
815 } else {
816 "normal"
817 };
818 dispatch_context.set("mouse_format", format);
819 };
820
821 if self.terminal.read(cx).last_content.selection.is_some() {
822 dispatch_context.add("selection");
823 }
824
825 dispatch_context
826 }
827
828 fn set_terminal(
829 &mut self,
830 terminal: Entity<Terminal>,
831 window: &mut Window,
832 cx: &mut Context<TerminalView>,
833 ) {
834 self._terminal_subscriptions =
835 subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
836 self.terminal = terminal;
837 }
838
839 // Hack: Using editor in terminal causes cyclic dependency i.e. editor -> terminal -> project -> editor.
840 fn map_show_scrollbar_from_editor_to_terminal(
841 show_scrollbar: editor::ShowScrollbar,
842 ) -> terminal_settings::ShowScrollbar {
843 match show_scrollbar {
844 editor::ShowScrollbar::Auto => terminal_settings::ShowScrollbar::Auto,
845 editor::ShowScrollbar::System => terminal_settings::ShowScrollbar::System,
846 editor::ShowScrollbar::Always => terminal_settings::ShowScrollbar::Always,
847 editor::ShowScrollbar::Never => terminal_settings::ShowScrollbar::Never,
848 }
849 }
850
851 fn should_show_scrollbar(cx: &App) -> bool {
852 let show = TerminalSettings::get_global(cx)
853 .scrollbar
854 .show
855 .unwrap_or_else(|| {
856 Self::map_show_scrollbar_from_editor_to_terminal(
857 EditorSettings::get_global(cx).scrollbar.show,
858 )
859 });
860 match show {
861 terminal_settings::ShowScrollbar::Auto => true,
862 terminal_settings::ShowScrollbar::System => true,
863 terminal_settings::ShowScrollbar::Always => true,
864 terminal_settings::ShowScrollbar::Never => false,
865 }
866 }
867
868 fn should_autohide_scrollbar(cx: &App) -> bool {
869 let show = TerminalSettings::get_global(cx)
870 .scrollbar
871 .show
872 .unwrap_or_else(|| {
873 Self::map_show_scrollbar_from_editor_to_terminal(
874 EditorSettings::get_global(cx).scrollbar.show,
875 )
876 });
877 match show {
878 terminal_settings::ShowScrollbar::Auto => true,
879 terminal_settings::ShowScrollbar::System => cx
880 .try_global::<ScrollbarAutoHide>()
881 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
882 terminal_settings::ShowScrollbar::Always => false,
883 terminal_settings::ShowScrollbar::Never => true,
884 }
885 }
886
887 fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
888 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
889 if !Self::should_autohide_scrollbar(cx) {
890 return;
891 }
892 self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
893 cx.background_executor()
894 .timer(SCROLLBAR_SHOW_INTERVAL)
895 .await;
896 panel
897 .update(cx, |panel, cx| {
898 panel.show_scrollbar = false;
899 cx.notify();
900 })
901 .log_err();
902 }))
903 }
904
905 fn render_scrollbar(&self, window: &Window, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
906 if !Self::should_show_scrollbar(cx)
907 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
908 || !self.content_mode(window, cx).is_scrollable()
909 {
910 return None;
911 }
912
913 if self.terminal.read(cx).total_lines() == self.terminal.read(cx).viewport_lines() {
914 return None;
915 }
916
917 self.scroll_handle.update(self.terminal.read(cx));
918
919 if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
920 self.terminal.update(cx, |term, _| {
921 let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
922 match delta.cmp(&0) {
923 std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
924 std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
925 std::cmp::Ordering::Equal => {}
926 }
927 });
928 }
929
930 Some(
931 div()
932 .occlude()
933 .id("terminal-view-scroll")
934 .on_mouse_move(cx.listener(|_, _, _window, cx| {
935 cx.notify();
936 cx.stop_propagation()
937 }))
938 .on_hover(|_, _window, cx| {
939 cx.stop_propagation();
940 })
941 .on_any_mouse_down(|_, _window, cx| {
942 cx.stop_propagation();
943 })
944 .on_mouse_up(
945 MouseButton::Left,
946 cx.listener(|terminal_view, _, window, cx| {
947 if !terminal_view.scrollbar_state.is_dragging()
948 && !terminal_view.focus_handle.contains_focused(window, cx)
949 {
950 terminal_view.hide_scrollbar(cx);
951 cx.notify();
952 }
953 cx.stop_propagation();
954 }),
955 )
956 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
957 cx.notify();
958 }))
959 .absolute()
960 .top_0()
961 .bottom_0()
962 .right_0()
963 .h_full()
964 .w(TERMINAL_SCROLLBAR_WIDTH)
965 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
966 )
967 }
968
969 fn rerun_button(task: &TaskState) -> Option<IconButton> {
970 if !task.show_rerun {
971 return None;
972 }
973
974 let task_id = task.id.clone();
975 Some(
976 IconButton::new("rerun-icon", IconName::Rerun)
977 .icon_size(IconSize::Small)
978 .size(ButtonSize::Compact)
979 .icon_color(Color::Default)
980 .shape(ui::IconButtonShape::Square)
981 .tooltip(move |window, cx| {
982 Tooltip::for_action("Rerun task", &RerunTask, window, cx)
983 })
984 .on_click(move |_, window, cx| {
985 window.dispatch_action(Box::new(terminal_rerun_override(&task_id)), cx);
986 }),
987 )
988 }
989}
990
991fn terminal_rerun_override(task: &TaskId) -> zed_actions::Rerun {
992 zed_actions::Rerun {
993 task_id: Some(task.0.clone()),
994 allow_concurrent_runs: Some(true),
995 use_new_terminal: Some(false),
996 reevaluate_context: false,
997 }
998}
999
1000fn subscribe_for_terminal_events(
1001 terminal: &Entity<Terminal>,
1002 workspace: WeakEntity<Workspace>,
1003 window: &mut Window,
1004 cx: &mut Context<TerminalView>,
1005) -> Vec<Subscription> {
1006 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
1007 let mut previous_cwd = None;
1008 let terminal_events_subscription = cx.subscribe_in(
1009 terminal,
1010 window,
1011 move |terminal_view, terminal, event, window, cx| {
1012 let current_cwd = terminal.read(cx).working_directory();
1013 if current_cwd != previous_cwd {
1014 previous_cwd = current_cwd;
1015 terminal_view.cwd_serialized = false;
1016 }
1017
1018 match event {
1019 Event::Wakeup => {
1020 cx.notify();
1021 cx.emit(Event::Wakeup);
1022 cx.emit(ItemEvent::UpdateTab);
1023 cx.emit(SearchEvent::MatchesInvalidated);
1024 }
1025
1026 Event::Bell => {
1027 terminal_view.has_bell = true;
1028 cx.emit(Event::Wakeup);
1029 }
1030
1031 Event::BlinkChanged(blinking) => {
1032 if matches!(
1033 TerminalSettings::get_global(cx).blinking,
1034 TerminalBlink::TerminalControlled
1035 ) {
1036 terminal_view.blinking_terminal_enabled = *blinking;
1037 }
1038 }
1039
1040 Event::TitleChanged => {
1041 cx.emit(ItemEvent::UpdateTab);
1042 }
1043
1044 Event::NewNavigationTarget(maybe_navigation_target) => {
1045 match maybe_navigation_target
1046 .as_ref()
1047 .zip(terminal.read(cx).last_content.last_hovered_word.as_ref())
1048 {
1049 Some((MaybeNavigationTarget::Url(url), hovered_word)) => {
1050 if Some(hovered_word)
1051 != terminal_view
1052 .hover
1053 .as_ref()
1054 .map(|hover| &hover.hovered_word)
1055 {
1056 terminal_view.hover = Some(HoverTarget {
1057 tooltip: url.clone(),
1058 hovered_word: hovered_word.clone(),
1059 });
1060 terminal_view.hover_tooltip_update = Task::ready(());
1061 cx.notify();
1062 }
1063 }
1064 Some((MaybeNavigationTarget::PathLike(path_like_target), hovered_word)) => {
1065 if Some(hovered_word)
1066 != terminal_view
1067 .hover
1068 .as_ref()
1069 .map(|hover| &hover.hovered_word)
1070 {
1071 let valid_files_to_open_task = possible_open_target(
1072 &workspace,
1073 &path_like_target.terminal_dir,
1074 &path_like_target.maybe_path,
1075 cx,
1076 );
1077 let hovered_word = hovered_word.clone();
1078
1079 terminal_view.hover = None;
1080 terminal_view.hover_tooltip_update =
1081 cx.spawn(async move |terminal_view, cx| {
1082 let file_to_open = valid_files_to_open_task.await;
1083 terminal_view
1084 .update(cx, |terminal_view, _| match file_to_open {
1085 Some(
1086 OpenTarget::File(path, _)
1087 | OpenTarget::Worktree(path, _),
1088 ) => {
1089 terminal_view.hover = Some(HoverTarget {
1090 tooltip: path.to_string(|path| {
1091 path.to_string_lossy().to_string()
1092 }),
1093 hovered_word,
1094 });
1095 }
1096 None => {
1097 terminal_view.hover = None;
1098 }
1099 })
1100 .ok();
1101 });
1102 cx.notify();
1103 }
1104 }
1105 None => {
1106 terminal_view.hover = None;
1107 terminal_view.hover_tooltip_update = Task::ready(());
1108 cx.notify();
1109 }
1110 }
1111 }
1112
1113 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
1114 MaybeNavigationTarget::Url(url) => cx.open_url(url),
1115
1116 MaybeNavigationTarget::PathLike(path_like_target) => {
1117 if terminal_view.hover.is_none() {
1118 return;
1119 }
1120 let task_workspace = workspace.clone();
1121 let path_like_target = path_like_target.clone();
1122 cx.spawn_in(window, async move |terminal_view, cx| {
1123 let open_target = terminal_view
1124 .update(cx, |_, cx| {
1125 possible_open_target(
1126 &task_workspace,
1127 &path_like_target.terminal_dir,
1128 &path_like_target.maybe_path,
1129 cx,
1130 )
1131 })?
1132 .await;
1133 if let Some(open_target) = open_target {
1134 let path_to_open = open_target.path();
1135 let opened_items = task_workspace
1136 .update_in(cx, |workspace, window, cx| {
1137 workspace.open_paths(
1138 vec![path_to_open.path.clone()],
1139 OpenOptions {
1140 visible: Some(OpenVisible::OnlyDirectories),
1141 ..Default::default()
1142 },
1143 None,
1144 window,
1145 cx,
1146 )
1147 })
1148 .context("workspace update")?
1149 .await;
1150 if opened_items.len() != 1 {
1151 debug_panic!(
1152 "Received {} items for one path {path_to_open:?}",
1153 opened_items.len(),
1154 );
1155 }
1156
1157 if let Some(opened_item) = opened_items.first() {
1158 if open_target.is_file() {
1159 if let Some(Ok(opened_item)) = opened_item {
1160 if let Some(row) = path_to_open.row {
1161 let col = path_to_open.column.unwrap_or(0);
1162 if let Some(active_editor) =
1163 opened_item.downcast::<Editor>()
1164 {
1165 active_editor
1166 .downgrade()
1167 .update_in(cx, |editor, window, cx| {
1168 editor.go_to_singleton_buffer_point(
1169 language::Point::new(
1170 row.saturating_sub(1),
1171 col.saturating_sub(1),
1172 ),
1173 window,
1174 cx,
1175 )
1176 })
1177 .log_err();
1178 }
1179 }
1180 }
1181 } else if open_target.is_dir() {
1182 task_workspace.update(cx, |workspace, cx| {
1183 workspace.project().update(cx, |_, cx| {
1184 cx.emit(project::Event::ActivateProjectPanel);
1185 })
1186 })?;
1187 }
1188 }
1189 }
1190
1191 anyhow::Ok(())
1192 })
1193 .detach_and_log_err(cx)
1194 }
1195 },
1196 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
1197 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
1198 Event::SelectionsChanged => {
1199 window.invalidate_character_coordinates();
1200 cx.emit(SearchEvent::ActiveMatchChanged)
1201 }
1202 }
1203 },
1204 );
1205 vec![terminal_subscription, terminal_events_subscription]
1206}
1207
1208#[derive(Debug, Clone)]
1209enum OpenTarget {
1210 Worktree(PathWithPosition, Entry),
1211 File(PathWithPosition, Metadata),
1212}
1213
1214impl OpenTarget {
1215 fn is_file(&self) -> bool {
1216 match self {
1217 OpenTarget::Worktree(_, entry) => entry.is_file(),
1218 OpenTarget::File(_, metadata) => !metadata.is_dir,
1219 }
1220 }
1221
1222 fn is_dir(&self) -> bool {
1223 match self {
1224 OpenTarget::Worktree(_, entry) => entry.is_dir(),
1225 OpenTarget::File(_, metadata) => metadata.is_dir,
1226 }
1227 }
1228
1229 fn path(&self) -> &PathWithPosition {
1230 match self {
1231 OpenTarget::Worktree(path, _) => path,
1232 OpenTarget::File(path, _) => path,
1233 }
1234 }
1235}
1236
1237fn possible_open_target(
1238 workspace: &WeakEntity<Workspace>,
1239 cwd: &Option<PathBuf>,
1240 maybe_path: &str,
1241 cx: &App,
1242) -> Task<Option<OpenTarget>> {
1243 let Some(workspace) = workspace.upgrade() else {
1244 return Task::ready(None);
1245 };
1246 // We have to check for both paths, as on Unix, certain paths with positions are valid file paths too.
1247 // We can be on FS remote part, without real FS, so cannot canonicalize or check for existence the path right away.
1248 let mut potential_paths = Vec::new();
1249 let original_path = PathWithPosition::from_path(PathBuf::from(maybe_path));
1250 let path_with_position = PathWithPosition::parse_str(maybe_path);
1251 let worktree_candidates = workspace
1252 .read(cx)
1253 .worktrees(cx)
1254 .sorted_by_key(|worktree| {
1255 let worktree_root = worktree.read(cx).abs_path();
1256 match cwd
1257 .as_ref()
1258 .and_then(|cwd| worktree_root.strip_prefix(cwd).ok())
1259 {
1260 Some(cwd_child) => cwd_child.components().count(),
1261 None => usize::MAX,
1262 }
1263 })
1264 .collect::<Vec<_>>();
1265 // Since we do not check paths via FS and joining, we need to strip off potential `./`, `a/`, `b/` prefixes out of it.
1266 for prefix_str in GIT_DIFF_PATH_PREFIXES.iter().chain(std::iter::once(&".")) {
1267 if let Some(stripped) = original_path.path.strip_prefix(prefix_str).ok() {
1268 potential_paths.push(PathWithPosition {
1269 path: stripped.to_owned(),
1270 row: original_path.row,
1271 column: original_path.column,
1272 });
1273 }
1274 if let Some(stripped) = path_with_position.path.strip_prefix(prefix_str).ok() {
1275 potential_paths.push(PathWithPosition {
1276 path: stripped.to_owned(),
1277 row: path_with_position.row,
1278 column: path_with_position.column,
1279 });
1280 }
1281 }
1282
1283 let insert_both_paths = original_path != path_with_position;
1284 potential_paths.insert(0, original_path);
1285 if insert_both_paths {
1286 potential_paths.insert(1, path_with_position);
1287 }
1288
1289 // If we won't find paths "easily", we can traverse the entire worktree to look what ends with the potential path suffix.
1290 // That will be slow, though, so do the fast checks first.
1291 let mut worktree_paths_to_check = Vec::new();
1292 for worktree in &worktree_candidates {
1293 let worktree_root = worktree.read(cx).abs_path();
1294 let mut paths_to_check = Vec::with_capacity(potential_paths.len());
1295
1296 for path_with_position in &potential_paths {
1297 let path_to_check = if worktree_root.ends_with(&path_with_position.path) {
1298 let root_path_with_position = PathWithPosition {
1299 path: worktree_root.to_path_buf(),
1300 row: path_with_position.row,
1301 column: path_with_position.column,
1302 };
1303 match worktree.read(cx).root_entry() {
1304 Some(root_entry) => {
1305 return Task::ready(Some(OpenTarget::Worktree(
1306 root_path_with_position,
1307 root_entry.clone(),
1308 )));
1309 }
1310 None => root_path_with_position,
1311 }
1312 } else {
1313 PathWithPosition {
1314 path: path_with_position
1315 .path
1316 .strip_prefix(&worktree_root)
1317 .unwrap_or(&path_with_position.path)
1318 .to_owned(),
1319 row: path_with_position.row,
1320 column: path_with_position.column,
1321 }
1322 };
1323
1324 if path_to_check.path.is_relative() {
1325 if let Some(entry) = worktree.read(cx).entry_for_path(&path_to_check.path) {
1326 return Task::ready(Some(OpenTarget::Worktree(
1327 PathWithPosition {
1328 path: worktree_root.join(&entry.path),
1329 row: path_to_check.row,
1330 column: path_to_check.column,
1331 },
1332 entry.clone(),
1333 )));
1334 }
1335 }
1336
1337 paths_to_check.push(path_to_check);
1338 }
1339
1340 if !paths_to_check.is_empty() {
1341 worktree_paths_to_check.push((worktree.clone(), paths_to_check));
1342 }
1343 }
1344
1345 // Before entire worktree traversal(s), make an attempt to do FS checks if available.
1346 let fs_paths_to_check = if workspace.read(cx).project().read(cx).is_local() {
1347 potential_paths
1348 .into_iter()
1349 .flat_map(|path_to_check| {
1350 let mut paths_to_check = Vec::new();
1351 let maybe_path = &path_to_check.path;
1352 if maybe_path.starts_with("~") {
1353 if let Some(home_path) =
1354 maybe_path
1355 .strip_prefix("~")
1356 .ok()
1357 .and_then(|stripped_maybe_path| {
1358 Some(dirs::home_dir()?.join(stripped_maybe_path))
1359 })
1360 {
1361 paths_to_check.push(PathWithPosition {
1362 path: home_path,
1363 row: path_to_check.row,
1364 column: path_to_check.column,
1365 });
1366 }
1367 } else {
1368 paths_to_check.push(PathWithPosition {
1369 path: maybe_path.clone(),
1370 row: path_to_check.row,
1371 column: path_to_check.column,
1372 });
1373 if maybe_path.is_relative() {
1374 if let Some(cwd) = &cwd {
1375 paths_to_check.push(PathWithPosition {
1376 path: cwd.join(maybe_path),
1377 row: path_to_check.row,
1378 column: path_to_check.column,
1379 });
1380 }
1381 for worktree in &worktree_candidates {
1382 paths_to_check.push(PathWithPosition {
1383 path: worktree.read(cx).abs_path().join(maybe_path),
1384 row: path_to_check.row,
1385 column: path_to_check.column,
1386 });
1387 }
1388 }
1389 }
1390 paths_to_check
1391 })
1392 .collect()
1393 } else {
1394 Vec::new()
1395 };
1396
1397 let worktree_check_task = cx.spawn(async move |cx| {
1398 for (worktree, worktree_paths_to_check) in worktree_paths_to_check {
1399 let found_entry = worktree
1400 .update(cx, |worktree, _| {
1401 let worktree_root = worktree.abs_path();
1402 let mut traversal = worktree.traverse_from_path(true, true, false, "".as_ref());
1403 while let Some(entry) = traversal.next() {
1404 if let Some(path_in_worktree) = worktree_paths_to_check
1405 .iter()
1406 .find(|path_to_check| entry.path.ends_with(&path_to_check.path))
1407 {
1408 return Some(OpenTarget::Worktree(
1409 PathWithPosition {
1410 path: worktree_root.join(&entry.path),
1411 row: path_in_worktree.row,
1412 column: path_in_worktree.column,
1413 },
1414 entry.clone(),
1415 ));
1416 }
1417 }
1418 None
1419 })
1420 .ok()?;
1421 if let Some(found_entry) = found_entry {
1422 return Some(found_entry);
1423 }
1424 }
1425 None
1426 });
1427
1428 let fs = workspace.read(cx).project().read(cx).fs().clone();
1429 cx.background_spawn(async move {
1430 for mut path_to_check in fs_paths_to_check {
1431 if let Some(fs_path_to_check) = fs.canonicalize(&path_to_check.path).await.ok() {
1432 if let Some(metadata) = fs.metadata(&fs_path_to_check).await.ok().flatten() {
1433 path_to_check.path = fs_path_to_check;
1434 return Some(OpenTarget::File(path_to_check, metadata));
1435 }
1436 }
1437 }
1438
1439 worktree_check_task.await
1440 })
1441}
1442
1443fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
1444 let str = query.as_str();
1445 if query.is_regex() {
1446 if str == "." {
1447 return None;
1448 }
1449 RegexSearch::new(str).ok()
1450 } else {
1451 RegexSearch::new(®ex::escape(str)).ok()
1452 }
1453}
1454
1455impl TerminalView {
1456 fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1457 self.clear_bell(cx);
1458 self.pause_cursor_blinking(window, cx);
1459
1460 self.terminal.update(cx, |term, cx| {
1461 let handled = term.try_keystroke(
1462 &event.keystroke,
1463 TerminalSettings::get_global(cx).option_as_meta,
1464 );
1465 if handled {
1466 cx.stop_propagation();
1467 }
1468 });
1469 }
1470
1471 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1472 self.terminal.update(cx, |terminal, _| {
1473 terminal.set_cursor_shape(self.cursor_shape);
1474 terminal.focus_in();
1475 });
1476 self.blink_cursors(self.blink_epoch, window, cx);
1477 window.invalidate_character_coordinates();
1478 cx.notify();
1479 }
1480
1481 fn focus_out(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1482 self.terminal.update(cx, |terminal, _| {
1483 terminal.focus_out();
1484 terminal.set_cursor_shape(CursorShape::Hollow);
1485 });
1486 self.hide_scrollbar(cx);
1487 cx.notify();
1488 }
1489}
1490
1491impl Render for TerminalView {
1492 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1493 let terminal_handle = self.terminal.clone();
1494 let terminal_view_handle = cx.entity();
1495
1496 let focused = self.focus_handle.is_focused(window);
1497
1498 // Always calculate scrollbar width to prevent layout shift
1499 let scrollbar_width = if Self::should_show_scrollbar(cx)
1500 && self.content_mode(window, cx).is_scrollable()
1501 && self.terminal.read(cx).total_lines() > self.terminal.read(cx).viewport_lines()
1502 {
1503 TERMINAL_SCROLLBAR_WIDTH
1504 } else {
1505 px(0.)
1506 };
1507
1508 div()
1509 .id("terminal-view")
1510 .size_full()
1511 .relative()
1512 .track_focus(&self.focus_handle(cx))
1513 .key_context(self.dispatch_context(cx))
1514 .on_action(cx.listener(TerminalView::send_text))
1515 .on_action(cx.listener(TerminalView::send_keystroke))
1516 .on_action(cx.listener(TerminalView::copy))
1517 .on_action(cx.listener(TerminalView::paste))
1518 .on_action(cx.listener(TerminalView::clear))
1519 .on_action(cx.listener(TerminalView::scroll_line_up))
1520 .on_action(cx.listener(TerminalView::scroll_line_down))
1521 .on_action(cx.listener(TerminalView::scroll_page_up))
1522 .on_action(cx.listener(TerminalView::scroll_page_down))
1523 .on_action(cx.listener(TerminalView::scroll_to_top))
1524 .on_action(cx.listener(TerminalView::scroll_to_bottom))
1525 .on_action(cx.listener(TerminalView::toggle_vi_mode))
1526 .on_action(cx.listener(TerminalView::show_character_palette))
1527 .on_action(cx.listener(TerminalView::select_all))
1528 .on_action(cx.listener(TerminalView::rerun_task))
1529 .on_key_down(cx.listener(Self::key_down))
1530 .on_mouse_down(
1531 MouseButton::Right,
1532 cx.listener(|this, event: &MouseDownEvent, window, cx| {
1533 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1534 if this.terminal.read(cx).last_content.selection.is_none() {
1535 this.terminal.update(cx, |terminal, _| {
1536 terminal.select_word_at_event_position(event);
1537 });
1538 };
1539 this.deploy_context_menu(event.position, window, cx);
1540 cx.notify();
1541 }
1542 }),
1543 )
1544 .on_hover(cx.listener(|this, hovered, window, cx| {
1545 if *hovered {
1546 this.show_scrollbar = true;
1547 this.hide_scrollbar_task.take();
1548 cx.notify();
1549 } else if !this.focus_handle.contains_focused(window, cx) {
1550 this.hide_scrollbar(cx);
1551 }
1552 }))
1553 .child(
1554 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1555 div()
1556 .size_full()
1557 .bg(cx.theme().colors().editor_background)
1558 .when(scrollbar_width > px(0.), |div| div.pr(scrollbar_width))
1559 .child(TerminalElement::new(
1560 terminal_handle,
1561 terminal_view_handle,
1562 self.workspace.clone(),
1563 self.focus_handle.clone(),
1564 focused,
1565 self.should_show_cursor(focused, cx),
1566 self.block_below_cursor.clone(),
1567 self.mode.clone(),
1568 ))
1569 .when_some(self.render_scrollbar(window, cx), |div, scrollbar| {
1570 div.child(scrollbar)
1571 }),
1572 )
1573 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1574 deferred(
1575 anchored()
1576 .position(*position)
1577 .anchor(gpui::Corner::TopLeft)
1578 .child(menu.clone()),
1579 )
1580 .with_priority(1)
1581 }))
1582 }
1583}
1584
1585impl Item for TerminalView {
1586 type Event = ItemEvent;
1587
1588 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1589 let terminal = self.terminal().read(cx);
1590 let title = terminal.title(false);
1591 let pid = terminal.pty_info.pid_getter().fallback_pid();
1592
1593 Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
1594 cx.new(|_| TerminalTooltip::new(title.clone(), pid)).into()
1595 })))
1596 }
1597
1598 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1599 let terminal = self.terminal().read(cx);
1600 let title = terminal.title(true);
1601
1602 let (icon, icon_color, rerun_button) = match terminal.task() {
1603 Some(terminal_task) => match &terminal_task.status {
1604 TaskStatus::Running => (
1605 IconName::PlayFilled,
1606 Color::Disabled,
1607 TerminalView::rerun_button(terminal_task),
1608 ),
1609 TaskStatus::Unknown => (
1610 IconName::Warning,
1611 Color::Warning,
1612 TerminalView::rerun_button(terminal_task),
1613 ),
1614 TaskStatus::Completed { success } => {
1615 let rerun_button = TerminalView::rerun_button(terminal_task);
1616
1617 if *success {
1618 (IconName::Check, Color::Success, rerun_button)
1619 } else {
1620 (IconName::XCircle, Color::Error, rerun_button)
1621 }
1622 }
1623 },
1624 None => (IconName::Terminal, Color::Muted, None),
1625 };
1626
1627 h_flex()
1628 .gap_1()
1629 .group("term-tab-icon")
1630 .child(
1631 h_flex()
1632 .group("term-tab-icon")
1633 .child(
1634 div()
1635 .when(rerun_button.is_some(), |this| {
1636 this.hover(|style| style.invisible().w_0())
1637 })
1638 .child(Icon::new(icon).color(icon_color)),
1639 )
1640 .when_some(rerun_button, |this, rerun_button| {
1641 this.child(
1642 div()
1643 .absolute()
1644 .visible_on_hover("term-tab-icon")
1645 .child(rerun_button),
1646 )
1647 }),
1648 )
1649 .child(Label::new(title).color(params.text_color()))
1650 .into_any()
1651 }
1652
1653 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
1654 let terminal = self.terminal().read(cx);
1655 terminal.title(detail == 0).into()
1656 }
1657
1658 fn telemetry_event_text(&self) -> Option<&'static str> {
1659 None
1660 }
1661
1662 fn clone_on_split(
1663 &self,
1664 workspace_id: Option<WorkspaceId>,
1665 window: &mut Window,
1666 cx: &mut Context<Self>,
1667 ) -> Option<Entity<Self>> {
1668 let terminal = self
1669 .project
1670 .update(cx, |project, cx| {
1671 let terminal = self.terminal().read(cx);
1672 let working_directory = terminal
1673 .working_directory()
1674 .or_else(|| Some(project.active_project_directory(cx)?.to_path_buf()));
1675 let python_venv_directory = terminal.python_venv_directory.clone();
1676 project.create_terminal_with_venv(
1677 TerminalKind::Shell(working_directory),
1678 python_venv_directory,
1679 cx,
1680 )
1681 })
1682 .ok()?
1683 .log_err()?;
1684
1685 Some(cx.new(|cx| {
1686 TerminalView::new(
1687 terminal,
1688 self.workspace.clone(),
1689 workspace_id,
1690 self.project.clone(),
1691 window,
1692 cx,
1693 )
1694 }))
1695 }
1696
1697 fn is_dirty(&self, cx: &gpui::App) -> bool {
1698 match self.terminal.read(cx).task() {
1699 Some(task) => task.status == TaskStatus::Running,
1700 None => self.has_bell(),
1701 }
1702 }
1703
1704 fn has_conflict(&self, _cx: &App) -> bool {
1705 false
1706 }
1707
1708 fn can_save_as(&self, _cx: &App) -> bool {
1709 false
1710 }
1711
1712 fn is_singleton(&self, _cx: &App) -> bool {
1713 true
1714 }
1715
1716 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1717 Some(Box::new(handle.clone()))
1718 }
1719
1720 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1721 if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1722 ToolbarItemLocation::PrimaryLeft
1723 } else {
1724 ToolbarItemLocation::Hidden
1725 }
1726 }
1727
1728 fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1729 Some(vec![BreadcrumbText {
1730 text: self.terminal().read(cx).breadcrumb_text.clone(),
1731 highlights: None,
1732 font: None,
1733 }])
1734 }
1735
1736 fn added_to_workspace(
1737 &mut self,
1738 workspace: &mut Workspace,
1739 _: &mut Window,
1740 cx: &mut Context<Self>,
1741 ) {
1742 if self.terminal().read(cx).task().is_none() {
1743 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1744 log::debug!(
1745 "Updating workspace id for the terminal, old: {old_id:?}, new: {new_id:?}",
1746 );
1747 cx.background_spawn(TERMINAL_DB.update_workspace_id(
1748 new_id,
1749 old_id,
1750 cx.entity_id().as_u64(),
1751 ))
1752 .detach();
1753 }
1754 self.workspace_id = workspace.database_id();
1755 }
1756 }
1757
1758 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1759 f(*event)
1760 }
1761}
1762
1763impl SerializableItem for TerminalView {
1764 fn serialized_item_kind() -> &'static str {
1765 "Terminal"
1766 }
1767
1768 fn cleanup(
1769 workspace_id: WorkspaceId,
1770 alive_items: Vec<workspace::ItemId>,
1771 _window: &mut Window,
1772 cx: &mut App,
1773 ) -> Task<anyhow::Result<()>> {
1774 delete_unloaded_items(alive_items, workspace_id, "terminals", &TERMINAL_DB, cx)
1775 }
1776
1777 fn serialize(
1778 &mut self,
1779 _workspace: &mut Workspace,
1780 item_id: workspace::ItemId,
1781 _closing: bool,
1782 _: &mut Window,
1783 cx: &mut Context<Self>,
1784 ) -> Option<Task<anyhow::Result<()>>> {
1785 let terminal = self.terminal().read(cx);
1786 if terminal.task().is_some() {
1787 return None;
1788 }
1789
1790 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1791 self.cwd_serialized = true;
1792 Some(cx.background_spawn(async move {
1793 TERMINAL_DB
1794 .save_working_directory(item_id, workspace_id, cwd)
1795 .await
1796 }))
1797 } else {
1798 None
1799 }
1800 }
1801
1802 fn should_serialize(&self, _: &Self::Event) -> bool {
1803 !self.cwd_serialized
1804 }
1805
1806 fn deserialize(
1807 project: Entity<Project>,
1808 workspace: WeakEntity<Workspace>,
1809 workspace_id: workspace::WorkspaceId,
1810 item_id: workspace::ItemId,
1811 window: &mut Window,
1812 cx: &mut App,
1813 ) -> Task<anyhow::Result<Entity<Self>>> {
1814 window.spawn(cx, async move |cx| {
1815 let cwd = cx
1816 .update(|_window, cx| {
1817 let from_db = TERMINAL_DB
1818 .get_working_directory(item_id, workspace_id)
1819 .log_err()
1820 .flatten();
1821 if from_db
1822 .as_ref()
1823 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1824 {
1825 from_db
1826 } else {
1827 workspace
1828 .upgrade()
1829 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1830 }
1831 })
1832 .ok()
1833 .flatten();
1834
1835 let terminal = project
1836 .update(cx, |project, cx| {
1837 project.create_terminal(TerminalKind::Shell(cwd), cx)
1838 })?
1839 .await?;
1840 cx.update(|window, cx| {
1841 cx.new(|cx| {
1842 TerminalView::new(
1843 terminal,
1844 workspace,
1845 Some(workspace_id),
1846 project.downgrade(),
1847 window,
1848 cx,
1849 )
1850 })
1851 })
1852 })
1853 }
1854}
1855
1856impl SearchableItem for TerminalView {
1857 type Match = RangeInclusive<Point>;
1858
1859 fn supported_options(&self) -> SearchOptions {
1860 SearchOptions {
1861 case: false,
1862 word: false,
1863 regex: true,
1864 replacement: false,
1865 selection: false,
1866 find_in_results: false,
1867 }
1868 }
1869
1870 /// Clear stored matches
1871 fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1872 self.terminal().update(cx, |term, _| term.clear_matches())
1873 }
1874
1875 /// Store matches returned from find_matches somewhere for rendering
1876 fn update_matches(
1877 &mut self,
1878 matches: &[Self::Match],
1879 _window: &mut Window,
1880 cx: &mut Context<Self>,
1881 ) {
1882 self.terminal()
1883 .update(cx, |term, _| term.matches = matches.to_vec())
1884 }
1885
1886 /// Returns the selection content to pre-load into this search
1887 fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1888 self.terminal()
1889 .read(cx)
1890 .last_content
1891 .selection_text
1892 .clone()
1893 .unwrap_or_default()
1894 }
1895
1896 /// Focus match at given index into the Vec of matches
1897 fn activate_match(
1898 &mut self,
1899 index: usize,
1900 _: &[Self::Match],
1901 _window: &mut Window,
1902 cx: &mut Context<Self>,
1903 ) {
1904 self.terminal()
1905 .update(cx, |term, _| term.activate_match(index));
1906 cx.notify();
1907 }
1908
1909 /// Add selections for all matches given.
1910 fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1911 self.terminal()
1912 .update(cx, |term, _| term.select_matches(matches));
1913 cx.notify();
1914 }
1915
1916 /// Get all of the matches for this query, should be done on the background
1917 fn find_matches(
1918 &mut self,
1919 query: Arc<SearchQuery>,
1920 _: &mut Window,
1921 cx: &mut Context<Self>,
1922 ) -> Task<Vec<Self::Match>> {
1923 if let Some(s) = regex_search_for_query(&query) {
1924 self.terminal()
1925 .update(cx, |term, cx| term.find_matches(s, cx))
1926 } else {
1927 Task::ready(vec![])
1928 }
1929 }
1930
1931 /// Reports back to the search toolbar what the active match should be (the selection)
1932 fn active_match_index(
1933 &mut self,
1934 direction: Direction,
1935 matches: &[Self::Match],
1936 _: &mut Window,
1937 cx: &mut Context<Self>,
1938 ) -> Option<usize> {
1939 // Selection head might have a value if there's a selection that isn't
1940 // associated with a match. Therefore, if there are no matches, we should
1941 // report None, no matter the state of the terminal
1942 let res = if !matches.is_empty() {
1943 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1944 // If selection head is contained in a match. Return that match
1945 match direction {
1946 Direction::Prev => {
1947 // If no selection before selection head, return the first match
1948 Some(
1949 matches
1950 .iter()
1951 .enumerate()
1952 .rev()
1953 .find(|(_, search_match)| {
1954 search_match.contains(&selection_head)
1955 || search_match.start() < &selection_head
1956 })
1957 .map(|(ix, _)| ix)
1958 .unwrap_or(0),
1959 )
1960 }
1961 Direction::Next => {
1962 // If no selection after selection head, return the last match
1963 Some(
1964 matches
1965 .iter()
1966 .enumerate()
1967 .find(|(_, search_match)| {
1968 search_match.contains(&selection_head)
1969 || search_match.start() > &selection_head
1970 })
1971 .map(|(ix, _)| ix)
1972 .unwrap_or(matches.len().saturating_sub(1)),
1973 )
1974 }
1975 }
1976 } else {
1977 // Matches found but no active selection, return the first last one (closest to cursor)
1978 Some(matches.len().saturating_sub(1))
1979 }
1980 } else {
1981 None
1982 };
1983
1984 res
1985 }
1986 fn replace(
1987 &mut self,
1988 _: &Self::Match,
1989 _: &SearchQuery,
1990 _window: &mut Window,
1991 _: &mut Context<Self>,
1992 ) {
1993 // Replacement is not supported in terminal view, so this is a no-op.
1994 }
1995}
1996
1997///Gets the working directory for the given workspace, respecting the user's settings.
1998/// None implies "~" on whichever machine we end up on.
1999pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
2000 match &TerminalSettings::get_global(cx).working_directory {
2001 WorkingDirectory::CurrentProjectDirectory => workspace
2002 .project()
2003 .read(cx)
2004 .active_project_directory(cx)
2005 .as_deref()
2006 .map(Path::to_path_buf),
2007 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
2008 WorkingDirectory::AlwaysHome => None,
2009 WorkingDirectory::Always { directory } => {
2010 shellexpand::full(&directory) //TODO handle this better
2011 .ok()
2012 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
2013 .filter(|dir| dir.is_dir())
2014 }
2015 }
2016}
2017///Gets the first project's home directory, or the home directory
2018fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
2019 let worktree = workspace.worktrees(cx).next()?.read(cx);
2020 if !worktree.root_entry()?.is_dir() {
2021 return None;
2022 }
2023 Some(worktree.abs_path().to_path_buf())
2024}
2025
2026#[cfg(test)]
2027mod tests {
2028 use super::*;
2029 use gpui::TestAppContext;
2030 use project::{Entry, Project, ProjectPath, Worktree};
2031 use std::path::Path;
2032 use workspace::AppState;
2033
2034 // Working directory calculation tests
2035
2036 // No Worktrees in project -> home_dir()
2037 #[gpui::test]
2038 async fn no_worktree(cx: &mut TestAppContext) {
2039 let (project, workspace) = init_test(cx).await;
2040 cx.read(|cx| {
2041 let workspace = workspace.read(cx);
2042 let active_entry = project.read(cx).active_entry();
2043
2044 //Make sure environment is as expected
2045 assert!(active_entry.is_none());
2046 assert!(workspace.worktrees(cx).next().is_none());
2047
2048 let res = default_working_directory(workspace, cx);
2049 assert_eq!(res, None);
2050 let res = first_project_directory(workspace, cx);
2051 assert_eq!(res, None);
2052 });
2053 }
2054
2055 // No active entry, but a worktree, worktree is a file -> home_dir()
2056 #[gpui::test]
2057 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
2058 let (project, workspace) = init_test(cx).await;
2059
2060 create_file_wt(project.clone(), "/root.txt", cx).await;
2061 cx.read(|cx| {
2062 let workspace = workspace.read(cx);
2063 let active_entry = project.read(cx).active_entry();
2064
2065 //Make sure environment is as expected
2066 assert!(active_entry.is_none());
2067 assert!(workspace.worktrees(cx).next().is_some());
2068
2069 let res = default_working_directory(workspace, cx);
2070 assert_eq!(res, None);
2071 let res = first_project_directory(workspace, cx);
2072 assert_eq!(res, None);
2073 });
2074 }
2075
2076 // No active entry, but a worktree, worktree is a folder -> worktree_folder
2077 #[gpui::test]
2078 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
2079 let (project, workspace) = init_test(cx).await;
2080
2081 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
2082 cx.update(|cx| {
2083 let workspace = workspace.read(cx);
2084 let active_entry = project.read(cx).active_entry();
2085
2086 assert!(active_entry.is_none());
2087 assert!(workspace.worktrees(cx).next().is_some());
2088
2089 let res = default_working_directory(workspace, cx);
2090 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
2091 let res = first_project_directory(workspace, cx);
2092 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
2093 });
2094 }
2095
2096 // Active entry with a work tree, worktree is a file -> worktree_folder()
2097 #[gpui::test]
2098 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
2099 let (project, workspace) = init_test(cx).await;
2100
2101 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
2102 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
2103 insert_active_entry_for(wt2, entry2, project.clone(), cx);
2104
2105 cx.update(|cx| {
2106 let workspace = workspace.read(cx);
2107 let active_entry = project.read(cx).active_entry();
2108
2109 assert!(active_entry.is_some());
2110
2111 let res = default_working_directory(workspace, cx);
2112 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
2113 let res = first_project_directory(workspace, cx);
2114 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
2115 });
2116 }
2117
2118 // Active entry, with a worktree, worktree is a folder -> worktree_folder
2119 #[gpui::test]
2120 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
2121 let (project, workspace) = init_test(cx).await;
2122
2123 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
2124 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
2125 insert_active_entry_for(wt2, entry2, project.clone(), cx);
2126
2127 cx.update(|cx| {
2128 let workspace = workspace.read(cx);
2129 let active_entry = project.read(cx).active_entry();
2130
2131 assert!(active_entry.is_some());
2132
2133 let res = default_working_directory(workspace, cx);
2134 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
2135 let res = first_project_directory(workspace, cx);
2136 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
2137 });
2138 }
2139
2140 /// Creates a worktree with 1 file: /root.txt
2141 pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
2142 let params = cx.update(AppState::test);
2143 cx.update(|cx| {
2144 terminal::init(cx);
2145 theme::init(theme::LoadThemes::JustBase, cx);
2146 Project::init_settings(cx);
2147 language::init(cx);
2148 });
2149
2150 let project = Project::test(params.fs.clone(), [], cx).await;
2151 let workspace = cx
2152 .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
2153 .root(cx)
2154 .unwrap();
2155
2156 (project, workspace)
2157 }
2158
2159 /// Creates a worktree with 1 folder: /root{suffix}/
2160 async fn create_folder_wt(
2161 project: Entity<Project>,
2162 path: impl AsRef<Path>,
2163 cx: &mut TestAppContext,
2164 ) -> (Entity<Worktree>, Entry) {
2165 create_wt(project, true, path, cx).await
2166 }
2167
2168 /// Creates a worktree with 1 file: /root{suffix}.txt
2169 async fn create_file_wt(
2170 project: Entity<Project>,
2171 path: impl AsRef<Path>,
2172 cx: &mut TestAppContext,
2173 ) -> (Entity<Worktree>, Entry) {
2174 create_wt(project, false, path, cx).await
2175 }
2176
2177 async fn create_wt(
2178 project: Entity<Project>,
2179 is_dir: bool,
2180 path: impl AsRef<Path>,
2181 cx: &mut TestAppContext,
2182 ) -> (Entity<Worktree>, Entry) {
2183 let (wt, _) = project
2184 .update(cx, |project, cx| {
2185 project.find_or_create_worktree(path, true, cx)
2186 })
2187 .await
2188 .unwrap();
2189
2190 let entry = cx
2191 .update(|cx| {
2192 wt.update(cx, |wt, cx| {
2193 wt.create_entry(Path::new(""), is_dir, None, cx)
2194 })
2195 })
2196 .await
2197 .unwrap()
2198 .to_included()
2199 .unwrap();
2200
2201 (wt, entry)
2202 }
2203
2204 pub fn insert_active_entry_for(
2205 wt: Entity<Worktree>,
2206 entry: Entry,
2207 project: Entity<Project>,
2208 cx: &mut TestAppContext,
2209 ) {
2210 cx.update(|cx| {
2211 let p = ProjectPath {
2212 worktree_id: wt.read(cx).id(),
2213 path: entry.path,
2214 };
2215 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
2216 });
2217 }
2218}