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