1use std::collections::BTreeMap;
44use std::sync::{Arc, Mutex};
45
46use egui::text::LayoutJob;
47use egui::{Color32, FontId, Key, TextFormat, Ui};
48use egui_pop_core::icon::{Icon, IconRef};
49use egui_pop_core::kit::{Component, Kit, Part, State as KitState, Tone};
50use egui_pop_core::lock;
51use egui_pop_core::overlay::{self, Closing, Kind, OverlaySpec};
52use egui_pop_core::strings::{self, Arg};
53use egui_pop_core::theme::Tokens;
54use egui_pop_core::ui::UiPop as _;
55use egui_pop_model::commands::CommandSpec;
56use egui_pop_model::fuzzy::{self, Match};
57use egui_pop_model::ids::{BlockId, CommandId, PluginId};
58use egui_pop_model::keymap::BindOptions;
59use egui_pop_model::when::WhenContext;
60use serde_json::{Map, Value as Json, json};
61
62use crate::app::{AppHandle, MENU_VIEW};
63use crate::hooks::PaletteEntry;
64use crate::services::ServiceToken;
65use crate::strings as txt;
66use crate::zones::{self, Block};
67use crate::{Ctx, Plugin, PluginError};
68
69pub const CMD_PALETTE: CommandId = CommandId::from_static("app.palette");
71
72pub const PALETTE: ServiceToken<Palette> = ServiceToken::new("app.palette");
74
75pub const OWNER: &str = "egui_pop.palette";
77pub const POPUP_PREFIX: &str = "palette@";
79pub const POPUP_LISTENER: &str = "pop.palette.popup";
82
83pub const RECENT: usize = 8;
85
86#[derive(Debug, Default)]
88pub struct PalettePlugin;
89
90impl Plugin for PalettePlugin {
91 fn id(&self) -> PluginId {
92 PluginId::from_static("egui_pop.palette")
93 }
94
95 fn title(&self) -> String {
96 "Command palette".into()
97 }
98
99 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
100 ctx.service(&PALETTE, Palette::default())?;
101 ctx.command(
102 CommandSpec::new(CMD_PALETTE, "Command palette", "View")
103 .icon("command")
104 .description("Search and run any command.")
105 .key_with("Ctrl+Shift+P", BindOptions::global().through_modal())
107 .key_with("F1", BindOptions::global().through_modal())
108 .menu(MENU_VIEW, "0_palette", 0)
109 .hidden(),
110 |call| {
111 let p = call.app.service(&PALETTE).ok_or("no palette")?;
112 let group = call.app.current_window_group();
114 if p.is_open_in(group) {
115 p.close_in(group);
116 } else {
117 p.open_in(group, call.app.when_context());
118 }
119 Ok(json!({ "open": p.is_open_in(group), "window": call.app.window_of_group(group) }))
120 },
121 )?;
122 ctx.block(
124 zones::WINDOW_OVERLAYS,
125 Block::add(BlockId::from_static("egui_pop.palette"), 0, show),
126 );
127 Ok(())
128 }
129}
130
131#[derive(Clone, Debug)]
133struct Prompt {
134 command: CommandId,
135 title: String,
136 args: Vec<(String, Json)>,
138 at: usize,
139 values: Map<String, Json>,
140 input: String,
141 error: Option<ArgError>,
142}
143
144#[derive(Clone, Debug, PartialEq)]
147#[non_exhaustive]
148pub struct PickItem {
149 pub label: String,
151 pub command: CommandId,
153 pub args: Json,
155}
156
157impl PickItem {
158 pub fn new(label: impl Into<String>, command: CommandId, args: Json) -> Self {
159 Self {
160 label: label.into(),
161 command,
162 args,
163 }
164 }
165}
166
167#[derive(Clone, Debug, Default, PartialEq)]
183#[non_exhaustive]
184pub struct QuickPick {
185 pub title: String,
187 pub hint: String,
189 pub items: Vec<PickItem>,
191}
192
193impl QuickPick {
194 pub fn new(title: impl Into<String>, hint: impl Into<String>) -> Self {
195 Self {
196 title: title.into(),
197 hint: hint.into(),
198 items: Vec::new(),
199 }
200 }
201
202 pub fn item(mut self, item: PickItem) -> Self {
204 self.items.push(item);
205 self
206 }
207}
208
209pub fn rank_pick(items: &[PickItem], query: &str) -> Vec<(usize, Vec<usize>)> {
212 if query.trim().is_empty() {
213 return (0..items.len()).map(|i| (i, Vec::new())).collect();
214 }
215 let mut out: Vec<(i32, usize, Vec<usize>)> = items
216 .iter()
217 .enumerate()
218 .filter_map(|(i, it)| fuzzy::score(query, &it.label).map(|m| (m.score, i, m.positions)))
219 .collect();
220 out.sort_by_key(|(s, i, _)| (std::cmp::Reverse(*s), *i));
221 out.into_iter().map(|(_, i, p)| (i, p)).collect()
222}
223
224#[derive(Debug, Default)]
225struct State {
226 open: bool,
227 pick: Option<QuickPick>,
229 context: WhenContext,
232 query: String,
233 selected: usize,
234 prompt: Option<Prompt>,
235 window: Option<egui::ViewportId>,
237}
238
239#[derive(Debug, Default)]
244pub struct Palette(Arc<Mutex<BTreeMap<egui::ViewportId, State>>>);
245
246fn group_now() -> egui::ViewportId {
249 crate::windows::current_group().unwrap_or(egui::ViewportId::ROOT)
250}
251
252impl Palette {
253 pub fn is_open(&self) -> bool {
256 self.is_open_in(group_now())
257 }
258
259 pub fn is_open_in(&self, group: egui::ViewportId) -> bool {
261 lock(&self.0).get(&group).is_some_and(|s| s.open)
262 }
263
264 pub fn open_groups(&self) -> Vec<egui::ViewportId> {
266 lock(&self.0)
267 .iter()
268 .filter(|(_, s)| s.open)
269 .map(|(g, _)| *g)
270 .collect()
271 }
272
273 pub fn open(&self, context: WhenContext) {
276 self.open_in(group_now(), context);
277 }
278
279 pub fn open_in(&self, group: egui::ViewportId, context: WhenContext) {
281 lock(&self.0).insert(
282 group,
283 State {
284 open: true,
285 context,
286 ..State::default()
287 },
288 );
289 }
290
291 pub fn pick_in(&self, group: egui::ViewportId, context: WhenContext, pick: QuickPick) {
294 lock(&self.0).insert(
295 group,
296 State {
297 open: true,
298 context,
299 pick: Some(pick),
300 ..State::default()
301 },
302 );
303 }
304
305 pub fn pick_of(&self, group: egui::ViewportId) -> Option<QuickPick> {
307 lock(&self.0).get(&group).and_then(|s| s.pick.clone())
308 }
309
310 pub fn close(&self) {
312 self.close_in(group_now());
313 }
314
315 pub fn close_in(&self, group: egui::ViewportId) {
317 lock(&self.0).remove(&group);
318 }
319
320 pub fn window(&self) -> Option<egui::ViewportId> {
324 self.window_in(group_now())
325 }
326
327 pub fn window_in(&self, group: egui::ViewportId) -> Option<egui::ViewportId> {
329 let s = lock(&self.0);
330 let s = s.get(&group)?;
331 s.open.then_some(s.window).flatten()
332 }
333
334 pub fn query(&self) -> String {
336 lock(&self.0)
337 .get(&group_now())
338 .map(|s| s.query.clone())
339 .unwrap_or_default()
340 }
341
342 pub fn context_in(&self, group: egui::ViewportId) -> Option<WhenContext> {
345 lock(&self.0).get(&group).map(|s| s.context.clone())
346 }
347}
348
349pub fn is_open(app: &AppHandle) -> bool {
352 app.service(&PALETTE).is_some_and(|p| p.is_open())
353}
354
355pub fn is_open_in(app: &AppHandle, group: egui::ViewportId) -> bool {
358 app.service(&PALETTE).is_some_and(|p| p.is_open_in(group))
359}
360
361fn recent(app: &AppHandle) -> Vec<CommandId> {
363 let mut out: Vec<CommandId> = Vec::new();
364 for r in app.history().iter().rev() {
365 if r.id != CMD_PALETTE && r.result.is_ok() && !out.contains(&r.id) {
366 out.push(r.id.clone());
367 if out.len() == RECENT {
368 break;
369 }
370 }
371 }
372 out
373}
374
375#[derive(Clone, Debug, PartialEq)]
377pub struct Ranked {
378 pub entry: PaletteEntry,
379 pub label: String,
381 pub positions: Vec<usize>,
383 pub recent: bool,
384}
385
386pub fn rank(
391 entries: &[PaletteEntry],
392 query: &str,
393 recent: &[CommandId],
394 applies: impl Fn(&CommandId) -> bool,
395) -> Vec<Ranked> {
396 rank_with(entries, query, recent, applies, |e| {
397 format!("{}: {}", e.category, e.title)
398 })
399}
400
401pub(crate) fn search(app: &AppHandle, query: &str) -> Vec<Ranked> {
404 let ctx = app.egui();
405 let cx = app.when_context();
406 rank_with(
407 &app.palette(),
408 query,
409 &recent(app),
410 |c| app.applies(c, &cx),
411 |e| shown(&ctx, e),
412 )
413}
414
415pub fn rank_with(
418 entries: &[PaletteEntry],
419 query: &str,
420 recent: &[CommandId],
421 applies: impl Fn(&CommandId) -> bool,
422 label: impl Fn(&PaletteEntry) -> String,
423) -> Vec<Ranked> {
424 let mut out: Vec<(i32, usize, Ranked)> = Vec::new();
425 for (i, e) in entries.iter().enumerate() {
426 if !applies(&e.command) {
427 continue;
428 }
429 let label = label(e);
430 let by_label = fuzzy::score(query, &label);
431 let by_id = fuzzy::score(query, e.command.as_str()).map(|m| Match {
432 score: m.score - 16,
433 positions: Vec::new(),
434 });
435 let best = match (by_label, by_id) {
436 (Some(a), Some(b)) => Some(if b.score > a.score { b } else { a }),
437 (a, b) => a.or(b),
438 };
439 let Some(m) = best else { continue };
440 let at = recent.iter().position(|r| *r == e.command);
441 let bonus = at.map_or(0, |n| (RECENT - n) as i32 * 4);
442 let score = if query.trim().is_empty() {
443 at.map_or(0, |n| 1000 - n as i32)
444 } else {
445 m.score + bonus
446 };
447 out.push((
448 score,
449 i,
450 Ranked {
451 entry: e.clone(),
452 label,
453 positions: m.positions,
454 recent: at.is_some(),
455 },
456 ));
457 }
458 out.sort_by_key(|(s, i, _)| (std::cmp::Reverse(*s), *i));
459 out.into_iter().map(|(_, _, r)| r).collect()
460}
461
462pub fn shown(ctx: &egui::Context, e: &PaletteEntry) -> String {
465 strings::tr_args(
466 ctx,
467 &txt::COMMAND_LABEL,
468 &[
469 ("category", &strings::category(ctx, &e.category)),
470 (
471 "title",
472 &strings::command_title(ctx, e.command.as_str(), &e.title),
473 ),
474 ],
475 )
476}
477
478fn arguments(spec: &CommandSpec) -> Vec<(String, Json)> {
480 match &spec.args {
481 Json::Object(m) => m.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
482 _ => Vec::new(),
483 }
484}
485
486#[derive(Clone, Debug, PartialEq)]
488enum ArgError {
489 Bool(String),
490 Number(String),
491 Json(String),
492}
493
494impl ArgError {
495 fn text(&self, ctx: &egui::Context) -> String {
497 match self {
498 ArgError::Bool(t) => strings::tr_args(ctx, &txt::PALETTE_NOT_BOOL, &[("input", t)]),
499 ArgError::Number(t) => strings::tr_args(ctx, &txt::PALETTE_NOT_NUMBER, &[("input", t)]),
500 ArgError::Json(e) => strings::tr_args(ctx, &txt::PALETTE_NOT_JSON, &[("error", e)]),
501 }
502 }
503}
504
505fn parse_arg(input: &str, example: &Json) -> Result<Json, ArgError> {
507 let t = input.trim();
508 if t.is_empty() {
509 return Ok(example.clone());
510 }
511 match example {
512 Json::Bool(_) => match t {
513 "true" | "yes" | "on" => Ok(Json::Bool(true)),
514 "false" | "no" | "off" => Ok(Json::Bool(false)),
515 _ => Err(ArgError::Bool(t.into())),
516 },
517 Json::Number(n) if n.is_f64() => t
518 .parse::<f64>()
519 .map(|v| json!(v))
520 .map_err(|_| ArgError::Number(t.into())),
521 Json::Number(_) => t
522 .parse::<i64>()
523 .map(|v| json!(v))
524 .or_else(|_| t.parse::<f64>().map(|v| json!(v)))
525 .map_err(|_| ArgError::Number(t.into())),
526 Json::String(_) => Ok(Json::String(t.into())),
527 _ => serde_json::from_str(t).map_err(|e| ArgError::Json(e.to_string())),
528 }
529}
530
531fn highlighted(row: &Component, state: KitState, label: &str, positions: &[usize]) -> LayoutJob {
534 let font = FontId::default();
535 let normal = row.style(state).text;
536 let strong = row.style_toned(Tone::Accent, state).text;
537 let mut job = LayoutJob::default();
538 for (i, c) in label.chars().enumerate() {
539 let hit = positions.contains(&i);
540 job.append(
541 c.encode_utf8(&mut [0; 4]),
542 0.0,
543 TextFormat {
544 font_id: font.clone(),
545 color: if hit { strong } else { normal },
546 underline: if hit {
547 egui::Stroke::new(1.0, strong)
548 } else {
549 egui::Stroke::NONE
550 },
551 background: Color32::TRANSPARENT,
552 ..TextFormat::default()
553 },
554 );
555 }
556 job
557}
558
559fn row_state(ui: &Ui, selected: bool) -> KitState {
562 let state = ui
563 .ctx()
564 .read_response(ui.next_auto_id())
565 .map_or(KitState::REST, |r| KitState::from_response(&r));
566 KitState::REST
567 .with(
568 KitState::HOVER,
569 state.contains(KitState::HOVER) && !selected,
570 )
571 .with(KitState::ACTIVE, state.contains(KitState::ACTIVE))
572 .with(KitState::FOCUS, state.contains(KitState::FOCUS))
573 .with(KitState::SELECTED, selected)
574}
575
576const SPEC_ID: &str = "egui_pop.palette";
577
578fn show(ui: &mut Ui, app: &AppHandle) {
580 let Some(p) = app.service(&PALETTE) else {
581 return;
582 };
583 let ctx = ui.ctx().clone();
584 let group = app.window_group(ctx.viewport_id());
585 lock(&p.0).retain(|g, _| app.window_group(*g) == *g);
587 let mut open = p.is_open_in(group);
588 if !open {
589 return;
590 }
591 let window = {
595 let mut all = lock(&p.0);
596 let Some(s) = all.get_mut(&group) else { return };
597 *s.window.get_or_insert_with(|| app.shown_in(group))
598 };
599 if app.still_open(window) != ctx.viewport_id() {
600 return;
601 }
602 let spec = OverlaySpec::new(SPEC_ID, "Command palette", Kind::Modal).keep_on_escape();
604 app.name_overlay(
605 spec.id,
606 window,
607 format!("{POPUP_PREFIX}{}", app.registry_window_of(window)),
608 OWNER,
609 );
610 let entries = app.palette();
611 let recent = recent(app);
612 let mut run: Option<(CommandId, Json, WhenContext)> = None;
613 let mut close = false;
614 overlay::show(&ctx, &spec, &mut open, None, |ui| {
615 let mut all = lock(&p.0);
616 let Some(s) = all.get_mut(&group) else { return };
617 let cx = s.context.clone();
618 if let Some(prompt) = &mut s.prompt {
619 if let Some(done) = ask(ui, prompt) {
620 match done {
621 Some(args) => run = Some((prompt.command.clone(), args, cx)),
622 None => s.prompt = None,
623 }
624 }
625 return;
626 }
627 let (title, hint) = match &s.pick {
628 Some(pick) => (pick.title.clone(), pick.hint.clone()),
629 None => (
630 strings::tr(&ctx, &txt::PALETTE_TITLE),
631 strings::tr(&ctx, &txt::PALETTE_HINT),
632 ),
633 };
634 let title = ui.strong(title);
635 let edit = ui
636 .add(
637 egui::TextEdit::singleline(&mut s.query)
638 .hint_text(hint)
639 .desired_width(f32::INFINITY),
640 )
641 .labelled_by(title.id);
642 edit.request_focus();
643 egui_pop_core::focus::escape_passes(ui.ctx(), edit.id);
644 if edit.changed() {
645 s.selected = 0;
646 }
647 if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
648 close = true;
649 return;
650 }
651 if let Some(pick) = &s.pick {
653 let rows: Vec<Row> = rank_pick(&pick.items, &s.query)
654 .into_iter()
655 .map(|(i, positions)| Row {
656 label: pick.items[i].label.clone(),
657 positions,
658 icon: None,
659 keys: String::new(),
660 command: pick.items[i].command.clone(),
661 args: pick.items[i].args.clone(),
662 })
663 .collect();
664 let selected = move_selection(ui, &mut s.selected, rows.len());
665 let mut chosen = ui
666 .input(|i| i.key_pressed(Key::Enter))
667 .then_some(selected)
668 .filter(|i| *i < rows.len());
669 ui.separator();
670 if let Some(i) = draw_rows(ui, &rows, selected, edit.changed(), edit.id) {
671 chosen = Some(i);
672 }
673 if rows.is_empty() {
674 ui.weak(strings::tr(&ctx, &txt::PALETTE_PICK_NO_MATCH));
675 }
676 if let Some(r) = chosen.and_then(|i| rows.get(i)) {
677 run = Some((r.command.clone(), r.args.clone(), cx));
678 }
679 return;
680 }
681 let hits = rank_with(
682 &entries,
683 &s.query,
684 &recent,
685 |c| app.applies(c, &cx),
686 |e| shown(&ctx, e),
687 );
688 let rows: Vec<Row> = hits
689 .iter()
690 .map(|h| {
691 let icon = app
692 .command(&h.entry.command)
693 .and_then(|c| c.icon)
694 .map(|declared| {
695 let name =
696 crate::layout_controls::command_icon(app, &h.entry.command, &declared)
697 .to_string();
698 (IconRef::from(&name).or_placeholder("palette"), name)
699 });
700 let mut keys = h.entry.keys.first().cloned().unwrap_or_default();
701 if h.recent && s.query.trim().is_empty() {
702 keys = if keys.is_empty() {
703 strings::tr(&ctx, &txt::PALETTE_RECENT)
704 } else {
705 strings::tr_args(&ctx, &txt::PALETTE_RECENT_KEYS, &[("keys", &keys)])
706 };
707 }
708 Row {
709 label: h.label.clone(),
710 positions: h.positions.clone(),
711 icon,
712 keys,
713 command: h.entry.command.clone(),
714 args: Json::Null,
715 }
716 })
717 .collect();
718 let selected = move_selection(ui, &mut s.selected, rows.len());
719 let mut chosen = None;
720 if ui.input(|i| i.key_pressed(Key::Enter)) {
721 chosen = rows.get(selected).map(|r| r.command.clone());
722 }
723 ui.separator();
724 if let Some(i) = draw_rows(ui, &rows, selected, edit.changed(), edit.id) {
725 chosen = Some(rows[i].command.clone());
726 }
727 if rows.is_empty() {
728 ui.weak(strings::tr(&ctx, &txt::PALETTE_NO_MATCH));
729 }
730 if let Some(c) = chosen {
731 let spec = app.command(&c);
732 let args = spec.as_ref().map(arguments).unwrap_or_default();
733 if args.is_empty() {
734 run = Some((c, Json::Null, cx));
735 } else {
736 s.prompt = Some(Prompt {
737 command: c,
738 title: spec
739 .map(|s| strings::command_title(&ctx, s.id.as_str(), &s.title))
740 .unwrap_or_default(),
741 args,
742 at: 0,
743 values: Map::new(),
744 input: String::new(),
745 error: None,
746 });
747 }
748 }
749 });
750 if let Some((command, args, context)) = run {
751 p.close_in(group);
752 app.close_overlay(&ctx, spec.id, Closing::Chosen);
753 app.request_run_in(command, args, context);
754 } else if close {
755 p.close_in(group);
756 app.close_overlay(&ctx, spec.id, Closing::Escape);
757 } else if !open {
758 p.close_in(group);
759 }
760}
761
762struct Row {
764 label: String,
765 positions: Vec<usize>,
767 icon: Option<(Icon, String)>,
769 keys: String,
771 command: CommandId,
772 args: Json,
773}
774
775fn move_selection(ui: &Ui, selected: &mut usize, len: usize) -> usize {
777 if ui.input(|i| i.key_pressed(Key::ArrowDown)) {
778 *selected = (*selected + 1).min(len.saturating_sub(1));
779 }
780 if ui.input(|i| i.key_pressed(Key::ArrowUp)) {
781 *selected = selected.saturating_sub(1);
782 }
783 (*selected).min(len.saturating_sub(1))
784}
785
786fn draw_rows(
789 ui: &mut Ui,
790 rows: &[Row],
791 selected: usize,
792 typed: bool,
793 field: egui::Id,
794) -> Option<usize> {
795 let ctx = ui.ctx().clone();
796 let mut chosen = None;
797 let mut selected_row = None;
798 ui.scroll_area(egui::ScrollArea::vertical().max_height(320.0), |ui| {
799 ui.with_layout(egui::Layout::top_down_justified(egui::Align::LEFT), |ui| {
802 let kit = Kit::of(ui.ctx());
803 let row = &kit.command_palette_row;
804 let border = ui.visuals().widgets.inactive.bg_stroke.width;
807 let side = Tokens::of(ui.ctx()).size.icon_inline;
808 let column = rows.iter().any(|r| r.icon.is_some());
810 for (i, h) in rows.iter().enumerate() {
811 let on = i == selected;
812 let state = row_state(ui, on);
813 let under = ui.painter().add(egui::Shape::Noop);
814 let slot = egui::Id::unique((
815 "egui_pop_palette_icon",
816 h.command.as_str(),
817 h.args.to_string(),
818 ));
819 let label = highlighted(row, state, &h.label, &h.positions);
820 let mut atoms: Vec<egui::Atom<'_>> = Vec::with_capacity(2);
821 if column {
822 atoms.push(egui::Atom::custom(
823 egui::IdSalt::new(slot),
824 egui::vec2(side, side),
825 ));
826 }
827 atoms.push(label.into());
828 let mut b = egui::Button::new(egui::Atoms::from(atoms))
829 .selected(on)
830 .frame_when_inactive(on)
831 .fill(Color32::TRANSPARENT)
832 .stroke(egui::Stroke::new(border, Color32::TRANSPARENT));
833 if !h.keys.is_empty() {
834 let muted = row.style_toned(Tone::Muted, state).text;
835 b = b.shortcut_text(egui::RichText::new(h.keys.clone()).color(muted));
836 }
837 let r = b.atom_ui(ui);
838 if let (Some(rect), Some((icon, name))) = (r.rect(egui::IdSalt::new(slot)), &h.icon)
839 {
840 icon.paint(ui.painter(), rect, row.style(state).text);
841 egui_pop_core::icon::registry::record(&ctx, "palette", &h.label, name);
842 }
843 let r = r.response;
844 if on {
845 selected_row = Some(r.id);
846 }
847 let part = Part {
848 rect: r.rect,
849 room: r.rect,
850 state,
851 label: None,
852 };
853 row.paint_under(ui, under, &part, None);
854 if on && typed {
855 r.scroll_to_me(None);
856 }
857 if r.clicked() {
858 chosen = Some(i);
859 }
860 }
861 });
862 });
863 if let Some(row) = selected_row {
866 ctx.accesskit_node_builder(field, |node| {
867 node.set_active_descendant(row.accesskit_id());
868 });
869 }
870 chosen
871}
872
873pub(crate) fn popup_closed(app: &AppHandle, popup: &str) -> bool {
877 let Some(window) = popup.strip_prefix(POPUP_PREFIX) else {
878 return false;
879 };
880 let Some(p) = app.service(&PALETTE) else {
881 return false;
882 };
883 let groups: Vec<egui::ViewportId> = p
884 .open_groups()
885 .into_iter()
886 .filter(|g| {
887 p.window_in(*g)
888 .is_some_and(|v| app.registry_window_of(v) == window)
889 })
890 .collect();
891 for g in &groups {
892 p.close_in(*g);
893 }
894 !groups.is_empty()
895}
896
897fn ask(ui: &mut Ui, prompt: &mut Prompt) -> Option<Option<Json>> {
900 let (name, example) = prompt.args[prompt.at].clone();
901 let ctx = ui.ctx().clone();
902 let title = ui.strong(strings::tr_args(
903 &ctx,
904 &txt::PALETTE_ARGUMENT_TITLE,
905 &[("command", &prompt.title), ("argument", &name)],
906 ));
907 let edit = ui
908 .add(
909 egui::TextEdit::singleline(&mut prompt.input)
910 .hint_text(example.to_string())
911 .desired_width(f32::INFINITY),
912 )
913 .labelled_by(title.id);
914 edit.request_focus();
915 egui_pop_core::focus::escape_passes(ui.ctx(), edit.id);
916 ui.weak(strings::tr_with(
917 &ctx,
918 &txt::PALETTE_ARGUMENT_HELP,
919 &[
920 ("at", (prompt.at + 1).into()),
921 ("count", prompt.args.len().into()),
922 ("example", Arg::Str(&example.to_string())),
923 ],
924 ));
925 if let Some(e) = &prompt.error {
926 ui.colored_label(ui.visuals().error_fg_color, e.text(&ctx));
927 }
928 if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
930 return Some(None);
931 }
932 if !ui.input(|i| i.key_pressed(Key::Enter)) {
933 return None;
934 }
935 match parse_arg(&prompt.input, &example) {
936 Ok(v) => {
937 prompt.values.insert(name, v);
938 prompt.input.clear();
939 prompt.error = None;
940 prompt.at += 1;
941 (prompt.at == prompt.args.len()).then(|| Some(Json::Object(prompt.values.clone())))
942 }
943 Err(e) => {
944 prompt.error = Some(e);
945 None
946 }
947 }
948}
949
950#[cfg(test)]
951mod tests {
952 use super::*;
953
954 fn entry(id: &'static str, category: &str, title: &str) -> PaletteEntry {
955 PaletteEntry {
956 command: CommandId::from_static(id),
957 title: title.into(),
958 category: category.into(),
959 keys: Vec::new(),
960 }
961 }
962
963 #[test]
964 fn recent_commands_come_first_and_the_query_ranks_the_rest() {
965 let entries = [
966 entry("file.open", "File", "Open file"),
967 entry("view.zoom", "View", "Zoom in"),
968 entry("edit.undo", "Edit", "Undo"),
969 entry("edit.hidden", "Edit", "Not here"),
970 ];
971 let recent = [CommandId::from_static("edit.undo")];
972 let here = |c: &CommandId| c.as_str() != "edit.hidden";
973 let ids = |r: Vec<Ranked>| {
974 r.into_iter()
975 .map(|r| r.entry.command.to_string())
976 .collect::<Vec<_>>()
977 };
978 assert_eq!(
979 ids(rank(&entries, "", &recent, here)),
980 ["edit.undo", "file.open", "view.zoom"]
981 );
982 assert_eq!(ids(rank(&entries, "zi", &recent, here)), ["view.zoom"]);
983 assert_eq!(ids(rank(&entries, "fileopen", &[], here)), ["file.open"]);
985 let r = rank(&entries, "of", &[], here);
986 assert_eq!(r[0].label, "File: Open file");
987 assert_eq!(r[0].positions, [6, 11]);
988 }
989
990 #[test]
991 fn arguments_are_read_as_their_example() {
992 assert_eq!(parse_arg("", &json!(100)), Ok(json!(100)));
993 assert_eq!(parse_arg("50", &json!(100)), Ok(json!(50)));
994 assert_eq!(parse_arg("0.5", &json!(1.5)), Ok(json!(0.5)));
995 assert!(parse_arg("lots", &json!(100)).is_err());
996 assert_eq!(parse_arg("yes", &json!(false)), Ok(json!(true)));
997 assert_eq!(parse_arg(" a b ", &json!("x")), Ok(json!("a b")));
998 assert_eq!(parse_arg("[1, 2]", &json!([0])), Ok(json!([1, 2])));
999 }
1000}