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, 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 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 #[cfg(not(target_os = "windows"))]
802 let mut fetch_metadata_tasks = potential_paths
803 .into_iter()
804 .map(|potential_path| async {
805 let metadata = fs.metadata(&potential_path).await.ok().flatten();
806 (
807 PathWithPosition {
808 path: potential_path,
809 row,
810 column,
811 },
812 metadata,
813 )
814 })
815 .collect::<FuturesUnordered<_>>();
816
817 #[cfg(target_os = "windows")]
818 let mut fetch_metadata_tasks = potential_paths
819 .iter()
820 .map(|potential_path| async {
821 let metadata = fs.metadata(potential_path).await.ok().flatten();
822 let path = PathBuf::from(
823 potential_path
824 .to_string_lossy()
825 .trim_start_matches("\\\\?\\"),
826 );
827 (PathWithPosition { path, row, column }, metadata)
828 })
829 .collect::<FuturesUnordered<_>>();
830
831 while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
832 if let Some(metadata) = metadata {
833 paths_with_metadata.push((path, metadata));
834 }
835 }
836
837 paths_with_metadata
838 })
839}
840
841fn possible_open_targets(
842 fs: Arc<dyn Fs>,
843 workspace: &WeakView<Workspace>,
844 cwd: &Option<PathBuf>,
845 maybe_path: &String,
846 cx: &mut ViewContext<TerminalView>,
847) -> Task<Vec<(PathWithPosition, Metadata)>> {
848 let path_position = PathWithPosition::parse_str(maybe_path.as_str());
849 let row = path_position.row;
850 let column = path_position.column;
851 let maybe_path = path_position.path;
852
853 let abs_path = if maybe_path.is_absolute() {
854 Some(maybe_path)
855 } else if maybe_path.starts_with("~") {
856 maybe_path
857 .strip_prefix("~")
858 .ok()
859 .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
860 } else {
861 let mut potential_cwd_and_workspace_paths = HashSet::default();
862 if let Some(cwd) = cwd {
863 let abs_path = Path::join(cwd, &maybe_path);
864 let canonicalized_path = abs_path.canonicalize().unwrap_or(abs_path);
865 potential_cwd_and_workspace_paths.insert(canonicalized_path);
866 }
867 if let Some(workspace) = workspace.upgrade() {
868 workspace.update(cx, |workspace, cx| {
869 for potential_worktree_path in workspace
870 .worktrees(cx)
871 .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
872 {
873 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
874 }
875
876 for prefix in GIT_DIFF_PATH_PREFIXES {
877 let prefix_str = &prefix.to_string();
878 if maybe_path.starts_with(prefix_str) {
879 let stripped = maybe_path.strip_prefix(prefix_str).unwrap_or(&maybe_path);
880 for potential_worktree_path in workspace
881 .worktrees(cx)
882 .map(|worktree| worktree.read(cx).abs_path().join(&stripped))
883 {
884 potential_cwd_and_workspace_paths.insert(potential_worktree_path);
885 }
886 }
887 }
888 });
889 }
890
891 return possible_open_paths_metadata(
892 fs,
893 row,
894 column,
895 potential_cwd_and_workspace_paths,
896 cx,
897 );
898 };
899
900 let canonicalized_paths = match abs_path {
901 Some(abs_path) => match abs_path.canonicalize() {
902 Ok(path) => HashSet::from_iter([path]),
903 Err(_) => HashSet::default(),
904 },
905 None => HashSet::default(),
906 };
907
908 possible_open_paths_metadata(fs, row, column, canonicalized_paths, cx)
909}
910
911fn regex_to_literal(regex: &str) -> String {
912 regex
913 .chars()
914 .flat_map(|c| {
915 if REGEX_SPECIAL_CHARS.contains(&c) {
916 vec!['\\', c]
917 } else {
918 vec![c]
919 }
920 })
921 .collect()
922}
923
924pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
925 let query = query.as_str();
926 if query == "." {
927 return None;
928 }
929 let searcher = RegexSearch::new(query);
930 searcher.ok()
931}
932
933impl TerminalView {
934 fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) {
935 self.clear_bell(cx);
936 self.pause_cursor_blinking(cx);
937
938 self.terminal.update(cx, |term, cx| {
939 let handled = term.try_keystroke(
940 &event.keystroke,
941 TerminalSettings::get_global(cx).option_as_meta,
942 );
943 if handled {
944 cx.stop_propagation();
945 }
946 });
947 }
948
949 fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
950 self.terminal.update(cx, |terminal, _| {
951 terminal.set_cursor_shape(self.cursor_shape);
952 terminal.focus_in();
953 });
954 self.blink_cursors(self.blink_epoch, cx);
955 cx.invalidate_character_coordinates();
956 cx.notify();
957 }
958
959 fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
960 self.terminal.update(cx, |terminal, _| {
961 terminal.focus_out();
962 terminal.set_cursor_shape(CursorShape::Hollow);
963 });
964 cx.notify();
965 }
966}
967
968impl Render for TerminalView {
969 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
970 let terminal_handle = self.terminal.clone();
971 let terminal_view_handle = cx.view().clone();
972
973 let focused = self.focus_handle.is_focused(cx);
974
975 div()
976 .size_full()
977 .relative()
978 .track_focus(&self.focus_handle(cx))
979 .key_context(self.dispatch_context(cx))
980 .on_action(cx.listener(TerminalView::send_text))
981 .on_action(cx.listener(TerminalView::send_keystroke))
982 .on_action(cx.listener(TerminalView::copy))
983 .on_action(cx.listener(TerminalView::paste))
984 .on_action(cx.listener(TerminalView::clear))
985 .on_action(cx.listener(TerminalView::scroll_line_up))
986 .on_action(cx.listener(TerminalView::scroll_line_down))
987 .on_action(cx.listener(TerminalView::scroll_page_up))
988 .on_action(cx.listener(TerminalView::scroll_page_down))
989 .on_action(cx.listener(TerminalView::scroll_to_top))
990 .on_action(cx.listener(TerminalView::scroll_to_bottom))
991 .on_action(cx.listener(TerminalView::toggle_vi_mode))
992 .on_action(cx.listener(TerminalView::show_character_palette))
993 .on_action(cx.listener(TerminalView::select_all))
994 .on_key_down(cx.listener(Self::key_down))
995 .on_mouse_down(
996 MouseButton::Right,
997 cx.listener(|this, event: &MouseDownEvent, cx| {
998 if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
999 this.deploy_context_menu(event.position, cx);
1000 cx.notify();
1001 }
1002 }),
1003 )
1004 .child(
1005 // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1006 div().size_full().child(TerminalElement::new(
1007 terminal_handle,
1008 terminal_view_handle,
1009 self.workspace.clone(),
1010 self.focus_handle.clone(),
1011 focused,
1012 self.should_show_cursor(focused, cx),
1013 self.can_navigate_to_selected_word,
1014 self.block_below_cursor.clone(),
1015 )),
1016 )
1017 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1018 deferred(
1019 anchored()
1020 .position(*position)
1021 .anchor(gpui::AnchorCorner::TopLeft)
1022 .child(menu.clone()),
1023 )
1024 .with_priority(1)
1025 }))
1026 }
1027}
1028
1029impl Item for TerminalView {
1030 type Event = ItemEvent;
1031
1032 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
1033 Some(self.terminal().read(cx).title(false).into())
1034 }
1035
1036 fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
1037 let terminal = self.terminal().read(cx);
1038 let title = terminal.title(true);
1039 let rerun_button = |task_id: task::TaskId| {
1040 IconButton::new("rerun-icon", IconName::Rerun)
1041 .icon_size(IconSize::Small)
1042 .size(ButtonSize::Compact)
1043 .icon_color(Color::Default)
1044 .shape(ui::IconButtonShape::Square)
1045 .tooltip(|cx| Tooltip::text("Rerun task", cx))
1046 .on_click(move |_, cx| {
1047 cx.dispatch_action(Box::new(tasks_ui::Rerun {
1048 task_id: Some(task_id.clone()),
1049 ..tasks_ui::Rerun::default()
1050 }));
1051 })
1052 };
1053
1054 let (icon, icon_color, rerun_button) = match terminal.task() {
1055 Some(terminal_task) => match &terminal_task.status {
1056 TaskStatus::Running => (IconName::Play, Color::Disabled, None),
1057 TaskStatus::Unknown => (
1058 IconName::Warning,
1059 Color::Warning,
1060 Some(rerun_button(terminal_task.id.clone())),
1061 ),
1062 TaskStatus::Completed { success } => {
1063 let rerun_button = rerun_button(terminal_task.id.clone());
1064 if *success {
1065 (IconName::Check, Color::Success, Some(rerun_button))
1066 } else {
1067 (IconName::XCircle, Color::Error, Some(rerun_button))
1068 }
1069 }
1070 },
1071 None => (IconName::Terminal, Color::Muted, None),
1072 };
1073
1074 h_flex()
1075 .gap_1()
1076 .group("term-tab-icon")
1077 .child(
1078 h_flex()
1079 .group("term-tab-icon")
1080 .child(
1081 div()
1082 .when(rerun_button.is_some(), |this| {
1083 this.hover(|style| style.invisible().w_0())
1084 })
1085 .child(Icon::new(icon).color(icon_color)),
1086 )
1087 .when_some(rerun_button, |this, rerun_button| {
1088 this.child(
1089 div()
1090 .absolute()
1091 .visible_on_hover("term-tab-icon")
1092 .child(rerun_button),
1093 )
1094 }),
1095 )
1096 .child(Label::new(title).color(params.text_color()))
1097 .into_any()
1098 }
1099
1100 fn telemetry_event_text(&self) -> Option<&'static str> {
1101 None
1102 }
1103
1104 fn clone_on_split(
1105 &self,
1106 _workspace_id: Option<WorkspaceId>,
1107 _cx: &mut ViewContext<Self>,
1108 ) -> Option<View<Self>> {
1109 //From what I can tell, there's no way to tell the current working
1110 //Directory of the terminal from outside the shell. There might be
1111 //solutions to this, but they are non-trivial and require more IPC
1112
1113 // Some(TerminalContainer::new(
1114 // Err(anyhow::anyhow!("failed to instantiate terminal")),
1115 // workspace_id,
1116 // cx,
1117 // ))
1118
1119 // TODO
1120 None
1121 }
1122
1123 fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
1124 match self.terminal.read(cx).task() {
1125 Some(task) => task.status == TaskStatus::Running,
1126 None => self.has_bell(),
1127 }
1128 }
1129
1130 fn has_conflict(&self, _cx: &AppContext) -> bool {
1131 false
1132 }
1133
1134 fn is_singleton(&self, _cx: &AppContext) -> bool {
1135 true
1136 }
1137
1138 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1139 Some(Box::new(handle.clone()))
1140 }
1141
1142 fn breadcrumb_location(&self) -> ToolbarItemLocation {
1143 if self.show_title {
1144 ToolbarItemLocation::PrimaryLeft
1145 } else {
1146 ToolbarItemLocation::Hidden
1147 }
1148 }
1149
1150 fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
1151 Some(vec![BreadcrumbText {
1152 text: self.terminal().read(cx).breadcrumb_text.clone(),
1153 highlights: None,
1154 font: None,
1155 }])
1156 }
1157
1158 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
1159 if self.terminal().read(cx).task().is_none() {
1160 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1161 cx.background_executor()
1162 .spawn(TERMINAL_DB.update_workspace_id(new_id, old_id, cx.entity_id().as_u64()))
1163 .detach();
1164 }
1165 self.workspace_id = workspace.database_id();
1166 }
1167 }
1168
1169 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1170 f(*event)
1171 }
1172}
1173
1174impl SerializableItem for TerminalView {
1175 fn serialized_item_kind() -> &'static str {
1176 "Terminal"
1177 }
1178
1179 fn cleanup(
1180 workspace_id: WorkspaceId,
1181 alive_items: Vec<workspace::ItemId>,
1182 cx: &mut WindowContext,
1183 ) -> Task<gpui::Result<()>> {
1184 cx.spawn(|_| TERMINAL_DB.delete_unloaded_items(workspace_id, alive_items))
1185 }
1186
1187 fn serialize(
1188 &mut self,
1189 _workspace: &mut Workspace,
1190 item_id: workspace::ItemId,
1191 _closing: bool,
1192 cx: &mut ViewContext<Self>,
1193 ) -> Option<Task<gpui::Result<()>>> {
1194 let terminal = self.terminal().read(cx);
1195 if terminal.task().is_some() {
1196 return None;
1197 }
1198
1199 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1200 Some(cx.background_executor().spawn(async move {
1201 TERMINAL_DB
1202 .save_working_directory(item_id, workspace_id, cwd)
1203 .await
1204 }))
1205 } else {
1206 None
1207 }
1208 }
1209
1210 fn should_serialize(&self, event: &Self::Event) -> bool {
1211 matches!(event, ItemEvent::UpdateTab)
1212 }
1213
1214 fn deserialize(
1215 project: Model<Project>,
1216 workspace: WeakView<Workspace>,
1217 workspace_id: workspace::WorkspaceId,
1218 item_id: workspace::ItemId,
1219 cx: &mut ViewContext<Pane>,
1220 ) -> Task<anyhow::Result<View<Self>>> {
1221 let window = cx.window_handle();
1222 cx.spawn(|pane, mut cx| async move {
1223 let cwd = cx
1224 .update(|cx| {
1225 let from_db = TERMINAL_DB
1226 .get_working_directory(item_id, workspace_id)
1227 .log_err()
1228 .flatten();
1229 if from_db
1230 .as_ref()
1231 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1232 {
1233 from_db
1234 } else {
1235 workspace
1236 .upgrade()
1237 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1238 }
1239 })
1240 .ok()
1241 .flatten();
1242
1243 let terminal = project.update(&mut cx, |project, cx| {
1244 project.create_terminal(TerminalKind::Shell(cwd), window, cx)
1245 })??;
1246 pane.update(&mut cx, |_, cx| {
1247 cx.new_view(|cx| TerminalView::new(terminal, workspace, Some(workspace_id), cx))
1248 })
1249 })
1250 }
1251}
1252
1253impl SearchableItem for TerminalView {
1254 type Match = RangeInclusive<Point>;
1255
1256 fn supported_options() -> SearchOptions {
1257 SearchOptions {
1258 case: false,
1259 word: false,
1260 regex: true,
1261 replacement: false,
1262 selection: false,
1263 }
1264 }
1265
1266 /// Clear stored matches
1267 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1268 self.terminal().update(cx, |term, _| term.matches.clear())
1269 }
1270
1271 /// Store matches returned from find_matches somewhere for rendering
1272 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1273 self.terminal()
1274 .update(cx, |term, _| term.matches = matches.to_vec())
1275 }
1276
1277 /// Returns the selection content to pre-load into this search
1278 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1279 self.terminal()
1280 .read(cx)
1281 .last_content
1282 .selection_text
1283 .clone()
1284 .unwrap_or_default()
1285 }
1286
1287 /// Focus match at given index into the Vec of matches
1288 fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
1289 self.terminal()
1290 .update(cx, |term, _| term.activate_match(index));
1291 cx.notify();
1292 }
1293
1294 /// Add selections for all matches given.
1295 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1296 self.terminal()
1297 .update(cx, |term, _| term.select_matches(matches));
1298 cx.notify();
1299 }
1300
1301 /// Get all of the matches for this query, should be done on the background
1302 fn find_matches(
1303 &mut self,
1304 query: Arc<SearchQuery>,
1305 cx: &mut ViewContext<Self>,
1306 ) -> Task<Vec<Self::Match>> {
1307 let searcher = match &*query {
1308 SearchQuery::Text { .. } => regex_search_for_query(
1309 &(SearchQuery::text(
1310 regex_to_literal(query.as_str()),
1311 query.whole_word(),
1312 query.case_sensitive(),
1313 query.include_ignored(),
1314 query.files_to_include().clone(),
1315 query.files_to_exclude().clone(),
1316 None,
1317 )
1318 .unwrap()),
1319 ),
1320 SearchQuery::Regex { .. } => regex_search_for_query(&query),
1321 };
1322
1323 if let Some(s) = searcher {
1324 self.terminal()
1325 .update(cx, |term, cx| term.find_matches(s, cx))
1326 } else {
1327 Task::ready(vec![])
1328 }
1329 }
1330
1331 /// Reports back to the search toolbar what the active match should be (the selection)
1332 fn active_match_index(
1333 &mut self,
1334 matches: &[Self::Match],
1335 cx: &mut ViewContext<Self>,
1336 ) -> Option<usize> {
1337 // Selection head might have a value if there's a selection that isn't
1338 // associated with a match. Therefore, if there are no matches, we should
1339 // report None, no matter the state of the terminal
1340 let res = if !matches.is_empty() {
1341 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1342 // If selection head is contained in a match. Return that match
1343 if let Some(ix) = matches
1344 .iter()
1345 .enumerate()
1346 .find(|(_, search_match)| {
1347 search_match.contains(&selection_head)
1348 || search_match.start() > &selection_head
1349 })
1350 .map(|(ix, _)| ix)
1351 {
1352 Some(ix)
1353 } else {
1354 // If no selection after selection head, return the last match
1355 Some(matches.len().saturating_sub(1))
1356 }
1357 } else {
1358 // Matches found but no active selection, return the first last one (closest to cursor)
1359 Some(matches.len().saturating_sub(1))
1360 }
1361 } else {
1362 None
1363 };
1364
1365 res
1366 }
1367 fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1368 // Replacement is not supported in terminal view, so this is a no-op.
1369 }
1370}
1371
1372///Gets the working directory for the given workspace, respecting the user's settings.
1373/// None implies "~" on whichever machine we end up on.
1374pub fn default_working_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1375 match &TerminalSettings::get_global(cx).working_directory {
1376 WorkingDirectory::CurrentProjectDirectory => {
1377 workspace.project().read(cx).active_project_directory(cx)
1378 }
1379 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1380 WorkingDirectory::AlwaysHome => None,
1381 WorkingDirectory::Always { directory } => {
1382 shellexpand::full(&directory) //TODO handle this better
1383 .ok()
1384 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1385 .filter(|dir| dir.is_dir())
1386 }
1387 }
1388}
1389///Gets the first project's home directory, or the home directory
1390fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1391 let worktree = workspace.worktrees(cx).next()?.read(cx);
1392 if !worktree.root_entry()?.is_dir() {
1393 return None;
1394 }
1395 Some(worktree.abs_path().to_path_buf())
1396}
1397
1398#[cfg(test)]
1399mod tests {
1400 use super::*;
1401 use gpui::TestAppContext;
1402 use project::{Entry, Project, ProjectPath, Worktree};
1403 use std::path::Path;
1404 use workspace::AppState;
1405
1406 // Working directory calculation tests
1407
1408 // No Worktrees in project -> home_dir()
1409 #[gpui::test]
1410 async fn no_worktree(cx: &mut TestAppContext) {
1411 let (project, workspace) = init_test(cx).await;
1412 cx.read(|cx| {
1413 let workspace = workspace.read(cx);
1414 let active_entry = project.read(cx).active_entry();
1415
1416 //Make sure environment is as expected
1417 assert!(active_entry.is_none());
1418 assert!(workspace.worktrees(cx).next().is_none());
1419
1420 let res = default_working_directory(workspace, cx);
1421 assert_eq!(res, None);
1422 let res = first_project_directory(workspace, cx);
1423 assert_eq!(res, None);
1424 });
1425 }
1426
1427 // No active entry, but a worktree, worktree is a file -> home_dir()
1428 #[gpui::test]
1429 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1430 let (project, workspace) = init_test(cx).await;
1431
1432 create_file_wt(project.clone(), "/root.txt", cx).await;
1433 cx.read(|cx| {
1434 let workspace = workspace.read(cx);
1435 let active_entry = project.read(cx).active_entry();
1436
1437 //Make sure environment is as expected
1438 assert!(active_entry.is_none());
1439 assert!(workspace.worktrees(cx).next().is_some());
1440
1441 let res = default_working_directory(workspace, cx);
1442 assert_eq!(res, None);
1443 let res = first_project_directory(workspace, cx);
1444 assert_eq!(res, None);
1445 });
1446 }
1447
1448 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1449 #[gpui::test]
1450 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1451 let (project, workspace) = init_test(cx).await;
1452
1453 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1454 cx.update(|cx| {
1455 let workspace = workspace.read(cx);
1456 let active_entry = project.read(cx).active_entry();
1457
1458 assert!(active_entry.is_none());
1459 assert!(workspace.worktrees(cx).next().is_some());
1460
1461 let res = default_working_directory(workspace, cx);
1462 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1463 let res = first_project_directory(workspace, cx);
1464 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1465 });
1466 }
1467
1468 // Active entry with a work tree, worktree is a file -> home_dir()
1469 #[gpui::test]
1470 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1471 let (project, workspace) = init_test(cx).await;
1472
1473 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1474 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1475 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1476
1477 cx.update(|cx| {
1478 let workspace = workspace.read(cx);
1479 let active_entry = project.read(cx).active_entry();
1480
1481 assert!(active_entry.is_some());
1482
1483 let res = default_working_directory(workspace, cx);
1484 assert_eq!(res, None);
1485 let res = first_project_directory(workspace, cx);
1486 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1487 });
1488 }
1489
1490 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1491 #[gpui::test]
1492 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1493 let (project, workspace) = init_test(cx).await;
1494
1495 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1496 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1497 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1498
1499 cx.update(|cx| {
1500 let workspace = workspace.read(cx);
1501 let active_entry = project.read(cx).active_entry();
1502
1503 assert!(active_entry.is_some());
1504
1505 let res = default_working_directory(workspace, cx);
1506 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1507 let res = first_project_directory(workspace, cx);
1508 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1509 });
1510 }
1511
1512 /// Creates a worktree with 1 file: /root.txt
1513 pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1514 let params = cx.update(AppState::test);
1515 cx.update(|cx| {
1516 terminal::init(cx);
1517 theme::init(theme::LoadThemes::JustBase, cx);
1518 Project::init_settings(cx);
1519 language::init(cx);
1520 });
1521
1522 let project = Project::test(params.fs.clone(), [], cx).await;
1523 let workspace = cx
1524 .add_window(|cx| Workspace::test_new(project.clone(), cx))
1525 .root_view(cx)
1526 .unwrap();
1527
1528 (project, workspace)
1529 }
1530
1531 /// Creates a worktree with 1 folder: /root{suffix}/
1532 async fn create_folder_wt(
1533 project: Model<Project>,
1534 path: impl AsRef<Path>,
1535 cx: &mut TestAppContext,
1536 ) -> (Model<Worktree>, Entry) {
1537 create_wt(project, true, path, cx).await
1538 }
1539
1540 /// Creates a worktree with 1 file: /root{suffix}.txt
1541 async fn create_file_wt(
1542 project: Model<Project>,
1543 path: impl AsRef<Path>,
1544 cx: &mut TestAppContext,
1545 ) -> (Model<Worktree>, Entry) {
1546 create_wt(project, false, path, cx).await
1547 }
1548
1549 async fn create_wt(
1550 project: Model<Project>,
1551 is_dir: bool,
1552 path: impl AsRef<Path>,
1553 cx: &mut TestAppContext,
1554 ) -> (Model<Worktree>, Entry) {
1555 let (wt, _) = project
1556 .update(cx, |project, cx| {
1557 project.find_or_create_worktree(path, true, cx)
1558 })
1559 .await
1560 .unwrap();
1561
1562 let entry = cx
1563 .update(|cx| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1564 .await
1565 .unwrap()
1566 .to_included()
1567 .unwrap();
1568
1569 (wt, entry)
1570 }
1571
1572 pub fn insert_active_entry_for(
1573 wt: Model<Worktree>,
1574 entry: Entry,
1575 project: Model<Project>,
1576 cx: &mut TestAppContext,
1577 ) {
1578 cx.update(|cx| {
1579 let p = ProjectPath {
1580 worktree_id: wt.read(cx).id(),
1581 path: entry.path,
1582 };
1583 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1584 });
1585 }
1586
1587 #[test]
1588 fn escapes_only_special_characters() {
1589 assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1590 }
1591
1592 #[test]
1593 fn empty_string_stays_empty() {
1594 assert_eq!(regex_to_literal(""), "".to_string());
1595 }
1596}