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