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