1mod active_toolchain;
2
3pub use active_toolchain::ActiveToolchain;
4use editor::Editor;
5use fuzzy::{match_strings, StringMatch, StringMatchCandidate};
6use gpui::{
7 actions, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
8 ParentElement, Render, Styled, Task, WeakEntity, Window,
9};
10use language::{LanguageName, Toolchain, ToolchainList};
11use picker::{Picker, PickerDelegate};
12use project::{Project, WorktreeId};
13use std::{path::Path, sync::Arc};
14use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
15use util::ResultExt;
16use workspace::{ModalView, Workspace};
17
18actions!(toolchain, [Select]);
19
20pub fn init(cx: &mut App) {
21 cx.observe_new(ToolchainSelector::register).detach();
22}
23
24pub struct ToolchainSelector {
25 picker: Entity<Picker<ToolchainSelectorDelegate>>,
26}
27
28impl ToolchainSelector {
29 fn register(
30 workspace: &mut Workspace,
31 _window: Option<&mut Window>,
32 _: &mut Context<Workspace>,
33 ) {
34 workspace.register_action(move |workspace, _: &Select, window, cx| {
35 Self::toggle(workspace, window, cx);
36 });
37 }
38
39 fn toggle(
40 workspace: &mut Workspace,
41 window: &mut Window,
42 cx: &mut Context<Workspace>,
43 ) -> Option<()> {
44 let (_, buffer, _) = workspace
45 .active_item(cx)?
46 .act_as::<Editor>(cx)?
47 .read(cx)
48 .active_excerpt(cx)?;
49 let project = workspace.project().clone();
50
51 let language_name = buffer.read(cx).language()?.name();
52 let worktree_id = buffer.read(cx).file()?.worktree_id(cx);
53 let worktree_root_path = project
54 .read(cx)
55 .worktree_for_id(worktree_id, cx)?
56 .read(cx)
57 .abs_path();
58 let workspace_id = workspace.database_id()?;
59 let weak = workspace.weak_handle();
60 cx.spawn_in(window, move |workspace, mut cx| async move {
61 let active_toolchain = workspace::WORKSPACE_DB
62 .toolchain(workspace_id, worktree_id, language_name.clone())
63 .await
64 .ok()
65 .flatten();
66 workspace
67 .update_in(&mut cx, |this, window, cx| {
68 this.toggle_modal(window, cx, move |window, cx| {
69 ToolchainSelector::new(
70 weak,
71 project,
72 active_toolchain,
73 worktree_id,
74 worktree_root_path,
75 language_name,
76 window,
77 cx,
78 )
79 });
80 })
81 .ok();
82 })
83 .detach();
84
85 Some(())
86 }
87
88 #[allow(clippy::too_many_arguments)]
89 fn new(
90 workspace: WeakEntity<Workspace>,
91 project: Entity<Project>,
92 active_toolchain: Option<Toolchain>,
93 worktree_id: WorktreeId,
94 worktree_root: Arc<Path>,
95 language_name: LanguageName,
96 window: &mut Window,
97 cx: &mut Context<Self>,
98 ) -> Self {
99 let toolchain_selector = cx.entity().downgrade();
100 let picker = cx.new(|cx| {
101 let delegate = ToolchainSelectorDelegate::new(
102 active_toolchain,
103 toolchain_selector,
104 workspace,
105 worktree_id,
106 worktree_root,
107 project,
108 language_name,
109 window,
110 cx,
111 );
112 Picker::uniform_list(delegate, window, cx)
113 });
114 Self { picker }
115 }
116}
117
118impl Render for ToolchainSelector {
119 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
120 v_flex().w(rems(34.)).child(self.picker.clone())
121 }
122}
123
124impl Focusable for ToolchainSelector {
125 fn focus_handle(&self, cx: &App) -> FocusHandle {
126 self.picker.focus_handle(cx)
127 }
128}
129
130impl EventEmitter<DismissEvent> for ToolchainSelector {}
131impl ModalView for ToolchainSelector {}
132
133pub struct ToolchainSelectorDelegate {
134 toolchain_selector: WeakEntity<ToolchainSelector>,
135 candidates: ToolchainList,
136 matches: Vec<StringMatch>,
137 selected_index: usize,
138 workspace: WeakEntity<Workspace>,
139 worktree_id: WorktreeId,
140 worktree_abs_path_root: Arc<Path>,
141 placeholder_text: Arc<str>,
142 _fetch_candidates_task: Task<Option<()>>,
143}
144
145impl ToolchainSelectorDelegate {
146 #[allow(clippy::too_many_arguments)]
147 fn new(
148 active_toolchain: Option<Toolchain>,
149 toolchain_selector: WeakEntity<ToolchainSelector>,
150 workspace: WeakEntity<Workspace>,
151 worktree_id: WorktreeId,
152 worktree_abs_path_root: Arc<Path>,
153 project: Entity<Project>,
154 language_name: LanguageName,
155 window: &mut Window,
156 cx: &mut Context<Picker<Self>>,
157 ) -> Self {
158 let _fetch_candidates_task = cx.spawn_in(window, {
159 let project = project.clone();
160 move |this, mut cx| async move {
161 let term = project
162 .update(&mut cx, |this, _| {
163 Project::toolchain_term(this.languages().clone(), language_name.clone())
164 })
165 .ok()?
166 .await?;
167 let placeholder_text = format!("Select a {}…", term.to_lowercase()).into();
168 let _ = this.update_in(&mut cx, move |this, window, cx| {
169 this.delegate.placeholder_text = placeholder_text;
170 this.refresh_placeholder(window, cx);
171 });
172 let available_toolchains = project
173 .update(&mut cx, |this, cx| {
174 this.available_toolchains(worktree_id, language_name, cx)
175 })
176 .ok()?
177 .await?;
178
179 let _ = this.update_in(&mut cx, move |this, window, cx| {
180 this.delegate.candidates = available_toolchains;
181
182 if let Some(active_toolchain) = active_toolchain {
183 if let Some(position) = this
184 .delegate
185 .candidates
186 .toolchains
187 .iter()
188 .position(|toolchain| *toolchain == active_toolchain)
189 {
190 this.delegate.set_selected_index(position, window, cx);
191 }
192 }
193 this.update_matches(this.query(cx), window, cx);
194 });
195
196 Some(())
197 }
198 });
199 let placeholder_text = "Select a toolchain…".to_string().into();
200 Self {
201 toolchain_selector,
202 candidates: Default::default(),
203 matches: vec![],
204 selected_index: 0,
205 workspace,
206 worktree_id,
207 worktree_abs_path_root,
208 placeholder_text,
209 _fetch_candidates_task,
210 }
211 }
212 fn relativize_path(path: SharedString, worktree_root: &Path) -> SharedString {
213 Path::new(&path.as_ref())
214 .strip_prefix(&worktree_root)
215 .ok()
216 .map(|suffix| Path::new(".").join(suffix))
217 .and_then(|path| path.to_str().map(String::from).map(SharedString::from))
218 .unwrap_or(path)
219 }
220}
221
222impl PickerDelegate for ToolchainSelectorDelegate {
223 type ListItem = ListItem;
224
225 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
226 self.placeholder_text.clone()
227 }
228
229 fn match_count(&self) -> usize {
230 self.matches.len()
231 }
232
233 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
234 if let Some(string_match) = self.matches.get(self.selected_index) {
235 let toolchain = self.candidates.toolchains[string_match.candidate_id].clone();
236 if let Some(workspace_id) = self
237 .workspace
238 .update(cx, |this, _| this.database_id())
239 .ok()
240 .flatten()
241 {
242 let workspace = self.workspace.clone();
243 let worktree_id = self.worktree_id;
244 cx.spawn_in(window, |_, mut cx| async move {
245 workspace::WORKSPACE_DB
246 .set_toolchain(workspace_id, worktree_id, toolchain.clone())
247 .await
248 .log_err();
249 workspace
250 .update(&mut cx, |this, cx| {
251 this.project().update(cx, |this, cx| {
252 this.activate_toolchain(worktree_id, toolchain, cx)
253 })
254 })
255 .ok()?
256 .await;
257 Some(())
258 })
259 .detach();
260 }
261 }
262 self.dismissed(window, cx);
263 }
264
265 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
266 self.toolchain_selector
267 .update(cx, |_, cx| cx.emit(DismissEvent))
268 .log_err();
269 }
270
271 fn selected_index(&self) -> usize {
272 self.selected_index
273 }
274
275 fn set_selected_index(
276 &mut self,
277 ix: usize,
278 _window: &mut Window,
279 _: &mut Context<Picker<Self>>,
280 ) {
281 self.selected_index = ix;
282 }
283
284 fn update_matches(
285 &mut self,
286 query: String,
287 window: &mut Window,
288 cx: &mut Context<Picker<Self>>,
289 ) -> gpui::Task<()> {
290 let background = cx.background_executor().clone();
291 let candidates = self.candidates.clone();
292 let worktree_root_path = self.worktree_abs_path_root.clone();
293 cx.spawn_in(window, |this, mut cx| async move {
294 let matches = if query.is_empty() {
295 candidates
296 .toolchains
297 .into_iter()
298 .enumerate()
299 .map(|(index, candidate)| {
300 let path = Self::relativize_path(candidate.path, &worktree_root_path);
301 let string = format!("{}{}", candidate.name, path);
302 StringMatch {
303 candidate_id: index,
304 string,
305 positions: Vec::new(),
306 score: 0.0,
307 }
308 })
309 .collect()
310 } else {
311 let candidates = candidates
312 .toolchains
313 .into_iter()
314 .enumerate()
315 .map(|(candidate_id, toolchain)| {
316 let path = Self::relativize_path(toolchain.path, &worktree_root_path);
317 let string = format!("{}{}", toolchain.name, path);
318 StringMatchCandidate::new(candidate_id, &string)
319 })
320 .collect::<Vec<_>>();
321 match_strings(
322 &candidates,
323 &query,
324 false,
325 100,
326 &Default::default(),
327 background,
328 )
329 .await
330 };
331
332 this.update(&mut cx, |this, cx| {
333 let delegate = &mut this.delegate;
334 delegate.matches = matches;
335 delegate.selected_index = delegate
336 .selected_index
337 .min(delegate.matches.len().saturating_sub(1));
338 cx.notify();
339 })
340 .log_err();
341 })
342 }
343
344 fn render_match(
345 &self,
346 ix: usize,
347 selected: bool,
348 _window: &mut Window,
349 _: &mut Context<Picker<Self>>,
350 ) -> Option<Self::ListItem> {
351 let mat = &self.matches[ix];
352 let toolchain = &self.candidates.toolchains[mat.candidate_id];
353
354 let label = toolchain.name.clone();
355 let path = Self::relativize_path(toolchain.path.clone(), &self.worktree_abs_path_root);
356 let (name_highlights, mut path_highlights) = mat
357 .positions
358 .iter()
359 .cloned()
360 .partition::<Vec<_>, _>(|index| *index < label.len());
361 path_highlights.iter_mut().for_each(|index| {
362 *index -= label.len();
363 });
364 Some(
365 ListItem::new(ix)
366 .inset(true)
367 .spacing(ListItemSpacing::Sparse)
368 .toggle_state(selected)
369 .child(HighlightedLabel::new(label, name_highlights))
370 .child(
371 HighlightedLabel::new(path, path_highlights)
372 .size(LabelSize::Small)
373 .color(Color::Muted),
374 ),
375 )
376 }
377}