1mod active_toolchain;
2
3pub use active_toolchain::ActiveToolchain;
4use convert_case::Casing as _;
5use editor::Editor;
6use file_finder::OpenPathDelegate;
7use futures::channel::oneshot;
8use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
9use gpui::{
10 Action, Animation, AnimationExt, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle,
11 Focusable, KeyContext, ParentElement, Render, Styled, Subscription, Task, WeakEntity, Window,
12 actions, pulsating_between,
13};
14use language::{Language, LanguageName, Toolchain, ToolchainScope};
15use picker::{Picker, PickerDelegate};
16use project::{DirectoryLister, Project, ProjectPath, Toolchains, WorktreeId};
17use std::{
18 borrow::Cow,
19 path::{Path, PathBuf},
20 sync::Arc,
21 time::Duration,
22};
23use ui::{
24 Divider, HighlightedLabel, KeyBinding, List, ListItem, ListItemSpacing, Navigable,
25 NavigableEntry, prelude::*,
26};
27use util::{ResultExt, maybe, paths::PathStyle, rel_path::RelPath};
28use workspace::{ModalView, Workspace};
29
30actions!(
31 toolchain,
32 [
33 /// Selects a toolchain for the current project.
34 Select,
35 /// Adds a new toolchain for the current project.
36 AddToolchain
37 ]
38);
39
40pub fn init(cx: &mut App) {
41 cx.observe_new(ToolchainSelector::register).detach();
42}
43
44pub struct ToolchainSelector {
45 state: State,
46 create_search_state: Arc<dyn Fn(&mut Window, &mut Context<Self>) -> SearchState + 'static>,
47 language: Option<Arc<Language>>,
48 project: Entity<Project>,
49 language_name: LanguageName,
50 worktree_id: WorktreeId,
51 relative_path: Arc<RelPath>,
52}
53
54#[derive(Clone)]
55struct SearchState {
56 picker: Entity<Picker<ToolchainSelectorDelegate>>,
57}
58
59struct AddToolchainState {
60 state: AddState,
61 project: Entity<Project>,
62 language_name: LanguageName,
63 root_path: ProjectPath,
64 weak: WeakEntity<ToolchainSelector>,
65}
66
67struct ScopePickerState {
68 entries: [NavigableEntry; 3],
69 selected_scope: ToolchainScope,
70}
71
72#[expect(
73 dead_code,
74 reason = "These tasks have to be kept alive to run to completion"
75)]
76enum PathInputState {
77 WaitingForPath(Task<()>),
78 Resolving(Task<()>),
79}
80
81enum AddState {
82 Path {
83 picker: Entity<Picker<file_finder::OpenPathDelegate>>,
84 error: Option<Arc<str>>,
85 input_state: PathInputState,
86 _subscription: Subscription,
87 },
88 Name {
89 toolchain: Toolchain,
90 editor: Entity<Editor>,
91 scope_picker: ScopePickerState,
92 },
93}
94
95impl AddToolchainState {
96 fn new(
97 project: Entity<Project>,
98 language_name: LanguageName,
99 root_path: ProjectPath,
100 window: &mut Window,
101 cx: &mut Context<ToolchainSelector>,
102 ) -> Entity<Self> {
103 let weak = cx.weak_entity();
104
105 cx.new(|cx| {
106 let (lister, rx) = Self::create_path_browser_delegate(project.clone(), cx);
107 let picker = cx.new(|cx| Picker::uniform_list(lister, window, cx));
108 Self {
109 state: AddState::Path {
110 _subscription: cx.subscribe(&picker, |_, _, _: &DismissEvent, cx| {
111 cx.stop_propagation();
112 }),
113 picker,
114 error: None,
115 input_state: Self::wait_for_path(rx, window, cx),
116 },
117 project,
118 language_name,
119 root_path,
120 weak,
121 }
122 })
123 }
124
125 fn create_path_browser_delegate(
126 project: Entity<Project>,
127 cx: &mut Context<Self>,
128 ) -> (OpenPathDelegate, oneshot::Receiver<Option<Vec<PathBuf>>>) {
129 let (tx, rx) = oneshot::channel();
130 let weak = cx.weak_entity();
131 let path_style = project.read(cx).path_style(cx);
132 let lister =
133 OpenPathDelegate::new(tx, DirectoryLister::Project(project), false, path_style)
134 .show_hidden()
135 .with_footer(Arc::new(move |_, cx| {
136 let error = weak
137 .read_with(cx, |this, _| {
138 if let AddState::Path { error, .. } = &this.state {
139 error.clone()
140 } else {
141 None
142 }
143 })
144 .ok()
145 .flatten();
146 let is_loading = weak
147 .read_with(cx, |this, _| {
148 matches!(
149 this.state,
150 AddState::Path {
151 input_state: PathInputState::Resolving(_),
152 ..
153 }
154 )
155 })
156 .unwrap_or_default();
157 Some(
158 v_flex()
159 .child(Divider::horizontal())
160 .child(
161 h_flex()
162 .p_1()
163 .justify_between()
164 .gap_2()
165 .child(
166 Label::new("Select Toolchain Path")
167 .color(Color::Muted)
168 .map(|this| {
169 if is_loading {
170 this.with_animation(
171 "select-toolchain-label",
172 Animation::new(Duration::from_secs(2))
173 .repeat()
174 .with_easing(pulsating_between(
175 0.4, 0.8,
176 )),
177 |label, delta| label.alpha(delta),
178 )
179 .into_any()
180 } else {
181 this.into_any_element()
182 }
183 }),
184 )
185 .when_some(error, |this, error| {
186 this.child(Label::new(error).color(Color::Error))
187 }),
188 )
189 .into_any(),
190 )
191 }));
192
193 (lister, rx)
194 }
195 fn resolve_path(
196 path: PathBuf,
197 root_path: ProjectPath,
198 language_name: LanguageName,
199 project: Entity<Project>,
200 window: &mut Window,
201 cx: &mut Context<Self>,
202 ) -> PathInputState {
203 PathInputState::Resolving(cx.spawn_in(window, async move |this, cx| {
204 _ = maybe!(async move {
205 let toolchain = project
206 .update(cx, |this, cx| {
207 this.resolve_toolchain(path.clone(), language_name, cx)
208 })?
209 .await;
210 let Ok(toolchain) = toolchain else {
211 // Go back to the path input state
212 _ = this.update_in(cx, |this, window, cx| {
213 if let AddState::Path {
214 input_state,
215 picker,
216 error,
217 ..
218 } = &mut this.state
219 && matches!(input_state, PathInputState::Resolving(_))
220 {
221 let Err(e) = toolchain else { unreachable!() };
222 *error = Some(Arc::from(e.to_string()));
223 let (delegate, rx) =
224 Self::create_path_browser_delegate(this.project.clone(), cx);
225 picker.update(cx, |picker, cx| {
226 *picker = Picker::uniform_list(delegate, window, cx);
227 picker.set_query(
228 Arc::from(path.to_string_lossy().as_ref()),
229 window,
230 cx,
231 );
232 });
233 *input_state = Self::wait_for_path(rx, window, cx);
234 this.focus_handle(cx).focus(window);
235 }
236 });
237 return Err(anyhow::anyhow!("Failed to resolve toolchain"));
238 };
239 let resolved_toolchain_path = project.read_with(cx, |this, cx| {
240 this.find_project_path(&toolchain.path.as_ref(), cx)
241 })?;
242
243 // Suggest a default scope based on the applicability.
244 let scope = if let Some(project_path) = resolved_toolchain_path {
245 if !root_path.path.as_ref().is_empty() && project_path.starts_with(&root_path) {
246 ToolchainScope::Subproject(root_path.worktree_id, root_path.path)
247 } else {
248 ToolchainScope::Project
249 }
250 } else {
251 // This path lies outside of the project.
252 ToolchainScope::Global
253 };
254
255 _ = this.update_in(cx, |this, window, cx| {
256 let scope_picker = ScopePickerState {
257 entries: std::array::from_fn(|_| NavigableEntry::focusable(cx)),
258 selected_scope: scope,
259 };
260 this.state = AddState::Name {
261 editor: cx.new(|cx| {
262 let mut editor = Editor::single_line(window, cx);
263 editor.set_text(toolchain.name.as_ref(), window, cx);
264 editor
265 }),
266 toolchain,
267 scope_picker,
268 };
269 this.focus_handle(cx).focus(window);
270 });
271
272 Result::<_, anyhow::Error>::Ok(())
273 })
274 .await;
275 }))
276 }
277
278 fn wait_for_path(
279 rx: oneshot::Receiver<Option<Vec<PathBuf>>>,
280 window: &mut Window,
281 cx: &mut Context<Self>,
282 ) -> PathInputState {
283 let task = cx.spawn_in(window, async move |this, cx| {
284 maybe!(async move {
285 let result = rx.await.log_err()?;
286
287 let path = result
288 .into_iter()
289 .flat_map(|paths| paths.into_iter())
290 .next()?;
291 this.update_in(cx, |this, window, cx| {
292 if let AddState::Path {
293 input_state, error, ..
294 } = &mut this.state
295 && matches!(input_state, PathInputState::WaitingForPath(_))
296 {
297 error.take();
298 *input_state = Self::resolve_path(
299 path,
300 this.root_path.clone(),
301 this.language_name.clone(),
302 this.project.clone(),
303 window,
304 cx,
305 );
306 }
307 })
308 .ok()?;
309 Some(())
310 })
311 .await;
312 });
313 PathInputState::WaitingForPath(task)
314 }
315
316 fn confirm_toolchain(
317 &mut self,
318 _: &menu::Confirm,
319 window: &mut Window,
320 cx: &mut Context<Self>,
321 ) {
322 let AddState::Name {
323 toolchain,
324 editor,
325 scope_picker,
326 } = &mut self.state
327 else {
328 return;
329 };
330
331 let text = editor.read(cx).text(cx);
332 if text.is_empty() {
333 return;
334 }
335
336 toolchain.name = SharedString::from(text);
337 self.project.update(cx, |this, cx| {
338 this.add_toolchain(toolchain.clone(), scope_picker.selected_scope.clone(), cx);
339 });
340 _ = self.weak.update(cx, |this, cx| {
341 this.state = State::Search((this.create_search_state)(window, cx));
342 this.focus_handle(cx).focus(window);
343 cx.notify();
344 });
345 }
346}
347impl Focusable for AddToolchainState {
348 fn focus_handle(&self, cx: &App) -> FocusHandle {
349 match &self.state {
350 AddState::Path { picker, .. } => picker.focus_handle(cx),
351 AddState::Name { editor, .. } => editor.focus_handle(cx),
352 }
353 }
354}
355
356impl AddToolchainState {
357 fn select_scope(&mut self, scope: ToolchainScope, cx: &mut Context<Self>) {
358 if let AddState::Name { scope_picker, .. } = &mut self.state {
359 scope_picker.selected_scope = scope;
360 cx.notify();
361 }
362 }
363}
364
365impl Focusable for State {
366 fn focus_handle(&self, cx: &App) -> FocusHandle {
367 match self {
368 State::Search(state) => state.picker.focus_handle(cx),
369 State::AddToolchain(state) => state.focus_handle(cx),
370 }
371 }
372}
373impl Render for AddToolchainState {
374 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
375 let theme = cx.theme().clone();
376 let weak = self.weak.upgrade();
377 let label = SharedString::new_static("Add");
378
379 v_flex()
380 .size_full()
381 // todo: These modal styles shouldn't be needed as the modal picker already has `elevation_3`
382 // They get duplicated in the middle state of adding a virtual env, but then are needed for this last state
383 .bg(cx.theme().colors().elevated_surface_background)
384 .border_1()
385 .border_color(cx.theme().colors().border_variant)
386 .rounded_lg()
387 .when_some(weak, |this, weak| {
388 this.on_action(window.listener_for(
389 &weak,
390 |this: &mut ToolchainSelector, _: &menu::Cancel, window, cx| {
391 this.state = State::Search((this.create_search_state)(window, cx));
392 this.state.focus_handle(cx).focus(window);
393 cx.notify();
394 },
395 ))
396 })
397 .on_action(cx.listener(Self::confirm_toolchain))
398 .map(|this| match &self.state {
399 AddState::Path { picker, .. } => this.child(picker.clone()),
400 AddState::Name {
401 editor,
402 scope_picker,
403 ..
404 } => {
405 let scope_options = [
406 ToolchainScope::Global,
407 ToolchainScope::Project,
408 ToolchainScope::Subproject(
409 self.root_path.worktree_id,
410 self.root_path.path.clone(),
411 ),
412 ];
413
414 let mut navigable_scope_picker = Navigable::new(
415 v_flex()
416 .child(
417 h_flex()
418 .w_full()
419 .p_2()
420 .border_b_1()
421 .border_color(theme.colors().border)
422 .child(editor.clone()),
423 )
424 .child(
425 v_flex()
426 .child(
427 Label::new("Scope")
428 .size(LabelSize::Small)
429 .color(Color::Muted)
430 .mt_1()
431 .ml_2(),
432 )
433 .child(List::new().children(
434 scope_options.iter().enumerate().map(|(i, scope)| {
435 let is_selected = *scope == scope_picker.selected_scope;
436 let label = scope.label();
437 let description = scope.description();
438 let scope_clone_for_action = scope.clone();
439 let scope_clone_for_click = scope.clone();
440
441 div()
442 .id(SharedString::from(format!("scope-option-{i}")))
443 .track_focus(&scope_picker.entries[i].focus_handle)
444 .on_action(cx.listener(
445 move |this, _: &menu::Confirm, _, cx| {
446 this.select_scope(
447 scope_clone_for_action.clone(),
448 cx,
449 );
450 },
451 ))
452 .child(
453 ListItem::new(SharedString::from(format!(
454 "scope-{i}"
455 )))
456 .toggle_state(
457 is_selected
458 || scope_picker.entries[i]
459 .focus_handle
460 .contains_focused(window, cx),
461 )
462 .inset(true)
463 .spacing(ListItemSpacing::Sparse)
464 .child(
465 h_flex()
466 .gap_2()
467 .child(Label::new(label))
468 .child(
469 Label::new(description)
470 .size(LabelSize::Small)
471 .color(Color::Muted),
472 ),
473 )
474 .on_click(cx.listener(move |this, _, _, cx| {
475 this.select_scope(
476 scope_clone_for_click.clone(),
477 cx,
478 );
479 })),
480 )
481 }),
482 ))
483 .child(Divider::horizontal())
484 .child(h_flex().p_1p5().justify_end().map(|this| {
485 let is_disabled = editor.read(cx).is_empty(cx);
486 let handle = self.focus_handle(cx);
487 this.child(
488 Button::new("add-toolchain", label)
489 .disabled(is_disabled)
490 .key_binding(KeyBinding::for_action_in(
491 &menu::Confirm,
492 &handle,
493 cx,
494 ))
495 .on_click(cx.listener(|this, _, window, cx| {
496 this.confirm_toolchain(
497 &menu::Confirm,
498 window,
499 cx,
500 );
501 }))
502 .map(|this| {
503 if false {
504 this.with_animation(
505 "inspecting-user-toolchain",
506 Animation::new(Duration::from_millis(
507 500,
508 ))
509 .repeat()
510 .with_easing(pulsating_between(
511 0.4, 0.8,
512 )),
513 |label, delta| label.alpha(delta),
514 )
515 .into_any()
516 } else {
517 this.into_any_element()
518 }
519 }),
520 )
521 })),
522 )
523 .into_any_element(),
524 );
525
526 for entry in &scope_picker.entries {
527 navigable_scope_picker = navigable_scope_picker.entry(entry.clone());
528 }
529
530 this.child(navigable_scope_picker.render(window, cx))
531 }
532 })
533 }
534}
535
536#[derive(Clone)]
537enum State {
538 Search(SearchState),
539 AddToolchain(Entity<AddToolchainState>),
540}
541
542impl RenderOnce for State {
543 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
544 match self {
545 State::Search(state) => state.picker.into_any_element(),
546 State::AddToolchain(state) => state.into_any_element(),
547 }
548 }
549}
550impl ToolchainSelector {
551 fn register(
552 workspace: &mut Workspace,
553 _window: Option<&mut Window>,
554 _: &mut Context<Workspace>,
555 ) {
556 workspace.register_action(move |workspace, _: &Select, window, cx| {
557 Self::toggle(workspace, window, cx);
558 });
559 workspace.register_action(move |workspace, _: &AddToolchain, window, cx| {
560 let Some(toolchain_selector) = workspace.active_modal::<Self>(cx) else {
561 Self::toggle(workspace, window, cx);
562 return;
563 };
564
565 toolchain_selector.update(cx, |toolchain_selector, cx| {
566 toolchain_selector.handle_add_toolchain(&AddToolchain, window, cx);
567 });
568 });
569 }
570
571 fn toggle(
572 workspace: &mut Workspace,
573 window: &mut Window,
574 cx: &mut Context<Workspace>,
575 ) -> Option<()> {
576 let (_, buffer, _) = workspace
577 .active_item(cx)?
578 .act_as::<Editor>(cx)?
579 .read(cx)
580 .active_excerpt(cx)?;
581 let project = workspace.project().clone();
582
583 let language_name = buffer.read(cx).language()?.name();
584 let worktree_id = buffer.read(cx).file()?.worktree_id(cx);
585 let relative_path: Arc<RelPath> = buffer.read(cx).file()?.path().parent()?.into();
586 let worktree_root_path = project
587 .read(cx)
588 .worktree_for_id(worktree_id, cx)?
589 .read(cx)
590 .abs_path();
591 let weak = workspace.weak_handle();
592 cx.spawn_in(window, async move |workspace, cx| {
593 let active_toolchain = project
594 .read_with(cx, |this, cx| {
595 this.active_toolchain(
596 ProjectPath {
597 worktree_id,
598 path: relative_path.clone(),
599 },
600 language_name.clone(),
601 cx,
602 )
603 })?
604 .await;
605 workspace
606 .update_in(cx, |this, window, cx| {
607 this.toggle_modal(window, cx, move |window, cx| {
608 ToolchainSelector::new(
609 weak,
610 project,
611 active_toolchain,
612 worktree_id,
613 worktree_root_path,
614 relative_path,
615 language_name,
616 window,
617 cx,
618 )
619 });
620 })
621 .ok();
622 anyhow::Ok(())
623 })
624 .detach();
625
626 Some(())
627 }
628
629 fn new(
630 workspace: WeakEntity<Workspace>,
631 project: Entity<Project>,
632 active_toolchain: Option<Toolchain>,
633 worktree_id: WorktreeId,
634 worktree_root: Arc<Path>,
635 relative_path: Arc<RelPath>,
636 language_name: LanguageName,
637 window: &mut Window,
638 cx: &mut Context<Self>,
639 ) -> Self {
640 let language_registry = project.read(cx).languages().clone();
641 cx.spawn({
642 let language_name = language_name.clone();
643 async move |this, cx| {
644 let language = language_registry
645 .language_for_name(&language_name.0)
646 .await
647 .ok();
648 this.update(cx, |this, cx| {
649 this.language = language;
650 cx.notify();
651 })
652 .ok();
653 }
654 })
655 .detach();
656 let project_clone = project.clone();
657 let language_name_clone = language_name.clone();
658 let relative_path_clone = relative_path.clone();
659
660 let create_search_state = Arc::new(move |window: &mut Window, cx: &mut Context<Self>| {
661 let toolchain_selector = cx.entity().downgrade();
662 let picker = cx.new(|cx| {
663 let delegate = ToolchainSelectorDelegate::new(
664 active_toolchain.clone(),
665 toolchain_selector,
666 workspace.clone(),
667 worktree_id,
668 worktree_root.clone(),
669 project_clone.clone(),
670 relative_path_clone.clone(),
671 language_name_clone.clone(),
672 window,
673 cx,
674 );
675 Picker::uniform_list(delegate, window, cx)
676 });
677 let picker_focus_handle = picker.focus_handle(cx);
678 picker.update(cx, |picker, _| {
679 picker.delegate.focus_handle = picker_focus_handle.clone();
680 });
681 SearchState { picker }
682 });
683
684 Self {
685 state: State::Search(create_search_state(window, cx)),
686 create_search_state,
687 language: None,
688 project,
689 language_name,
690 worktree_id,
691 relative_path,
692 }
693 }
694
695 fn handle_add_toolchain(
696 &mut self,
697 _: &AddToolchain,
698 window: &mut Window,
699 cx: &mut Context<Self>,
700 ) {
701 if matches!(self.state, State::Search(_)) {
702 self.state = State::AddToolchain(AddToolchainState::new(
703 self.project.clone(),
704 self.language_name.clone(),
705 ProjectPath {
706 worktree_id: self.worktree_id,
707 path: self.relative_path.clone(),
708 },
709 window,
710 cx,
711 ));
712 self.state.focus_handle(cx).focus(window);
713 cx.notify();
714 }
715 }
716}
717
718impl Render for ToolchainSelector {
719 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
720 let mut key_context = KeyContext::new_with_defaults();
721 key_context.add("ToolchainSelector");
722
723 v_flex()
724 .key_context(key_context)
725 .w(rems(34.))
726 .on_action(cx.listener(Self::handle_add_toolchain))
727 .child(self.state.clone().render(window, cx))
728 }
729}
730
731impl Focusable for ToolchainSelector {
732 fn focus_handle(&self, cx: &App) -> FocusHandle {
733 self.state.focus_handle(cx)
734 }
735}
736
737impl EventEmitter<DismissEvent> for ToolchainSelector {}
738impl ModalView for ToolchainSelector {}
739
740pub struct ToolchainSelectorDelegate {
741 toolchain_selector: WeakEntity<ToolchainSelector>,
742 candidates: Arc<[(Toolchain, Option<ToolchainScope>)]>,
743 matches: Vec<StringMatch>,
744 selected_index: usize,
745 workspace: WeakEntity<Workspace>,
746 worktree_id: WorktreeId,
747 worktree_abs_path_root: Arc<Path>,
748 relative_path: Arc<RelPath>,
749 placeholder_text: Arc<str>,
750 add_toolchain_text: Arc<str>,
751 project: Entity<Project>,
752 focus_handle: FocusHandle,
753 _fetch_candidates_task: Task<Option<()>>,
754}
755
756impl ToolchainSelectorDelegate {
757 fn new(
758 active_toolchain: Option<Toolchain>,
759 toolchain_selector: WeakEntity<ToolchainSelector>,
760 workspace: WeakEntity<Workspace>,
761 worktree_id: WorktreeId,
762 worktree_abs_path_root: Arc<Path>,
763 project: Entity<Project>,
764 relative_path: Arc<RelPath>,
765 language_name: LanguageName,
766 window: &mut Window,
767 cx: &mut Context<Picker<Self>>,
768 ) -> Self {
769 let _project = project.clone();
770 let path_style = project.read(cx).path_style(cx);
771
772 let _fetch_candidates_task = cx.spawn_in(window, {
773 async move |this, cx| {
774 let meta = _project
775 .read_with(cx, |this, _| {
776 Project::toolchain_metadata(this.languages().clone(), language_name.clone())
777 })
778 .ok()?
779 .await?;
780 let relative_path = this
781 .update(cx, |this, cx| {
782 this.delegate.add_toolchain_text = format!(
783 "Add {}",
784 meta.term.as_ref().to_case(convert_case::Case::Title)
785 )
786 .into();
787 cx.notify();
788 this.delegate.relative_path.clone()
789 })
790 .ok()?;
791
792 let Toolchains {
793 toolchains: available_toolchains,
794 root_path: relative_path,
795 user_toolchains,
796 } = _project
797 .update(cx, |this, cx| {
798 this.available_toolchains(
799 ProjectPath {
800 worktree_id,
801 path: relative_path.clone(),
802 },
803 language_name,
804 cx,
805 )
806 })
807 .ok()?
808 .await?;
809 let pretty_path = {
810 if relative_path.is_empty() {
811 Cow::Borrowed("worktree root")
812 } else {
813 Cow::Owned(format!("`{}`", relative_path.display(path_style)))
814 }
815 };
816 let placeholder_text =
817 format!("Select a {} for {pretty_path}…", meta.term.to_lowercase(),).into();
818 let _ = this.update_in(cx, move |this, window, cx| {
819 this.delegate.relative_path = relative_path;
820 this.delegate.placeholder_text = placeholder_text;
821 this.refresh_placeholder(window, cx);
822 });
823
824 let _ = this.update_in(cx, move |this, window, cx| {
825 this.delegate.candidates = user_toolchains
826 .into_iter()
827 .flat_map(|(scope, toolchains)| {
828 toolchains
829 .into_iter()
830 .map(move |toolchain| (toolchain, Some(scope.clone())))
831 })
832 .chain(
833 available_toolchains
834 .toolchains
835 .into_iter()
836 .map(|toolchain| (toolchain, None)),
837 )
838 .collect();
839
840 if let Some(active_toolchain) = active_toolchain
841 && let Some(position) = this
842 .delegate
843 .candidates
844 .iter()
845 .position(|(toolchain, _)| *toolchain == active_toolchain)
846 {
847 this.delegate.set_selected_index(position, window, cx);
848 }
849 this.update_matches(this.query(cx), window, cx);
850 });
851
852 Some(())
853 }
854 });
855 let placeholder_text = "Select a toolchain…".to_string().into();
856 Self {
857 toolchain_selector,
858 candidates: Default::default(),
859 matches: vec![],
860 selected_index: 0,
861 workspace,
862 worktree_id,
863 worktree_abs_path_root,
864 placeholder_text,
865 relative_path,
866 _fetch_candidates_task,
867 project,
868 focus_handle: cx.focus_handle(),
869 add_toolchain_text: Arc::from("Add Toolchain"),
870 }
871 }
872 fn relativize_path(
873 path: SharedString,
874 worktree_root: &Path,
875 path_style: PathStyle,
876 ) -> SharedString {
877 Path::new(&path.as_ref())
878 .strip_prefix(&worktree_root)
879 .ok()
880 .and_then(|suffix| suffix.to_str())
881 .map(|suffix| format!(".{}{suffix}", path_style.primary_separator()).into())
882 .unwrap_or(path)
883 }
884}
885
886impl PickerDelegate for ToolchainSelectorDelegate {
887 type ListItem = ListItem;
888
889 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
890 self.placeholder_text.clone()
891 }
892
893 fn match_count(&self) -> usize {
894 self.matches.len()
895 }
896
897 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
898 if let Some(string_match) = self.matches.get(self.selected_index) {
899 let (toolchain, _) = self.candidates[string_match.candidate_id].clone();
900 if let Some(workspace_id) = self
901 .workspace
902 .read_with(cx, |this, _| this.database_id())
903 .ok()
904 .flatten()
905 {
906 let workspace = self.workspace.clone();
907 let worktree_id = self.worktree_id;
908 let path = self.relative_path.clone();
909 let relative_path = self.relative_path.clone();
910 cx.spawn_in(window, async move |_, cx| {
911 workspace::WORKSPACE_DB
912 .set_toolchain(workspace_id, worktree_id, relative_path, toolchain.clone())
913 .await
914 .log_err();
915 workspace
916 .update(cx, |this, cx| {
917 this.project().update(cx, |this, cx| {
918 this.activate_toolchain(
919 ProjectPath { worktree_id, path },
920 toolchain,
921 cx,
922 )
923 })
924 })
925 .ok()?
926 .await;
927 Some(())
928 })
929 .detach();
930 }
931 }
932 self.dismissed(window, cx);
933 }
934
935 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
936 self.toolchain_selector
937 .update(cx, |_, cx| cx.emit(DismissEvent))
938 .log_err();
939 }
940
941 fn selected_index(&self) -> usize {
942 self.selected_index
943 }
944
945 fn set_selected_index(
946 &mut self,
947 ix: usize,
948 _window: &mut Window,
949 _: &mut Context<Picker<Self>>,
950 ) {
951 self.selected_index = ix;
952 }
953
954 fn update_matches(
955 &mut self,
956 query: String,
957 window: &mut Window,
958 cx: &mut Context<Picker<Self>>,
959 ) -> gpui::Task<()> {
960 let background = cx.background_executor().clone();
961 let candidates = self.candidates.clone();
962 let worktree_root_path = self.worktree_abs_path_root.clone();
963 let path_style = self.project.read(cx).path_style(cx);
964 cx.spawn_in(window, async move |this, cx| {
965 let matches = if query.is_empty() {
966 candidates
967 .into_iter()
968 .enumerate()
969 .map(|(index, (candidate, _))| {
970 let path = Self::relativize_path(
971 candidate.path.clone(),
972 &worktree_root_path,
973 path_style,
974 );
975 let string = format!("{}{}", candidate.name, path);
976 StringMatch {
977 candidate_id: index,
978 string,
979 positions: Vec::new(),
980 score: 0.0,
981 }
982 })
983 .collect()
984 } else {
985 let candidates = candidates
986 .into_iter()
987 .enumerate()
988 .map(|(candidate_id, (toolchain, _))| {
989 let path = Self::relativize_path(
990 toolchain.path.clone(),
991 &worktree_root_path,
992 path_style,
993 );
994 let string = format!("{}{}", toolchain.name, path);
995 StringMatchCandidate::new(candidate_id, &string)
996 })
997 .collect::<Vec<_>>();
998 match_strings(
999 &candidates,
1000 &query,
1001 false,
1002 true,
1003 100,
1004 &Default::default(),
1005 background,
1006 )
1007 .await
1008 };
1009
1010 this.update(cx, |this, cx| {
1011 let delegate = &mut this.delegate;
1012 delegate.matches = matches;
1013 delegate.selected_index = delegate
1014 .selected_index
1015 .min(delegate.matches.len().saturating_sub(1));
1016 cx.notify();
1017 })
1018 .log_err();
1019 })
1020 }
1021
1022 fn render_match(
1023 &self,
1024 ix: usize,
1025 selected: bool,
1026 _: &mut Window,
1027 cx: &mut Context<Picker<Self>>,
1028 ) -> Option<Self::ListItem> {
1029 let mat = &self.matches.get(ix)?;
1030 let (toolchain, scope) = &self.candidates.get(mat.candidate_id)?;
1031
1032 let label = toolchain.name.clone();
1033 let path_style = self.project.read(cx).path_style(cx);
1034 let path = Self::relativize_path(
1035 toolchain.path.clone(),
1036 &self.worktree_abs_path_root,
1037 path_style,
1038 );
1039 let (name_highlights, mut path_highlights) = mat
1040 .positions
1041 .iter()
1042 .cloned()
1043 .partition::<Vec<_>, _>(|index| *index < label.len());
1044 path_highlights.iter_mut().for_each(|index| {
1045 *index -= label.len();
1046 });
1047 let id: SharedString = format!("toolchain-{ix}",).into();
1048 Some(
1049 ListItem::new(id)
1050 .inset(true)
1051 .spacing(ListItemSpacing::Sparse)
1052 .toggle_state(selected)
1053 .child(HighlightedLabel::new(label, name_highlights))
1054 .child(
1055 HighlightedLabel::new(path, path_highlights)
1056 .size(LabelSize::Small)
1057 .color(Color::Muted),
1058 )
1059 .when_some(scope.as_ref(), |this, scope| {
1060 let id: SharedString = format!(
1061 "delete-custom-toolchain-{}-{}",
1062 toolchain.name, toolchain.path
1063 )
1064 .into();
1065 let toolchain = toolchain.clone();
1066 let scope = scope.clone();
1067
1068 this.end_slot(IconButton::new(id, IconName::Trash).on_click(cx.listener(
1069 move |this, _, _, cx| {
1070 this.delegate.project.update(cx, |this, cx| {
1071 this.remove_toolchain(toolchain.clone(), scope.clone(), cx)
1072 });
1073
1074 this.delegate.matches.retain_mut(|m| {
1075 if m.candidate_id == ix {
1076 return false;
1077 } else if m.candidate_id > ix {
1078 m.candidate_id -= 1;
1079 }
1080 true
1081 });
1082
1083 this.delegate.candidates = this
1084 .delegate
1085 .candidates
1086 .iter()
1087 .enumerate()
1088 .filter_map(|(i, toolchain)| (ix != i).then_some(toolchain.clone()))
1089 .collect();
1090
1091 if this.delegate.selected_index >= ix {
1092 this.delegate.selected_index =
1093 this.delegate.selected_index.saturating_sub(1);
1094 }
1095 cx.stop_propagation();
1096 cx.notify();
1097 },
1098 )))
1099 }),
1100 )
1101 }
1102 fn render_footer(
1103 &self,
1104 _window: &mut Window,
1105 cx: &mut Context<Picker<Self>>,
1106 ) -> Option<AnyElement> {
1107 Some(
1108 v_flex()
1109 .rounded_b_md()
1110 .child(Divider::horizontal())
1111 .child(
1112 h_flex()
1113 .p_1p5()
1114 .gap_0p5()
1115 .justify_end()
1116 .child(
1117 Button::new("xd", self.add_toolchain_text.clone())
1118 .key_binding(KeyBinding::for_action_in(
1119 &AddToolchain,
1120 &self.focus_handle,
1121 cx,
1122 ))
1123 .on_click(|_, window, cx| {
1124 window.dispatch_action(Box::new(AddToolchain), cx)
1125 }),
1126 )
1127 .child(
1128 Button::new("select", "Select")
1129 .key_binding(KeyBinding::for_action_in(
1130 &menu::Confirm,
1131 &self.focus_handle,
1132 cx,
1133 ))
1134 .on_click(|_, window, cx| {
1135 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1136 }),
1137 ),
1138 )
1139 .into_any_element(),
1140 )
1141 }
1142}