Skip to main content

egui_pop_api/
palette.rs

1//! The command palette, as a plugin ([`PalettePlugin`], in
2//! `DefaultPlugins`): every palette command that applies where the
3//! palette opened, ranked by a fuzzy match of `Category: Title` as
4//! shown, in the interface's language (and the command's id), the
5//! commands run lately first. A command declaring arguments (an example object, `{"percent": 100}`) asks for each in
6//! turn, the example's value as the default; Enter runs it in the
7//! context the palette opened in.
8//!
9//! A command declaring an icon ([`CommandSpec::icon`]) shows it in a
10//! column before its title, as JetBrains' Find Action does; the column is
11//! kept on every row while one of the matches has an icon, so the titles
12//! align. The icon is decorative: the title is the row's name.
13//!
14//! A **quick pick** ([`QuickPick`], [`Palette::pick_in`]) shows a list of
15//! choices instead of the commands, filtered by the same fuzzy match:
16//! each choice runs a command with its arguments, as VS Code's quick
17//! picks do. The workbench's "Open panel…" (`workbench.panel.pick`) is
18//! one: every declared panel, opened where it was.
19//!
20//! Keys: `Ctrl+Shift+P` and `F1` open and close it (through modals), the
21//! arrows move the selection, Enter runs, Escape closes (or leaves an
22//! argument prompt).
23//!
24//! Each application window has its own palette (ADR 0025): it opens in
25//! the window it is asked in, offers what applies there (that window's
26//! commands, `when: "appWindow == 'import'"`, and the global ones), runs
27//! there, and blocks that window only. In the main window's group it
28//! opens in the window the user works in ([`AppHandle::active_window`]),
29//! a detached panel's included, as VS Code's auxiliary windows do, goes
30//! to the main window if that one closes, and blocks the main window and
31//! its detached panels while it is open.
32//!
33//! ```
34//! use egui_pop_api::{App, palette};
35//!
36//! let app = App::builder()
37//!     .plugin(palette::PalettePlugin)
38//!     .build(&egui::Context::default())
39//!     .unwrap();
40//! assert!(!palette::is_open(app.handle()));
41//! ```
42
43use 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
69/// Opens and closes the palette.
70pub const CMD_PALETTE: CommandId = CommandId::from_static("app.palette");
71
72/// The palette's state, as a service.
73pub const PALETTE: ServiceToken<Palette> = ServiceToken::new("app.palette");
74
75/// The palette's owner on the bus: its popup is `palette@<window>`.
76pub const OWNER: &str = "egui_pop.palette";
77/// The start of the palette's popup id.
78pub const POPUP_PREFIX: &str = "palette@";
79/// The palette's listener on `pop.popup.close`: closed by anyone (its window
80/// closing under it), it closes in its window's group.
81pub const POPUP_LISTENER: &str = "pop.palette.popup";
82
83/// How many recent commands come first.
84pub const RECENT: usize = 8;
85
86/// The plugin.
87#[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                // Through modals: the palette is one, and closes on its key.
106                .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                // In the window it is asked in.
113                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        // Drawn in every window, shown in its own.
123        ctx.block(
124            zones::WINDOW_OVERLAYS,
125            Block::add(BlockId::from_static("egui_pop.palette"), 0, show),
126        );
127        Ok(())
128    }
129}
130
131/// An argument being asked for.
132#[derive(Clone, Debug)]
133struct Prompt {
134    command: CommandId,
135    title: String,
136    /// Each argument's name and example.
137    args: Vec<(String, Json)>,
138    at: usize,
139    values: Map<String, Json>,
140    input: String,
141    error: Option<ArgError>,
142}
143
144/// A choice of a quick pick: shown as `label`, it runs `command` with
145/// `args`.
146#[derive(Clone, Debug, PartialEq)]
147#[non_exhaustive]
148pub struct PickItem {
149    /// As shown and matched, in the interface's language.
150    pub label: String,
151    /// The command it runs.
152    pub command: CommandId,
153    /// Its arguments.
154    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/// A list of choices the palette offers in place of the commands
168/// ([`Palette::pick_in`]): typed text filters them by a fuzzy match of
169/// their labels, Enter runs the selected one's command, Escape closes.
170///
171/// ```
172/// use egui_pop_api::palette::{PickItem, QuickPick};
173/// use egui_pop_model::ids::CommandId;
174///
175/// let pick = QuickPick::new("Open panel", "Type a panel's name")
176///     .item(PickItem::new("Outline", CommandId::from_static("workbench.panel.open"),
177///         serde_json::json!({ "panel": "app.outline" })));
178/// assert_eq!(pick.items.len(), 1);
179/// ```
180///
181/// Need (dialog): a quick pick, a filtered list of choices in the palette.
182#[derive(Clone, Debug, Default, PartialEq)]
183#[non_exhaustive]
184pub struct QuickPick {
185    /// The palette's title while it shows the pick.
186    pub title: String,
187    /// The hint in its empty text field.
188    pub hint: String,
189    /// The choices, in the order shown without a query.
190    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    /// Adds a choice.
203    pub fn item(mut self, item: PickItem) -> Self {
204        self.items.push(item);
205        self
206    }
207}
208
209/// The choices of a pick matching `query`, as (index, matched characters)
210/// best first; without a query, all of them in their order.
211pub 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    /// A quick pick shown in place of the commands.
228    pick: Option<QuickPick>,
229    /// The context when the palette opened: its commands are offered and
230    /// run there.
231    context: WhenContext,
232    query: String,
233    selected: usize,
234    prompt: Option<Prompt>,
235    /// The window it is shown in: the active one when it first draws.
236    window: Option<egui::ViewportId>,
237}
238
239/// The palettes' state, one per window group
240/// (`AppHandle::window_group`): open or not, the query.
241///
242/// Need (dialog): a command palette.
243#[derive(Debug, Default)]
244pub struct Palette(Arc<Mutex<BTreeMap<egui::ViewportId, State>>>);
245
246/// The group meant when none is named: the current one (the window being
247/// drawn or commanded), else the main window's.
248fn group_now() -> egui::ViewportId {
249    crate::windows::current_group().unwrap_or(egui::ViewportId::ROOT)
250}
251
252impl Palette {
253    /// Whether it is open in the current window group (the main window's
254    /// outside a pass or a command).
255    pub fn is_open(&self) -> bool {
256        self.is_open_in(group_now())
257    }
258
259    /// Whether it is open in a window group.
260    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    /// The window groups it is open in.
265    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    /// Opens it in the current window group, offering what applies in
274    /// `context`.
275    pub fn open(&self, context: WhenContext) {
276        self.open_in(group_now(), context);
277    }
278
279    /// Opens it in a window group, offering what applies in `context`.
280    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    /// Opens it in a window group on a quick pick: its choices in place
292    /// of the commands, run in `context`.
293    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    /// The quick pick it shows in a window group, if any.
306    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    /// Closes it in the current window group.
311    pub fn close(&self) {
312        self.close_in(group_now());
313    }
314
315    /// Closes it in a window group.
316    pub fn close_in(&self, group: egui::ViewportId) {
317        lock(&self.0).remove(&group);
318    }
319
320    /// The window it is shown in, in the current window group, once open
321    /// and drawn: in the main window's group, the one the user worked in
322    /// when it opened (`AppHandle::active_window`).
323    pub fn window(&self) -> Option<egui::ViewportId> {
324        self.window_in(group_now())
325    }
326
327    /// The window it is shown in, in a window group, once open and drawn.
328    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    /// The query typed, in the current window group.
335    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    /// The context it was opened in, in a window group: what it offers
343    /// and runs in.
344    pub fn context_in(&self, group: egui::ViewportId) -> Option<WhenContext> {
345        lock(&self.0).get(&group).map(|s| s.context.clone())
346    }
347}
348
349/// Whether the application's palette is open in the current window group
350/// (the main window's outside a pass or a command).
351pub fn is_open(app: &AppHandle) -> bool {
352    app.service(&PALETTE).is_some_and(|p| p.is_open())
353}
354
355/// Whether the palette is open in a window group
356/// (`AppHandle::window_group`).
357pub 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
361/// The commands run lately, most recent first, each once.
362fn 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/// One line of the list.
376#[derive(Clone, Debug, PartialEq)]
377pub struct Ranked {
378    pub entry: PaletteEntry,
379    /// `Category: Title`, as shown.
380    pub label: String,
381    /// The matched characters of `label`.
382    pub positions: Vec<usize>,
383    pub recent: bool,
384}
385
386/// The palette's list for a query: the entries that apply, best first.
387/// Without a query, the recent ones first, then by category and title;
388/// with one, by fuzzy score (`Category: Title`, or the id a little
389/// behind), a recent command winning ties and close calls.
390pub 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
401/// The palette's list for `query` in this application, now
402/// (`AppHandle::palette_search`).
403pub(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
415/// As [`rank`], each entry shown and matched as `label` gives it (the
416/// palette passes the label in the interface's language: [`shown`]).
417pub 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
462/// An entry as the palette shows it, `Category: Title` in the
463/// interface's language (the entry itself stays English).
464pub 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
478/// The arguments a command asks for: the keys of its example object.
479fn 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/// Why a typed answer was refused: it is not the type its example is.
487#[derive(Clone, Debug, PartialEq)]
488enum ArgError {
489    Bool(String),
490    Number(String),
491    Json(String),
492}
493
494impl ArgError {
495    /// As the prompt says it.
496    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
505/// A typed answer, read as the example's type; empty: the example.
506fn 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
531/// The label in the row's `text`, its matched characters underlined in
532/// the row's `accent` tone.
533fn 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
559/// A row's state, from the last pass as egui's own frame would be:
560/// `selected` for the command Enter runs, never `hover` then.
561fn 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
578/// Draws the palette while it is open.
579fn 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    // A closed window's palette goes with it.
586    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    // Shown in the window of its group it opened in (the active one
592    // then), or the main window once that one is closed; drawn in that
593    // window's pass only.
594    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    // The palette handles Escape itself: back from a prompt, else close.
603    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        // A quick pick: its choices, each running its command.
652        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
762/// A line of the palette's list: a command, or a quick pick's choice.
763struct Row {
764    label: String,
765    /// The matched characters of `label`.
766    positions: Vec<usize>,
767    /// The icon and its name, for a command declaring one.
768    icon: Option<(Icon, String)>,
769    /// Shown at the end of the line: its keys, "recent".
770    keys: String,
771    command: CommandId,
772    args: Json,
773}
774
775/// The arrows move the selection; the selected line, kept in the list.
776fn 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
786/// Draws the list's lines; the one clicked. The selected line is the
787/// `field`'s active descendant.
788fn 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        // Justified, left-aligned: a line without keys keeps its
800        // label at the start, as the others.
801        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            // egui's margin keeps room for its own border: kept,
805            // unseen; the kit paints the row's box under it.
806            let border = ui.visuals().widgets.inactive.bg_stroke.width;
807            let side = Tokens::of(ui.ctx()).size.icon_inline;
808            // A column for the icons while one of the lines has one.
809            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    // The selected line as the field's active descendant: a screen reader
864    // reads it as the arrows move, the focus staying in the field.
865    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
873/// [`POPUP_LISTENER`]: the palette's popup closed by a request (its
874/// window closing under it): it closes in the group of that window, in
875/// this call. Whether it was open there.
876pub(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
897/// Asks for the prompt's current argument. `Some(Some(args))`: all
898/// given; `Some(None)`: given up (Escape); `None`: still asking.
899fn 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    // Escape here goes back to the list instead of closing the palette.
929    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        // The id matches too, behind the label.
984        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}