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_breadcrumbs: bool,
113 block_below_cursor: Option<Rc<BlockProperties>>,
114 scroll_top: Pixels,
115 _subscriptions: Vec<Subscription>,
116 _terminal_subscriptions: Vec<Subscription>,
117}
118
119impl EventEmitter<Event> for TerminalView {}
120impl EventEmitter<ItemEvent> for TerminalView {}
121impl EventEmitter<SearchEvent> for TerminalView {}
122
123impl FocusableView for TerminalView {
124 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
125 self.focus_handle.clone()
126 }
127}
128
129impl TerminalView {
130 ///Create a new Terminal in the current working directory or the user's home directory
131 pub fn deploy(
132 workspace: &mut Workspace,
133 _: &NewCenterTerminal,
134 cx: &mut ViewContext<Workspace>,
135 ) {
136 let working_directory = default_working_directory(workspace, cx);
137
138 let window = cx.window_handle();
139 let terminal = workspace
140 .project()
141 .update(cx, |project, cx| {
142 project.create_terminal(TerminalKind::Shell(working_directory), window, cx)
143 })
144 .notify_err(workspace, cx);
145
146 if let Some(terminal) = terminal {
147 let view = cx.new_view(|cx| {
148 TerminalView::new(
149 terminal,
150 workspace.weak_handle(),
151 workspace.database_id(),
152 cx,
153 )
154 });
155 workspace.add_item_to_active_pane(Box::new(view), None, true, cx);
156 }
157 }
158
159 pub fn new(
160 terminal: Model<Terminal>,
161 workspace: WeakView<Workspace>,
162 workspace_id: Option<WorkspaceId>,
163 cx: &mut ViewContext<Self>,
164 ) -> Self {
165 let workspace_handle = workspace.clone();
166 let terminal_subscriptions = subscribe_for_terminal_events(&terminal, workspace, cx);
167
168 let focus_handle = cx.focus_handle();
169 let focus_in = cx.on_focus_in(&focus_handle, |terminal_view, cx| {
170 terminal_view.focus_in(cx);
171 });
172 let focus_out = cx.on_focus_out(&focus_handle, |terminal_view, _event, cx| {
173 terminal_view.focus_out(cx);
174 });
175 let cursor_shape = TerminalSettings::get_global(cx)
176 .cursor_shape
177 .unwrap_or_default();
178
179 Self {
180 terminal,
181 workspace: workspace_handle,
182 has_bell: false,
183 focus_handle,
184 context_menu: None,
185 cursor_shape,
186 blink_state: true,
187 blinking_terminal_enabled: false,
188 blinking_paused: false,
189 blink_epoch: 0,
190 can_navigate_to_selected_word: false,
191 workspace_id,
192 show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
193 block_below_cursor: None,
194 scroll_top: Pixels::ZERO,
195 _subscriptions: vec![
196 focus_in,
197 focus_out,
198 cx.observe_global::<SettingsStore>(Self::settings_changed),
199 ],
200 _terminal_subscriptions: terminal_subscriptions,
201 }
202 }
203
204 pub fn model(&self) -> &Model<Terminal> {
205 &self.terminal
206 }
207
208 pub fn has_bell(&self) -> bool {
209 self.has_bell
210 }
211
212 pub fn clear_bell(&mut self, cx: &mut ViewContext<TerminalView>) {
213 self.has_bell = false;
214 cx.emit(Event::Wakeup);
215 }
216
217 pub fn deploy_context_menu(
218 &mut self,
219 position: gpui::Point<Pixels>,
220 cx: &mut ViewContext<Self>,
221 ) {
222 let assistant_enabled = self
223 .workspace
224 .upgrade()
225 .and_then(|workspace| workspace.read(cx).panel::<TerminalPanel>(cx))
226 .map_or(false, |terminal_panel| {
227 terminal_panel.read(cx).assistant_enabled()
228 });
229 let context_menu = ContextMenu::build(cx, |menu, _| {
230 menu.context(self.focus_handle.clone())
231 .action("New Terminal", Box::new(NewTerminal))
232 .separator()
233 .action("Copy", Box::new(Copy))
234 .action("Paste", Box::new(Paste))
235 .action("Select All", Box::new(SelectAll))
236 .action("Clear", Box::new(Clear))
237 .when(assistant_enabled, |menu| {
238 menu.separator()
239 .action("Inline Assist", Box::new(InlineAssist::default()))
240 })
241 .separator()
242 .action("Close", Box::new(CloseActiveItem { save_intent: None }))
243 });
244
245 cx.focus_view(&context_menu);
246 let subscription =
247 cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
248 if this.context_menu.as_ref().is_some_and(|context_menu| {
249 context_menu.0.focus_handle(cx).contains_focused(cx)
250 }) {
251 cx.focus_self();
252 }
253 this.context_menu.take();
254 cx.notify();
255 });
256
257 self.context_menu = Some((context_menu, position, subscription));
258 }
259
260 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
261 let settings = TerminalSettings::get_global(cx);
262 self.show_breadcrumbs = settings.toolbar.breadcrumbs;
263
264 let new_cursor_shape = settings.cursor_shape.unwrap_or_default();
265 let old_cursor_shape = self.cursor_shape;
266 if old_cursor_shape != new_cursor_shape {
267 self.cursor_shape = new_cursor_shape;
268 self.terminal.update(cx, |term, _| {
269 term.set_cursor_shape(self.cursor_shape);
270 });
271 }
272
273 cx.notify();
274 }
275
276 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
277 if self
278 .terminal
279 .read(cx)
280 .last_content
281 .mode
282 .contains(TermMode::ALT_SCREEN)
283 {
284 self.terminal.update(cx, |term, cx| {
285 term.try_keystroke(
286 &Keystroke::parse("ctrl-cmd-space").unwrap(),
287 TerminalSettings::get_global(cx).option_as_meta,
288 )
289 });
290 } else {
291 cx.show_character_palette();
292 }
293 }
294
295 fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
296 self.terminal.update(cx, |term, _| term.select_all());
297 cx.notify();
298 }
299
300 fn clear(&mut self, _: &Clear, cx: &mut ViewContext<Self>) {
301 self.scroll_top = px(0.);
302 self.terminal.update(cx, |term, _| term.clear());
303 cx.notify();
304 }
305
306 fn max_scroll_top(&self, cx: &AppContext) -> Pixels {
307 let terminal = self.terminal.read(cx);
308
309 let Some(block) = self.block_below_cursor.as_ref() else {
310 return Pixels::ZERO;
311 };
312
313 let line_height = terminal.last_content().size.line_height;
314 let mut terminal_lines = terminal.total_lines();
315 let viewport_lines = terminal.viewport_lines();
316 if terminal.total_lines() == terminal.viewport_lines() {
317 let mut last_line = None;
318 for cell in terminal.last_content.cells.iter().rev() {
319 if !is_blank(cell) {
320 break;
321 }
322
323 let last_line = last_line.get_or_insert(cell.point.line);
324 if *last_line != cell.point.line {
325 terminal_lines -= 1;
326 }
327 *last_line = cell.point.line;
328 }
329 }
330
331 let max_scroll_top_in_lines =
332 (block.height as usize).saturating_sub(viewport_lines.saturating_sub(terminal_lines));
333
334 max_scroll_top_in_lines as f32 * line_height
335 }
336
337 fn scroll_wheel(
338 &mut self,
339 event: &ScrollWheelEvent,
340 origin: gpui::Point<Pixels>,
341 cx: &mut ViewContext<Self>,
342 ) {
343 let terminal_content = self.terminal.read(cx).last_content();
344
345 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
346 let line_height = terminal_content.size.line_height;
347 let y_delta = event.delta.pixel_delta(line_height).y;
348 if y_delta < Pixels::ZERO || self.scroll_top > Pixels::ZERO {
349 self.scroll_top = cmp::max(
350 Pixels::ZERO,
351 cmp::min(self.scroll_top - y_delta, self.max_scroll_top(cx)),
352 );
353 cx.notify();
354 return;
355 }
356 }
357
358 self.terminal
359 .update(cx, |term, _| term.scroll_wheel(event, origin));
360 }
361
362 fn scroll_line_up(&mut self, _: &ScrollLineUp, cx: &mut ViewContext<Self>) {
363 let terminal_content = self.terminal.read(cx).last_content();
364 if self.block_below_cursor.is_some()
365 && terminal_content.display_offset == 0
366 && self.scroll_top > Pixels::ZERO
367 {
368 let line_height = terminal_content.size.line_height;
369 self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
370 return;
371 }
372
373 self.terminal.update(cx, |term, _| term.scroll_line_up());
374 cx.notify();
375 }
376
377 fn scroll_line_down(&mut self, _: &ScrollLineDown, cx: &mut ViewContext<Self>) {
378 let terminal_content = self.terminal.read(cx).last_content();
379 if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
380 let max_scroll_top = self.max_scroll_top(cx);
381 if self.scroll_top < max_scroll_top {
382 let line_height = terminal_content.size.line_height;
383 self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
384 }
385 return;
386 }
387
388 self.terminal.update(cx, |term, _| term.scroll_line_down());
389 cx.notify();
390 }
391
392 fn scroll_page_up(&mut self, _: &ScrollPageUp, cx: &mut ViewContext<Self>) {
393 if self.scroll_top == Pixels::ZERO {
394 self.terminal.update(cx, |term, _| term.scroll_page_up());
395 } else {
396 let line_height = self.terminal.read(cx).last_content.size.line_height();
397 let visible_block_lines = (self.scroll_top / line_height) as usize;
398 let viewport_lines = self.terminal.read(cx).viewport_lines();
399 let visible_content_lines = viewport_lines - visible_block_lines;
400
401 if visible_block_lines >= viewport_lines {
402 self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
403 } else {
404 self.scroll_top = px(0.);
405 self.terminal
406 .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
407 }
408 }
409 cx.notify();
410 }
411
412 fn scroll_page_down(&mut self, _: &ScrollPageDown, cx: &mut ViewContext<Self>) {
413 self.terminal.update(cx, |term, _| term.scroll_page_down());
414 let terminal = self.terminal.read(cx);
415 if terminal.last_content().display_offset < terminal.viewport_lines() {
416 self.scroll_top = self.max_scroll_top(cx);
417 }
418 cx.notify();
419 }
420
421 fn scroll_to_top(&mut self, _: &ScrollToTop, cx: &mut ViewContext<Self>) {
422 self.terminal.update(cx, |term, _| term.scroll_to_top());
423 cx.notify();
424 }
425
426 fn scroll_to_bottom(&mut self, _: &ScrollToBottom, cx: &mut ViewContext<Self>) {
427 self.terminal.update(cx, |term, _| term.scroll_to_bottom());
428 if self.block_below_cursor.is_some() {
429 self.scroll_top = self.max_scroll_top(cx);
430 }
431 cx.notify();
432 }
433
434 fn toggle_vi_mode(&mut self, _: &ToggleViMode, cx: &mut ViewContext<Self>) {
435 self.terminal.update(cx, |term, _| term.toggle_vi_mode());
436 cx.notify();
437 }
438
439 pub fn should_show_cursor(&self, focused: bool, cx: &mut gpui::ViewContext<Self>) -> bool {
440 //Don't blink the cursor when not focused, blinking is disabled, or paused
441 if !focused
442 || self.blinking_paused
443 || self
444 .terminal
445 .read(cx)
446 .last_content
447 .mode
448 .contains(TermMode::ALT_SCREEN)
449 {
450 return true;
451 }
452
453 match TerminalSettings::get_global(cx).blinking {
454 //If the user requested to never blink, don't blink it.
455 TerminalBlink::Off => true,
456 //If the terminal is controlling it, check terminal mode
457 TerminalBlink::TerminalControlled => {
458 !self.blinking_terminal_enabled || self.blink_state
459 }
460 TerminalBlink::On => self.blink_state,
461 }
462 }
463
464 fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
465 if epoch == self.blink_epoch && !self.blinking_paused {
466 self.blink_state = !self.blink_state;
467 cx.notify();
468
469 let epoch = self.next_blink_epoch();
470 cx.spawn(|this, mut cx| async move {
471 Timer::after(CURSOR_BLINK_INTERVAL).await;
472 this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx))
473 .ok();
474 })
475 .detach();
476 }
477 }
478
479 pub fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
480 self.blink_state = true;
481 cx.notify();
482
483 let epoch = self.next_blink_epoch();
484 cx.spawn(|this, mut cx| async move {
485 Timer::after(CURSOR_BLINK_INTERVAL).await;
486 this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
487 .ok();
488 })
489 .detach();
490 }
491
492 pub fn terminal(&self) -> &Model<Terminal> {
493 &self.terminal
494 }
495
496 pub fn set_block_below_cursor(&mut self, block: BlockProperties, cx: &mut ViewContext<Self>) {
497 self.block_below_cursor = Some(Rc::new(block));
498 self.scroll_to_bottom(&ScrollToBottom, cx);
499 cx.notify();
500 }
501
502 pub fn clear_block_below_cursor(&mut self, cx: &mut ViewContext<Self>) {
503 self.block_below_cursor = None;
504 self.scroll_top = Pixels::ZERO;
505 cx.notify();
506 }
507
508 fn next_blink_epoch(&mut self) -> usize {
509 self.blink_epoch += 1;
510 self.blink_epoch
511 }
512
513 fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
514 if epoch == self.blink_epoch {
515 self.blinking_paused = false;
516 self.blink_cursors(epoch, cx);
517 }
518 }
519
520 ///Attempt to paste the clipboard into the terminal
521 fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
522 self.terminal.update(cx, |term, _| term.copy());
523 cx.notify();
524 }
525
526 ///Attempt to paste the clipboard into the terminal
527 fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
528 if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
529 self.terminal
530 .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
531 }
532 }
533
534 fn send_text(&mut self, text: &SendText, cx: &mut ViewContext<Self>) {
535 self.clear_bell(cx);
536 self.terminal.update(cx, |term, _| {
537 term.input(text.0.to_string());
538 });
539 }
540
541 fn send_keystroke(&mut self, text: &SendKeystroke, cx: &mut ViewContext<Self>) {
542 if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
543 self.clear_bell(cx);
544 self.terminal.update(cx, |term, cx| {
545 term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
546 });
547 }
548 }
549
550 fn dispatch_context(&self, cx: &AppContext) -> KeyContext {
551 let mut dispatch_context = KeyContext::new_with_defaults();
552 dispatch_context.add("Terminal");
553
554 let mode = self.terminal.read(cx).last_content.mode;
555 dispatch_context.set(
556 "screen",
557 if mode.contains(TermMode::ALT_SCREEN) {
558 "alt"
559 } else {
560 "normal"
561 },
562 );
563
564 if mode.contains(TermMode::APP_CURSOR) {
565 dispatch_context.add("DECCKM");
566 }
567 if mode.contains(TermMode::APP_KEYPAD) {
568 dispatch_context.add("DECPAM");
569 } else {
570 dispatch_context.add("DECPNM");
571 }
572 if mode.contains(TermMode::SHOW_CURSOR) {
573 dispatch_context.add("DECTCEM");
574 }
575 if mode.contains(TermMode::LINE_WRAP) {
576 dispatch_context.add("DECAWM");
577 }
578 if mode.contains(TermMode::ORIGIN) {
579 dispatch_context.add("DECOM");
580 }
581 if mode.contains(TermMode::INSERT) {
582 dispatch_context.add("IRM");
583 }
584 //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
585 if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
586 dispatch_context.add("LNM");
587 }
588 if mode.contains(TermMode::FOCUS_IN_OUT) {
589 dispatch_context.add("report_focus");
590 }
591 if mode.contains(TermMode::ALTERNATE_SCROLL) {
592 dispatch_context.add("alternate_scroll");
593 }
594 if mode.contains(TermMode::BRACKETED_PASTE) {
595 dispatch_context.add("bracketed_paste");
596 }
597 if mode.intersects(TermMode::MOUSE_MODE) {
598 dispatch_context.add("any_mouse_reporting");
599 }
600 {
601 let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
602 "click"
603 } else if mode.contains(TermMode::MOUSE_DRAG) {
604 "drag"
605 } else if mode.contains(TermMode::MOUSE_MOTION) {
606 "motion"
607 } else {
608 "off"
609 };
610 dispatch_context.set("mouse_reporting", mouse_reporting);
611 }
612 {
613 let format = if mode.contains(TermMode::SGR_MOUSE) {
614 "sgr"
615 } else if mode.contains(TermMode::UTF8_MOUSE) {
616 "utf8"
617 } else {
618 "normal"
619 };
620 dispatch_context.set("mouse_format", format);
621 };
622 dispatch_context
623 }
624
625 fn set_terminal(&mut self, terminal: Model<Terminal>, cx: &mut ViewContext<'_, TerminalView>) {
626 self._terminal_subscriptions =
627 subscribe_for_terminal_events(&terminal, self.workspace.clone(), cx);
628 self.terminal = terminal;
629 }
630}
631
632fn subscribe_for_terminal_events(
633 terminal: &Model<Terminal>,
634 workspace: WeakView<Workspace>,
635 cx: &mut ViewContext<'_, TerminalView>,
636) -> Vec<Subscription> {
637 let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
638 let terminal_events_subscription =
639 cx.subscribe(terminal, move |this, _, event, cx| match event {
640 Event::Wakeup => {
641 cx.notify();
642 cx.emit(Event::Wakeup);
643 cx.emit(ItemEvent::UpdateTab);
644 cx.emit(SearchEvent::MatchesInvalidated);
645 }
646
647 Event::Bell => {
648 this.has_bell = true;
649 cx.emit(Event::Wakeup);
650 }
651
652 Event::BlinkChanged(blinking) => {
653 if matches!(
654 TerminalSettings::get_global(cx).blinking,
655 TerminalBlink::TerminalControlled
656 ) {
657 this.blinking_terminal_enabled = *blinking;
658 }
659 }
660
661 Event::TitleChanged => {
662 cx.emit(ItemEvent::UpdateTab);
663 }
664
665 Event::NewNavigationTarget(maybe_navigation_target) => {
666 this.can_navigate_to_selected_word = match maybe_navigation_target {
667 Some(MaybeNavigationTarget::Url(_)) => true,
668 Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
669 if let Ok(fs) = workspace.update(cx, |workspace, cx| {
670 workspace.project().read(cx).fs().clone()
671 }) {
672 let valid_files_to_open_task = possible_open_targets(
673 fs,
674 &workspace,
675 &path_like_target.terminal_dir,
676 &path_like_target.maybe_path,
677 cx,
678 );
679 !smol::block_on(valid_files_to_open_task).is_empty()
680 } else {
681 false
682 }
683 }
684 None => false,
685 }
686 }
687
688 Event::Open(maybe_navigation_target) => match maybe_navigation_target {
689 MaybeNavigationTarget::Url(url) => cx.open_url(url),
690
691 MaybeNavigationTarget::PathLike(path_like_target) => {
692 if !this.can_navigate_to_selected_word {
693 return;
694 }
695 let task_workspace = workspace.clone();
696 let Some(fs) = workspace
697 .update(cx, |workspace, cx| {
698 workspace.project().read(cx).fs().clone()
699 })
700 .ok()
701 else {
702 return;
703 };
704
705 let path_like_target = path_like_target.clone();
706 cx.spawn(|terminal_view, mut cx| async move {
707 let valid_files_to_open = terminal_view
708 .update(&mut cx, |_, cx| {
709 possible_open_targets(
710 fs,
711 &task_workspace,
712 &path_like_target.terminal_dir,
713 &path_like_target.maybe_path,
714 cx,
715 )
716 })?
717 .await;
718 let paths_to_open = valid_files_to_open
719 .iter()
720 .map(|(p, _)| p.path.clone())
721 .collect();
722 let opened_items = task_workspace
723 .update(&mut cx, |workspace, cx| {
724 workspace.open_paths(
725 paths_to_open,
726 OpenVisible::OnlyDirectories,
727 None,
728 cx,
729 )
730 })
731 .context("workspace update")?
732 .await;
733
734 let mut has_dirs = false;
735 for ((path, metadata), opened_item) in valid_files_to_open
736 .into_iter()
737 .zip(opened_items.into_iter())
738 {
739 if metadata.is_dir {
740 has_dirs = true;
741 } else if let Some(Ok(opened_item)) = opened_item {
742 if let Some(row) = path.row {
743 let col = path.column.unwrap_or(0);
744 if let Some(active_editor) = opened_item.downcast::<Editor>() {
745 active_editor
746 .downgrade()
747 .update(&mut cx, |editor, cx| {
748 let snapshot = editor.snapshot(cx).display_snapshot;
749 let point = snapshot.buffer_snapshot.clip_point(
750 language::Point::new(
751 row.saturating_sub(1),
752 col.saturating_sub(1),
753 ),
754 Bias::Left,
755 );
756 editor.change_selections(
757 Some(Autoscroll::center()),
758 cx,
759 |s| s.select_ranges([point..point]),
760 );
761 })
762 .log_err();
763 }
764 }
765 }
766 }
767
768 if has_dirs {
769 task_workspace.update(&mut cx, |workspace, cx| {
770 workspace.project().update(cx, |_, cx| {
771 cx.emit(project::Event::ActivateProjectPanel);
772 })
773 })?;
774 }
775
776 anyhow::Ok(())
777 })
778 .detach_and_log_err(cx)
779 }
780 },
781 Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
782 Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
783 Event::SelectionsChanged => {
784 cx.invalidate_character_coordinates();
785 cx.emit(SearchEvent::ActiveMatchChanged)
786 }
787 });
788 vec![terminal_subscription, terminal_events_subscription]
789}
790
791fn possible_open_paths_metadata(
792 fs: Arc<dyn Fs>,
793 row: Option<u32>,
794 column: Option<u32>,
795 potential_paths: HashSet<PathBuf>,
796 cx: &mut ViewContext<TerminalView>,
797) -> Task<Vec<(PathWithPosition, Metadata)>> {
798 cx.background_executor().spawn(async move {
799 let mut paths_with_metadata = Vec::with_capacity(potential_paths.len());
800
801 #[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(zed_actions::Rerun {
1048 task_id: Some(task_id.0.clone()),
1049 allow_concurrent_runs: Some(true),
1050 use_new_terminal: Some(false),
1051 reevaluate_context: false,
1052 }));
1053 })
1054 };
1055
1056 let (icon, icon_color, rerun_button) = match terminal.task() {
1057 Some(terminal_task) => match &terminal_task.status {
1058 TaskStatus::Running => (
1059 IconName::Play,
1060 Color::Disabled,
1061 Some(rerun_button(terminal_task.id.clone())),
1062 ),
1063 TaskStatus::Unknown => (
1064 IconName::Warning,
1065 Color::Warning,
1066 Some(rerun_button(terminal_task.id.clone())),
1067 ),
1068 TaskStatus::Completed { success } => {
1069 let rerun_button = rerun_button(terminal_task.id.clone());
1070 if *success {
1071 (IconName::Check, Color::Success, Some(rerun_button))
1072 } else {
1073 (IconName::XCircle, Color::Error, Some(rerun_button))
1074 }
1075 }
1076 },
1077 None => (IconName::Terminal, Color::Muted, None),
1078 };
1079
1080 h_flex()
1081 .gap_1()
1082 .group("term-tab-icon")
1083 .child(
1084 h_flex()
1085 .group("term-tab-icon")
1086 .child(
1087 div()
1088 .when(rerun_button.is_some(), |this| {
1089 this.hover(|style| style.invisible().w_0())
1090 })
1091 .child(Icon::new(icon).color(icon_color)),
1092 )
1093 .when_some(rerun_button, |this, rerun_button| {
1094 this.child(
1095 div()
1096 .absolute()
1097 .visible_on_hover("term-tab-icon")
1098 .child(rerun_button),
1099 )
1100 }),
1101 )
1102 .child(Label::new(title).color(params.text_color()))
1103 .into_any()
1104 }
1105
1106 fn telemetry_event_text(&self) -> Option<&'static str> {
1107 None
1108 }
1109
1110 fn clone_on_split(
1111 &self,
1112 _workspace_id: Option<WorkspaceId>,
1113 _cx: &mut ViewContext<Self>,
1114 ) -> Option<View<Self>> {
1115 //From what I can tell, there's no way to tell the current working
1116 //Directory of the terminal from outside the shell. There might be
1117 //solutions to this, but they are non-trivial and require more IPC
1118
1119 // Some(TerminalContainer::new(
1120 // Err(anyhow::anyhow!("failed to instantiate terminal")),
1121 // workspace_id,
1122 // cx,
1123 // ))
1124
1125 // TODO
1126 None
1127 }
1128
1129 fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
1130 match self.terminal.read(cx).task() {
1131 Some(task) => task.status == TaskStatus::Running,
1132 None => self.has_bell(),
1133 }
1134 }
1135
1136 fn has_conflict(&self, _cx: &AppContext) -> bool {
1137 false
1138 }
1139
1140 fn is_singleton(&self, _cx: &AppContext) -> bool {
1141 true
1142 }
1143
1144 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1145 Some(Box::new(handle.clone()))
1146 }
1147
1148 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
1149 if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1150 ToolbarItemLocation::PrimaryLeft
1151 } else {
1152 ToolbarItemLocation::Hidden
1153 }
1154 }
1155
1156 fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
1157 Some(vec![BreadcrumbText {
1158 text: self.terminal().read(cx).breadcrumb_text.clone(),
1159 highlights: None,
1160 font: None,
1161 }])
1162 }
1163
1164 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
1165 if self.terminal().read(cx).task().is_none() {
1166 if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1167 cx.background_executor()
1168 .spawn(TERMINAL_DB.update_workspace_id(new_id, old_id, cx.entity_id().as_u64()))
1169 .detach();
1170 }
1171 self.workspace_id = workspace.database_id();
1172 }
1173 }
1174
1175 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1176 f(*event)
1177 }
1178}
1179
1180impl SerializableItem for TerminalView {
1181 fn serialized_item_kind() -> &'static str {
1182 "Terminal"
1183 }
1184
1185 fn cleanup(
1186 workspace_id: WorkspaceId,
1187 alive_items: Vec<workspace::ItemId>,
1188 cx: &mut WindowContext,
1189 ) -> Task<gpui::Result<()>> {
1190 cx.spawn(|_| TERMINAL_DB.delete_unloaded_items(workspace_id, alive_items))
1191 }
1192
1193 fn serialize(
1194 &mut self,
1195 _workspace: &mut Workspace,
1196 item_id: workspace::ItemId,
1197 _closing: bool,
1198 cx: &mut ViewContext<Self>,
1199 ) -> Option<Task<gpui::Result<()>>> {
1200 let terminal = self.terminal().read(cx);
1201 if terminal.task().is_some() {
1202 return None;
1203 }
1204
1205 if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1206 Some(cx.background_executor().spawn(async move {
1207 TERMINAL_DB
1208 .save_working_directory(item_id, workspace_id, cwd)
1209 .await
1210 }))
1211 } else {
1212 None
1213 }
1214 }
1215
1216 fn should_serialize(&self, event: &Self::Event) -> bool {
1217 matches!(event, ItemEvent::UpdateTab)
1218 }
1219
1220 fn deserialize(
1221 project: Model<Project>,
1222 workspace: WeakView<Workspace>,
1223 workspace_id: workspace::WorkspaceId,
1224 item_id: workspace::ItemId,
1225 cx: &mut ViewContext<Pane>,
1226 ) -> Task<anyhow::Result<View<Self>>> {
1227 let window = cx.window_handle();
1228 cx.spawn(|pane, mut cx| async move {
1229 let cwd = cx
1230 .update(|cx| {
1231 let from_db = TERMINAL_DB
1232 .get_working_directory(item_id, workspace_id)
1233 .log_err()
1234 .flatten();
1235 if from_db
1236 .as_ref()
1237 .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1238 {
1239 from_db
1240 } else {
1241 workspace
1242 .upgrade()
1243 .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1244 }
1245 })
1246 .ok()
1247 .flatten();
1248
1249 let terminal = project.update(&mut cx, |project, cx| {
1250 project.create_terminal(TerminalKind::Shell(cwd), window, cx)
1251 })??;
1252 pane.update(&mut cx, |_, cx| {
1253 cx.new_view(|cx| TerminalView::new(terminal, workspace, Some(workspace_id), cx))
1254 })
1255 })
1256 }
1257}
1258
1259impl SearchableItem for TerminalView {
1260 type Match = RangeInclusive<Point>;
1261
1262 fn supported_options() -> SearchOptions {
1263 SearchOptions {
1264 case: false,
1265 word: false,
1266 regex: true,
1267 replacement: false,
1268 selection: false,
1269 }
1270 }
1271
1272 /// Clear stored matches
1273 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1274 self.terminal().update(cx, |term, _| term.matches.clear())
1275 }
1276
1277 /// Store matches returned from find_matches somewhere for rendering
1278 fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1279 self.terminal()
1280 .update(cx, |term, _| term.matches = matches.to_vec())
1281 }
1282
1283 /// Returns the selection content to pre-load into this search
1284 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1285 self.terminal()
1286 .read(cx)
1287 .last_content
1288 .selection_text
1289 .clone()
1290 .unwrap_or_default()
1291 }
1292
1293 /// Focus match at given index into the Vec of matches
1294 fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
1295 self.terminal()
1296 .update(cx, |term, _| term.activate_match(index));
1297 cx.notify();
1298 }
1299
1300 /// Add selections for all matches given.
1301 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1302 self.terminal()
1303 .update(cx, |term, _| term.select_matches(matches));
1304 cx.notify();
1305 }
1306
1307 /// Get all of the matches for this query, should be done on the background
1308 fn find_matches(
1309 &mut self,
1310 query: Arc<SearchQuery>,
1311 cx: &mut ViewContext<Self>,
1312 ) -> Task<Vec<Self::Match>> {
1313 let searcher = match &*query {
1314 SearchQuery::Text { .. } => regex_search_for_query(
1315 &(SearchQuery::text(
1316 regex_to_literal(query.as_str()),
1317 query.whole_word(),
1318 query.case_sensitive(),
1319 query.include_ignored(),
1320 query.files_to_include().clone(),
1321 query.files_to_exclude().clone(),
1322 None,
1323 )
1324 .unwrap()),
1325 ),
1326 SearchQuery::Regex { .. } => regex_search_for_query(&query),
1327 };
1328
1329 if let Some(s) = searcher {
1330 self.terminal()
1331 .update(cx, |term, cx| term.find_matches(s, cx))
1332 } else {
1333 Task::ready(vec![])
1334 }
1335 }
1336
1337 /// Reports back to the search toolbar what the active match should be (the selection)
1338 fn active_match_index(
1339 &mut self,
1340 matches: &[Self::Match],
1341 cx: &mut ViewContext<Self>,
1342 ) -> Option<usize> {
1343 // Selection head might have a value if there's a selection that isn't
1344 // associated with a match. Therefore, if there are no matches, we should
1345 // report None, no matter the state of the terminal
1346 let res = if !matches.is_empty() {
1347 if let Some(selection_head) = self.terminal().read(cx).selection_head {
1348 // If selection head is contained in a match. Return that match
1349 if let Some(ix) = matches
1350 .iter()
1351 .enumerate()
1352 .find(|(_, search_match)| {
1353 search_match.contains(&selection_head)
1354 || search_match.start() > &selection_head
1355 })
1356 .map(|(ix, _)| ix)
1357 {
1358 Some(ix)
1359 } else {
1360 // If no selection after selection head, return the last match
1361 Some(matches.len().saturating_sub(1))
1362 }
1363 } else {
1364 // Matches found but no active selection, return the first last one (closest to cursor)
1365 Some(matches.len().saturating_sub(1))
1366 }
1367 } else {
1368 None
1369 };
1370
1371 res
1372 }
1373 fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1374 // Replacement is not supported in terminal view, so this is a no-op.
1375 }
1376}
1377
1378///Gets the working directory for the given workspace, respecting the user's settings.
1379/// None implies "~" on whichever machine we end up on.
1380pub fn default_working_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1381 match &TerminalSettings::get_global(cx).working_directory {
1382 WorkingDirectory::CurrentProjectDirectory => {
1383 workspace.project().read(cx).active_project_directory(cx)
1384 }
1385 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1386 WorkingDirectory::AlwaysHome => None,
1387 WorkingDirectory::Always { directory } => {
1388 shellexpand::full(&directory) //TODO handle this better
1389 .ok()
1390 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1391 .filter(|dir| dir.is_dir())
1392 }
1393 }
1394}
1395///Gets the first project's home directory, or the home directory
1396fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1397 let worktree = workspace.worktrees(cx).next()?.read(cx);
1398 if !worktree.root_entry()?.is_dir() {
1399 return None;
1400 }
1401 Some(worktree.abs_path().to_path_buf())
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406 use super::*;
1407 use gpui::TestAppContext;
1408 use project::{Entry, Project, ProjectPath, Worktree};
1409 use std::path::Path;
1410 use workspace::AppState;
1411
1412 // Working directory calculation tests
1413
1414 // No Worktrees in project -> home_dir()
1415 #[gpui::test]
1416 async fn no_worktree(cx: &mut TestAppContext) {
1417 let (project, workspace) = init_test(cx).await;
1418 cx.read(|cx| {
1419 let workspace = workspace.read(cx);
1420 let active_entry = project.read(cx).active_entry();
1421
1422 //Make sure environment is as expected
1423 assert!(active_entry.is_none());
1424 assert!(workspace.worktrees(cx).next().is_none());
1425
1426 let res = default_working_directory(workspace, cx);
1427 assert_eq!(res, None);
1428 let res = first_project_directory(workspace, cx);
1429 assert_eq!(res, None);
1430 });
1431 }
1432
1433 // No active entry, but a worktree, worktree is a file -> home_dir()
1434 #[gpui::test]
1435 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1436 let (project, workspace) = init_test(cx).await;
1437
1438 create_file_wt(project.clone(), "/root.txt", cx).await;
1439 cx.read(|cx| {
1440 let workspace = workspace.read(cx);
1441 let active_entry = project.read(cx).active_entry();
1442
1443 //Make sure environment is as expected
1444 assert!(active_entry.is_none());
1445 assert!(workspace.worktrees(cx).next().is_some());
1446
1447 let res = default_working_directory(workspace, cx);
1448 assert_eq!(res, None);
1449 let res = first_project_directory(workspace, cx);
1450 assert_eq!(res, None);
1451 });
1452 }
1453
1454 // No active entry, but a worktree, worktree is a folder -> worktree_folder
1455 #[gpui::test]
1456 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1457 let (project, workspace) = init_test(cx).await;
1458
1459 let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1460 cx.update(|cx| {
1461 let workspace = workspace.read(cx);
1462 let active_entry = project.read(cx).active_entry();
1463
1464 assert!(active_entry.is_none());
1465 assert!(workspace.worktrees(cx).next().is_some());
1466
1467 let res = default_working_directory(workspace, cx);
1468 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1469 let res = first_project_directory(workspace, cx);
1470 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1471 });
1472 }
1473
1474 // Active entry with a work tree, worktree is a file -> worktree_folder()
1475 #[gpui::test]
1476 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1477 let (project, workspace) = init_test(cx).await;
1478
1479 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1480 let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1481 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1482
1483 cx.update(|cx| {
1484 let workspace = workspace.read(cx);
1485 let active_entry = project.read(cx).active_entry();
1486
1487 assert!(active_entry.is_some());
1488
1489 let res = default_working_directory(workspace, cx);
1490 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1491 let res = first_project_directory(workspace, cx);
1492 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1493 });
1494 }
1495
1496 // Active entry, with a worktree, worktree is a folder -> worktree_folder
1497 #[gpui::test]
1498 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1499 let (project, workspace) = init_test(cx).await;
1500
1501 let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1502 let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1503 insert_active_entry_for(wt2, entry2, project.clone(), cx);
1504
1505 cx.update(|cx| {
1506 let workspace = workspace.read(cx);
1507 let active_entry = project.read(cx).active_entry();
1508
1509 assert!(active_entry.is_some());
1510
1511 let res = default_working_directory(workspace, cx);
1512 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1513 let res = first_project_directory(workspace, cx);
1514 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1515 });
1516 }
1517
1518 /// Creates a worktree with 1 file: /root.txt
1519 pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1520 let params = cx.update(AppState::test);
1521 cx.update(|cx| {
1522 terminal::init(cx);
1523 theme::init(theme::LoadThemes::JustBase, cx);
1524 Project::init_settings(cx);
1525 language::init(cx);
1526 });
1527
1528 let project = Project::test(params.fs.clone(), [], cx).await;
1529 let workspace = cx
1530 .add_window(|cx| Workspace::test_new(project.clone(), cx))
1531 .root_view(cx)
1532 .unwrap();
1533
1534 (project, workspace)
1535 }
1536
1537 /// Creates a worktree with 1 folder: /root{suffix}/
1538 async fn create_folder_wt(
1539 project: Model<Project>,
1540 path: impl AsRef<Path>,
1541 cx: &mut TestAppContext,
1542 ) -> (Model<Worktree>, Entry) {
1543 create_wt(project, true, path, cx).await
1544 }
1545
1546 /// Creates a worktree with 1 file: /root{suffix}.txt
1547 async fn create_file_wt(
1548 project: Model<Project>,
1549 path: impl AsRef<Path>,
1550 cx: &mut TestAppContext,
1551 ) -> (Model<Worktree>, Entry) {
1552 create_wt(project, false, path, cx).await
1553 }
1554
1555 async fn create_wt(
1556 project: Model<Project>,
1557 is_dir: bool,
1558 path: impl AsRef<Path>,
1559 cx: &mut TestAppContext,
1560 ) -> (Model<Worktree>, Entry) {
1561 let (wt, _) = project
1562 .update(cx, |project, cx| {
1563 project.find_or_create_worktree(path, true, cx)
1564 })
1565 .await
1566 .unwrap();
1567
1568 let entry = cx
1569 .update(|cx| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1570 .await
1571 .unwrap()
1572 .to_included()
1573 .unwrap();
1574
1575 (wt, entry)
1576 }
1577
1578 pub fn insert_active_entry_for(
1579 wt: Model<Worktree>,
1580 entry: Entry,
1581 project: Model<Project>,
1582 cx: &mut TestAppContext,
1583 ) {
1584 cx.update(|cx| {
1585 let p = ProjectPath {
1586 worktree_id: wt.read(cx).id(),
1587 path: entry.path,
1588 };
1589 project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1590 });
1591 }
1592
1593 #[test]
1594 fn escapes_only_special_characters() {
1595 assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1596 }
1597
1598 #[test]
1599 fn empty_string_stays_empty() {
1600 assert_eq!(regex_to_literal(""), "".to_string());
1601 }
1602}