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