on master help sign in
Merge pull request #7264 from the-mikedavis/merge-picker-and-filepicker
06d63d6Pascal Kuthe
helix-term/src/commands.rs+24−30
@@ -55,8 +55,8 @@ use crate::{
55 job::Callback,
55 job::Callback,
56 keymap::ReverseKeymap,
56 keymap::ReverseKeymap,
57 ui::{
57 ui::{
58− self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem,
58+ self, editor::InsertEvent, lsp::SignatureHelp, overlay::overlaid, CompletionItem, Picker,
59− FilePicker, Picker, Popup, Prompt, PromptEvent,
59+ Popup, Prompt, PromptEvent,
60 },
60 },
61};
61};
62
62
@@ -2156,7 +2156,7 @@ fn global_search(cx: &mut Context) {
2156 return;
2156 return;
2157 }
2157 }
2158
2158
2159− let picker = FilePicker::new(
2159+ let picker = Picker::new(
2160 all_matches,
2160 all_matches,
2161 current_path,
2161 current_path,
2162 move |cx, FileResult { path, line_num }, action| {
2162 move |cx, FileResult { path, line_num }, action| {
@@ -2184,11 +2184,9 @@ fn global_search(cx: &mut Context) {
2184
2184
2185 doc.set_selection(view.id, Selection::single(start, end));
2185 doc.set_selection(view.id, Selection::single(start, end));
2186 align_view(doc, view, Align::Center);
2186 align_view(doc, view, Align::Center);
2187− },
2188− |_editor, FileResult { path, line_num }| {
2187+ }).with_preview(|_editor, FileResult { path, line_num }| {
2189 Some((path.clone().into(), Some((*line_num, *line_num))))
2188 Some((path.clone().into(), Some((*line_num, *line_num))))
2190− },
2191− );
2189+ });
2192 compositor.push(Box::new(overlaid(picker)));
2190 compositor.push(Box::new(overlaid(picker)));
2193 },
2191 },
2194 ));
2192 ));
@@ -2579,22 +2577,18 @@ fn buffer_picker(cx: &mut Context) {
2579 // mru
2577 // mru
2580 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
2578 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
2581
2579
2582− let picker = FilePicker::new(
2583− items,
2584− (),
2585− |cx, meta, action| {
2580+ let picker = Picker::new(items, (), |cx, meta, action| {
2586− cx.editor.switch(meta.id, action);
2581+ cx.editor.switch(meta.id, action);
2587− },
2582+ })
2588− |editor, meta| {
2583+ .with_preview(|editor, meta| {
2589− let doc = &editor.documents.get(&meta.id)?;
2584+ let doc = &editor.documents.get(&meta.id)?;
2590− let &view_id = doc.selections().keys().next()?;
2585+ let &view_id = doc.selections().keys().next()?;
2591− let line = doc
2586+ let line = doc
2592− .selection(view_id)
2587+ .selection(view_id)
2593− .primary()
2588+ .primary()
2594− .cursor_line(doc.text().slice(..));
2589+ .cursor_line(doc.text().slice(..));
2595− Some((meta.id.into(), Some((line, line))))
2590+ Some((meta.id.into(), Some((line, line))))
2596− },
2597− );
2591+ });
2598 cx.push_layer(Box::new(overlaid(picker)));
2592 cx.push_layer(Box::new(overlaid(picker)));
2599}
2593}
2600
2594
@@ -2660,7 +2654,7 @@ fn jumplist_picker(cx: &mut Context) {
2660 }
2654 }
2661 };
2655 };
2662
2656
2663− let picker = FilePicker::new(
2657+ let picker = Picker::new(
2664 cx.editor
2658 cx.editor
2665 .tree
2659 .tree
2666 .views()
2660 .views()
@@ -2678,12 +2672,12 @@ fn jumplist_picker(cx: &mut Context) {
2678 doc.set_selection(view.id, meta.selection.clone());
2672 doc.set_selection(view.id, meta.selection.clone());
2679 view.ensure_cursor_in_view_center(doc, config.scrolloff);
2673 view.ensure_cursor_in_view_center(doc, config.scrolloff);
2680 },
2674 },
2675+ )
2681− |editor, meta| {
2676+ .with_preview(|editor, meta| {
2682− let doc = &editor.documents.get(&meta.id)?;
2677+ let doc = &editor.documents.get(&meta.id)?;
2683− let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2678+ let line = meta.selection.primary().cursor_line(doc.text().slice(..));
2684− Some((meta.id.into(), Some((line, line))))
2679+ Some((meta.id.into(), Some((line, line))))
2685− },
2686− );
2680+ });
2687 cx.push_layer(Box::new(overlaid(picker)));
2681 cx.push_layer(Box::new(overlaid(picker)));
2688}
2682}
2689
2683
helix-term/src/commands/dap.rs+44−50
@@ -2,7 +2,7 @@ use super::{Context, Editor};
2use crate::{
2use crate::{
3 compositor::{self, Compositor},
3 compositor::{self, Compositor},
4 job::{Callback, Jobs},
4 job::{Callback, Jobs},
5− ui::{self, overlay::overlaid, FilePicker, Picker, Popup, Prompt, PromptEvent, Text},
5+ ui::{self, overlay::overlaid, Picker, Popup, Prompt, PromptEvent, Text},
6};
6};
7use dap::{StackFrame, Thread, ThreadStates};
7use dap::{StackFrame, Thread, ThreadStates};
8use helix_core::syntax::{DebugArgumentValue, DebugConfigCompletion, DebugTemplate};
8use helix_core::syntax::{DebugArgumentValue, DebugConfigCompletion, DebugTemplate};
@@ -73,21 +73,19 @@ fn thread_picker(
73 let debugger = debugger!(editor);
73 let debugger = debugger!(editor);
74
74
75 let thread_states = debugger.thread_states.clone();
75 let thread_states = debugger.thread_states.clone();
76− let picker = FilePicker::new(
76+ let picker = Picker::new(threads, thread_states, move |cx, thread, _action| {
77− threads,
78− thread_states,
79− move |cx, thread, _action| callback_fn(cx.editor, thread),
77+ callback_fn(cx.editor, thread)
78+ })
80− move |editor, thread| {
79+ .with_preview(move |editor, thread| {
81− let frames = editor.debugger.as_ref()?.stack_frames.get(&thread.id)?;
80+ let frames = editor.debugger.as_ref()?.stack_frames.get(&thread.id)?;
82− let frame = frames.get(0)?;
81+ let frame = frames.get(0)?;
83− let path = frame.source.as_ref()?.path.clone()?;
82+ let path = frame.source.as_ref()?.path.clone()?;
84− let pos = Some((
83+ let pos = Some((
85− frame.line.saturating_sub(1),
84+ frame.line.saturating_sub(1),
86− frame.end_line.unwrap_or(frame.line).saturating_sub(1),
85+ frame.end_line.unwrap_or(frame.line).saturating_sub(1),
87− ));
86+ ));
88− Some((path.into(), pos))
87+ Some((path.into(), pos))
89− },
90− );
88+ });
91 compositor.push(Box::new(picker));
89 compositor.push(Box::new(picker));
92 },
90 },
93 );
91 );
@@ -728,39 +726,35 @@ pub fn dap_switch_stack_frame(cx: &mut Context) {
728
726
729 let frames = debugger.stack_frames[&thread_id].clone();
727 let frames = debugger.stack_frames[&thread_id].clone();
730
728
731− let picker = FilePicker::new(
732− frames,
733− (),
734− move |cx, frame, _action| {
729+ let picker = Picker::new(frames, (), move |cx, frame, _action| {
735− let debugger = debugger!(cx.editor);
730+ let debugger = debugger!(cx.editor);
736− // TODO: this should be simpler to find
731+ // TODO: this should be simpler to find
737− let pos = debugger.stack_frames[&thread_id]
732+ let pos = debugger.stack_frames[&thread_id]
738− .iter()
733+ .iter()
739− .position(|f| f.id == frame.id);
734+ .position(|f| f.id == frame.id);
740− debugger.active_frame = pos;
735+ debugger.active_frame = pos;
741−
736+
742− let frame = debugger.stack_frames[&thread_id]
737+ let frame = debugger.stack_frames[&thread_id]
743− .get(pos.unwrap_or(0))
738+ .get(pos.unwrap_or(0))
744− .cloned();
739+ .cloned();
745− if let Some(frame) = &frame {
740+ if let Some(frame) = &frame {
746− jump_to_stack_frame(cx.editor, frame);
741+ jump_to_stack_frame(cx.editor, frame);
747− }
742+ }
748− },
743+ })
749− move |_editor, frame| {
744+ .with_preview(move |_editor, frame| {
750− frame
745+ frame
751− .source
746+ .source
752− .as_ref()
747+ .as_ref()
753− .and_then(|source| source.path.clone())
748+ .and_then(|source| source.path.clone())
754− .map(|path| {
749+ .map(|path| {
755− (
750+ (
756− path.into(),
751+ path.into(),
757− Some((
752+ Some((
758− frame.line.saturating_sub(1),
753+ frame.line.saturating_sub(1),
759− frame.end_line.unwrap_or(frame.line).saturating_sub(1),
754+ frame.end_line.unwrap_or(frame.line).saturating_sub(1),
760− )),
755+ )),
761− )
762− })
756+ )
763− },
757+ })
764− );
758+ });
765 cx.push_layer(Box::new(picker))
759 cx.push_layer(Box::new(picker))
766}
760}
helix-term/src/commands/lsp.rs+41−49
@@ -31,8 +31,8 @@ use crate::{
31 compositor::{self, Compositor},
31 compositor::{self, Compositor},
32 job::Callback,
32 job::Callback,
33 ui::{
33 ui::{
34− self, lsp::SignatureHelp, overlay::overlaid, DynamicPicker, FileLocation, FilePicker,
34+ self, lsp::SignatureHelp, overlay::overlaid, DynamicPicker, FileLocation, Picker, Popup,
35− Popup, PromptEvent,
35+ PromptEvent,
36 },
36 },
37};
37};
38
38
@@ -236,48 +236,44 @@ fn jump_to_location(
236 align_view(doc, view, Align::Center);
236 align_view(doc, view, Align::Center);
237}
237}
238
238
239−type SymbolPicker = FilePicker<SymbolInformationItem>;
239+type SymbolPicker = Picker<SymbolInformationItem>;
240
240
241fn sym_picker(symbols: Vec<SymbolInformationItem>, current_path: Option<lsp::Url>) -> SymbolPicker {
241fn sym_picker(symbols: Vec<SymbolInformationItem>, current_path: Option<lsp::Url>) -> SymbolPicker {
242 // TODO: drop current_path comparison and instead use workspace: bool flag?
242 // TODO: drop current_path comparison and instead use workspace: bool flag?
243− FilePicker::new(
244− symbols,
245− current_path.clone(),
243+ Picker::new(symbols, current_path.clone(), move |cx, item, action| {
246− move |cx, item, action| {
247− let (view, doc) = current!(cx.editor);
244+ let (view, doc) = current!(cx.editor);
248− push_jump(view, doc);
245+ push_jump(view, doc);
249−
246+
250− if current_path.as_ref() != Some(&item.symbol.location.uri) {
247+ if current_path.as_ref() != Some(&item.symbol.location.uri) {
251− let uri = &item.symbol.location.uri;
248+ let uri = &item.symbol.location.uri;
252− let path = match uri.to_file_path() {
249+ let path = match uri.to_file_path() {
253− Ok(path) => path,
250+ Ok(path) => path,
254− Err(_) => {
251+ Err(_) => {
255− let err = format!("unable to convert URI to filepath: {}", uri);
252+ let err = format!("unable to convert URI to filepath: {}", uri);
256− cx.editor.set_error(err);
257− return;
258− }
259− };
260− if let Err(err) = cx.editor.open(&path, action) {
261− let err = format!("failed to open document: {}: {}", uri, err);
262− log::error!("{}", err);
263 cx.editor.set_error(err);
253 cx.editor.set_error(err);
264 return;
254 return;
265 }
255 }
256+ };
257+ if let Err(err) = cx.editor.open(&path, action) {
258+ let err = format!("failed to open document: {}: {}", uri, err);
259+ log::error!("{}", err);
260+ cx.editor.set_error(err);
261+ return;
266 }
262 }
263+ }
267
264
268− let (view, doc) = current!(cx.editor);
265+ let (view, doc) = current!(cx.editor);
269
266
270− if let Some(range) =
267+ if let Some(range) =
271− lsp_range_to_range(doc.text(), item.symbol.location.range, item.offset_encoding)
268+ lsp_range_to_range(doc.text(), item.symbol.location.range, item.offset_encoding)
272− {
269+ {
273− // we flip the range so that the cursor sits on the start of the symbol
270+ // we flip the range so that the cursor sits on the start of the symbol
274− // (for example start of the function).
271+ // (for example start of the function).
275− doc.set_selection(view.id, Selection::single(range.head, range.anchor));
272+ doc.set_selection(view.id, Selection::single(range.head, range.anchor));
276− align_view(doc, view, Align::Center);
273+ align_view(doc, view, Align::Center);
277− }
274+ }
278− },
275+ })
279− move |_editor, item| Some(location_to_file_location(&item.symbol.location)),
276+ .with_preview(move |_editor, item| Some(location_to_file_location(&item.symbol.location)))
280− )
281 .truncate_start(false)
277 .truncate_start(false)
282}
278}
283
279
@@ -292,7 +288,7 @@ fn diag_picker(
292 diagnostics: BTreeMap<lsp::Url, Vec<(lsp::Diagnostic, usize)>>,
288 diagnostics: BTreeMap<lsp::Url, Vec<(lsp::Diagnostic, usize)>>,
293 current_path: Option<lsp::Url>,
289 current_path: Option<lsp::Url>,
294 format: DiagnosticsFormat,
290 format: DiagnosticsFormat,
295−) -> FilePicker<PickerDiagnostic> {
291+) -> Picker<PickerDiagnostic> {
296 // TODO: drop current_path comparison and instead use workspace: bool flag?
292 // TODO: drop current_path comparison and instead use workspace: bool flag?
297
293
298 // flatten the map to a vec of (url, diag) pairs
294 // flatten the map to a vec of (url, diag) pairs
@@ -318,7 +314,7 @@ fn diag_picker(
318 error: cx.editor.theme.get("error"),
314 error: cx.editor.theme.get("error"),
319 };
315 };
320
316
321− FilePicker::new(
317+ Picker::new(
322 flat_diag,
318 flat_diag,
323 (styles, format),
319 (styles, format),
324 move |cx,
320 move |cx,
@@ -345,11 +341,11 @@ fn diag_picker(
345 align_view(doc, view, Align::Center);
341 align_view(doc, view, Align::Center);
346 }
342 }
347 },
343 },
348− move |_editor, PickerDiagnostic { url, diag, .. }| {
349− let location = lsp::Location::new(url.clone(), diag.range);
350− Some(location_to_file_location(&location))
351− },
352 )
344 )
345+ .with_preview(move |_editor, PickerDiagnostic { url, diag, .. }| {
346+ let location = lsp::Location::new(url.clone(), diag.range);
347+ Some(location_to_file_location(&location))
348+ })
353 .truncate_start(false)
349 .truncate_start(false)
354}
350}
355
351
@@ -1047,14 +1043,10 @@ fn goto_impl(
1047 editor.set_error("No definition found.");
1043 editor.set_error("No definition found.");
1048 }
1044 }
1049 _locations => {
1045 _locations => {
1050− let picker = FilePicker::new(
1051− locations,
1052− cwdir,
1053− move |cx, location, action| {
1046+ let picker = Picker::new(locations, cwdir, move |cx, location, action| {
1054− jump_to_location(cx.editor, location, offset_encoding, action)
1047+ jump_to_location(cx.editor, location, offset_encoding, action)
1055− },
1048+ })
1056− move |_editor, location| Some(location_to_file_location(location)),
1049+ .with_preview(move |_editor, location| Some(location_to_file_location(location)));
1057− );
1058 compositor.push(Box::new(overlaid(picker)));
1050 compositor.push(Box::new(overlaid(picker)));
1059 }
1051 }
1060 }
1052 }
helix-term/src/ui/mod.rs+13−17
@@ -21,7 +21,7 @@ pub use completion::{Completion, CompletionItem};
21pub use editor::EditorView;
21pub use editor::EditorView;
22pub use markdown::Markdown;
22pub use markdown::Markdown;
23pub use menu::Menu;
23pub use menu::Menu;
24−pub use picker::{DynamicPicker, FileLocation, FilePicker, Picker};
24+pub use picker::{DynamicPicker, FileLocation, Picker};
25pub use popup::Popup;
25pub use popup::Popup;
26pub use prompt::{Prompt, PromptEvent};
26pub use prompt::{Prompt, PromptEvent};
27pub use spinner::{ProgressSpinners, Spinner};
27pub use spinner::{ProgressSpinners, Spinner};
@@ -158,7 +158,7 @@ pub fn regex_prompt(
158 cx.push_layer(Box::new(prompt));
158 cx.push_layer(Box::new(prompt));
159}
159}
160
160
161−pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> FilePicker<PathBuf> {
161+pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> Picker<PathBuf> {
162 use ignore::{types::TypesBuilder, WalkBuilder};
162 use ignore::{types::TypesBuilder, WalkBuilder};
163 use std::time::Instant;
163 use std::time::Instant;
164
164
@@ -217,21 +217,17 @@ pub fn file_picker(root: PathBuf, config: &helix_view::editor::Config) -> FilePi
217
217
218 log::debug!("file_picker init {:?}", Instant::now().duration_since(now));
218 log::debug!("file_picker init {:?}", Instant::now().duration_since(now));
219
219
220− FilePicker::new(
221− files,
222− root,
223− move |cx, path: &PathBuf, action| {
220+ Picker::new(files, root, move |cx, path: &PathBuf, action| {
224− if let Err(e) = cx.editor.open(path, action) {
221+ if let Err(e) = cx.editor.open(path, action) {
225− let err = if let Some(err) = e.source() {
222+ let err = if let Some(err) = e.source() {
226− format!("{}", err)
223+ format!("{}", err)
227− } else {
224+ } else {
228− format!("unable to open \"{}\"", path.display())
225+ format!("unable to open \"{}\"", path.display())
229− };
226+ };
230− cx.editor.set_error(err);
227+ cx.editor.set_error(err);
231− }
228+ }
232− },
229+ })
233− |_editor, path| Some((path.clone().into(), None)),
230+ .with_preview(|_editor, path| Some((path.clone().into(), None)))
234− )
235}
231}
236
232
237pub mod completers {
233pub mod completers {
helix-term/src/ui/picker.rs+368−410
@@ -77,16 +77,6 @@ type FileCallback<T> = Box<dyn Fn(&Editor, &T) -> Option<FileLocation>>;
77/// File path and range of lines (used to align and highlight lines)
77/// File path and range of lines (used to align and highlight lines)
78pub type FileLocation = (PathOrId, Option<(usize, usize)>);
78pub type FileLocation = (PathOrId, Option<(usize, usize)>);
79
79
80−pub struct FilePicker<T: Item> {
81− picker: Picker<T>,
82− pub truncate_start: bool,
83− /// Caches paths to documents
84− preview_cache: HashMap<PathBuf, CachedPreview>,
85− read_buffer: Vec<u8>,
86− /// Given an item in the picker, return the file path and line number to display.
87− file_fn: FileCallback<T>,
88−}
89−
90pub enum CachedPreview {
80pub enum CachedPreview {
91 Document(Box<Document>),
81 Document(Box<Document>),
92 Binary,
82 Binary,
@@ -124,325 +114,6 @@ impl Preview<'_, '_> {
124 }
114 }
125}
115}
126
116
127−impl<T: Item + 'static> FilePicker<T> {
128− pub fn new(
129− options: Vec<T>,
130− editor_data: T::Data,
131− callback_fn: impl Fn(&mut Context, &T, Action) + 'static,
132− preview_fn: impl Fn(&Editor, &T) -> Option<FileLocation> + 'static,
133− ) -> Self {
134− let truncate_start = true;
135− let mut picker = Picker::new(options, editor_data, callback_fn);
136− picker.truncate_start = truncate_start;
137−
138− Self {
139− picker,
140− truncate_start,
141− preview_cache: HashMap::new(),
142− read_buffer: Vec::with_capacity(1024),
143− file_fn: Box::new(preview_fn),
144− }
145− }
146−
147− pub fn truncate_start(mut self, truncate_start: bool) -> Self {
148− self.truncate_start = truncate_start;
149− self.picker.truncate_start = truncate_start;
150− self
151− }
152−
153− fn current_file(&self, editor: &Editor) -> Option<FileLocation> {
154− self.picker
155− .selection()
156− .and_then(|current| (self.file_fn)(editor, current))
157− .and_then(|(path_or_id, line)| path_or_id.get_canonicalized().ok().zip(Some(line)))
158− }
159−
160− /// Get (cached) preview for a given path. If a document corresponding
161− /// to the path is already open in the editor, it is used instead.
162− fn get_preview<'picker, 'editor>(
163− &'picker mut self,
164− path_or_id: PathOrId,
165− editor: &'editor Editor,
166− ) -> Preview<'picker, 'editor> {
167− match path_or_id {
168− PathOrId::Path(path) => {
169− let path = &path;
170− if let Some(doc) = editor.document_by_path(path) {
171− return Preview::EditorDocument(doc);
172− }
173−
174− if self.preview_cache.contains_key(path) {
175− return Preview::Cached(&self.preview_cache[path]);
176− }
177−
178− let data = std::fs::File::open(path).and_then(|file| {
179− let metadata = file.metadata()?;
180− // Read up to 1kb to detect the content type
181− let n = file.take(1024).read_to_end(&mut self.read_buffer)?;
182− let content_type = content_inspector::inspect(&self.read_buffer[..n]);
183− self.read_buffer.clear();
184− Ok((metadata, content_type))
185− });
186− let preview = data
187− .map(
188− |(metadata, content_type)| match (metadata.len(), content_type) {
189− (_, content_inspector::ContentType::BINARY) => CachedPreview::Binary,
190− (size, _) if size > MAX_FILE_SIZE_FOR_PREVIEW => {
191− CachedPreview::LargeFile
192− }
193− _ => {
194− // TODO: enable syntax highlighting; blocked by async rendering
195− Document::open(path, None, None, editor.config.clone())
196− .map(|doc| CachedPreview::Document(Box::new(doc)))
197− .unwrap_or(CachedPreview::NotFound)
198− }
199− },
200− )
201− .unwrap_or(CachedPreview::NotFound);
202− self.preview_cache.insert(path.to_owned(), preview);
203− Preview::Cached(&self.preview_cache[path])
204− }
205− PathOrId::Id(id) => {
206− let doc = editor.documents.get(&id).unwrap();
207− Preview::EditorDocument(doc)
208− }
209− }
210− }
211−
212− fn handle_idle_timeout(&mut self, cx: &mut Context) -> EventResult {
213− let Some((current_file, _)) = self.current_file(cx.editor) else {
214− return EventResult::Consumed(None)
215− };
216−
217− // Try to find a document in the cache
218− let doc = match &current_file {
219− PathOrId::Id(doc_id) => doc_mut!(cx.editor, doc_id),
220− PathOrId::Path(path) => match self.preview_cache.get_mut(path) {
221− Some(CachedPreview::Document(ref mut doc)) => doc,
222− _ => return EventResult::Consumed(None),
223− },
224− };
225−
226− let mut callback: Option<compositor::Callback> = None;
227−
228− // Then attempt to highlight it if it has no language set
229− if doc.language_config().is_none() {
230− if let Some(language_config) = doc.detect_language_config(&cx.editor.syn_loader) {
231− doc.language = Some(language_config.clone());
232− let text = doc.text().clone();
233− let loader = cx.editor.syn_loader.clone();
234− let job = tokio::task::spawn_blocking(move || {
235− let syntax = language_config
236− .highlight_config(&loader.scopes())
237− .and_then(|highlight_config| Syntax::new(&text, highlight_config, loader));
238− let callback = move |editor: &mut Editor, compositor: &mut Compositor| {
239− let Some(syntax) = syntax else {
240− log::info!("highlighting picker item failed");
241− return
242− };
243− let Some(Overlay { content: picker, .. }) = compositor.find::<Overlay<Self>>() else {
244− log::info!("picker closed before syntax highlighting finished");
245− return
246− };
247− // Try to find a document in the cache
248− let doc = match current_file {
249− PathOrId::Id(doc_id) => doc_mut!(editor, &doc_id),
250− PathOrId::Path(path) => match picker.preview_cache.get_mut(&path) {
251− Some(CachedPreview::Document(ref mut doc)) => doc,
252− _ => return,
253− },
254− };
255− doc.syntax = Some(syntax);
256− };
257− Callback::EditorCompositor(Box::new(callback))
258− });
259− let tmp: compositor::Callback = Box::new(move |_, ctx| {
260− ctx.jobs
261− .callback(job.map(|res| res.map_err(anyhow::Error::from)))
262− });
263− callback = Some(Box::new(tmp))
264− }
265− }
266−
267− // QUESTION: do we want to compute inlay hints in pickers too ? Probably not for now
268− // but it could be interesting in the future
269−
270− EventResult::Consumed(callback)
271− }
272−}
273−
274−impl<T: Item + 'static> Component for FilePicker<T> {
275− fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
276− // +---------+ +---------+
277− // |prompt | |preview |
278− // +---------+ | |
279− // |picker | | |
280− // | | | |
281− // +---------+ +---------+
282−
283− let render_preview = self.picker.show_preview && area.width > MIN_AREA_WIDTH_FOR_PREVIEW;
284− // -- Render the frame:
285− // clear area
286− let background = cx.editor.theme.get("ui.background");
287− let text = cx.editor.theme.get("ui.text");
288− surface.clear_with(area, background);
289−
290− let picker_width = if render_preview {
291− area.width / 2
292− } else {
293− area.width
294− };
295−
296− let picker_area = area.with_width(picker_width);
297− self.picker.render(picker_area, surface, cx);
298−
299− if !render_preview {
300− return;
301− }
302−
303− let preview_area = area.clip_left(picker_width);
304−
305− // don't like this but the lifetime sucks
306− let block = Block::default().borders(Borders::ALL);
307−
308− // calculate the inner area inside the box
309− let inner = block.inner(preview_area);
310− // 1 column gap on either side
311− let margin = Margin::horizontal(1);
312− let inner = inner.inner(&margin);
313− block.render(preview_area, surface);
314−
315− if let Some((path, range)) = self.current_file(cx.editor) {
316− let preview = self.get_preview(path, cx.editor);
317− let doc = match preview.document() {
318− Some(doc) => doc,
319− None => {
320− let alt_text = preview.placeholder();
321− let x = inner.x + inner.width.saturating_sub(alt_text.len() as u16) / 2;
322− let y = inner.y + inner.height / 2;
323− surface.set_stringn(x, y, alt_text, inner.width as usize, text);
324− return;
325− }
326− };
327−
328− // align to middle
329− let first_line = range
330− .map(|(start, end)| {
331− let height = end.saturating_sub(start) + 1;
332− let middle = start + (height.saturating_sub(1) / 2);
333− middle.saturating_sub(inner.height as usize / 2).min(start)
334− })
335− .unwrap_or(0);
336−
337− let offset = ViewPosition {
338− anchor: doc.text().line_to_char(first_line),
339− horizontal_offset: 0,
340− vertical_offset: 0,
341− };
342−
343− let mut highlights = EditorView::doc_syntax_highlights(
344− doc,
345− offset.anchor,
346− area.height,
347− &cx.editor.theme,
348− );
349− for spans in EditorView::doc_diagnostics_highlights(doc, &cx.editor.theme) {
350− if spans.is_empty() {
351− continue;
352− }
353− highlights = Box::new(helix_core::syntax::merge(highlights, spans));
354− }
355− let mut decorations: Vec<Box<dyn LineDecoration>> = Vec::new();
356−
357− if let Some((start, end)) = range {
358− let style = cx
359− .editor
360− .theme
361− .try_get("ui.highlight")
362− .unwrap_or_else(|| cx.editor.theme.get("ui.selection"));
363− let draw_highlight = move |renderer: &mut TextRenderer, pos: LinePos| {
364− if (start..=end).contains(&pos.doc_line) {
365− let area = Rect::new(
366− renderer.viewport.x,
367− renderer.viewport.y + pos.visual_line,
368− renderer.viewport.width,
369− 1,
370− );
371− renderer.surface.set_style(area, style)
372− }
373− };
374− decorations.push(Box::new(draw_highlight))
375− }
376−
377− render_document(
378− surface,
379− inner,
380− doc,
381− offset,
382− // TODO: compute text annotations asynchronously here (like inlay hints)
383− &TextAnnotations::default(),
384− highlights,
385− &cx.editor.theme,
386− &mut decorations,
387− &mut [],
388− );
389− }
390− }
391−
392− fn handle_event(&mut self, event: &Event, ctx: &mut Context) -> EventResult {
393− if let Event::IdleTimeout = event {
394− return self.handle_idle_timeout(ctx);
395− }
396− // TODO: keybinds for scrolling preview
397− self.picker.handle_event(event, ctx)
398− }
399−
400− fn cursor(&self, area: Rect, ctx: &Editor) -> (Option<Position>, CursorKind) {
401− self.picker.cursor(area, ctx)
402− }
403−
404− fn required_size(&mut self, (width, height): (u16, u16)) -> Option<(u16, u16)> {
405− let picker_width = if width > MIN_AREA_WIDTH_FOR_PREVIEW {
406− width / 2
407− } else {
408− width
409− };
410− self.picker.required_size((picker_width, height))?;
411− Some((width, height))
412− }
413−
414− fn id(&self) -> Option<&'static str> {
415− Some("file-picker")
416− }
417−}
418−
419−#[derive(PartialEq, Eq, Debug)]
420−struct PickerMatch {
421− score: i64,
422− index: usize,
423− len: usize,
424−}
425−
426−impl PickerMatch {
427− fn key(&self) -> impl Ord {
428− (cmp::Reverse(self.score), self.len, self.index)
429− }
430−}
431−
432−impl PartialOrd for PickerMatch {
433− fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
434− Some(self.cmp(other))
435− }
436−}
437−
438−impl Ord for PickerMatch {
439− fn cmp(&self, other: &Self) -> Ordering {
440− self.key().cmp(&other.key())
441− }
442−}
443−
444−type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
445−
446pub struct Picker<T: Item> {
117pub struct Picker<T: Item> {
447 options: Vec<T>,
118 options: Vec<T>,
448 editor_data: T::Data,
119 editor_data: T::Data,
@@ -457,17 +128,22 @@ pub struct Picker<T: Item> {
457 // pattern: String,
128 // pattern: String,
458 prompt: Prompt,
129 prompt: Prompt,
459 previous_pattern: (String, FuzzyQuery),
130 previous_pattern: (String, FuzzyQuery),
460− /// Whether to truncate the start (default true)
461− pub truncate_start: bool,
462 /// Whether to show the preview panel (default true)
131 /// Whether to show the preview panel (default true)
463 show_preview: bool,
132 show_preview: bool,
464 /// Constraints for tabular formatting
133 /// Constraints for tabular formatting
465 widths: Vec<Constraint>,
134 widths: Vec<Constraint>,
466
135
467 callback_fn: PickerCallback<T>,
136 callback_fn: PickerCallback<T>,
137+
138+ pub truncate_start: bool,
139+ /// Caches paths to documents
140+ preview_cache: HashMap<PathBuf, CachedPreview>,
141+ read_buffer: Vec<u8>,
142+ /// Given an item in the picker, return the file path and line number to display.
143+ file_fn: Option<FileCallback<T>>,
468}
144}
469
145
470−impl<T: Item> Picker<T> {
146+impl<T: Item + 'static> Picker<T> {
471 pub fn new(
147 pub fn new(
472 options: Vec<T>,
148 options: Vec<T>,
473 editor_data: T::Data,
149 editor_data: T::Data,
@@ -493,6 +169,9 @@ impl<T: Item> Picker<T> {
493 callback_fn: Box::new(callback_fn),
169 callback_fn: Box::new(callback_fn),
494 completion_height: 0,
170 completion_height: 0,
495 widths: Vec::new(),
171 widths: Vec::new(),
172+ preview_cache: HashMap::new(),
173+ read_buffer: Vec::with_capacity(1024),
174+ file_fn: None,
496 };
175 };
497
176
498 picker.calculate_column_widths();
177 picker.calculate_column_widths();
@@ -513,6 +192,19 @@ impl<T: Item> Picker<T> {
513 picker
192 picker
514 }
193 }
515
194
195+ pub fn truncate_start(mut self, truncate_start: bool) -> Self {
196+ self.truncate_start = truncate_start;
197+ self
198+ }
199+
200+ pub fn with_preview(
201+ mut self,
202+ preview_fn: impl Fn(&Editor, &T) -> Option<FileLocation> + 'static,
203+ ) -> Self {
204+ self.file_fn = Some(Box::new(preview_fn));
205+ self
206+ }
207+
516 pub fn set_options(&mut self, new_options: Vec<T>) {
208 pub fn set_options(&mut self, new_options: Vec<T>) {
517 self.options = new_options;
209 self.options = new_options;
518 self.cursor = 0;
210 self.cursor = 0;
@@ -679,92 +371,127 @@ impl<T: Item> Picker<T> {
679 }
371 }
680 EventResult::Consumed(None)
372 EventResult::Consumed(None)
681 }
373 }
682−}
683
374
684−// process:
375+ fn current_file(&self, editor: &Editor) -> Option<FileLocation> {
685−// - read all the files into a list, maxed out at a large value
376+ self.selection()
686−// - on input change:
377+ .and_then(|current| (self.file_fn.as_ref()?)(editor, current))
687−// - score all the names in relation to input
378+ .and_then(|(path_or_id, line)| path_or_id.get_canonicalized().ok().zip(Some(line)))
688−
689−impl<T: Item + 'static> Component for Picker<T> {
690− fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
691− self.completion_height = viewport.1.saturating_sub(4);
692− Some(viewport)
693 }
379 }
694
380
695− fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
381+ /// Get (cached) preview for a given path. If a document corresponding
696− let key_event = match event {
382+ /// to the path is already open in the editor, it is used instead.
697− Event::Key(event) => *event,
383+ fn get_preview<'picker, 'editor>(
698− Event::Paste(..) => return self.prompt_handle_event(event, cx),
384+ &'picker mut self,
699− Event::Resize(..) => return EventResult::Consumed(None),
385+ path_or_id: PathOrId,
700− _ => return EventResult::Ignored(None),
386+ editor: &'editor Editor,
701− };
387+ ) -> Preview<'picker, 'editor> {
702−
388+ match path_or_id {
703− let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor, _cx| {
389+ PathOrId::Path(path) => {
704− // remove the layer
390+ let path = &path;
705− compositor.last_picker = compositor.pop();
391+ if let Some(doc) = editor.document_by_path(path) {
706− })));
392+ return Preview::EditorDocument(doc);
707−
708− // So that idle timeout retriggers
709− cx.editor.reset_idle_timer();
710−
711− match key_event {
712− shift!(Tab) | key!(Up) | ctrl!('p') => {
713− self.move_by(1, Direction::Backward);
714− }
715− key!(Tab) | key!(Down) | ctrl!('n') => {
716− self.move_by(1, Direction::Forward);
717− }
718− key!(PageDown) | ctrl!('d') => {
719− self.page_down();
720− }
721− key!(PageUp) | ctrl!('u') => {
722− self.page_up();
723− }
724− key!(Home) => {
725− self.to_start();
726− }
727− key!(End) => {
728− self.to_end();
729− }
730− key!(Esc) | ctrl!('c') => {
731− return close_fn;
732− }
733− alt!(Enter) => {
734− if let Some(option) = self.selection() {
735− (self.callback_fn)(cx, option, Action::Load);
736− }
737− }
738− key!(Enter) => {
739− if let Some(option) = self.selection() {
740− (self.callback_fn)(cx, option, Action::Replace);
741− }
742− return close_fn;
743− }
744− ctrl!('s') => {
745− if let Some(option) = self.selection() {
746− (self.callback_fn)(cx, option, Action::HorizontalSplit);
747 }
393 }
748− return close_fn;
394+
749− }
395+ if self.preview_cache.contains_key(path) {
750− ctrl!('v') => {
396+ return Preview::Cached(&self.preview_cache[path]);
751− if let Some(option) = self.selection() {
752− (self.callback_fn)(cx, option, Action::VerticalSplit);
753 }
397 }
754− return close_fn;
398+
399+ let data = std::fs::File::open(path).and_then(|file| {
400+ let metadata = file.metadata()?;
401+ // Read up to 1kb to detect the content type
402+ let n = file.take(1024).read_to_end(&mut self.read_buffer)?;
403+ let content_type = content_inspector::inspect(&self.read_buffer[..n]);
404+ self.read_buffer.clear();
405+ Ok((metadata, content_type))
406+ });
407+ let preview = data
408+ .map(
409+ |(metadata, content_type)| match (metadata.len(), content_type) {
410+ (_, content_inspector::ContentType::BINARY) => CachedPreview::Binary,
411+ (size, _) if size > MAX_FILE_SIZE_FOR_PREVIEW => {
412+ CachedPreview::LargeFile
413+ }
414+ _ => {
415+ // TODO: enable syntax highlighting; blocked by async rendering
416+ Document::open(path, None, None, editor.config.clone())
417+ .map(|doc| CachedPreview::Document(Box::new(doc)))
418+ .unwrap_or(CachedPreview::NotFound)
419+ }
420+ },
421+ )
422+ .unwrap_or(CachedPreview::NotFound);
423+ self.preview_cache.insert(path.to_owned(), preview);
424+ Preview::Cached(&self.preview_cache[path])
755 }
425 }
756− ctrl!('t') => {
426+ PathOrId::Id(id) => {
757− self.toggle_preview();
427+ let doc = editor.documents.get(&id).unwrap();
428+ Preview::EditorDocument(doc)
758 }
429 }
759− _ => {
430+ }
760− self.prompt_handle_event(event, cx);
431+ }
432+
433+ fn handle_idle_timeout(&mut self, cx: &mut Context) -> EventResult {
434+ let Some((current_file, _)) = self.current_file(cx.editor) else {
435+ return EventResult::Consumed(None)
436+ };
437+
438+ // Try to find a document in the cache
439+ let doc = match &current_file {
440+ PathOrId::Id(doc_id) => doc_mut!(cx.editor, doc_id),
441+ PathOrId::Path(path) => match self.preview_cache.get_mut(path) {
442+ Some(CachedPreview::Document(ref mut doc)) => doc,
443+ _ => return EventResult::Consumed(None),
444+ },
445+ };
446+
447+ let mut callback: Option<compositor::Callback> = None;
448+
449+ // Then attempt to highlight it if it has no language set
450+ if doc.language_config().is_none() {
451+ if let Some(language_config) = doc.detect_language_config(&cx.editor.syn_loader) {
452+ doc.language = Some(language_config.clone());
453+ let text = doc.text().clone();
454+ let loader = cx.editor.syn_loader.clone();
455+ let job = tokio::task::spawn_blocking(move || {
456+ let syntax = language_config
457+ .highlight_config(&loader.scopes())
458+ .and_then(|highlight_config| Syntax::new(&text, highlight_config, loader));
459+ let callback = move |editor: &mut Editor, compositor: &mut Compositor| {
460+ let Some(syntax) = syntax else {
461+ log::info!("highlighting picker item failed");
462+ return
463+ };
464+ let Some(Overlay { content: picker, .. }) = compositor.find::<Overlay<Self>>() else {
465+ log::info!("picker closed before syntax highlighting finished");
466+ return
467+ };
468+ // Try to find a document in the cache
469+ let doc = match current_file {
470+ PathOrId::Id(doc_id) => doc_mut!(editor, &doc_id),
471+ PathOrId::Path(path) => match picker.preview_cache.get_mut(&path) {
472+ Some(CachedPreview::Document(ref mut doc)) => doc,
473+ _ => return,
474+ },
475+ };
476+ doc.syntax = Some(syntax);
477+ };
478+ Callback::EditorCompositor(Box::new(callback))
479+ });
480+ let tmp: compositor::Callback = Box::new(move |_, ctx| {
481+ ctx.jobs
482+ .callback(job.map(|res| res.map_err(anyhow::Error::from)))
483+ });
484+ callback = Some(Box::new(tmp))
761 }
485 }
762 }
486 }
763
487
488+ // QUESTION: do we want to compute inlay hints in pickers too ? Probably not for now
489+ // but it could be interesting in the future
490+
764− EventResult::Consumed(None)
491+ EventResult::Consumed(callback)
765 }
492 }
766
493
767− fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
494+ fn render_picker(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
768 let text_style = cx.editor.theme.get("ui.text");
495 let text_style = cx.editor.theme.get("ui.text");
769 let selected = cx.editor.theme.get("ui.text.focus");
496 let selected = cx.editor.theme.get("ui.text.focus");
770 let highlight_style = cx.editor.theme.get("special").add_modifier(Modifier::BOLD);
497 let highlight_style = cx.editor.theme.get("special").add_modifier(Modifier::BOLD);
@@ -930,6 +657,178 @@ impl<T: Item + 'static> Component for Picker<T> {
930 );
657 );
931 }
658 }
932
659
660+ fn render_preview(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
661+ // -- Render the frame:
662+ // clear area
663+ let background = cx.editor.theme.get("ui.background");
664+ let text = cx.editor.theme.get("ui.text");
665+ surface.clear_with(area, background);
666+
667+ // don't like this but the lifetime sucks
668+ let block = Block::default().borders(Borders::ALL);
669+
670+ // calculate the inner area inside the box
671+ let inner = block.inner(area);
672+ // 1 column gap on either side
673+ let margin = Margin::horizontal(1);
674+ let inner = inner.inner(&margin);
675+ block.render(area, surface);
676+
677+ if let Some((path, range)) = self.current_file(cx.editor) {
678+ let preview = self.get_preview(path, cx.editor);
679+ let doc = match preview.document() {
680+ Some(doc) => doc,
681+ None => {
682+ let alt_text = preview.placeholder();
683+ let x = inner.x + inner.width.saturating_sub(alt_text.len() as u16) / 2;
684+ let y = inner.y + inner.height / 2;
685+ surface.set_stringn(x, y, alt_text, inner.width as usize, text);
686+ return;
687+ }
688+ };
689+
690+ // align to middle
691+ let first_line = range
692+ .map(|(start, end)| {
693+ let height = end.saturating_sub(start) + 1;
694+ let middle = start + (height.saturating_sub(1) / 2);
695+ middle.saturating_sub(inner.height as usize / 2).min(start)
696+ })
697+ .unwrap_or(0);
698+
699+ let offset = ViewPosition {
700+ anchor: doc.text().line_to_char(first_line),
701+ horizontal_offset: 0,
702+ vertical_offset: 0,
703+ };
704+
705+ let mut highlights = EditorView::doc_syntax_highlights(
706+ doc,
707+ offset.anchor,
708+ area.height,
709+ &cx.editor.theme,
710+ );
711+ for spans in EditorView::doc_diagnostics_highlights(doc, &cx.editor.theme) {
712+ if spans.is_empty() {
713+ continue;
714+ }
715+ highlights = Box::new(helix_core::syntax::merge(highlights, spans));
716+ }
717+ let mut decorations: Vec<Box<dyn LineDecoration>> = Vec::new();
718+
719+ if let Some((start, end)) = range {
720+ let style = cx
721+ .editor
722+ .theme
723+ .try_get("ui.highlight")
724+ .unwrap_or_else(|| cx.editor.theme.get("ui.selection"));
725+ let draw_highlight = move |renderer: &mut TextRenderer, pos: LinePos| {
726+ if (start..=end).contains(&pos.doc_line) {
727+ let area = Rect::new(
728+ renderer.viewport.x,
729+ renderer.viewport.y + pos.visual_line,
730+ renderer.viewport.width,
731+ 1,
732+ );
733+ renderer.surface.set_style(area, style)
734+ }
735+ };
736+ decorations.push(Box::new(draw_highlight))
737+ }
738+
739+ render_document(
740+ surface,
741+ inner,
742+ doc,
743+ offset,
744+ // TODO: compute text annotations asynchronously here (like inlay hints)
745+ &TextAnnotations::default(),
746+ highlights,
747+ &cx.editor.theme,
748+ &mut decorations,
749+ &mut [],
750+ );
751+ }
752+ }
753+
754+ fn handle_event(&mut self, event: &Event, ctx: &mut Context) -> EventResult {
755+ if let Event::IdleTimeout = event {
756+ return self.handle_idle_timeout(ctx);
757+ }
758+ // TODO: keybinds for scrolling preview
759+
760+ let key_event = match event {
761+ Event::Key(event) => *event,
762+ Event::Paste(..) => return self.prompt_handle_event(event, ctx),
763+ Event::Resize(..) => return EventResult::Consumed(None),
764+ _ => return EventResult::Ignored(None),
765+ };
766+
767+ let close_fn =
768+ EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor, _ctx| {
769+ // remove the layer
770+ compositor.last_picker = compositor.pop();
771+ })));
772+
773+ // So that idle timeout retriggers
774+ ctx.editor.reset_idle_timer();
775+
776+ match key_event {
777+ shift!(Tab) | key!(Up) | ctrl!('p') => {
778+ self.move_by(1, Direction::Backward);
779+ }
780+ key!(Tab) | key!(Down) | ctrl!('n') => {
781+ self.move_by(1, Direction::Forward);
782+ }
783+ key!(PageDown) | ctrl!('d') => {
784+ self.page_down();
785+ }
786+ key!(PageUp) | ctrl!('u') => {
787+ self.page_up();
788+ }
789+ key!(Home) => {
790+ self.to_start();
791+ }
792+ key!(End) => {
793+ self.to_end();
794+ }
795+ key!(Esc) | ctrl!('c') => {
796+ return close_fn;
797+ }
798+ alt!(Enter) => {
799+ if let Some(option) = self.selection() {
800+ (self.callback_fn)(ctx, option, Action::Load);
801+ }
802+ }
803+ key!(Enter) => {
804+ if let Some(option) = self.selection() {
805+ (self.callback_fn)(ctx, option, Action::Replace);
806+ }
807+ return close_fn;
808+ }
809+ ctrl!('s') => {
810+ if let Some(option) = self.selection() {
811+ (self.callback_fn)(ctx, option, Action::HorizontalSplit);
812+ }
813+ return close_fn;
814+ }
815+ ctrl!('v') => {
816+ if let Some(option) = self.selection() {
817+ (self.callback_fn)(ctx, option, Action::VerticalSplit);
818+ }
819+ return close_fn;
820+ }
821+ ctrl!('t') => {
822+ self.toggle_preview();
823+ }
824+ _ => {
825+ self.prompt_handle_event(event, ctx);
826+ }
827+ }
828+
829+ EventResult::Consumed(None)
830+ }
831+
933 fn cursor(&self, area: Rect, editor: &Editor) -> (Option<Position>, CursorKind) {
832 fn cursor(&self, area: Rect, editor: &Editor) -> (Option<Position>, CursorKind) {
934 let block = Block::default().borders(Borders::ALL);
833 let block = Block::default().borders(Borders::ALL);
935 // calculate the inner area inside the box
834 // calculate the inner area inside the box
@@ -940,8 +839,67 @@ impl<T: Item + 'static> Component for Picker<T> {
940
839
941 self.prompt.cursor(area, editor)
840 self.prompt.cursor(area, editor)
942 }
841 }
842+
843+ fn required_size(&mut self, (width, height): (u16, u16)) -> Option<(u16, u16)> {
844+ self.completion_height = height.saturating_sub(4);
845+ Some((width, height))
846+ }
847+}
848+
849+impl<T: Item + 'static> Component for Picker<T> {
850+ fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
851+ // +---------+ +---------+
852+ // |prompt | |preview |
853+ // +---------+ | |
854+ // |picker | | |
855+ // | | | |
856+ // +---------+ +---------+
857+
858+ let render_preview = self.show_preview && area.width > MIN_AREA_WIDTH_FOR_PREVIEW;
859+
860+ let picker_width = if render_preview {
861+ area.width / 2
862+ } else {
863+ area.width
864+ };
865+
866+ let picker_area = area.with_width(picker_width);
867+ self.render_picker(picker_area, surface, cx);
868+
869+ if render_preview {
870+ let preview_area = area.clip_left(picker_width);
871+ self.render_preview(preview_area, surface, cx);
872+ }
873+ }
874+}
875+
876+#[derive(PartialEq, Eq, Debug)]
877+struct PickerMatch {
878+ score: i64,
879+ index: usize,
880+ len: usize,
881+}
882+
883+impl PickerMatch {
884+ fn key(&self) -> impl Ord {
885+ (cmp::Reverse(self.score), self.len, self.index)
886+ }
887+}
888+
889+impl PartialOrd for PickerMatch {
890+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
891+ Some(self.cmp(other))
892+ }
943}
893}
944
894
895+impl Ord for PickerMatch {
896+ fn cmp(&self, other: &Self) -> Ordering {
897+ self.key().cmp(&other.key())
898+ }
899+}
900+
901+type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
902+
945/// Returns a new list of options to replace the contents of the picker
903/// Returns a new list of options to replace the contents of the picker
946/// when called with the current picker query,
904/// when called with the current picker query,
947pub type DynQueryCallback<T> =
905pub type DynQueryCallback<T> =
@@ -950,7 +908,7 @@ pub type DynQueryCallback<T> =
950/// A picker that updates its contents via a callback whenever the
908/// A picker that updates its contents via a callback whenever the
951/// query string changes. Useful for live grep, workspace symbols, etc.
909/// query string changes. Useful for live grep, workspace symbols, etc.
952pub struct DynamicPicker<T: ui::menu::Item + Send> {
910pub struct DynamicPicker<T: ui::menu::Item + Send> {
953− file_picker: FilePicker<T>,
911+ file_picker: Picker<T>,
954 query_callback: DynQueryCallback<T>,
912 query_callback: DynQueryCallback<T>,
955 query: String,
913 query: String,
956}
914}
@@ -958,7 +916,7 @@ pub struct DynamicPicker<T: ui::menu::Item + Send> {
958impl<T: ui::menu::Item + Send> DynamicPicker<T> {
916impl<T: ui::menu::Item + Send> DynamicPicker<T> {
959 pub const ID: &'static str = "dynamic-picker";
917 pub const ID: &'static str = "dynamic-picker";
960
918
961− pub fn new(file_picker: FilePicker<T>, query_callback: DynQueryCallback<T>) -> Self {
919+ pub fn new(file_picker: Picker<T>, query_callback: DynQueryCallback<T>) -> Self {
962 Self {
920 Self {
963 file_picker,
921 file_picker,
964 query_callback,
922 query_callback,
@@ -974,7 +932,7 @@ impl<T: Item + Send + 'static> Component for DynamicPicker<T> {
974
932
975 fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
933 fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
976 let event_result = self.file_picker.handle_event(event, cx);
934 let event_result = self.file_picker.handle_event(event, cx);
977− let current_query = self.file_picker.picker.prompt.line();
935+ let current_query = self.file_picker.prompt.line();
978
936
979 if !matches!(event, Event::IdleTimeout) || self.query == *current_query {
937 if !matches!(event, Event::IdleTimeout) || self.query == *current_query {
980 return event_result;
938 return event_result;
@@ -990,7 +948,7 @@ impl<T: Item + Send + 'static> Component for DynamicPicker<T> {
990 // Wrapping of pickers in overlay is done outside the picker code,
948 // Wrapping of pickers in overlay is done outside the picker code,
991 // so this is fragile and will break if wrapped in some other widget.
949 // so this is fragile and will break if wrapped in some other widget.
992 let picker = match compositor.find_id::<Overlay<DynamicPicker<T>>>(Self::ID) {
950 let picker = match compositor.find_id::<Overlay<DynamicPicker<T>>>(Self::ID) {
993− Some(overlay) => &mut overlay.content.file_picker.picker,
951+ Some(overlay) => &mut overlay.content.file_picker,
994 None => return,
952 None => return,
995 };
953 };
996 picker.set_options(new_options);
954 picker.set_options(new_options);