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