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