Skip to content

Commit 14ee553

Browse files
committed
Consolidate DynamicPicker into Picker
DynamicPicker is a thin wrapper over Picker that holds some additional state, similar to the old FilePicker type. Like with FilePicker, we want to fold the two types together, having Picker optionally hold that extra state. The DynamicPicker is a little more complicated than FilePicker was though - it holds a query callback and current query string in state and provides some debounce for queries using the IdleTimeout event. We can move all of that state and debounce logic into an AsyncHook implementation, introduced here as `DynamicQueryHandler`. The hook receives updates to the primary query and debounces those events so that once a query has been idle for a short time (275ms) we re-run the query. A standard Picker created through `new` for example can be promoted into a Dynamic picker by chaining the new `with_dynamic_query` function, very similar to FilePicker's replacement `with_preview`. The workspace symbol picker has been migrated to the new way of writing dynamic pickers as an example. The child commit will promote global search into a dynamic Picker as well.
1 parent e5c1eac commit 14ee553

File tree

4 files changed

+145
-118
lines changed

4 files changed

+145
-118
lines changed

helix-term/src/commands/lsp.rs

Lines changed: 50 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use helix_view::{
2727
use crate::{
2828
compositor::{self, Compositor},
2929
job::Callback,
30-
ui::{self, overlay::overlaid, DynamicPicker, FileLocation, Picker, Popup, PromptEvent},
30+
ui::{self, overlay::overlaid, FileLocation, Picker, Popup, PromptEvent},
3131
};
3232

3333
use std::{
@@ -411,6 +411,8 @@ pub fn symbol_picker(cx: &mut Context) {
411411
}
412412

413413
pub fn workspace_symbol_picker(cx: &mut Context) {
414+
use crate::ui::picker::Injector;
415+
414416
let doc = doc!(cx.editor);
415417
if doc
416418
.language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols)
@@ -422,19 +424,21 @@ pub fn workspace_symbol_picker(cx: &mut Context) {
422424
return;
423425
}
424426

425-
let get_symbols = move |pattern: String, editor: &mut Editor| {
427+
let get_symbols = |pattern: &str, editor: &mut Editor, _data, injector: &Injector<_, _>| {
426428
let doc = doc!(editor);
427429
let mut seen_language_servers = HashSet::new();
428430
let mut futures: FuturesUnordered<_> = doc
429431
.language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols)
430432
.filter(|ls| seen_language_servers.insert(ls.id()))
431433
.map(|language_server| {
432-
let request = language_server.workspace_symbols(pattern.clone()).unwrap();
434+
let request = language_server
435+
.workspace_symbols(pattern.to_string())
436+
.unwrap();
433437
let offset_encoding = language_server.offset_encoding();
434438
async move {
435439
let json = request.await?;
436440

437-
let response =
441+
let response: Vec<_> =
438442
serde_json::from_value::<Option<Vec<lsp::SymbolInformation>>>(json)?
439443
.unwrap_or_default()
440444
.into_iter()
@@ -453,29 +457,56 @@ pub fn workspace_symbol_picker(cx: &mut Context) {
453457
editor.set_error("No configured language server supports workspace symbols");
454458
}
455459

460+
let injector = injector.clone();
456461
async move {
457-
let mut symbols = Vec::new();
458462
// TODO if one symbol request errors, all other requests are discarded (even if they're valid)
459-
while let Some(mut lsp_items) = futures.try_next().await? {
460-
symbols.append(&mut lsp_items);
463+
while let Some(lsp_items) = futures.try_next().await? {
464+
for item in lsp_items {
465+
injector.push(item)?;
466+
}
461467
}
462-
anyhow::Ok(symbols)
468+
Ok(())
463469
}
464470
.boxed()
465471
};
472+
let columns = vec![
473+
ui::PickerColumn::new("kind", |item: &SymbolInformationItem, _| {
474+
display_symbol_kind(item.symbol.kind).into()
475+
}),
476+
ui::PickerColumn::new("name", |item: &SymbolInformationItem, _| {
477+
item.symbol.name.as_str().into()
478+
})
479+
.without_filtering(),
480+
ui::PickerColumn::new("path", |item: &SymbolInformationItem, _| {
481+
match item.symbol.location.uri.to_file_path() {
482+
Ok(path) => path::get_relative_path(path.as_path())
483+
.to_string_lossy()
484+
.to_string()
485+
.into(),
486+
Err(_) => item.symbol.location.uri.to_string().into(),
487+
}
488+
}),
489+
];
466490

467-
let initial_symbols = get_symbols("".to_owned(), cx.editor);
468-
469-
cx.jobs.callback(async move {
470-
let symbols = initial_symbols.await?;
471-
let call = move |_editor: &mut Editor, compositor: &mut Compositor| {
472-
let picker = sym_picker(symbols, true);
473-
let dyn_picker = DynamicPicker::new(picker, Box::new(get_symbols));
474-
compositor.push(Box::new(overlaid(dyn_picker)))
475-
};
491+
let picker = Picker::new(
492+
columns,
493+
1, // name column
494+
vec![],
495+
(),
496+
move |cx, item, action| {
497+
jump_to_location(
498+
cx.editor,
499+
&item.symbol.location,
500+
item.offset_encoding,
501+
action,
502+
);
503+
},
504+
)
505+
.with_preview(|_editor, item| Some(location_to_file_location(&item.symbol.location)))
506+
.with_dynamic_query(get_symbols)
507+
.truncate_start(false);
476508

477-
Ok(Callback::EditorCompositor(Box::new(call)))
478-
});
509+
cx.push_layer(Box::new(overlaid(picker)));
479510
}
480511

481512
pub fn diagnostics_picker(cx: &mut Context) {

helix-term/src/ui/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ pub use completion::{Completion, CompletionItem};
2020
pub use editor::EditorView;
2121
pub use markdown::Markdown;
2222
pub use menu::Menu;
23-
pub use picker::{Column as PickerColumn, DynamicPicker, FileLocation, Picker};
23+
pub use picker::{Column as PickerColumn, FileLocation, Picker};
2424
pub use popup::Popup;
2525
pub use prompt::{Prompt, PromptEvent};
2626
pub use spinner::{ProgressSpinners, Spinner};

helix-term/src/ui/picker.rs

Lines changed: 23 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@ mod query;
44
use crate::{
55
alt,
66
compositor::{self, Component, Compositor, Context, Event, EventResult},
7-
ctrl,
8-
job::Callback,
9-
key, shift,
7+
ctrl, key, shift,
108
ui::{
119
self,
1210
document::{render_document, LineDecoration, LinePos, TextRenderer},
@@ -52,8 +50,6 @@ use helix_view::{
5250

5351
pub const ID: &str = "picker";
5452

55-
use super::overlay::Overlay;
56-
5753
pub const MIN_AREA_WIDTH_FOR_PREVIEW: u16 = 72;
5854
/// Biggest file size to preview in bytes
5955
pub const MAX_FILE_SIZE_FOR_PREVIEW: u64 = 10 * 1024 * 1024;
@@ -223,6 +219,11 @@ impl<T, D> Column<T, D> {
223219
}
224220
}
225221

222+
/// Returns a new list of options to replace the contents of the picker
223+
/// when called with the current picker query,
224+
type DynQueryCallback<T, D> =
225+
fn(&str, &mut Editor, Arc<D>, &Injector<T, D>) -> BoxFuture<'static, anyhow::Result<()>>;
226+
226227
pub struct Picker<T: 'static + Send + Sync, D: 'static> {
227228
column_names: Vec<&'static str>,
228229
columns: Arc<Vec<Column<T, D>>>,
@@ -253,6 +254,8 @@ pub struct Picker<T: 'static + Send + Sync, D: 'static> {
253254
file_fn: Option<FileCallback<T>>,
254255
/// An event handler for syntax highlighting the currently previewed file.
255256
preview_highlight_handler: tokio::sync::mpsc::Sender<Arc<Path>>,
257+
dynamic_query_running: bool,
258+
dynamic_query_handler: Option<tokio::sync::mpsc::Sender<Arc<str>>>,
256259
}
257260

258261
impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
@@ -362,6 +365,8 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
362365
read_buffer: Vec::with_capacity(1024),
363366
file_fn: None,
364367
preview_highlight_handler: handlers::PreviewHighlightHandler::<T, D>::default().spawn(),
368+
dynamic_query_running: false,
369+
dynamic_query_handler: None,
365370
}
366371
}
367372

@@ -396,12 +401,11 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
396401
self
397402
}
398403

399-
pub fn set_options(&mut self, new_options: Vec<T>) {
400-
self.matcher.restart(false);
401-
let injector = self.matcher.injector();
402-
for item in new_options {
403-
inject_nucleo_item(&injector, &self.columns, item, &self.editor_data);
404-
}
404+
pub fn with_dynamic_query(mut self, callback: DynQueryCallback<T, D>) -> Self {
405+
let handler = handlers::DynamicQueryHandler::new(callback).spawn();
406+
helix_event::send_blocking(&handler, self.primary_query().clone());
407+
self.dynamic_query_handler = Some(handler);
408+
self
405409
}
406410

407411
/// Move the cursor by a number of lines, either down (`Forward`) or up (`Backward`)
@@ -499,6 +503,9 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
499503
.reparse(i, pattern, CaseMatching::Smart, append);
500504
}
501505
self.query = new_query;
506+
if let Some(handler) = &self.dynamic_query_handler {
507+
helix_event::send_blocking(handler, self.primary_query().clone());
508+
}
502509
}
503510
}
504511
EventResult::Consumed(None)
@@ -610,7 +617,11 @@ impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Picker<T, D> {
610617

611618
let count = format!(
612619
"{}{}/{}",
613-
if status.running { "(running) " } else { "" },
620+
if status.running || self.dynamic_query_running {
621+
"(running) "
622+
} else {
623+
""
624+
},
614625
snapshot.matched_item_count(),
615626
snapshot.item_count(),
616627
);
@@ -1010,74 +1021,3 @@ impl<T: 'static + Send + Sync, D> Drop for Picker<T, D> {
10101021
}
10111022

10121023
type PickerCallback<T> = Box<dyn Fn(&mut Context, &T, Action)>;
1013-
1014-
/// Returns a new list of options to replace the contents of the picker
1015-
/// when called with the current picker query,
1016-
pub type DynQueryCallback<T> =
1017-
Box<dyn Fn(String, &mut Editor) -> BoxFuture<'static, anyhow::Result<Vec<T>>>>;
1018-
1019-
/// A picker that updates its contents via a callback whenever the
1020-
/// query string changes. Useful for live grep, workspace symbols, etc.
1021-
pub struct DynamicPicker<T: 'static + Send + Sync, D: 'static + Send + Sync> {
1022-
file_picker: Picker<T, D>,
1023-
query_callback: DynQueryCallback<T>,
1024-
query: String,
1025-
}
1026-
1027-
impl<T: Send + Sync, D: Send + Sync> DynamicPicker<T, D> {
1028-
pub fn new(file_picker: Picker<T, D>, query_callback: DynQueryCallback<T>) -> Self {
1029-
Self {
1030-
file_picker,
1031-
query_callback,
1032-
query: String::new(),
1033-
}
1034-
}
1035-
}
1036-
1037-
impl<T: Send + Sync + 'static, D: Send + Sync + 'static> Component for DynamicPicker<T, D> {
1038-
fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
1039-
self.file_picker.render(area, surface, cx);
1040-
}
1041-
1042-
fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
1043-
let event_result = self.file_picker.handle_event(event, cx);
1044-
let Some(current_query) = self.file_picker.primary_query() else {
1045-
return event_result;
1046-
};
1047-
1048-
if !matches!(event, Event::IdleTimeout) || self.query == *current_query {
1049-
return event_result;
1050-
}
1051-
1052-
self.query = current_query.to_string();
1053-
1054-
let new_options = (self.query_callback)(current_query.to_owned(), cx.editor);
1055-
1056-
cx.jobs.callback(async move {
1057-
let new_options = new_options.await?;
1058-
let callback = Callback::EditorCompositor(Box::new(move |_editor, compositor| {
1059-
// Wrapping of pickers in overlay is done outside the picker code,
1060-
// so this is fragile and will break if wrapped in some other widget.
1061-
let picker = match compositor.find_id::<Overlay<Self>>(ID) {
1062-
Some(overlay) => &mut overlay.content.file_picker,
1063-
None => return,
1064-
};
1065-
picker.set_options(new_options);
1066-
}));
1067-
anyhow::Ok(callback)
1068-
});
1069-
EventResult::Consumed(None)
1070-
}
1071-
1072-
fn cursor(&self, area: Rect, ctx: &Editor) -> (Option<Position>, CursorKind) {
1073-
self.file_picker.cursor(area, ctx)
1074-
}
1075-
1076-
fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
1077-
self.file_picker.required_size(viewport)
1078-
}
1079-
1080-
fn id(&self) -> Option<&'static str> {
1081-
Some(ID)
1082-
}
1083-
}

0 commit comments

Comments
 (0)