@@ -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)>);
80−pub struct FilePicker<T: Item> {
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>,
90pub enum CachedPreview {
80pub enum CachedPreview {
91 Document(Box<Document>),
81 Document(Box<Document>),
@@ -124,325 +114,6 @@ impl Preview<'_, '_> {
127−impl<T: Item + 'static> FilePicker<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,
134− let truncate_start = true;
135− let mut picker = Picker::new(options, editor_data, callback_fn);
136− picker.truncate_start = truncate_start;
141− preview_cache: HashMap::new(),
142− read_buffer: Vec::with_capacity(1024),
143− file_fn: Box::new(preview_fn),
147− pub fn truncate_start(mut self, truncate_start: bool) -> Self {
148− self.truncate_start = truncate_start;
149− self.picker.truncate_start = truncate_start;
153− fn current_file(&self, editor: &Editor) -> Option<FileLocation> {
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)))
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>(
164− path_or_id: PathOrId,
165− editor: &'editor Editor,
166− ) -> Preview<'picker, 'editor> {
168− PathOrId::Path(path) => {
170− if let Some(doc) = editor.document_by_path(path) {
171− return Preview::EditorDocument(doc);
174− if self.preview_cache.contains_key(path) {
175− return Preview::Cached(&self.preview_cache[path]);
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))
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
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)
201− .unwrap_or(CachedPreview::NotFound);
202− self.preview_cache.insert(path.to_owned(), preview);
203− Preview::Cached(&self.preview_cache[path])
205− PathOrId::Id(id) => {
206− let doc = editor.documents.get(&id).unwrap();
207− Preview::EditorDocument(doc)
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)
217− // Try to find a document in the cache
218− let doc = match ¤t_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),
226− let mut callback: Option<compositor::Callback> = None;
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");
243− let Some(Overlay { content: picker, .. }) = compositor.find::<Overlay<Self>>() else {
244− log::info!("picker closed before syntax highlighting finished");
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,
255− doc.syntax = Some(syntax);
257− Callback::EditorCompositor(Box::new(callback))
259− let tmp: compositor::Callback = Box::new(move |_, ctx| {
261− .callback(job.map(|res| res.map_err(anyhow::Error::from)))
263− callback = Some(Box::new(tmp))
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
270− EventResult::Consumed(callback)
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 |
281− // +---------+ +---------+
283− let render_preview = self.picker.show_preview && area.width > MIN_AREA_WIDTH_FOR_PREVIEW;
284− // -- Render the frame:
286− let background = cx.editor.theme.get("ui.background");
287− let text = cx.editor.theme.get("ui.text");
288− surface.clear_with(area, background);
290− let picker_width = if render_preview {
296− let picker_area = area.with_width(picker_width);
297− self.picker.render(picker_area, surface, cx);
299− if !render_preview {
303− let preview_area = area.clip_left(picker_width);
305− // don't like this but the lifetime sucks
306− let block = Block::default().borders(Borders::ALL);
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);
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() {
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);
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)
337− let offset = ViewPosition {
338− anchor: doc.text().line_to_char(first_line),
339− horizontal_offset: 0,
343− let mut highlights = EditorView::doc_syntax_highlights(
349− for spans in EditorView::doc_diagnostics_highlights(doc, &cx.editor.theme) {
350− if spans.is_empty() {
353− highlights = Box::new(helix_core::syntax::merge(highlights, spans));
355− let mut decorations: Vec<Box<dyn LineDecoration>> = Vec::new();
357− if let Some((start, end)) = range {
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,
371− renderer.surface.set_style(area, style)
374− decorations.push(Box::new(draw_highlight))
382− // TODO: compute text annotations asynchronously here (like inlay hints)
383− &TextAnnotations::default(),
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);
396− // TODO: keybinds for scrolling preview
397− self.picker.handle_event(event, ctx)
400− fn cursor(&self, area: Rect, ctx: &Editor) -> (Option<Position>, CursorKind) {
401− self.picker.cursor(area, ctx)
404− fn required_size(&mut self, (width, height): (u16, u16)) -> Option<(u16, u16)> {
405− let picker_width = if width > MIN_AREA_WIDTH_FOR_PREVIEW {
410− self.picker.required_size((picker_width, height))?;
411− Some((width, height))
414− fn id(&self) -> Option<&'static str> {
419−#[derive(PartialEq, Eq, Debug)]
427− fn key(&self) -> impl Ord {
428− (cmp::Reverse(self.score), self.len, self.index)
432−impl PartialOrd for PickerMatch {
433− fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
434− Some(self.cmp(other))
438−impl Ord for PickerMatch {
439− fn cmp(&self, other: &Self) -> Ordering {
440− self.key().cmp(&other.key())
444−type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
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>,
467 callback_fn: PickerCallback<T>,
136 callback_fn: PickerCallback<T>,
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>>,
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),
498 picker.calculate_column_widths();
177 picker.calculate_column_widths();
@@ -513,6 +192,19 @@ impl<T: Item> Picker<T> {
195+ pub fn truncate_start(mut self, truncate_start: bool) -> Self {
196+ self.truncate_start = truncate_start;
200+ pub fn with_preview(
202+ preview_fn: impl Fn(&Editor, &T) -> Option<FileLocation> + 'static,
204+ self.file_fn = Some(Box::new(preview_fn));
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> {
680 EventResult::Consumed(None)
372 EventResult::Consumed(None)
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)))
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);
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);
708− // So that idle timeout retriggers
709− cx.editor.reset_idle_timer();
712− shift!(Tab) | key!(Up) | ctrl!('p') => {
713− self.move_by(1, Direction::Backward);
715− key!(Tab) | key!(Down) | ctrl!('n') => {
716− self.move_by(1, Direction::Forward);
718− key!(PageDown) | ctrl!('d') => {
721− key!(PageUp) | ctrl!('u') => {
730− key!(Esc) | ctrl!('c') => {
734− if let Some(option) = self.selection() {
735− (self.callback_fn)(cx, option, Action::Load);
739− if let Some(option) = self.selection() {
740− (self.callback_fn)(cx, option, Action::Replace);
745− if let Some(option) = self.selection() {
746− (self.callback_fn)(cx, option, Action::HorizontalSplit);
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);
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))
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
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)
422+ .unwrap_or(CachedPreview::NotFound);
423+ self.preview_cache.insert(path.to_owned(), preview);
424+ Preview::Cached(&self.preview_cache[path])
756− ctrl!('t') => {
426+ PathOrId::Id(id) => {
757− self.toggle_preview();
427+ let doc = editor.documents.get(&id).unwrap();
428+ Preview::EditorDocument(doc)
760− self.prompt_handle_event(event, cx);
431+ }
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)
438+ // Try to find a document in the cache
439+ let doc = match ¤t_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),
447+ let mut callback: Option<compositor::Callback> = None;
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");
464+ let Some(Overlay { content: picker, .. }) = compositor.find::<Overlay<Self>>() else {
465+ log::info!("picker closed before syntax highlighting finished");
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,
476+ doc.syntax = Some(syntax);
478+ Callback::EditorCompositor(Box::new(callback))
480+ let tmp: compositor::Callback = Box::new(move |_, ctx| {
482+ .callback(job.map(|res| res.map_err(anyhow::Error::from)))
484+ callback = Some(Box::new(tmp))
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
764− EventResult::Consumed(None)
491+ EventResult::Consumed(callback)
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> {
660+ fn render_preview(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
661+ // -- Render the frame:
663+ let background = cx.editor.theme.get("ui.background");
664+ let text = cx.editor.theme.get("ui.text");
665+ surface.clear_with(area, background);
667+ // don't like this but the lifetime sucks
668+ let block = Block::default().borders(Borders::ALL);
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);
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() {
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);
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)
699+ let offset = ViewPosition {
700+ anchor: doc.text().line_to_char(first_line),
701+ horizontal_offset: 0,
705+ let mut highlights = EditorView::doc_syntax_highlights(
711+ for spans in EditorView::doc_diagnostics_highlights(doc, &cx.editor.theme) {
712+ if spans.is_empty() {
715+ highlights = Box::new(helix_core::syntax::merge(highlights, spans));
717+ let mut decorations: Vec<Box<dyn LineDecoration>> = Vec::new();
719+ if let Some((start, end)) = range {
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,
733+ renderer.surface.set_style(area, style)
736+ decorations.push(Box::new(draw_highlight))
744+ // TODO: compute text annotations asynchronously here (like inlay hints)
745+ &TextAnnotations::default(),
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);
758+ // TODO: keybinds for scrolling preview
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),
768+ EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor, _ctx| {
770+ compositor.last_picker = compositor.pop();
773+ // So that idle timeout retriggers
774+ ctx.editor.reset_idle_timer();
777+ shift!(Tab) | key!(Up) | ctrl!('p') => {
778+ self.move_by(1, Direction::Backward);
780+ key!(Tab) | key!(Down) | ctrl!('n') => {
781+ self.move_by(1, Direction::Forward);
783+ key!(PageDown) | ctrl!('d') => {
786+ key!(PageUp) | ctrl!('u') => {
795+ key!(Esc) | ctrl!('c') => {
799+ if let Some(option) = self.selection() {
800+ (self.callback_fn)(ctx, option, Action::Load);
804+ if let Some(option) = self.selection() {
805+ (self.callback_fn)(ctx, option, Action::Replace);
810+ if let Some(option) = self.selection() {
811+ (self.callback_fn)(ctx, option, Action::HorizontalSplit);
816+ if let Some(option) = self.selection() {
817+ (self.callback_fn)(ctx, option, Action::VerticalSplit);
822+ self.toggle_preview();
825+ self.prompt_handle_event(event, ctx);
829+ EventResult::Consumed(None)
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> {
941 self.prompt.cursor(area, editor)
840 self.prompt.cursor(area, editor)
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))
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 |
856+ // +---------+ +---------+
858+ let render_preview = self.show_preview && area.width > MIN_AREA_WIDTH_FOR_PREVIEW;
860+ let picker_width = if render_preview {
866+ let picker_area = area.with_width(picker_width);
867+ self.render_picker(picker_area, surface, cx);
870+ let preview_area = area.clip_left(picker_width);
871+ self.render_preview(preview_area, surface, cx);
876+#[derive(PartialEq, Eq, Debug)]
884+ fn key(&self) -> impl Ord {
885+ (cmp::Reverse(self.score), self.len, self.index)
889+impl PartialOrd for PickerMatch {
890+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
891+ Some(self.cmp(other))
895+impl Ord for PickerMatch {
896+ fn cmp(&self, other: &Self) -> Ordering {
897+ self.key().cmp(&other.key())
901+type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
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,
@@ -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";
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 {
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> {
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();
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,
996 picker.set_options(new_options);
954 picker.set_options(new_options);