1use std::path::Path;
2use std::sync::atomic::AtomicBool;
3use std::sync::Arc;
4
5use fuzzy::PathMatch;
6use gpui::{AppContext, DismissEvent, FocusHandle, FocusableView, Task, View, WeakModel, WeakView};
7use picker::{Picker, PickerDelegate};
8use project::{PathMatchCandidateSet, ProjectPath, WorktreeId};
9use ui::{prelude::*, ListItem, Tooltip};
10use util::ResultExt as _;
11use workspace::Workspace;
12
13use crate::context_picker::{ConfirmBehavior, ContextPicker};
14use crate::context_store::{ContextStore, IncludedFile};
15
16pub struct FileContextPicker {
17 picker: View<Picker<FileContextPickerDelegate>>,
18}
19
20impl FileContextPicker {
21 pub fn new(
22 context_picker: WeakView<ContextPicker>,
23 workspace: WeakView<Workspace>,
24 context_store: WeakModel<ContextStore>,
25 confirm_behavior: ConfirmBehavior,
26 cx: &mut ViewContext<Self>,
27 ) -> Self {
28 let delegate = FileContextPickerDelegate::new(
29 context_picker,
30 workspace,
31 context_store,
32 confirm_behavior,
33 );
34 let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx));
35
36 Self { picker }
37 }
38}
39
40impl FocusableView for FileContextPicker {
41 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
42 self.picker.focus_handle(cx)
43 }
44}
45
46impl Render for FileContextPicker {
47 fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
48 self.picker.clone()
49 }
50}
51
52pub struct FileContextPickerDelegate {
53 context_picker: WeakView<ContextPicker>,
54 workspace: WeakView<Workspace>,
55 context_store: WeakModel<ContextStore>,
56 confirm_behavior: ConfirmBehavior,
57 matches: Vec<PathMatch>,
58 selected_index: usize,
59}
60
61impl FileContextPickerDelegate {
62 pub fn new(
63 context_picker: WeakView<ContextPicker>,
64 workspace: WeakView<Workspace>,
65 context_store: WeakModel<ContextStore>,
66 confirm_behavior: ConfirmBehavior,
67 ) -> Self {
68 Self {
69 context_picker,
70 workspace,
71 context_store,
72 confirm_behavior,
73 matches: Vec::new(),
74 selected_index: 0,
75 }
76 }
77
78 fn search(
79 &mut self,
80 query: String,
81 cancellation_flag: Arc<AtomicBool>,
82 workspace: &View<Workspace>,
83 cx: &mut ViewContext<Picker<Self>>,
84 ) -> Task<Vec<PathMatch>> {
85 if query.is_empty() {
86 let workspace = workspace.read(cx);
87 let project = workspace.project().read(cx);
88 let recent_matches = workspace
89 .recent_navigation_history(Some(10), cx)
90 .into_iter()
91 .filter_map(|(project_path, _)| {
92 let worktree = project.worktree_for_id(project_path.worktree_id, cx)?;
93 Some(PathMatch {
94 score: 0.,
95 positions: Vec::new(),
96 worktree_id: project_path.worktree_id.to_usize(),
97 path: project_path.path,
98 path_prefix: worktree.read(cx).root_name().into(),
99 distance_to_relative_ancestor: 0,
100 is_dir: false,
101 })
102 });
103
104 let file_matches = project.worktrees(cx).flat_map(|worktree| {
105 let worktree = worktree.read(cx);
106 let path_prefix: Arc<str> = worktree.root_name().into();
107 worktree.files(true, 0).map(move |entry| PathMatch {
108 score: 0.,
109 positions: Vec::new(),
110 worktree_id: worktree.id().to_usize(),
111 path: entry.path.clone(),
112 path_prefix: path_prefix.clone(),
113 distance_to_relative_ancestor: 0,
114 is_dir: false,
115 })
116 });
117
118 Task::ready(recent_matches.chain(file_matches).collect())
119 } else {
120 let worktrees = workspace.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
121 let candidate_sets = worktrees
122 .into_iter()
123 .map(|worktree| {
124 let worktree = worktree.read(cx);
125
126 PathMatchCandidateSet {
127 snapshot: worktree.snapshot(),
128 include_ignored: worktree
129 .root_entry()
130 .map_or(false, |entry| entry.is_ignored),
131 include_root_name: true,
132 candidates: project::Candidates::Files,
133 }
134 })
135 .collect::<Vec<_>>();
136
137 let executor = cx.background_executor().clone();
138 cx.foreground_executor().spawn(async move {
139 fuzzy::match_path_sets(
140 candidate_sets.as_slice(),
141 query.as_str(),
142 None,
143 false,
144 100,
145 &cancellation_flag,
146 executor,
147 )
148 .await
149 })
150 }
151 }
152}
153
154impl PickerDelegate for FileContextPickerDelegate {
155 type ListItem = ListItem;
156
157 fn match_count(&self) -> usize {
158 self.matches.len()
159 }
160
161 fn selected_index(&self) -> usize {
162 self.selected_index
163 }
164
165 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
166 self.selected_index = ix;
167 }
168
169 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
170 "Search files…".into()
171 }
172
173 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
174 let Some(workspace) = self.workspace.upgrade() else {
175 return Task::ready(());
176 };
177
178 let search_task = self.search(query, Arc::<AtomicBool>::default(), &workspace, cx);
179
180 cx.spawn(|this, mut cx| async move {
181 // TODO: This should be probably be run in the background.
182 let paths = search_task.await;
183
184 this.update(&mut cx, |this, _cx| {
185 this.delegate.matches = paths;
186 })
187 .log_err();
188 })
189 }
190
191 fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
192 let Some(mat) = self.matches.get(self.selected_index) else {
193 return;
194 };
195
196 let workspace = self.workspace.clone();
197 let Some(project) = workspace
198 .upgrade()
199 .map(|workspace| workspace.read(cx).project().clone())
200 else {
201 return;
202 };
203 let path = mat.path.clone();
204
205 if self
206 .context_store
207 .update(cx, |context_store, _cx| {
208 match context_store.included_file(&path) {
209 Some(IncludedFile::Direct(context_id)) => {
210 context_store.remove_context(&context_id);
211 true
212 }
213 Some(IncludedFile::InDirectory(_)) => true,
214 None => false,
215 }
216 })
217 .unwrap_or(true)
218 {
219 return;
220 }
221
222 let worktree_id = WorktreeId::from_usize(mat.worktree_id);
223 let confirm_behavior = self.confirm_behavior;
224 cx.spawn(|this, mut cx| async move {
225 let Some(open_buffer_task) = project
226 .update(&mut cx, |project, cx| {
227 let project_path = ProjectPath {
228 worktree_id,
229 path: path.clone(),
230 };
231
232 let task = project.open_buffer(project_path, cx);
233
234 Some(task)
235 })
236 .ok()
237 .flatten()
238 else {
239 return anyhow::Ok(());
240 };
241
242 let buffer = open_buffer_task.await?;
243
244 this.update(&mut cx, |this, cx| {
245 this.delegate
246 .context_store
247 .update(cx, |context_store, cx| {
248 context_store.insert_file(buffer.read(cx));
249 })?;
250
251 match confirm_behavior {
252 ConfirmBehavior::KeepOpen => {}
253 ConfirmBehavior::Close => this.delegate.dismissed(cx),
254 }
255
256 anyhow::Ok(())
257 })??;
258
259 anyhow::Ok(())
260 })
261 .detach_and_log_err(cx);
262 }
263
264 fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
265 self.context_picker
266 .update(cx, |this, cx| {
267 this.reset_mode();
268 cx.emit(DismissEvent);
269 })
270 .ok();
271 }
272
273 fn render_match(
274 &self,
275 ix: usize,
276 selected: bool,
277 cx: &mut ViewContext<Picker<Self>>,
278 ) -> Option<Self::ListItem> {
279 let path_match = &self.matches[ix];
280
281 let (file_name, directory) = if path_match.path.as_ref() == Path::new("") {
282 (SharedString::from(path_match.path_prefix.clone()), None)
283 } else {
284 let file_name = path_match
285 .path
286 .file_name()
287 .unwrap_or_default()
288 .to_string_lossy()
289 .to_string()
290 .into();
291
292 let mut directory = format!("{}/", path_match.path_prefix);
293 if let Some(parent) = path_match
294 .path
295 .parent()
296 .filter(|parent| parent != &Path::new(""))
297 {
298 directory.push_str(&parent.to_string_lossy());
299 directory.push('/');
300 }
301
302 (file_name, Some(directory))
303 };
304
305 let added = self
306 .context_store
307 .upgrade()
308 .and_then(|context_store| context_store.read(cx).included_file(&path_match.path));
309
310 Some(
311 ListItem::new(ix)
312 .inset(true)
313 .toggle_state(selected)
314 .child(
315 h_flex()
316 .gap_2()
317 .child(Label::new(file_name))
318 .children(directory.map(|directory| {
319 Label::new(directory)
320 .size(LabelSize::Small)
321 .color(Color::Muted)
322 })),
323 )
324 .when_some(added, |el, added| match added {
325 IncludedFile::Direct(_) => {
326 el.end_slot(Label::new("Added").size(LabelSize::XSmall))
327 }
328 IncludedFile::InDirectory(dir_name) => {
329 let dir_name = dir_name.to_string_lossy().into_owned();
330
331 el.end_slot(Label::new("Included").size(LabelSize::XSmall))
332 .tooltip(move |cx| Tooltip::text(format!("in {dir_name}"), cx))
333 }
334 }),
335 )
336 }
337}