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,
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, Pane, ToolbarItemLocation,
37 Workspace, 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_title: 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_title: TerminalSettings::get_global(cx).toolbar.title,
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_title = settings.toolbar.title;
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 pub fn should_show_cursor(&self, focused: bool, cx: &mut gpui::ViewContext<Self>) -> bool {
435 //Don't blink the cursor when not focused, blinking is disabled, or paused
436 if !focused
437 || self.blinking_paused
438 || self
439 .terminal
440 .read(cx)
441 .last_content
442 .mode
443 .contains(TermMode::ALT_SCREEN)
444 {
445 return true;
446 }
447
448 match TerminalSettings::get_global(cx).blinking {
449 //If the user requested to never blink, don't blink it.
450 TerminalBlink::Off => true,
451 //If the terminal is controlling it, check terminal mode
452 TerminalBlink::TerminalControlled => {
453 !self.blinking_terminal_enabled || self.blink_state
454 }
455 TerminalBlink::On => self.blink_state,
456 }
457 }
458
459 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
460 if epoch == self.blink_epoch && !self.blinking_paused {
461 self.blink_state = !self.blink_state;
462 cx.notify();
463
464 let epoch = self.next_blink_epoch();
465 cx.spawn(|this, mut cx| async move {
466 Timer::after(CURSOR_BLINK_INTERVAL).await;
467 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx))
468 .ok();
469 })
470 .detach();
471 }
472 }
473
474 pub fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
475 self.blink_state = true;
476 cx.notify();
477
478 let epoch = self.next_blink_epoch();
479 cx.spawn(|this, mut cx| async move {
480 Timer::after(CURSOR_BLINK_INTERVAL).await;
481 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
482 .ok();
483 })
484 .detach();
485 }
486
487 pub fn terminal(&self) -> &Model<Terminal> {
488 &self.terminal
489 }
490
491 pub fn set_block_below_cursor(&mut self, block: BlockProperties, cx: &mut ViewContext<Self>) {
492 self.block_below_cursor = Some(Rc::new(block));
493 self.scroll_to_bottom(&ScrollToBottom, cx);
494 cx.notify();
495 }
496
497 pub fn clear_block_below_cursor(&mut self, cx: &mut ViewContext<Self>) {
498 self.block_below_cursor = None;
499 self.scroll_top = Pixels::ZERO;
500 cx.notify();
501 }
502
503 fn next_blink_epoch(&mut self) -> usize {
504 self.blink_epoch += 1;
505 self.blink_epoch
506 }
507
508 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
509 if epoch == self.blink_epoch {
510 self.blinking_paused = false;
511 self.blink_cursors(epoch, cx);
512 }
513 }
514
515 ///Attempt to paste the clipboard into the terminal
516 fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
517 self.terminal.update(cx, |term, _| term.copy());
518 cx.notify();
519 }
520
521 ///Attempt to paste the clipboard into the terminal
522 fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
523 if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
524 self.terminal
525 .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
526 }
527 }
528
529 fn send_text(&mut self, text: &SendText, cx: &mut ViewContext<Self>) {
530 self.clear_bell(cx);
531 self.terminal.update(cx, |term, _| {
532 term.input(text.0.to_string());
533 });
534 }
535
536 fn send_keystroke(&mut self, text: &SendKeystroke, cx: &mut ViewContext<Self>) {
537 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
538 self.clear_bell(cx);
539 self.terminal.update(cx, |term, cx| {
540 term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
541 });
542 }
543 }
544
545 fn dispatch_context(&self, cx: &AppContext) -> KeyContext {
546 let mut dispatch_context = KeyContext::new_with_defaults();
547 dispatch_context.add("Terminal");
548
549 let mode = self.terminal.read(cx).last_content.mode;
550 dispatch_context.set(
551 "screen",
552 if mode.contains(TermMode::ALT_SCREEN) {
553 "alt"
554 } else {
555 "normal"
556 },
557 );
558
559 if mode.contains(TermMode::APP_CURSOR) {
560 dispatch_context.add("DECCKM");
561 }
562 if mode.contains(TermMode::APP_KEYPAD) {
563 dispatch_context.add("DECPAM");
564 } else {
565 dispatch_context.add("DECPNM");
566 }
567 if mode.contains(TermMode::SHOW_CURSOR) {
568 dispatch_context.add("DECTCEM");
569 }
570 if mode.contains(TermMode::LINE_WRAP) {
571 dispatch_context.add("DECAWM");
572 }
573 if mode.contains(TermMode::ORIGIN) {
574 dispatch_context.add("DECOM");
575 }
576 if mode.contains(TermMode::INSERT) {
577 dispatch_context.add("IRM");
578 }
579 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
580 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
581 dispatch_context.add("LNM");
582 }
583 if mode.contains(TermMode::FOCUS_IN_OUT) {
584 dispatch_context.add("report_focus");
585 }
586 if mode.contains(TermMode::ALTERNATE_SCROLL) {
587 dispatch_context.add("alternate_scroll");
588 }
589 if mode.contains(TermMode::BRACKETED_PASTE) {
590 dispatch_context.add("bracketed_paste");
591 }
592 if mode.intersects(TermMode::MOUSE_MODE) {
593 dispatch_context.add("any_mouse_reporting");
594 }
595 {
596 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
597 "click"
598 } else if mode.contains(TermMode::MOUSE_DRAG) {
599 "drag"
600 } else if mode.contains(TermMode::MOUSE_MOTION) {
601 "motion"
602 } else {
603 "off"
604 };
605 dispatch_context.set("mouse_reporting", mouse_reporting);
606 }
607 {
608 let format = if mode.contains(TermMode::SGR_MOUSE) {
609 "sgr"
610 } else if mode.contains(TermMode::UTF8_MOUSE) {
611 "utf8"
612 } else {
613 "normal"
614 };
615 dispatch_context.set("mouse_format", format);
616 };
617 dispatch_context
618 }
619
620 fn set_terminal(&mut self, terminal: Model<Terminal>, cx: &mut ViewContext<'_, TerminalView>) {
621 self._terminal_subscriptions =
622 subscribe_for_terminal_events(&terminal, self.workspace.clone(), cx);
623 self.terminal = terminal;
624 }
625}
626
627fn subscribe_for_terminal_events(
628 terminal: &Model<Terminal>,
629 workspace: WeakView<Workspace>,
630 cx: &mut ViewContext<'_, TerminalView>,
631) -> Vec<Subscription> {
632 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
633 let terminal_events_subscription =
634 cx.subscribe(terminal, move |this, _, event, cx| match event {
635 Event::Wakeup => {
636 cx.notify();
637 cx.emit(Event::Wakeup);
638 cx.emit(ItemEvent::UpdateTab);
639 cx.emit(SearchEvent::MatchesInvalidated);
640 }
641
642 Event::Bell => {
643 this.has_bell = true;
644 cx.emit(Event::Wakeup);
645 }
646
647 Event::BlinkChanged(blinking) => {
648 if matches!(
649 TerminalSettings::get_global(cx).blinking,
650 TerminalBlink::TerminalControlled
651 ) {
652 this.blinking_terminal_enabled = *blinking;
653 }
654 }
655
656 Event::TitleChanged => {
657 cx.emit(ItemEvent::UpdateTab);
658 }
659
660 Event::NewNavigationTarget(maybe_navigation_target) => {
661 this.can_navigate_to_selected_word = match maybe_navigation_target {
662 Some(MaybeNavigationTarget::Url(_)) => true,
663 Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
664 if let Ok(fs) = workspace.update(cx, |workspace, cx| {
665 workspace.project().read(cx).fs().clone()
666 }) {
667 let valid_files_to_open_task = possible_open_targets(
668 fs,
669 &workspace,
670 &path_like_target.terminal_dir,
671 &path_like_target.maybe_path,
672 cx,
673 );
674 !smol::block_on(valid_files_to_open_task).is_empty()
675 } else {
676 false
677 }
678 }
679 None => false,
680 }
681 }
682
683 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
684 MaybeNavigationTarget::Url(url) => cx.open_url(url),
685
686 MaybeNavigationTarget::PathLike(path_like_target) => {
687 if !this.can_navigate_to_selected_word {
688 return;
689 }
690 let task_workspace = workspace.clone();
691 let Some(fs) = workspace
692 .update(cx, |workspace, cx| {
693 workspace.project().read(cx).fs().clone()
694 })
695 .ok()
696 else {
697 return;
698 };
699
700 let path_like_target = path_like_target.clone();
701 cx.spawn(|terminal_view, mut cx| async move {
702 let valid_files_to_open = terminal_view
703 .update(&mut cx, |_, cx| {
704 possible_open_targets(
705 fs,
706 &task_workspace,
707 &path_like_target.terminal_dir,
708 &path_like_target.maybe_path,
709 cx,
710 )
711 })?
712 .await;
713 let paths_to_open = valid_files_to_open
714 .iter()
715 .map(|(p, _)| p.path.clone())
716 .collect();
717 let opened_items = task_workspace
718 .update(&mut cx, |workspace, cx| {
719 workspace.open_paths(
720 paths_to_open,
721 OpenVisible::OnlyDirectories,
722 None,
723 cx,
724 )
725 })
726 .context("workspace update")?
727 .await;
728
729 let mut has_dirs = false;
730 for ((path, metadata), opened_item) in valid_files_to_open
731 .into_iter()
732 .zip(opened_items.into_iter())
733 {
734 if metadata.is_dir {
735 has_dirs = true;
736 } else if let Some(Ok(opened_item)) = opened_item {
737 if let Some(row) = path.row {
738 let col = path.column.unwrap_or(0);
739 if let Some(active_editor) = opened_item.downcast::<Editor>() {
740 active_editor
741 .downgrade()
742 .update(&mut cx, |editor, cx| {
743 let snapshot = editor.snapshot(cx).display_snapshot;
744 let point = snapshot.buffer_snapshot.clip_point(
745 language::Point::new(
746 row.saturating_sub(1),
747 col.saturating_sub(1),
748 ),
749 Bias::Left,
750 );
751 editor.change_selections(
752 Some(Autoscroll::center()),
753 cx,
754 |s| s.select_ranges([point..point]),
755 );
756 })
757 .log_err();
758 }
759 }
760 }
761 }
762
763 if has_dirs {
764 task_workspace.update(&mut cx, |workspace, cx| {
765 workspace.project().update(cx, |_, cx| {
766 cx.emit(project::Event::ActivateProjectPanel);
767 })
768 })?;
769 }
770
771 anyhow::Ok(())
772 })
773 .detach_and_log_err(cx)
774 }
775 },
776 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
777 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
778 Event::SelectionsChanged => {
779 cx.invalidate_character_coordinates();
780 cx.emit(SearchEvent::ActiveMatchChanged)
781 }
782 });
783 vec![terminal_subscription, terminal_events_subscription]
784}
785
786fn possible_open_paths_metadata(
787 fs: Arc<dyn Fs>,
788 row: Option<u32>,
789 column: Option<u32>,
790 potential_paths: HashSet<PathBuf>,
791 cx: &mut ViewContext<TerminalView>,
792) -> Task<Vec<(PathWithPosition, Metadata)>> {
793 cx.background_executor().spawn(async move {
794 let mut paths_with_metadata = Vec::with_capacity(potential_paths.len());
795
796 let mut fetch_metadata_tasks = potential_paths
797 .into_iter()
798 .map(|potential_path| async {
799 let metadata = fs.metadata(&potential_path).await.ok().flatten();
800 (
801 PathWithPosition {
802 path: potential_path,
803 row,
804 column,
805 },
806 metadata,
807 )
808 })
809 .collect::<FuturesUnordered<_>>();
810
811 while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
812 if let Some(metadata) = metadata {
813 paths_with_metadata.push((path, metadata));
814 }
815 }
816
817 paths_with_metadata
818 })
819}
820
821fn possible_open_targets(
822 fs: Arc<dyn Fs>,
823 workspace: &WeakView<Workspace>,
824 cwd: &Option<PathBuf>,
825 maybe_path: &String,
826 cx: &mut ViewContext<TerminalView>,
827) -> Task<Vec<(PathWithPosition, Metadata)>> {
828 let path_position = PathWithPosition::parse_str(maybe_path.as_str());
829 let row = path_position.row;
830 let column = path_position.column;
831 let maybe_path = path_position.path;
832
833 let abs_path = if maybe_path.is_absolute() {
834 Some(maybe_path)
835 } else if maybe_path.starts_with("~") {
836 maybe_path
837 .strip_prefix("~")
838 .ok()
839 .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
840 } else {
841 let mut potential_cwd_and_workspace_paths = HashSet::default();
842 if let Some(cwd) = cwd {
843 let abs_path = Path::join(cwd, &maybe_path);
844 let canonicalized_path = abs_path.canonicalize().unwrap_or(abs_path);
845 potential_cwd_and_workspace_paths.insert(canonicalized_path);
846 }
847 if let Some(workspace) = workspace.upgrade() {
848 workspace.update(cx, |workspace, cx| {
849 for potential_worktree_path in workspace
850 .worktrees(cx)
851 .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
852 {
853 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
854 }
855
856 for prefix in GIT_DIFF_PATH_PREFIXES {
857 let prefix_str = &prefix.to_string();
858 if maybe_path.starts_with(prefix_str) {
859 let stripped = maybe_path.strip_prefix(prefix_str).unwrap_or(&maybe_path);
860 for potential_worktree_path in workspace
861 .worktrees(cx)
862 .map(|worktree| worktree.read(cx).abs_path().join(&stripped))
863 {
864 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
865 }
866 }
867 }
868 });
869 }
870
871 return possible_open_paths_metadata(
872 fs,
873 row,
874 column,
875 potential_cwd_and_workspace_paths,
876 cx,
877 );
878 };
879
880 let canonicalized_paths = match abs_path {
881 Some(abs_path) => match abs_path.canonicalize() {
882 Ok(path) => HashSet::from_iter([path]),
883 Err(_) => HashSet::default(),
884 },
885 None => HashSet::default(),
886 };
887
888 possible_open_paths_metadata(fs, row, column, canonicalized_paths, cx)
889}
890
891fn regex_to_literal(regex: &str) -> String {
892 regex
893 .chars()
894 .flat_map(|c| {
895 if REGEX_SPECIAL_CHARS.contains(&c) {
896 vec!['\\', c]
897 } else {
898 vec![c]
899 }
900 })
901 .collect()
902}
903
904pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
905 let query = query.as_str();
906 if query == "." {
907 return None;
908 }
909 let searcher = RegexSearch::new(query);
910 searcher.ok()
911}
912
913impl TerminalView {
914 fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) {
915 self.clear_bell(cx);
916 self.pause_cursor_blinking(cx);
917
918 self.terminal.update(cx, |term, cx| {
919 let handled = term.try_keystroke(
920 &event.keystroke,
921 TerminalSettings::get_global(cx).option_as_meta,
922 );
923 if handled {
924 cx.stop_propagation();
925 }
926 });
927 }
928
929 fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
930 self.terminal.update(cx, |terminal, _| {
931 terminal.set_cursor_shape(self.cursor_shape);
932 terminal.focus_in();
933 });
934 self.blink_cursors(self.blink_epoch, cx);
935 cx.invalidate_character_coordinates();
936 cx.notify();
937 }
938
939 fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
940 self.terminal.update(cx, |terminal, _| {
941 terminal.focus_out();
942 terminal.set_cursor_shape(CursorShape::Hollow);
943 });
944 cx.notify();
945 }
946}
947
948impl Render for TerminalView {
949 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
950 let terminal_handle = self.terminal.clone();
951 let terminal_view_handle = cx.view().clone();
952
953 let focused = self.focus_handle.is_focused(cx);
954
955 div()
956 .size_full()
957 .relative()
958 .track_focus(&self.focus_handle)
959 .key_context(self.dispatch_context(cx))
960 .on_action(cx.listener(TerminalView::send_text))
961 .on_action(cx.listener(TerminalView::send_keystroke))
962 .on_action(cx.listener(TerminalView::copy))
963 .on_action(cx.listener(TerminalView::paste))
964 .on_action(cx.listener(TerminalView::clear))
965 .on_action(cx.listener(TerminalView::scroll_line_up))
966 .on_action(cx.listener(TerminalView::scroll_line_down))
967 .on_action(cx.listener(TerminalView::scroll_page_up))
968 .on_action(cx.listener(TerminalView::scroll_page_down))
969 .on_action(cx.listener(TerminalView::scroll_to_top))
970 .on_action(cx.listener(TerminalView::scroll_to_bottom))
971 .on_action(cx.listener(TerminalView::show_character_palette))
972 .on_action(cx.listener(TerminalView::select_all))
973 .on_key_down(cx.listener(Self::key_down))
974 .on_mouse_down(
975 MouseButton::Right,
976 cx.listener(|this, event: &MouseDownEvent, cx| {
977 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
978 this.deploy_context_menu(event.position, cx);
979 cx.notify();
980 }
981 }),
982 )
983 .child(
984 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
985 div().size_full().child(TerminalElement::new(
986 terminal_handle,
987 terminal_view_handle,
988 self.workspace.clone(),
989 self.focus_handle.clone(),
990 focused,
991 self.should_show_cursor(focused, cx),
992 self.can_navigate_to_selected_word,
993 self.block_below_cursor.clone(),
994 )),
995 )
996 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
997 deferred(
998 anchored()
999 .position(*position)
1000 .anchor(gpui::AnchorCorner::TopLeft)
1001 .child(menu.clone()),
1002 )
1003 .with_priority(1)
1004 }))
1005 }
1006}
1007
1008impl Item for TerminalView {
1009 type Event = ItemEvent;
1010
1011 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
1012 Some(self.terminal().read(cx).title(false).into())
1013 }
1014
1015 fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
1016 let terminal = self.terminal().read(cx);
1017 let title = terminal.title(true);
1018 let rerun_button = |task_id: task::TaskId| {
1019 IconButton::new("rerun-icon", IconName::Rerun)
1020 .icon_size(IconSize::Small)
1021 .size(ButtonSize::Compact)
1022 .icon_color(Color::Default)
1023 .shape(ui::IconButtonShape::Square)
1024 .tooltip(|cx| Tooltip::text("Rerun task", cx))
1025 .on_click(move |_, cx| {
1026 cx.dispatch_action(Box::new(tasks_ui::Rerun {
1027 task_id: Some(task_id.clone()),
1028 ..tasks_ui::Rerun::default()
1029 }));
1030 })
1031 };
1032
1033 let (icon, icon_color, rerun_button) = match terminal.task() {
1034 Some(terminal_task) => match &terminal_task.status {
1035 TaskStatus::Running => (IconName::Play, Color::Disabled, None),
1036 TaskStatus::Unknown => (
1037 IconName::Warning,
1038 Color::Warning,
1039 Some(rerun_button(terminal_task.id.clone())),
1040 ),
1041 TaskStatus::Completed { success } => {
1042 let rerun_button = rerun_button(terminal_task.id.clone());
1043 if *success {
1044 (IconName::Check, Color::Success, Some(rerun_button))
1045 } else {
1046 (IconName::XCircle, Color::Error, Some(rerun_button))
1047 }
1048 }
1049 },
1050 None => (IconName::Terminal, Color::Muted, None),
1051 };
1052
1053 h_flex()
1054 .gap_1()
1055 .group("term-tab-icon")
1056 .child(
1057 h_flex()
1058 .group("term-tab-icon")
1059 .child(
1060 div()
1061 .when(rerun_button.is_some(), |this| {
1062 this.hover(|style| style.invisible().w_0())
1063 })
1064 .child(Icon::new(icon).color(icon_color)),
1065 )
1066 .when_some(rerun_button, |this, rerun_button| {
1067 this.child(
1068 div()
1069 .absolute()
1070 .visible_on_hover("term-tab-icon")
1071 .child(rerun_button),
1072 )
1073 }),
1074 )
1075 .child(Label::new(title).color(params.text_color()))
1076 .into_any()
1077 }
1078
1079 fn telemetry_event_text(&self) -> Option<&'static str> {
1080 None
1081 }
1082
1083 fn clone_on_split(
1084 &self,
1085 _workspace_id: Option<WorkspaceId>,
1086 _cx: &mut ViewContext<Self>,
1087 ) -> Option<View<Self>> {
1088 //From what I can tell, there's no way to tell the current working
1089 //Directory of the terminal from outside the shell. There might be
1090 //solutions to this, but they are non-trivial and require more IPC
1091
1092 // Some(TerminalContainer::new(
1093 // Err(anyhow::anyhow!("failed to instantiate terminal")),
1094 // workspace_id,
1095 // cx,
1096 // ))
1097
1098 // TODO
1099 None
1100 }
1101
1102 fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
1103 match self.terminal.read(cx).task() {
1104 Some(task) => task.status == TaskStatus::Running,
1105 None => self.has_bell(),
1106 }
1107 }
1108
1109 fn has_conflict(&self, _cx: &AppContext) -> bool {
1110 false
1111 }
1112
1113 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1114 Some(Box::new(handle.clone()))
1115 }
1116
1117 fn breadcrumb_location(&self) -> ToolbarItemLocation {
1118 if self.show_title {
1119 ToolbarItemLocation::PrimaryLeft
1120 } else {
1121 ToolbarItemLocation::Hidden
1122 }
1123 }
1124
1125 fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
1126 Some(vec![BreadcrumbText {
1127 text: self.terminal().read(cx).breadcrumb_text.clone(),
1128 highlights: None,
1129 font: None,
1130 }])
1131 }
1132
1133 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
1134 if self.terminal().read(cx).task().is_none() {
1135 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1136 cx.background_executor()
1137 .spawn(TERMINAL_DB.update_workspace_id(new_id, old_id, cx.entity_id().as_u64()))
1138 .detach();
1139 }
1140 self.workspace_id = workspace.database_id();
1141 }
1142 }
1143
1144 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1145 f(*event)
1146 }
1147}
1148
1149impl SerializableItem for TerminalView {
1150 fn serialized_item_kind() -> &'static str {
1151 "Terminal"
1152 }
1153
1154 fn cleanup(
1155 workspace_id: WorkspaceId,
1156 alive_items: Vec<workspace::ItemId>,
1157 cx: &mut WindowContext,
1158 ) -> Task<gpui::Result<()>> {
1159 cx.spawn(|_| TERMINAL_DB.delete_unloaded_items(workspace_id, alive_items))
1160 }
1161
1162 fn serialize(
1163 &mut self,
1164 _workspace: &mut Workspace,
1165 item_id: workspace::ItemId,
1166 _closing: bool,
1167 cx: &mut ViewContext<Self>,
1168 ) -> Option<Task<gpui::Result<()>>> {
1169 let terminal = self.terminal().read(cx);
1170 if terminal.task().is_some() {
1171 return None;
1172 }
1173
1174 if let Some((cwd, workspace_id)) = terminal.get_cwd().zip(self.workspace_id) {
1175 Some(cx.background_executor().spawn(async move {
1176 TERMINAL_DB
1177 .save_working_directory(item_id, workspace_id, cwd)
1178 .await
1179 }))
1180 } else {
1181 None
1182 }
1183 }
1184
1185 fn should_serialize(&self, event: &Self::Event) -> bool {
1186 matches!(event, ItemEvent::UpdateTab)
1187 }
1188
1189 fn deserialize(
1190 project: Model<Project>,
1191 workspace: WeakView<Workspace>,
1192 workspace_id: workspace::WorkspaceId,
1193 item_id: workspace::ItemId,
1194 cx: &mut ViewContext<Pane>,
1195 ) -> Task<anyhow::Result<View<Self>>> {
1196 let window = cx.window_handle();
1197 cx.spawn(|pane, mut cx| async move {
1198 let cwd = cx
1199 .update(|cx| {
1200 let from_db = TERMINAL_DB
1201 .get_working_directory(item_id, workspace_id)
1202 .log_err()
1203 .flatten();
1204 if from_db
1205 .as_ref()
1206 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1207 {
1208 from_db
1209 } else {
1210 workspace
1211 .upgrade()
1212 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1213 }
1214 })
1215 .ok()
1216 .flatten();
1217
1218 let terminal = project.update(&mut cx, |project, cx| {
1219 project.create_terminal(TerminalKind::Shell(cwd), window, cx)
1220 })??;
1221 pane.update(&mut cx, |_, cx| {
1222 cx.new_view(|cx| TerminalView::new(terminal, workspace, Some(workspace_id), cx))
1223 })
1224 })
1225 }
1226}
1227
1228impl SearchableItem for TerminalView {
1229 type Match = RangeInclusive<Point>;
1230
1231 fn supported_options() -> SearchOptions {
1232 SearchOptions {
1233 case: false,
1234 word: false,
1235 regex: true,
1236 replacement: false,
1237 selection: false,
1238 }
1239 }
1240
1241 /// Clear stored matches
1242 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1243 self.terminal().update(cx, |term, _| term.matches.clear())
1244 }
1245
1246 /// Store matches returned from find_matches somewhere for rendering
1247 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1248 self.terminal()
1249 .update(cx, |term, _| term.matches = matches.to_vec())
1250 }
1251
1252 /// Returns the selection content to pre-load into this search
1253 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1254 self.terminal()
1255 .read(cx)
1256 .last_content
1257 .selection_text
1258 .clone()
1259 .unwrap_or_default()
1260 }
1261
1262 /// Focus match at given index into the Vec of matches
1263 fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
1264 self.terminal()
1265 .update(cx, |term, _| term.activate_match(index));
1266 cx.notify();
1267 }
1268
1269 /// Add selections for all matches given.
1270 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1271 self.terminal()
1272 .update(cx, |term, _| term.select_matches(matches));
1273 cx.notify();
1274 }
1275
1276 /// Get all of the matches for this query, should be done on the background
1277 fn find_matches(
1278 &mut self,
1279 query: Arc<SearchQuery>,
1280 cx: &mut ViewContext<Self>,
1281 ) -> Task<Vec<Self::Match>> {
1282 let searcher = match &*query {
1283 SearchQuery::Text { .. } => regex_search_for_query(
1284 &(SearchQuery::text(
1285 regex_to_literal(query.as_str()),
1286 query.whole_word(),
1287 query.case_sensitive(),
1288 query.include_ignored(),
1289 query.files_to_include().clone(),
1290 query.files_to_exclude().clone(),
1291 None,
1292 )
1293 .unwrap()),
1294 ),
1295 SearchQuery::Regex { .. } => regex_search_for_query(&query),
1296 };
1297
1298 if let Some(s) = searcher {
1299 self.terminal()
1300 .update(cx, |term, cx| term.find_matches(s, cx))
1301 } else {
1302 Task::ready(vec![])
1303 }
1304 }
1305
1306 /// Reports back to the search toolbar what the active match should be (the selection)
1307 fn active_match_index(
1308 &mut self,
1309 matches: &[Self::Match],
1310 cx: &mut ViewContext<Self>,
1311 ) -> Option<usize> {
1312 // Selection head might have a value if there's a selection that isn't
1313 // associated with a match. Therefore, if there are no matches, we should
1314 // report None, no matter the state of the terminal
1315 let res = if !matches.is_empty() {
1316 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1317 // If selection head is contained in a match. Return that match
1318 if let Some(ix) = matches
1319 .iter()
1320 .enumerate()
1321 .find(|(_, search_match)| {
1322 search_match.contains(&selection_head)
1323 || search_match.start() > &selection_head
1324 })
1325 .map(|(ix, _)| ix)
1326 {
1327 Some(ix)
1328 } else {
1329 // If no selection after selection head, return the last match
1330 Some(matches.len().saturating_sub(1))
1331 }
1332 } else {
1333 // Matches found but no active selection, return the first last one (closest to cursor)
1334 Some(matches.len().saturating_sub(1))
1335 }
1336 } else {
1337 None
1338 };
1339
1340 res
1341 }
1342 fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1343 // Replacement is not supported in terminal view, so this is a no-op.
1344 }
1345}
1346
1347///Gets the working directory for the given workspace, respecting the user's settings.
1348/// None implies "~" on whichever machine we end up on.
1349pub fn default_working_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1350 match &TerminalSettings::get_global(cx).working_directory {
1351 WorkingDirectory::CurrentProjectDirectory => {
1352 workspace.project().read(cx).active_project_directory(cx)
1353 }
1354 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1355 WorkingDirectory::AlwaysHome => None,
1356 WorkingDirectory::Always { directory } => {
1357 shellexpand::full(&directory) //TODO handle this better
1358 .ok()
1359 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1360 .filter(|dir| dir.is_dir())
1361 }
1362 }
1363}
1364///Gets the first project's home directory, or the home directory
1365fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1366 let worktree = workspace.worktrees(cx).next()?.read(cx);
1367 if !worktree.root_entry()?.is_dir() {
1368 return None;
1369 }
1370 Some(worktree.abs_path().to_path_buf())
1371}
1372
1373#[cfg(test)]
1374mod tests {
1375 use super::*;
1376 use gpui::TestAppContext;
1377 use project::{Entry, Project, ProjectPath, Worktree};
1378 use std::path::Path;
1379 use workspace::AppState;
1380
1381 // Working directory calculation tests
1382
1383 // No Worktrees in project -> home_dir()
1384 #[gpui::test]
1385 async fn no_worktree(cx: &mut TestAppContext) {
1386 let (project, workspace) = init_test(cx).await;
1387 cx.read(|cx| {
1388 let workspace = workspace.read(cx);
1389 let active_entry = project.read(cx).active_entry();
1390
1391 //Make sure environment is as expected
1392 assert!(active_entry.is_none());
1393 assert!(workspace.worktrees(cx).next().is_none());
1394
1395 let res = default_working_directory(workspace, cx);
1396 assert_eq!(res, None);
1397 let res = first_project_directory(workspace, cx);
1398 assert_eq!(res, None);
1399 });
1400 }
1401
1402 // No active entry, but a worktree, worktree is a file -> home_dir()
1403 #[gpui::test]
1404 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1405 let (project, workspace) = init_test(cx).await;
1406
1407 create_file_wt(project.clone(), "/root.txt", cx).await;
1408 cx.read(|cx| {
1409 let workspace = workspace.read(cx);
1410 let active_entry = project.read(cx).active_entry();
1411
1412 //Make sure environment is as expected
1413 assert!(active_entry.is_none());
1414 assert!(workspace.worktrees(cx).next().is_some());
1415
1416 let res = default_working_directory(workspace, cx);
1417 assert_eq!(res, None);
1418 let res = first_project_directory(workspace, cx);
1419 assert_eq!(res, None);
1420 });
1421 }
1422
1423 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1424 #[gpui::test]
1425 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1426 let (project, workspace) = init_test(cx).await;
1427
1428 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1429 cx.update(|cx| {
1430 let workspace = workspace.read(cx);
1431 let active_entry = project.read(cx).active_entry();
1432
1433 assert!(active_entry.is_none());
1434 assert!(workspace.worktrees(cx).next().is_some());
1435
1436 let res = default_working_directory(workspace, cx);
1437 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1438 let res = first_project_directory(workspace, cx);
1439 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1440 });
1441 }
1442
1443 // Active entry with a work tree, worktree is a file -> home_dir()
1444 #[gpui::test]
1445 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1446 let (project, workspace) = init_test(cx).await;
1447
1448 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1449 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1450 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1451
1452 cx.update(|cx| {
1453 let workspace = workspace.read(cx);
1454 let active_entry = project.read(cx).active_entry();
1455
1456 assert!(active_entry.is_some());
1457
1458 let res = default_working_directory(workspace, cx);
1459 assert_eq!(res, None);
1460 let res = first_project_directory(workspace, cx);
1461 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1462 });
1463 }
1464
1465 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1466 #[gpui::test]
1467 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1468 let (project, workspace) = init_test(cx).await;
1469
1470 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1471 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1472 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1473
1474 cx.update(|cx| {
1475 let workspace = workspace.read(cx);
1476 let active_entry = project.read(cx).active_entry();
1477
1478 assert!(active_entry.is_some());
1479
1480 let res = default_working_directory(workspace, cx);
1481 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1482 let res = first_project_directory(workspace, cx);
1483 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1484 });
1485 }
1486
1487 /// Creates a worktree with 1 file: /root.txt
1488 pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1489 let params = cx.update(AppState::test);
1490 cx.update(|cx| {
1491 terminal::init(cx);
1492 theme::init(theme::LoadThemes::JustBase, cx);
1493 Project::init_settings(cx);
1494 language::init(cx);
1495 });
1496
1497 let project = Project::test(params.fs.clone(), [], cx).await;
1498 let workspace = cx
1499 .add_window(|cx| Workspace::test_new(project.clone(), cx))
1500 .root_view(cx)
1501 .unwrap();
1502
1503 (project, workspace)
1504 }
1505
1506 /// Creates a worktree with 1 folder: /root{suffix}/
1507 async fn create_folder_wt(
1508 project: Model<Project>,
1509 path: impl AsRef<Path>,
1510 cx: &mut TestAppContext,
1511 ) -> (Model<Worktree>, Entry) {
1512 create_wt(project, true, path, cx).await
1513 }
1514
1515 /// Creates a worktree with 1 file: /root{suffix}.txt
1516 async fn create_file_wt(
1517 project: Model<Project>,
1518 path: impl AsRef<Path>,
1519 cx: &mut TestAppContext,
1520 ) -> (Model<Worktree>, Entry) {
1521 create_wt(project, false, path, cx).await
1522 }
1523
1524 async fn create_wt(
1525 project: Model<Project>,
1526 is_dir: bool,
1527 path: impl AsRef<Path>,
1528 cx: &mut TestAppContext,
1529 ) -> (Model<Worktree>, Entry) {
1530 let (wt, _) = project
1531 .update(cx, |project, cx| {
1532 project.find_or_create_worktree(path, true, cx)
1533 })
1534 .await
1535 .unwrap();
1536
1537 let entry = cx
1538 .update(|cx| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1539 .await
1540 .unwrap()
1541 .to_included()
1542 .unwrap();
1543
1544 (wt, entry)
1545 }
1546
1547 pub fn insert_active_entry_for(
1548 wt: Model<Worktree>,
1549 entry: Entry,
1550 project: Model<Project>,
1551 cx: &mut TestAppContext,
1552 ) {
1553 cx.update(|cx| {
1554 let p = ProjectPath {
1555 worktree_id: wt.read(cx).id(),
1556 path: entry.path,
1557 };
1558 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1559 });
1560 }
1561
1562 #[test]
1563 fn escapes_only_special_characters() {
1564 assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1565 }
1566
1567 #[test]
1568 fn empty_string_stays_empty() {
1569 assert_eq!(regex_to_literal(""), "".to_string());
1570 }
1571}