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::{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 let placeholder_text = format!(
176 "Select a {} for `{}`…",
177 term.to_lowercase(),
178 relative_path.to_string_lossy()
179 )
180 .into();
181 let _ = this.update_in(cx, move |this, window, cx| {
182 this.delegate.placeholder_text = placeholder_text;
183 this.refresh_placeholder(window, cx);
184 });
185
186 let available_toolchains = project
187 .update(cx, |this, cx| {
188 this.available_toolchains(
189 ProjectPath {
190 worktree_id,
191 path: relative_path.clone(),
192 },
193 language_name,
194 cx,
195 )
196 })
197 .ok()?
198 .await?;
199
200 let _ = this.update_in(cx, move |this, window, cx| {
201 this.delegate.candidates = available_toolchains;
202
203 if let Some(active_toolchain) = active_toolchain {
204 if let Some(position) = this
205 .delegate
206 .candidates
207 .toolchains
208 .iter()
209 .position(|toolchain| *toolchain == active_toolchain)
210 {
211 this.delegate.set_selected_index(position, window, cx);
212 }
213 }
214 this.update_matches(this.query(cx), window, cx);
215 });
216
217 Some(())
218 }
219 });
220 let placeholder_text = "Select a toolchain…".to_string().into();
221 Self {
222 toolchain_selector,
223 candidates: Default::default(),
224 matches: vec![],
225 selected_index: 0,
226 workspace,
227 worktree_id,
228 worktree_abs_path_root,
229 placeholder_text,
230 relative_path,
231 _fetch_candidates_task,
232 }
233 }
234 fn relativize_path(path: SharedString, worktree_root: &Path) -> SharedString {
235 Path::new(&path.as_ref())
236 .strip_prefix(&worktree_root)
237 .ok()
238 .map(|suffix| Path::new(".").join(suffix))
239 .and_then(|path| path.to_str().map(String::from).map(SharedString::from))
240 .unwrap_or(path)
241 }
242}
243
244impl PickerDelegate for ToolchainSelectorDelegate {
245 type ListItem = ListItem;
246
247 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
248 self.placeholder_text.clone()
249 }
250
251 fn match_count(&self) -> usize {
252 self.matches.len()
253 }
254
255 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
256 if let Some(string_match) = self.matches.get(self.selected_index) {
257 let toolchain = self.candidates.toolchains[string_match.candidate_id].clone();
258 if let Some(workspace_id) = self
259 .workspace
260 .read_with(cx, |this, _| this.database_id())
261 .ok()
262 .flatten()
263 {
264 let workspace = self.workspace.clone();
265 let worktree_id = self.worktree_id;
266 let path = self.relative_path.clone();
267 let relative_path = self.relative_path.to_string_lossy().into_owned();
268 cx.spawn_in(window, async move |_, cx| {
269 workspace::WORKSPACE_DB
270 .set_toolchain(workspace_id, worktree_id, relative_path, toolchain.clone())
271 .await
272 .log_err();
273 workspace
274 .update(cx, |this, cx| {
275 this.project().update(cx, |this, cx| {
276 this.activate_toolchain(
277 ProjectPath { worktree_id, path },
278 toolchain,
279 cx,
280 )
281 })
282 })
283 .ok()?
284 .await;
285 Some(())
286 })
287 .detach();
288 }
289 }
290 self.dismissed(window, cx);
291 }
292
293 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
294 self.toolchain_selector
295 .update(cx, |_, cx| cx.emit(DismissEvent))
296 .log_err();
297 }
298
299 fn selected_index(&self) -> usize {
300 self.selected_index
301 }
302
303 fn set_selected_index(
304 &mut self,
305 ix: usize,
306 _window: &mut Window,
307 _: &mut Context<Picker<Self>>,
308 ) {
309 self.selected_index = ix;
310 }
311
312 fn update_matches(
313 &mut self,
314 query: String,
315 window: &mut Window,
316 cx: &mut Context<Picker<Self>>,
317 ) -> gpui::Task<()> {
318 let background = cx.background_executor().clone();
319 let candidates = self.candidates.clone();
320 let worktree_root_path = self.worktree_abs_path_root.clone();
321 cx.spawn_in(window, async move |this, cx| {
322 let matches = if query.is_empty() {
323 candidates
324 .toolchains
325 .into_iter()
326 .enumerate()
327 .map(|(index, candidate)| {
328 let path = Self::relativize_path(candidate.path, &worktree_root_path);
329 let string = format!("{}{}", candidate.name, path);
330 StringMatch {
331 candidate_id: index,
332 string,
333 positions: Vec::new(),
334 score: 0.0,
335 }
336 })
337 .collect()
338 } else {
339 let candidates = candidates
340 .toolchains
341 .into_iter()
342 .enumerate()
343 .map(|(candidate_id, toolchain)| {
344 let path = Self::relativize_path(toolchain.path, &worktree_root_path);
345 let string = format!("{}{}", toolchain.name, path);
346 StringMatchCandidate::new(candidate_id, &string)
347 })
348 .collect::<Vec<_>>();
349 match_strings(
350 &candidates,
351 &query,
352 false,
353 100,
354 &Default::default(),
355 background,
356 )
357 .await
358 };
359
360 this.update(cx, |this, cx| {
361 let delegate = &mut this.delegate;
362 delegate.matches = matches;
363 delegate.selected_index = delegate
364 .selected_index
365 .min(delegate.matches.len().saturating_sub(1));
366 cx.notify();
367 })
368 .log_err();
369 })
370 }
371
372 fn render_match(
373 &self,
374 ix: usize,
375 selected: bool,
376 _window: &mut Window,
377 _: &mut Context<Picker<Self>>,
378 ) -> Option<Self::ListItem> {
379 let mat = &self.matches[ix];
380 let toolchain = &self.candidates.toolchains[mat.candidate_id];
381
382 let label = toolchain.name.clone();
383 let path = Self::relativize_path(toolchain.path.clone(), &self.worktree_abs_path_root);
384 let (name_highlights, mut path_highlights) = mat
385 .positions
386 .iter()
387 .cloned()
388 .partition::<Vec<_>, _>(|index| *index < label.len());
389 path_highlights.iter_mut().for_each(|index| {
390 *index -= label.len();
391 });
392 Some(
393 ListItem::new(ix)
394 .inset(true)
395 .spacing(ListItemSpacing::Sparse)
396 .toggle_state(selected)
397 .child(HighlightedLabel::new(label, name_highlights))
398 .child(
399 HighlightedLabel::new(path, path_highlights)
400 .size(LabelSize::Small)
401 .color(Color::Muted),
402 ),
403 )
404 }
405}