1use collections::{FxHashMap, HashMap};
2use language::LanguageRegistry;
3use paths::local_debug_file_relative_path;
4use std::{
5 borrow::Cow,
6 path::{Path, PathBuf},
7 sync::Arc,
8 usize,
9};
10use tasks_ui::{TaskOverrides, TasksModal};
11
12use dap::{
13 DapRegistry, DebugRequest, TelemetrySpawnLocation, adapters::DebugAdapterName, send_telemetry,
14};
15use editor::{Editor, EditorElement, EditorStyle};
16use fuzzy::{StringMatch, StringMatchCandidate};
17use gpui::{
18 Action, App, AppContext, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
19 HighlightStyle, InteractiveText, KeyContext, PromptButton, PromptLevel, Render, StyledText,
20 Subscription, TextStyle, UnderlineStyle, WeakEntity,
21};
22use itertools::Itertools as _;
23use picker::{Picker, PickerDelegate, highlighted_match_with_paths::HighlightedMatch};
24use project::{ProjectPath, TaskContexts, TaskSourceKind, task_store::TaskStore};
25use settings::{Settings, initial_local_debug_tasks_content};
26use task::{DebugScenario, RevealTarget, ZedDebugConfig};
27use theme::ThemeSettings;
28use ui::{
29 ActiveTheme, Button, ButtonCommon, ButtonSize, CheckboxWithLabel, Clickable, Color, Context,
30 ContextMenu, Disableable, DropdownMenu, FluentBuilder, Icon, IconName, IconSize,
31 IconWithIndicator, Indicator, InteractiveElement, IntoElement, KeyBinding, Label,
32 LabelCommon as _, LabelSize, ListItem, ListItemSpacing, ParentElement, RenderOnce,
33 SharedString, Styled, StyledExt, StyledTypography, ToggleButton, ToggleState, Toggleable,
34 Tooltip, Window, div, h_flex, px, relative, rems, v_flex,
35};
36use util::ResultExt;
37use workspace::{ModalView, Workspace, pane};
38
39use crate::{attach_modal::AttachModal, debugger_panel::DebugPanel};
40
41// enum SaveScenarioState {
42// Saving,
43// Saved((ProjectPath, SharedString)),
44// Failed(SharedString),
45// }
46
47pub(super) struct NewProcessModal {
48 workspace: WeakEntity<Workspace>,
49 debug_panel: WeakEntity<DebugPanel>,
50 mode: NewProcessMode,
51 debug_picker: Entity<Picker<DebugDelegate>>,
52 attach_mode: Entity<AttachMode>,
53 configure_mode: Entity<ConfigureMode>,
54 task_mode: TaskMode,
55 debugger: Option<DebugAdapterName>,
56 // save_scenario_state: Option<SaveScenarioState>,
57 _subscriptions: [Subscription; 3],
58}
59
60fn suggested_label(request: &DebugRequest, debugger: &str) -> SharedString {
61 match request {
62 DebugRequest::Launch(config) => {
63 let last_path_component = Path::new(&config.program)
64 .file_name()
65 .map(|name| name.to_string_lossy())
66 .unwrap_or_else(|| Cow::Borrowed(&config.program));
67
68 format!("{} ({debugger})", last_path_component).into()
69 }
70 DebugRequest::Attach(config) => format!(
71 "pid: {} ({debugger})",
72 config.process_id.unwrap_or(u32::MAX)
73 )
74 .into(),
75 }
76}
77
78impl NewProcessModal {
79 pub(super) fn show(
80 workspace: &mut Workspace,
81 window: &mut Window,
82 mode: NewProcessMode,
83 reveal_target: Option<RevealTarget>,
84 cx: &mut Context<Workspace>,
85 ) {
86 let Some(debug_panel) = workspace.panel::<DebugPanel>(cx) else {
87 return;
88 };
89 let task_store = workspace.project().read(cx).task_store().clone();
90 let languages = workspace.app_state().languages.clone();
91
92 cx.spawn_in(window, async move |workspace, cx| {
93 let task_contexts = workspace.update_in(cx, |workspace, window, cx| {
94 tasks_ui::task_contexts(workspace, window, cx)
95 })?;
96 workspace.update_in(cx, |workspace, window, cx| {
97 let workspace_handle = workspace.weak_handle();
98 workspace.toggle_modal(window, cx, |window, cx| {
99 let attach_mode = AttachMode::new(None, workspace_handle.clone(), window, cx);
100
101 let debug_picker = cx.new(|cx| {
102 let delegate =
103 DebugDelegate::new(debug_panel.downgrade(), task_store.clone());
104 Picker::uniform_list(delegate, window, cx).modal(false)
105 });
106
107 let configure_mode = ConfigureMode::new(window, cx);
108
109 let task_overrides = Some(TaskOverrides { reveal_target });
110
111 let task_mode = TaskMode {
112 task_modal: cx.new(|cx| {
113 TasksModal::new(
114 task_store.clone(),
115 Arc::new(TaskContexts::default()),
116 task_overrides,
117 false,
118 workspace_handle.clone(),
119 window,
120 cx,
121 )
122 }),
123 };
124
125 let _subscriptions = [
126 cx.subscribe(&debug_picker, |_, _, _, cx| {
127 cx.emit(DismissEvent);
128 }),
129 cx.subscribe(
130 &attach_mode.read(cx).attach_picker.clone(),
131 |_, _, _, cx| {
132 cx.emit(DismissEvent);
133 },
134 ),
135 cx.subscribe(&task_mode.task_modal, |_, _, _: &DismissEvent, cx| {
136 cx.emit(DismissEvent)
137 }),
138 ];
139
140 cx.spawn_in(window, {
141 let debug_picker = debug_picker.downgrade();
142 let configure_mode = configure_mode.downgrade();
143 let task_modal = task_mode.task_modal.downgrade();
144 let workspace = workspace_handle.clone();
145
146 async move |this, cx| {
147 let task_contexts = task_contexts.await;
148 let task_contexts = Arc::new(task_contexts);
149 let lsp_task_sources = task_contexts.lsp_task_sources.clone();
150 let task_position = task_contexts.latest_selection;
151 // Get LSP tasks and filter out based on language vs lsp preference
152 let (lsp_tasks, prefer_lsp) =
153 workspace.update(cx, |workspace, cx| {
154 let lsp_tasks = editor::lsp_tasks(
155 workspace.project().clone(),
156 &lsp_task_sources,
157 task_position,
158 cx,
159 );
160 let prefer_lsp = workspace
161 .active_item(cx)
162 .and_then(|item| item.downcast::<Editor>())
163 .map(|editor| {
164 editor
165 .read(cx)
166 .buffer()
167 .read(cx)
168 .language_settings(cx)
169 .tasks
170 .prefer_lsp
171 })
172 .unwrap_or(false);
173 (lsp_tasks, prefer_lsp)
174 })?;
175
176 let lsp_tasks = lsp_tasks.await;
177 let add_current_language_tasks = !prefer_lsp || lsp_tasks.is_empty();
178
179 let lsp_tasks = lsp_tasks
180 .into_iter()
181 .flat_map(|(kind, tasks_with_locations)| {
182 tasks_with_locations
183 .into_iter()
184 .sorted_by_key(|(location, task)| {
185 (location.is_none(), task.resolved_label.clone())
186 })
187 .map(move |(_, task)| (kind.clone(), task))
188 })
189 .collect::<Vec<_>>();
190
191 let Some(task_inventory) = task_store
192 .update(cx, |task_store, _| task_store.task_inventory().cloned())?
193 else {
194 return Ok(());
195 };
196
197 let (used_tasks, current_resolved_tasks) = task_inventory
198 .update(cx, |task_inventory, cx| {
199 task_inventory
200 .used_and_current_resolved_tasks(task_contexts.clone(), cx)
201 })?
202 .await;
203
204 debug_picker
205 .update_in(cx, |picker, window, cx| {
206 picker.delegate.tasks_loaded(
207 task_contexts.clone(),
208 languages,
209 lsp_tasks.clone(),
210 current_resolved_tasks.clone(),
211 add_current_language_tasks,
212 cx,
213 );
214 picker.refresh(window, cx);
215 cx.notify();
216 })
217 .ok();
218
219 if let Some(active_cwd) = task_contexts
220 .active_context()
221 .and_then(|context| context.cwd.clone())
222 {
223 configure_mode
224 .update_in(cx, |configure_mode, window, cx| {
225 configure_mode.load(active_cwd, window, cx);
226 })
227 .ok();
228 }
229
230 task_modal
231 .update_in(cx, |task_modal, window, cx| {
232 task_modal.tasks_loaded(
233 task_contexts,
234 lsp_tasks,
235 used_tasks,
236 current_resolved_tasks,
237 add_current_language_tasks,
238 window,
239 cx,
240 );
241 })
242 .ok();
243
244 this.update(cx, |_, cx| {
245 cx.notify();
246 })
247 .ok();
248
249 anyhow::Ok(())
250 }
251 })
252 .detach();
253
254 Self {
255 debug_picker,
256 attach_mode,
257 configure_mode,
258 task_mode,
259 debugger: None,
260 mode,
261 debug_panel: debug_panel.downgrade(),
262 workspace: workspace_handle,
263 // save_scenario_state: None,
264 _subscriptions,
265 }
266 });
267 })?;
268
269 anyhow::Ok(())
270 })
271 .detach();
272 }
273
274 fn render_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
275 let dap_menu = self.adapter_drop_down_menu(window, cx);
276 match self.mode {
277 NewProcessMode::Task => self
278 .task_mode
279 .task_modal
280 .read(cx)
281 .picker
282 .clone()
283 .into_any_element(),
284 NewProcessMode::Attach => self.attach_mode.update(cx, |this, cx| {
285 this.clone().render(window, cx).into_any_element()
286 }),
287 NewProcessMode::Launch => self.configure_mode.update(cx, |this, cx| {
288 this.clone().render(dap_menu, window, cx).into_any_element()
289 }),
290 NewProcessMode::Debug => v_flex()
291 .w(rems(34.))
292 .child(self.debug_picker.clone())
293 .into_any_element(),
294 }
295 }
296
297 fn mode_focus_handle(&self, cx: &App) -> FocusHandle {
298 match self.mode {
299 NewProcessMode::Task => self.task_mode.task_modal.focus_handle(cx),
300 NewProcessMode::Attach => self.attach_mode.read(cx).attach_picker.focus_handle(cx),
301 NewProcessMode::Launch => self.configure_mode.read(cx).program.focus_handle(cx),
302 NewProcessMode::Debug => self.debug_picker.focus_handle(cx),
303 }
304 }
305
306 fn debug_scenario(&self, debugger: &str, cx: &App) -> Option<DebugScenario> {
307 let request = match self.mode {
308 NewProcessMode::Launch => Some(DebugRequest::Launch(
309 self.configure_mode.read(cx).debug_request(cx),
310 )),
311 NewProcessMode::Attach => Some(DebugRequest::Attach(
312 self.attach_mode.read(cx).debug_request(),
313 )),
314 _ => None,
315 }?;
316 let label = suggested_label(&request, debugger);
317
318 let stop_on_entry = if let NewProcessMode::Launch = &self.mode {
319 Some(self.configure_mode.read(cx).stop_on_entry.selected())
320 } else {
321 None
322 };
323
324 let session_scenario = ZedDebugConfig {
325 adapter: debugger.to_owned().into(),
326 label,
327 request: request,
328 stop_on_entry,
329 };
330
331 cx.global::<DapRegistry>()
332 .adapter(&session_scenario.adapter)
333 .and_then(|adapter| adapter.config_from_zed_format(session_scenario).ok())
334 }
335
336 fn start_new_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
337 if self.debugger.as_ref().is_none() {
338 return;
339 }
340
341 if let NewProcessMode::Debug = &self.mode {
342 self.debug_picker.update(cx, |picker, cx| {
343 picker.delegate.confirm(false, window, cx);
344 });
345 return;
346 }
347
348 // TODO: Restore once we have proper, comment preserving edits
349 // if let NewProcessMode::Launch = &self.mode {
350 // if self.launch_mode.read(cx).save_to_debug_json.selected() {
351 // self.save_debug_scenario(window, cx);
352 // }
353 // }
354
355 let Some(debugger) = self.debugger.as_ref() else {
356 return;
357 };
358
359 let Some(config) = self.debug_scenario(debugger, cx) else {
360 log::error!("debug config not found in mode: {}", self.mode);
361 return;
362 };
363
364 let debug_panel = self.debug_panel.clone();
365 let Some(task_contexts) = self.task_contexts(cx) else {
366 return;
367 };
368 send_telemetry(&config, TelemetrySpawnLocation::Custom, cx);
369 let task_context = task_contexts.active_context().cloned().unwrap_or_default();
370 let worktree_id = task_contexts.worktree();
371 cx.spawn_in(window, async move |this, cx| {
372 debug_panel.update_in(cx, |debug_panel, window, cx| {
373 debug_panel.start_session(config, task_context, None, worktree_id, window, cx)
374 })?;
375 this.update(cx, |_, cx| {
376 cx.emit(DismissEvent);
377 })
378 .ok();
379 anyhow::Ok(())
380 })
381 .detach_and_log_err(cx);
382 }
383
384 fn update_attach_picker(
385 attach: &Entity<AttachMode>,
386 adapter: &DebugAdapterName,
387 window: &mut Window,
388 cx: &mut App,
389 ) {
390 attach.update(cx, |this, cx| {
391 if adapter.0 != this.definition.adapter {
392 this.definition.adapter = adapter.0.clone();
393
394 this.attach_picker.update(cx, |this, cx| {
395 this.picker.update(cx, |this, cx| {
396 this.delegate.definition.adapter = adapter.0.clone();
397 this.focus(window, cx);
398 })
399 });
400 }
401
402 cx.notify();
403 })
404 }
405
406 fn task_contexts(&self, cx: &App) -> Option<Arc<TaskContexts>> {
407 self.debug_picker.read(cx).delegate.task_contexts.clone()
408 }
409
410 // fn save_debug_scenario(&mut self, window: &mut Window, cx: &mut Context<Self>) {
411 // let Some((save_scenario, scenario_label)) = self
412 // .debugger
413 // .as_ref()
414 // .and_then(|debugger| self.debug_scenario(&debugger, cx))
415 // .zip(self.task_contexts(cx).and_then(|tcx| tcx.worktree()))
416 // .and_then(|(scenario, worktree_id)| {
417 // self.debug_panel
418 // .update(cx, |panel, cx| {
419 // panel.save_scenario(&scenario, worktree_id, window, cx)
420 // })
421 // .ok()
422 // .zip(Some(scenario.label.clone()))
423 // })
424 // else {
425 // return;
426 // };
427
428 // self.save_scenario_state = Some(SaveScenarioState::Saving);
429
430 // cx.spawn(async move |this, cx| {
431 // let res = save_scenario.await;
432
433 // this.update(cx, |this, _| match res {
434 // Ok(saved_file) => {
435 // this.save_scenario_state =
436 // Some(SaveScenarioState::Saved((saved_file, scenario_label)))
437 // }
438 // Err(error) => {
439 // this.save_scenario_state =
440 // Some(SaveScenarioState::Failed(error.to_string().into()))
441 // }
442 // })
443 // .ok();
444
445 // cx.background_executor().timer(Duration::from_secs(3)).await;
446 // this.update(cx, |this, _| this.save_scenario_state.take())
447 // .ok();
448 // })
449 // .detach();
450 // }
451
452 fn adapter_drop_down_menu(
453 &mut self,
454 window: &mut Window,
455 cx: &mut Context<Self>,
456 ) -> ui::DropdownMenu {
457 let workspace = self.workspace.clone();
458 let weak = cx.weak_entity();
459 let active_buffer = self.task_contexts(cx).and_then(|tc| {
460 tc.active_item_context
461 .as_ref()
462 .and_then(|aic| aic.1.as_ref().map(|l| l.buffer.clone()))
463 });
464
465 let active_buffer_language = active_buffer
466 .and_then(|buffer| buffer.read(cx).language())
467 .cloned();
468
469 let mut available_adapters = workspace
470 .update(cx, |_, cx| DapRegistry::global(cx).enumerate_adapters())
471 .unwrap_or_default();
472 if let Some(language) = active_buffer_language {
473 available_adapters.sort_by_key(|adapter| {
474 language
475 .config()
476 .debuggers
477 .get_index_of(adapter.0.as_ref())
478 .unwrap_or(usize::MAX)
479 });
480 if self.debugger.is_none() {
481 self.debugger = available_adapters.first().cloned();
482 }
483 }
484
485 let label = self
486 .debugger
487 .as_ref()
488 .map(|d| d.0.clone())
489 .unwrap_or_else(|| SELECT_DEBUGGER_LABEL.clone());
490
491 DropdownMenu::new(
492 "dap-adapter-picker",
493 label,
494 ContextMenu::build(window, cx, move |mut menu, _, _| {
495 let setter_for_name = |name: DebugAdapterName| {
496 let weak = weak.clone();
497 move |window: &mut Window, cx: &mut App| {
498 weak.update(cx, |this, cx| {
499 this.debugger = Some(name.clone());
500 cx.notify();
501 if let NewProcessMode::Attach = &this.mode {
502 Self::update_attach_picker(&this.attach_mode, &name, window, cx);
503 }
504 })
505 .ok();
506 }
507 };
508
509 for adapter in available_adapters.into_iter() {
510 menu = menu.entry(adapter.0.clone(), None, setter_for_name(adapter.clone()));
511 }
512
513 menu
514 }),
515 )
516 }
517
518 fn open_debug_json(&self, window: &mut Window, cx: &mut Context<NewProcessModal>) {
519 let this = cx.entity();
520 window
521 .spawn(cx, async move |cx| {
522 let worktree_id = this.update(cx, |this, cx| {
523 let tcx = this.task_contexts(cx);
524 tcx?.worktree()
525 })?;
526
527 let Some(worktree_id) = worktree_id else {
528 let _ = cx.prompt(
529 PromptLevel::Critical,
530 "Cannot open debug.json",
531 Some("You must have at least one project open"),
532 &[PromptButton::ok("Ok")],
533 );
534 return Ok(());
535 };
536
537 let editor = this
538 .update_in(cx, |this, window, cx| {
539 this.workspace.update(cx, |workspace, cx| {
540 workspace.open_path(
541 ProjectPath {
542 worktree_id,
543 path: local_debug_file_relative_path().into(),
544 },
545 None,
546 true,
547 window,
548 cx,
549 )
550 })
551 })??
552 .await?;
553
554 cx.update(|_window, cx| {
555 if let Some(editor) = editor.act_as::<Editor>(cx) {
556 editor.update(cx, |editor, cx| {
557 editor.buffer().update(cx, |buffer, cx| {
558 if let Some(singleton) = buffer.as_singleton() {
559 singleton.update(cx, |buffer, cx| {
560 if buffer.is_empty() {
561 buffer.edit(
562 [(0..0, initial_local_debug_tasks_content())],
563 None,
564 cx,
565 );
566 }
567 })
568 }
569 })
570 });
571 }
572 })
573 .ok();
574
575 this.update(cx, |_, cx| cx.emit(DismissEvent)).ok();
576
577 anyhow::Ok(())
578 })
579 .detach();
580 }
581}
582
583static SELECT_DEBUGGER_LABEL: SharedString = SharedString::new_static("Select Debugger");
584
585#[derive(Clone)]
586pub(crate) enum NewProcessMode {
587 Task,
588 Launch,
589 Attach,
590 Debug,
591}
592
593impl std::fmt::Display for NewProcessMode {
594 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
595 let mode = match self {
596 NewProcessMode::Task => "Run",
597 NewProcessMode::Debug => "Debug",
598 NewProcessMode::Attach => "Attach",
599 NewProcessMode::Launch => "Launch",
600 };
601
602 write!(f, "{}", mode)
603 }
604}
605
606impl Focusable for NewProcessMode {
607 fn focus_handle(&self, cx: &App) -> FocusHandle {
608 cx.focus_handle()
609 }
610}
611
612fn render_editor(editor: &Entity<Editor>, window: &mut Window, cx: &App) -> impl IntoElement {
613 let settings = ThemeSettings::get_global(cx);
614 let theme = cx.theme();
615
616 let text_style = TextStyle {
617 color: cx.theme().colors().text,
618 font_family: settings.buffer_font.family.clone(),
619 font_features: settings.buffer_font.features.clone(),
620 font_size: settings.buffer_font_size(cx).into(),
621 font_weight: settings.buffer_font.weight,
622 line_height: relative(settings.buffer_line_height.value()),
623 background_color: Some(theme.colors().editor_background),
624 ..Default::default()
625 };
626
627 let element = EditorElement::new(
628 editor,
629 EditorStyle {
630 background: theme.colors().editor_background,
631 local_player: theme.players().local(),
632 text: text_style,
633 ..Default::default()
634 },
635 );
636
637 div()
638 .rounded_md()
639 .p_1()
640 .border_1()
641 .border_color(theme.colors().border_variant)
642 .when(
643 editor.focus_handle(cx).contains_focused(window, cx),
644 |this| this.border_color(theme.colors().border_focused),
645 )
646 .child(element)
647 .bg(theme.colors().editor_background)
648}
649
650impl Render for NewProcessModal {
651 fn render(
652 &mut self,
653 window: &mut ui::Window,
654 cx: &mut ui::Context<Self>,
655 ) -> impl ui::IntoElement {
656 v_flex()
657 .size_full()
658 .w(rems(34.))
659 .key_context({
660 let mut key_context = KeyContext::new_with_defaults();
661 key_context.add("Pane");
662 key_context.add("RunModal");
663 key_context
664 })
665 .elevation_3(cx)
666 .bg(cx.theme().colors().elevated_surface_background)
667 .on_action(cx.listener(|_, _: &menu::Cancel, _, cx| {
668 cx.emit(DismissEvent);
669 }))
670 .on_action(cx.listener(|this, _: &pane::ActivateNextItem, window, cx| {
671 this.mode = match this.mode {
672 NewProcessMode::Task => NewProcessMode::Debug,
673 NewProcessMode::Debug => NewProcessMode::Attach,
674 NewProcessMode::Attach => NewProcessMode::Launch,
675 NewProcessMode::Launch => NewProcessMode::Task,
676 };
677
678 this.mode_focus_handle(cx).focus(window);
679 }))
680 .on_action(
681 cx.listener(|this, _: &pane::ActivatePreviousItem, window, cx| {
682 this.mode = match this.mode {
683 NewProcessMode::Task => NewProcessMode::Launch,
684 NewProcessMode::Debug => NewProcessMode::Task,
685 NewProcessMode::Attach => NewProcessMode::Debug,
686 NewProcessMode::Launch => NewProcessMode::Attach,
687 };
688
689 this.mode_focus_handle(cx).focus(window);
690 }),
691 )
692 .child(
693 h_flex()
694 .w_full()
695 .justify_around()
696 .p_2()
697 .child(
698 h_flex()
699 .justify_start()
700 .w_full()
701 .child(
702 ToggleButton::new(
703 "debugger-session-ui-tasks-button",
704 NewProcessMode::Task.to_string(),
705 )
706 .size(ButtonSize::Default)
707 .toggle_state(matches!(self.mode, NewProcessMode::Task))
708 .style(ui::ButtonStyle::Subtle)
709 .on_click(cx.listener(|this, _, window, cx| {
710 this.mode = NewProcessMode::Task;
711 this.mode_focus_handle(cx).focus(window);
712 cx.notify();
713 }))
714 .tooltip(Tooltip::text("Run predefined task"))
715 .first(),
716 )
717 .child(
718 ToggleButton::new(
719 "debugger-session-ui-launch-button",
720 NewProcessMode::Debug.to_string(),
721 )
722 .size(ButtonSize::Default)
723 .style(ui::ButtonStyle::Subtle)
724 .toggle_state(matches!(self.mode, NewProcessMode::Debug))
725 .on_click(cx.listener(|this, _, window, cx| {
726 this.mode = NewProcessMode::Debug;
727 this.mode_focus_handle(cx).focus(window);
728 cx.notify();
729 }))
730 .tooltip(Tooltip::text("Start a predefined debug scenario"))
731 .middle(),
732 )
733 .child(
734 ToggleButton::new(
735 "debugger-session-ui-attach-button",
736 NewProcessMode::Attach.to_string(),
737 )
738 .size(ButtonSize::Default)
739 .toggle_state(matches!(self.mode, NewProcessMode::Attach))
740 .style(ui::ButtonStyle::Subtle)
741 .on_click(cx.listener(|this, _, window, cx| {
742 this.mode = NewProcessMode::Attach;
743
744 if let Some(debugger) = this.debugger.as_ref() {
745 Self::update_attach_picker(
746 &this.attach_mode,
747 &debugger,
748 window,
749 cx,
750 );
751 }
752 this.mode_focus_handle(cx).focus(window);
753 cx.notify();
754 }))
755 .tooltip(Tooltip::text("Attach the debugger to a running process"))
756 .middle(),
757 )
758 .child(
759 ToggleButton::new(
760 "debugger-session-ui-custom-button",
761 NewProcessMode::Launch.to_string(),
762 )
763 .size(ButtonSize::Default)
764 .toggle_state(matches!(self.mode, NewProcessMode::Launch))
765 .style(ui::ButtonStyle::Subtle)
766 .on_click(cx.listener(|this, _, window, cx| {
767 this.mode = NewProcessMode::Launch;
768 this.mode_focus_handle(cx).focus(window);
769 cx.notify();
770 }))
771 .tooltip(Tooltip::text("Launch a new process with a debugger"))
772 .last(),
773 ),
774 )
775 .justify_between()
776 .border_color(cx.theme().colors().border_variant)
777 .border_b_1(),
778 )
779 .child(v_flex().child(self.render_mode(window, cx)))
780 .map(|el| {
781 let container = h_flex()
782 .justify_between()
783 .gap_2()
784 .p_2()
785 .border_color(cx.theme().colors().border_variant)
786 .border_t_1()
787 .w_full();
788 match self.mode {
789 NewProcessMode::Launch => el.child(
790 container
791 .child(
792 h_flex()
793 .text_ui_sm(cx)
794 .text_color(Color::Muted.color(cx))
795 .child(
796 InteractiveText::new(
797 "open-debug-json",
798 StyledText::new(
799 "Open .zed/debug.json for advanced configuration",
800 )
801 .with_highlights([(
802 5..20,
803 HighlightStyle {
804 underline: Some(UnderlineStyle {
805 thickness: px(1.0),
806 color: None,
807 wavy: false,
808 }),
809 ..Default::default()
810 },
811 )]),
812 )
813 .on_click(
814 vec![5..20],
815 {
816 let this = cx.entity();
817 move |_, window, cx| {
818 this.update(cx, |this, cx| {
819 this.open_debug_json(window, cx);
820 })
821 }
822 },
823 ),
824 ),
825 )
826 .child(
827 Button::new("debugger-spawn", "Start")
828 .on_click(cx.listener(|this, _, window, cx| {
829 this.start_new_session(window, cx)
830 }))
831 .disabled(
832 self.debugger.is_none()
833 || self
834 .configure_mode
835 .read(cx)
836 .program
837 .read(cx)
838 .is_empty(cx),
839 ),
840 ),
841 ),
842 NewProcessMode::Attach => el.child(
843 container
844 .child(div().child(self.adapter_drop_down_menu(window, cx)))
845 .child(
846 Button::new("debugger-spawn", "Start")
847 .on_click(cx.listener(|this, _, window, cx| {
848 this.start_new_session(window, cx)
849 }))
850 .disabled(
851 self.debugger.is_none()
852 || self
853 .attach_mode
854 .read(cx)
855 .attach_picker
856 .read(cx)
857 .picker
858 .read(cx)
859 .delegate
860 .match_count()
861 == 0,
862 ),
863 ),
864 ),
865 NewProcessMode::Debug => el,
866 NewProcessMode::Task => el,
867 }
868 })
869 }
870}
871
872impl EventEmitter<DismissEvent> for NewProcessModal {}
873impl Focusable for NewProcessModal {
874 fn focus_handle(&self, cx: &ui::App) -> gpui::FocusHandle {
875 self.mode_focus_handle(cx)
876 }
877}
878
879impl ModalView for NewProcessModal {}
880
881impl RenderOnce for AttachMode {
882 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
883 v_flex()
884 .w_full()
885 .track_focus(&self.attach_picker.focus_handle(cx))
886 .child(self.attach_picker.clone())
887 }
888}
889
890#[derive(Clone)]
891pub(super) struct ConfigureMode {
892 program: Entity<Editor>,
893 cwd: Entity<Editor>,
894 stop_on_entry: ToggleState,
895 // save_to_debug_json: ToggleState,
896}
897
898impl ConfigureMode {
899 pub(super) fn new(window: &mut Window, cx: &mut App) -> Entity<Self> {
900 let program = cx.new(|cx| Editor::single_line(window, cx));
901 program.update(cx, |this, cx| {
902 this.set_placeholder_text("ENV=Zed ~/bin/program --option", cx);
903 });
904
905 let cwd = cx.new(|cx| Editor::single_line(window, cx));
906 cwd.update(cx, |this, cx| {
907 this.set_placeholder_text("Ex: $ZED_WORKTREE_ROOT", cx);
908 });
909
910 cx.new(|_| Self {
911 program,
912 cwd,
913 stop_on_entry: ToggleState::Unselected,
914 // save_to_debug_json: ToggleState::Unselected,
915 })
916 }
917
918 fn load(&mut self, cwd: PathBuf, window: &mut Window, cx: &mut App) {
919 self.cwd.update(cx, |editor, cx| {
920 if editor.is_empty(cx) {
921 editor.set_text(cwd.to_string_lossy(), window, cx);
922 }
923 });
924 }
925
926 pub(super) fn debug_request(&self, cx: &App) -> task::LaunchRequest {
927 let cwd_text = self.cwd.read(cx).text(cx);
928 let cwd = if cwd_text.is_empty() {
929 None
930 } else {
931 Some(PathBuf::from(cwd_text))
932 };
933
934 if cfg!(windows) {
935 return task::LaunchRequest {
936 program: self.program.read(cx).text(cx),
937 cwd,
938 args: Default::default(),
939 env: Default::default(),
940 };
941 }
942 let command = self.program.read(cx).text(cx);
943 let mut args = shlex::split(&command).into_iter().flatten().peekable();
944 let mut env = FxHashMap::default();
945 while args.peek().is_some_and(|arg| arg.contains('=')) {
946 let arg = args.next().unwrap();
947 let (lhs, rhs) = arg.split_once('=').unwrap();
948 env.insert(lhs.to_string(), rhs.to_string());
949 }
950
951 let program = if let Some(program) = args.next() {
952 program
953 } else {
954 env = FxHashMap::default();
955 command
956 };
957
958 let args = args.collect::<Vec<_>>();
959
960 task::LaunchRequest {
961 program,
962 cwd,
963 args,
964 env,
965 }
966 }
967
968 fn render(
969 &mut self,
970 adapter_menu: DropdownMenu,
971 window: &mut Window,
972 cx: &mut ui::Context<Self>,
973 ) -> impl IntoElement {
974 v_flex()
975 .p_2()
976 .w_full()
977 .gap_3()
978 .track_focus(&self.program.focus_handle(cx))
979 .child(
980 h_flex()
981 .child(
982 Label::new("Debugger")
983 .size(ui::LabelSize::Small)
984 .color(Color::Muted),
985 )
986 .gap(ui::DynamicSpacing::Base08.rems(cx))
987 .child(adapter_menu),
988 )
989 .child(
990 Label::new("Program")
991 .size(ui::LabelSize::Small)
992 .color(Color::Muted),
993 )
994 .child(render_editor(&self.program, window, cx))
995 .child(
996 Label::new("Working Directory")
997 .size(ui::LabelSize::Small)
998 .color(Color::Muted),
999 )
1000 .child(render_editor(&self.cwd, window, cx))
1001 .child(
1002 CheckboxWithLabel::new(
1003 "debugger-stop-on-entry",
1004 Label::new("Stop on Entry")
1005 .size(ui::LabelSize::Small)
1006 .color(Color::Muted),
1007 self.stop_on_entry,
1008 {
1009 let this = cx.weak_entity();
1010 move |state, _, cx| {
1011 this.update(cx, |this, _| {
1012 this.stop_on_entry = *state;
1013 })
1014 .ok();
1015 }
1016 },
1017 )
1018 .checkbox_position(ui::IconPosition::End),
1019 )
1020 // TODO: restore once we have proper, comment preserving
1021 // file edits.
1022 // .child(
1023 // CheckboxWithLabel::new(
1024 // "debugger-save-to-debug-json",
1025 // Label::new("Save to debug.json")
1026 // .size(ui::LabelSize::Small)
1027 // .color(Color::Muted),
1028 // self.save_to_debug_json,
1029 // {
1030 // let this = cx.weak_entity();
1031 // move |state, _, cx| {
1032 // this.update(cx, |this, _| {
1033 // this.save_to_debug_json = *state;
1034 // })
1035 // .ok();
1036 // }
1037 // },
1038 // )
1039 // .checkbox_position(ui::IconPosition::End),
1040 // )
1041 }
1042}
1043
1044#[derive(Clone)]
1045pub(super) struct AttachMode {
1046 pub(super) definition: ZedDebugConfig,
1047 pub(super) attach_picker: Entity<AttachModal>,
1048}
1049
1050impl AttachMode {
1051 pub(super) fn new(
1052 debugger: Option<DebugAdapterName>,
1053 workspace: WeakEntity<Workspace>,
1054 window: &mut Window,
1055 cx: &mut Context<NewProcessModal>,
1056 ) -> Entity<Self> {
1057 let definition = ZedDebugConfig {
1058 adapter: debugger.unwrap_or(DebugAdapterName("".into())).0,
1059 label: "Attach New Session Setup".into(),
1060 request: dap::DebugRequest::Attach(task::AttachRequest { process_id: None }),
1061 stop_on_entry: Some(false),
1062 };
1063 let attach_picker = cx.new(|cx| {
1064 let modal = AttachModal::new(definition.clone(), workspace, false, window, cx);
1065 window.focus(&modal.focus_handle(cx));
1066
1067 modal
1068 });
1069
1070 cx.new(|_| Self {
1071 definition,
1072 attach_picker,
1073 })
1074 }
1075 pub(super) fn debug_request(&self) -> task::AttachRequest {
1076 task::AttachRequest { process_id: None }
1077 }
1078}
1079
1080#[derive(Clone)]
1081pub(super) struct TaskMode {
1082 pub(super) task_modal: Entity<TasksModal>,
1083}
1084
1085pub(super) struct DebugDelegate {
1086 task_store: Entity<TaskStore>,
1087 candidates: Vec<(Option<TaskSourceKind>, DebugScenario)>,
1088 selected_index: usize,
1089 matches: Vec<StringMatch>,
1090 prompt: String,
1091 debug_panel: WeakEntity<DebugPanel>,
1092 task_contexts: Option<Arc<TaskContexts>>,
1093 divider_index: Option<usize>,
1094 last_used_candidate_index: Option<usize>,
1095}
1096
1097impl DebugDelegate {
1098 pub(super) fn new(debug_panel: WeakEntity<DebugPanel>, task_store: Entity<TaskStore>) -> Self {
1099 Self {
1100 task_store,
1101 candidates: Vec::default(),
1102 selected_index: 0,
1103 matches: Vec::new(),
1104 prompt: String::new(),
1105 debug_panel,
1106 task_contexts: None,
1107 divider_index: None,
1108 last_used_candidate_index: None,
1109 }
1110 }
1111
1112 fn get_scenario_kind(
1113 languages: &Arc<LanguageRegistry>,
1114 dap_registry: &DapRegistry,
1115 scenario: DebugScenario,
1116 ) -> (Option<TaskSourceKind>, DebugScenario) {
1117 let language_names = languages.language_names();
1118 let language = dap_registry
1119 .adapter_language(&scenario.adapter)
1120 .map(|language| TaskSourceKind::Language {
1121 name: language.into(),
1122 });
1123
1124 let language = language.or_else(|| {
1125 scenario.label.split_whitespace().find_map(|word| {
1126 language_names
1127 .iter()
1128 .find(|name| name.eq_ignore_ascii_case(word))
1129 .map(|name| TaskSourceKind::Language {
1130 name: name.to_owned().into(),
1131 })
1132 })
1133 });
1134
1135 (language, scenario)
1136 }
1137
1138 pub fn tasks_loaded(
1139 &mut self,
1140 task_contexts: Arc<TaskContexts>,
1141 languages: Arc<LanguageRegistry>,
1142 lsp_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
1143 current_resolved_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
1144 add_current_language_tasks: bool,
1145 cx: &mut Context<Picker<Self>>,
1146 ) {
1147 self.task_contexts = Some(task_contexts.clone());
1148
1149 let (recent, scenarios) = self
1150 .task_store
1151 .update(cx, |task_store, cx| {
1152 task_store.task_inventory().map(|inventory| {
1153 inventory.update(cx, |inventory, cx| {
1154 inventory.list_debug_scenarios(
1155 &task_contexts,
1156 lsp_tasks,
1157 current_resolved_tasks,
1158 add_current_language_tasks,
1159 cx,
1160 )
1161 })
1162 })
1163 })
1164 .unwrap_or_default();
1165
1166 if !recent.is_empty() {
1167 self.last_used_candidate_index = Some(recent.len() - 1);
1168 }
1169
1170 let dap_registry = cx.global::<DapRegistry>();
1171 let hide_vscode = scenarios.iter().any(|(kind, _)| match kind {
1172 TaskSourceKind::Worktree {
1173 id: _,
1174 directory_in_worktree: dir,
1175 id_base: _,
1176 } => dir.ends_with(".zed"),
1177 _ => false,
1178 });
1179
1180 self.candidates = recent
1181 .into_iter()
1182 .map(|scenario| Self::get_scenario_kind(&languages, &dap_registry, scenario))
1183 .chain(
1184 scenarios
1185 .into_iter()
1186 .filter(|(kind, _)| match kind {
1187 TaskSourceKind::Worktree {
1188 id: _,
1189 directory_in_worktree: dir,
1190 id_base: _,
1191 } => !(hide_vscode && dir.ends_with(".vscode")),
1192 _ => true,
1193 })
1194 .map(|(kind, scenario)| {
1195 let (language, scenario) =
1196 Self::get_scenario_kind(&languages, &dap_registry, scenario);
1197 (language.or(Some(kind)), scenario)
1198 }),
1199 )
1200 .collect();
1201 }
1202}
1203
1204impl PickerDelegate for DebugDelegate {
1205 type ListItem = ui::ListItem;
1206
1207 fn match_count(&self) -> usize {
1208 self.matches.len()
1209 }
1210
1211 fn selected_index(&self) -> usize {
1212 self.selected_index
1213 }
1214
1215 fn set_selected_index(
1216 &mut self,
1217 ix: usize,
1218 _window: &mut Window,
1219 _cx: &mut Context<picker::Picker<Self>>,
1220 ) {
1221 self.selected_index = ix;
1222 }
1223
1224 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> std::sync::Arc<str> {
1225 "Find a debug task, or debug a command.".into()
1226 }
1227
1228 fn update_matches(
1229 &mut self,
1230 query: String,
1231 window: &mut Window,
1232 cx: &mut Context<picker::Picker<Self>>,
1233 ) -> gpui::Task<()> {
1234 let candidates = self.candidates.clone();
1235
1236 cx.spawn_in(window, async move |picker, cx| {
1237 let candidates: Vec<_> = candidates
1238 .into_iter()
1239 .enumerate()
1240 .map(|(index, (_, candidate))| {
1241 StringMatchCandidate::new(index, candidate.label.as_ref())
1242 })
1243 .collect();
1244
1245 let matches = fuzzy::match_strings(
1246 &candidates,
1247 &query,
1248 true,
1249 1000,
1250 &Default::default(),
1251 cx.background_executor().clone(),
1252 )
1253 .await;
1254
1255 picker
1256 .update(cx, |picker, _| {
1257 let delegate = &mut picker.delegate;
1258
1259 delegate.matches = matches;
1260 delegate.prompt = query;
1261
1262 delegate.divider_index = delegate.last_used_candidate_index.and_then(|index| {
1263 let index = delegate
1264 .matches
1265 .partition_point(|matching_task| matching_task.candidate_id <= index);
1266 Some(index).and_then(|index| (index != 0).then(|| index - 1))
1267 });
1268
1269 if delegate.matches.is_empty() {
1270 delegate.selected_index = 0;
1271 } else {
1272 delegate.selected_index =
1273 delegate.selected_index.min(delegate.matches.len() - 1);
1274 }
1275 })
1276 .log_err();
1277 })
1278 }
1279
1280 fn separators_after_indices(&self) -> Vec<usize> {
1281 if let Some(i) = self.divider_index {
1282 vec![i]
1283 } else {
1284 Vec::new()
1285 }
1286 }
1287
1288 fn confirm_input(
1289 &mut self,
1290 _secondary: bool,
1291 window: &mut Window,
1292 cx: &mut Context<Picker<Self>>,
1293 ) {
1294 let text = self.prompt.clone();
1295 let (task_context, worktree_id) = self
1296 .task_contexts
1297 .as_ref()
1298 .and_then(|task_contexts| {
1299 Some((
1300 task_contexts.active_context().cloned()?,
1301 task_contexts.worktree(),
1302 ))
1303 })
1304 .unwrap_or_default();
1305
1306 let mut args = shlex::split(&text).into_iter().flatten().peekable();
1307 let mut env = HashMap::default();
1308 while args.peek().is_some_and(|arg| arg.contains('=')) {
1309 let arg = args.next().unwrap();
1310 let (lhs, rhs) = arg.split_once('=').unwrap();
1311 env.insert(lhs.to_string(), rhs.to_string());
1312 }
1313
1314 let program = if let Some(program) = args.next() {
1315 program
1316 } else {
1317 env = HashMap::default();
1318 text
1319 };
1320
1321 let args = args.collect::<Vec<_>>();
1322 let task = task::TaskTemplate {
1323 label: "one-off".to_owned(),
1324 env,
1325 command: program,
1326 args,
1327 ..Default::default()
1328 };
1329
1330 let Some(location) = self
1331 .task_contexts
1332 .as_ref()
1333 .and_then(|cx| cx.location().cloned())
1334 else {
1335 return;
1336 };
1337 let file = location.buffer.read(cx).file();
1338 let language = location.buffer.read(cx).language();
1339 let language_name = language.as_ref().map(|l| l.name());
1340 let Some(adapter): Option<DebugAdapterName> =
1341 language::language_settings::language_settings(language_name, file, cx)
1342 .debuggers
1343 .first()
1344 .map(SharedString::from)
1345 .map(Into::into)
1346 .or_else(|| {
1347 language.and_then(|l| {
1348 l.config()
1349 .debuggers
1350 .first()
1351 .map(SharedString::from)
1352 .map(Into::into)
1353 })
1354 })
1355 else {
1356 return;
1357 };
1358 let Some(debug_scenario) = cx
1359 .global::<DapRegistry>()
1360 .locators()
1361 .iter()
1362 .find_map(|locator| locator.1.create_scenario(&task, "one-off", adapter.clone()))
1363 else {
1364 return;
1365 };
1366
1367 send_telemetry(&debug_scenario, TelemetrySpawnLocation::ScenarioList, cx);
1368
1369 self.debug_panel
1370 .update(cx, |panel, cx| {
1371 panel.start_session(debug_scenario, task_context, None, worktree_id, window, cx);
1372 })
1373 .ok();
1374
1375 cx.emit(DismissEvent);
1376 }
1377
1378 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<picker::Picker<Self>>) {
1379 let debug_scenario = self
1380 .matches
1381 .get(self.selected_index())
1382 .and_then(|match_candidate| self.candidates.get(match_candidate.candidate_id).cloned());
1383
1384 let Some((_, debug_scenario)) = debug_scenario else {
1385 return;
1386 };
1387
1388 let (task_context, worktree_id) = self
1389 .task_contexts
1390 .as_ref()
1391 .and_then(|task_contexts| {
1392 Some((
1393 task_contexts.active_context().cloned()?,
1394 task_contexts.worktree(),
1395 ))
1396 })
1397 .unwrap_or_default();
1398
1399 send_telemetry(&debug_scenario, TelemetrySpawnLocation::ScenarioList, cx);
1400 self.debug_panel
1401 .update(cx, |panel, cx| {
1402 panel.start_session(debug_scenario, task_context, None, worktree_id, window, cx);
1403 })
1404 .ok();
1405
1406 cx.emit(DismissEvent);
1407 }
1408
1409 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<picker::Picker<Self>>) {
1410 cx.emit(DismissEvent);
1411 }
1412
1413 fn render_footer(
1414 &self,
1415 window: &mut Window,
1416 cx: &mut Context<Picker<Self>>,
1417 ) -> Option<ui::AnyElement> {
1418 let current_modifiers = window.modifiers();
1419 let footer = h_flex()
1420 .w_full()
1421 .h_8()
1422 .p_2()
1423 .justify_between()
1424 .rounded_b_sm()
1425 .bg(cx.theme().colors().ghost_element_selected)
1426 .border_t_1()
1427 .border_color(cx.theme().colors().border_variant)
1428 .child(
1429 // TODO: add button to open selected task in debug.json
1430 h_flex().into_any_element(),
1431 )
1432 .map(|this| {
1433 if (current_modifiers.alt || self.matches.is_empty()) && !self.prompt.is_empty() {
1434 let action = picker::ConfirmInput {
1435 secondary: current_modifiers.secondary(),
1436 }
1437 .boxed_clone();
1438 this.children(KeyBinding::for_action(&*action, window, cx).map(|keybind| {
1439 Button::new("launch-custom", "Launch Custom")
1440 .label_size(LabelSize::Small)
1441 .key_binding(keybind)
1442 .on_click(move |_, window, cx| {
1443 window.dispatch_action(action.boxed_clone(), cx)
1444 })
1445 }))
1446 } else {
1447 this.children(KeyBinding::for_action(&menu::Confirm, window, cx).map(
1448 |keybind| {
1449 let is_recent_selected =
1450 self.divider_index >= Some(self.selected_index);
1451 let run_entry_label =
1452 if is_recent_selected { "Rerun" } else { "Spawn" };
1453
1454 Button::new("spawn", run_entry_label)
1455 .label_size(LabelSize::Small)
1456 .key_binding(keybind)
1457 .on_click(|_, window, cx| {
1458 window.dispatch_action(menu::Confirm.boxed_clone(), cx);
1459 })
1460 },
1461 ))
1462 }
1463 });
1464 Some(footer.into_any_element())
1465 }
1466
1467 fn render_match(
1468 &self,
1469 ix: usize,
1470 selected: bool,
1471 window: &mut Window,
1472 cx: &mut Context<picker::Picker<Self>>,
1473 ) -> Option<Self::ListItem> {
1474 let hit = &self.matches[ix];
1475
1476 let highlighted_location = HighlightedMatch {
1477 text: hit.string.clone(),
1478 highlight_positions: hit.positions.clone(),
1479 char_count: hit.string.chars().count(),
1480 color: Color::Default,
1481 };
1482 let task_kind = &self.candidates[hit.candidate_id].0;
1483
1484 let icon = match task_kind {
1485 Some(TaskSourceKind::UserInput) => Some(Icon::new(IconName::Terminal)),
1486 Some(TaskSourceKind::AbsPath { .. }) => Some(Icon::new(IconName::Settings)),
1487 Some(TaskSourceKind::Worktree { .. }) => Some(Icon::new(IconName::FileTree)),
1488 Some(TaskSourceKind::Lsp {
1489 language_name: name,
1490 ..
1491 })
1492 | Some(TaskSourceKind::Language { name }) => file_icons::FileIcons::get(cx)
1493 .get_icon_for_type(&name.to_lowercase(), cx)
1494 .map(Icon::from_path),
1495 None => Some(Icon::new(IconName::HistoryRerun)),
1496 }
1497 .map(|icon| icon.color(Color::Muted).size(IconSize::Small));
1498 let indicator = if matches!(task_kind, Some(TaskSourceKind::Lsp { .. })) {
1499 Some(Indicator::icon(
1500 Icon::new(IconName::BoltFilled)
1501 .color(Color::Muted)
1502 .size(IconSize::Small),
1503 ))
1504 } else {
1505 None
1506 };
1507 let icon = icon.map(|icon| {
1508 IconWithIndicator::new(icon, indicator)
1509 .indicator_border_color(Some(cx.theme().colors().border_transparent))
1510 });
1511
1512 Some(
1513 ListItem::new(SharedString::from(format!("debug-scenario-selection-{ix}")))
1514 .inset(true)
1515 .start_slot::<IconWithIndicator>(icon)
1516 .spacing(ListItemSpacing::Sparse)
1517 .toggle_state(selected)
1518 .child(highlighted_location.render(window, cx)),
1519 )
1520 }
1521}
1522
1523pub(crate) fn resolve_path(path: &mut String) {
1524 if path.starts_with('~') {
1525 let home = paths::home_dir().to_string_lossy().to_string();
1526 let trimmed_path = path.trim().to_owned();
1527 *path = trimmed_path.replacen('~', &home, 1);
1528 } else if let Some(strip_path) = path.strip_prefix(&format!(".{}", std::path::MAIN_SEPARATOR)) {
1529 *path = format!(
1530 "$ZED_WORKTREE_ROOT{}{}",
1531 std::path::MAIN_SEPARATOR,
1532 &strip_path
1533 );
1534 };
1535}