Skip to main content

egui_pop_api/
selection.rs

1//! The application-wide selection: what the user selected and what the
2//! pointer is over, shared by every panel.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! A tree, a list and a canvas showing the same things select and hover
8//! them together: a click in one highlights the item in the others, and
9//! hovering a row lights up the same item everywhere. The selection is
10//! one [`SelectionService`] (the [`SELECTION`] token), provided by
11//! [`SelectionPlugin`]; widgets opt in (`TreeView::shared`,
12//! `ListView::shared` in `egui_pop_views`, or a canvas of the
13//! application's calling [`SelectionService::click`] and
14//! [`SelectionService::hover`]).
15//!
16//! - **Items** are [`SelectionItem`]s: a string id each, a path such as
17//!   `photos/2024/0012.raw` or `entity:/world/points`. Widgets with
18//!   different keys meet on it.
19//! - **Gestures** ([`Gesture`]): a click replaces, Ctrl (Cmd on macOS)
20//!   toggles, Shift selects a range in the order the widget clicked gives,
21//!   Ctrl+Shift adds that range.
22//! - **Hover**: one item at most, said by the widget under the pointer
23//!   each pass; it goes when that widget says it hovers nothing, or stops
24//!   saying anything.
25//! - **Changes**: each bumps a revision; subscribers are called
26//!   ([`SelectionService::subscribe`]), the journal says
27//!   `selection.changed`, and the context keys follow: `hasSelection`,
28//!   `selectionCount`, `selectionCanBack` and `selectionCanForward`.
29//! - **History**: the past selections, walked by `selection.back` and
30//!   `selection.forward` (Alt+Left and Alt+Right while the focus is in a
31//!   widget bound to the selection, its [`SURFACE`]). A selection is not
32//!   an edit: undo does not see it.
33//! - **Agents**: the `selection` collector, and the `selection.set`,
34//!   `selection.add`, `selection.clear` and `selection.hover` commands.
35//!
36//! ```
37//! use egui_pop_api::selection::{Gesture, SelectionItem, SelectionService};
38//!
39//! let s = SelectionService::new();
40//! let order: Vec<SelectionItem> = ["a", "b", "c", "d"].map(SelectionItem::from).to_vec();
41//! s.click(&order[1], Gesture::Replace, &order, "list");
42//! s.click(&order[3], Gesture::Range, &order, "list");
43//! assert_eq!(s.items(), order[1..].to_vec());
44//! s.click(&order[2], Gesture::Toggle, &order, "list");
45//! assert_eq!(s.items(), vec![order[1].clone(), order[3].clone()]);
46//! assert!(s.back("test"));
47//! assert_eq!(s.len(), 3);
48//! ```
49
50use std::collections::HashSet;
51use std::fmt;
52use std::sync::{Arc, Mutex, MutexGuard};
53
54use egui::Modifiers;
55use egui_pop_model::commands::CommandSpec;
56use egui_pop_model::ids::{CommandId, PluginId};
57use egui_pop_model::keymap::BindOptions;
58use serde::Serialize;
59use serde_json::{Value as Json, json};
60
61use crate::hooks::On;
62use crate::services::ServiceToken;
63use crate::{AppHandle, Ctx, Plugin, PluginError};
64
65/// The plugin's id.
66pub const SELECTION_PLUGIN: PluginId = PluginId::from_static("egui_pop.selection");
67
68/// The selection service.
69pub const SELECTION: ServiceToken<SelectionService> = ServiceToken::new("egui_pop.selection");
70
71/// The focus surface of the widgets bound to the selection: Alt+Left and
72/// Alt+Right go back and forward through the selections there, and the
73/// context stack's `nav.back` keeps them elsewhere.
74pub const SURFACE: &str = "selection";
75
76/// The context key: something is selected (`true` or `false`).
77pub const CONTEXT_HAS: &str = "hasSelection";
78/// The context key: how many items are selected.
79pub const CONTEXT_COUNT: &str = "selectionCount";
80/// The context key: `selection.back` has a selection to go back to.
81pub const CONTEXT_CAN_BACK: &str = "selectionCanBack";
82/// The context key: `selection.forward` has a selection to go to.
83pub const CONTEXT_CAN_FORWARD: &str = "selectionCanForward";
84
85/// Back to the selection before (Alt+Left in a bound widget).
86pub const CMD_BACK: CommandId = CommandId::from_static("selection.back");
87/// Forward to the selection gone back from (Alt+Right in a bound widget).
88pub const CMD_FORWARD: CommandId = CommandId::from_static("selection.forward");
89/// Selects these items, and only them.
90pub const CMD_SET: CommandId = CommandId::from_static("selection.set");
91/// Adds items to the selection.
92pub const CMD_ADD: CommandId = CommandId::from_static("selection.add");
93/// Selects nothing.
94pub const CMD_CLEAR: CommandId = CommandId::from_static("selection.clear");
95/// Hovers an item, or none.
96pub const CMD_HOVER: CommandId = CommandId::from_static("selection.hover");
97
98/// The journal's event after a change of the selection or of the hovered
99/// item.
100pub const EVENT_CHANGED: &str = "selection.changed";
101
102/// How many past selections the history keeps.
103pub const HISTORY_CAP: usize = 100;
104
105/// The source a change made by an agent's command names.
106pub const SOURCE_COMMAND: &str = "command";
107
108pub use egui_pop_model::selection::SelectionItem;
109
110/// What a click does to the selection.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum Gesture {
113    /// Selects the item alone (a plain click).
114    Replace,
115    /// Adds the item, or removes it when selected (Ctrl, Cmd on macOS).
116    Toggle,
117    /// Selects from the anchor to the item, in the order the widget
118    /// gives, and only that (Shift).
119    Range,
120    /// Adds the range from the anchor to the item (Ctrl+Shift).
121    AddRange,
122}
123
124impl Gesture {
125    /// The gesture of a click with these modifiers.
126    pub fn of(modifiers: Modifiers) -> Self {
127        match (modifiers.command, modifiers.shift) {
128            (true, true) => Gesture::AddRange,
129            (false, true) => Gesture::Range,
130            (true, false) => Gesture::Toggle,
131            (false, false) => Gesture::Replace,
132        }
133    }
134}
135
136/// What changed, as subscribers get it.
137#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
138pub struct Change {
139    /// The selected items after the change, in the order selected.
140    pub items: Vec<SelectionItem>,
141    pub hovered: Option<SelectionItem>,
142    /// The selection's revision (the hover has its own).
143    pub revision: u64,
144    /// Whether the selected items changed (else only the hovered one).
145    pub selection: bool,
146    /// Who changed it: a widget's id, `command`, `history`.
147    pub source: String,
148}
149
150/// A subscription, to give back to [`SelectionService::unsubscribe`].
151#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
152pub struct Subscription(u64);
153
154type Listener = Arc<dyn Fn(&Change) + Send + Sync>;
155
156struct Hover {
157    item: SelectionItem,
158    source: String,
159    /// The egui pass it was last said in (`None`: until said otherwise,
160    /// an agent's).
161    pass: Option<u64>,
162}
163
164#[derive(Default)]
165struct Inner {
166    items: Vec<SelectionItem>,
167    set: HashSet<SelectionItem>,
168    anchor: Option<SelectionItem>,
169    hovered: Option<Hover>,
170    revision: u64,
171    hover_revision: u64,
172    source: String,
173    back: Vec<Vec<SelectionItem>>,
174    forward: Vec<Vec<SelectionItem>>,
175    listeners: Vec<(u64, Listener)>,
176    next_listener: u64,
177    /// The revisions the plugin last published (selection, hover).
178    published: (u64, u64),
179}
180
181impl Inner {
182    fn assign(&mut self, items: Vec<SelectionItem>) {
183        self.set.clear();
184        self.items.clear();
185        for i in items {
186            if self.set.insert(i.clone()) {
187                self.items.push(i);
188            }
189        }
190    }
191}
192
193/// The application-wide selection; see the [module](self).
194///
195/// Thread-safe: an application's worker may select too. Every change
196/// calls the subscribers once the lock is released and asks egui for a
197/// repaint.
198pub struct SelectionService {
199    inner: Mutex<Inner>,
200    egui: Mutex<Option<egui::Context>>,
201}
202
203impl fmt::Debug for SelectionService {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        let s = self.lock();
206        f.debug_struct("SelectionService")
207            .field("items", &s.items)
208            .field("hovered", &s.hovered.as_ref().map(|h| &h.item))
209            .field("revision", &s.revision)
210            .finish_non_exhaustive()
211    }
212}
213
214impl Default for SelectionService {
215    fn default() -> Self {
216        Self::new()
217    }
218}
219
220impl SelectionService {
221    /// An empty selection, on its own (the plugin provides the
222    /// application's).
223    pub fn new() -> Self {
224        Self {
225            inner: Mutex::new(Inner::default()),
226            egui: Mutex::new(None),
227        }
228    }
229
230    fn lock(&self) -> MutexGuard<'_, Inner> {
231        self.inner.lock().unwrap_or_else(|e| e.into_inner())
232    }
233
234    /// The context asked to repaint after a change.
235    pub fn set_egui(&self, ctx: &egui::Context) {
236        *self.egui.lock().unwrap_or_else(|e| e.into_inner()) = Some(ctx.clone());
237    }
238
239    /// The selected items, in the order they were selected.
240    pub fn items(&self) -> Vec<SelectionItem> {
241        self.lock().items.clone()
242    }
243
244    pub fn contains(&self, item: &SelectionItem) -> bool {
245        self.lock().set.contains(item)
246    }
247
248    pub fn len(&self) -> usize {
249        self.lock().items.len()
250    }
251
252    pub fn is_empty(&self) -> bool {
253        self.lock().items.is_empty()
254    }
255
256    /// Where a range (Shift) starts: the item last clicked.
257    pub fn anchor(&self) -> Option<SelectionItem> {
258        self.lock().anchor.clone()
259    }
260
261    /// The item under the pointer, in whichever widget.
262    pub fn hovered(&self) -> Option<SelectionItem> {
263        self.lock().hovered.as_ref().map(|h| h.item.clone())
264    }
265
266    pub fn is_hovered(&self, item: &SelectionItem) -> bool {
267        self.lock()
268            .hovered
269            .as_ref()
270            .is_some_and(|h| h.item == *item)
271    }
272
273    /// Bumped by each change of the selected items: a widget compares it
274    /// with the one it last saw to know whether to look again.
275    pub fn revision(&self) -> u64 {
276        self.lock().revision
277    }
278
279    /// Bumped by each change of the hovered item.
280    pub fn hover_revision(&self) -> u64 {
281        self.lock().hover_revision
282    }
283
284    /// Who made the last change of the selected items.
285    pub fn source(&self) -> String {
286        self.lock().source.clone()
287    }
288
289    /// Calls `f` after each change (also of the hovered item), from the
290    /// thread making it, the lock released.
291    pub fn subscribe(&self, f: impl Fn(&Change) + Send + Sync + 'static) -> Subscription {
292        let mut s = self.lock();
293        s.next_listener += 1;
294        let id = s.next_listener;
295        s.listeners.push((id, Arc::new(f)));
296        Subscription(id)
297    }
298
299    pub fn unsubscribe(&self, subscription: Subscription) {
300        self.lock()
301            .listeners
302            .retain(|(id, _)| *id != subscription.0);
303    }
304
305    /// Selects these items, and only them.
306    pub fn set(&self, items: impl IntoIterator<Item = SelectionItem>, source: &str) -> bool {
307        let items: Vec<SelectionItem> = items.into_iter().collect();
308        let anchor = items.last().cloned();
309        self.change(source, true, |s| {
310            s.assign(items);
311            s.anchor = anchor;
312        })
313    }
314
315    /// Adds these items (those already selected stay where they are).
316    pub fn add(&self, items: impl IntoIterator<Item = SelectionItem>, source: &str) -> bool {
317        let items: Vec<SelectionItem> = items.into_iter().collect();
318        self.change(source, true, |s| {
319            let mut all = s.items.clone();
320            all.extend(items.iter().cloned());
321            s.assign(all);
322            if let Some(last) = items.last() {
323                s.anchor = Some(last.clone());
324            }
325        })
326    }
327
328    /// Adds `add` and removes `remove`, as one change (one step of the
329    /// history): what a widget's Ctrl gesture does to its own items while
330    /// keeping the others'.
331    pub fn apply(
332        &self,
333        add: impl IntoIterator<Item = SelectionItem>,
334        remove: impl IntoIterator<Item = SelectionItem>,
335        source: &str,
336    ) -> bool {
337        let add: Vec<SelectionItem> = add.into_iter().collect();
338        let gone: HashSet<SelectionItem> = remove.into_iter().collect();
339        self.change(source, true, |s| {
340            let mut all: Vec<SelectionItem> = s
341                .items
342                .iter()
343                .filter(|i| !gone.contains(i))
344                .cloned()
345                .collect();
346            all.extend(add.iter().cloned());
347            s.assign(all);
348            if let Some(last) = add.last() {
349                s.anchor = Some(last.clone());
350            }
351        })
352    }
353
354    /// Removes these items.
355    pub fn remove(&self, items: impl IntoIterator<Item = SelectionItem>, source: &str) -> bool {
356        let gone: HashSet<SelectionItem> = items.into_iter().collect();
357        self.change(source, true, |s| {
358            let kept = s
359                .items
360                .iter()
361                .filter(|i| !gone.contains(i))
362                .cloned()
363                .collect();
364            s.assign(kept);
365        })
366    }
367
368    /// Adds the item, or removes it when selected.
369    pub fn toggle(&self, item: &SelectionItem, source: &str) -> bool {
370        self.change(source, true, |s| {
371            let mut all = s.items.clone();
372            if s.set.contains(item) {
373                all.retain(|i| i != item);
374            } else {
375                all.push(item.clone());
376            }
377            s.assign(all);
378            s.anchor = Some(item.clone());
379        })
380    }
381
382    /// Selects nothing.
383    pub fn clear(&self, source: &str) -> bool {
384        self.change(source, true, |s| {
385            s.assign(Vec::new());
386            s.anchor = None;
387        })
388    }
389
390    /// A click on `item` in a widget showing `order` (its items in the
391    /// order shown, for a range; empty when it has no order). A range
392    /// whose anchor is not in `order` selects the item alone. Returns
393    /// whether the selection changed.
394    pub fn click(
395        &self,
396        item: &SelectionItem,
397        gesture: Gesture,
398        order: &[SelectionItem],
399        source: &str,
400    ) -> bool {
401        match gesture {
402            Gesture::Replace => self.set([item.clone()], source),
403            Gesture::Toggle => self.toggle(item, source),
404            Gesture::Range | Gesture::AddRange => {
405                let anchor = self.anchor();
406                let range = anchor
407                    .as_ref()
408                    .and_then(|a| range(order, a, item))
409                    .unwrap_or_else(|| vec![item.clone()]);
410                self.change(source, true, |s| {
411                    let mut all = if gesture == Gesture::AddRange {
412                        s.items.clone()
413                    } else {
414                        Vec::new()
415                    };
416                    all.extend(range);
417                    s.assign(all);
418                    // The anchor stays: the next Shift+click ranges from it.
419                    s.anchor = anchor.clone().or_else(|| Some(item.clone()));
420                })
421            }
422        }
423    }
424
425    /// What the widget `source` hovers this pass (`None`: nothing of
426    /// it). A widget says it every pass it is drawn: its `None` clears a
427    /// hover it said, never another widget's; a hover no widget repeats
428    /// goes after a pass (the plugin sees to it).
429    pub fn hover(&self, source: &str, item: Option<&SelectionItem>) {
430        let pass = self
431            .egui
432            .lock()
433            .unwrap_or_else(|e| e.into_inner())
434            .as_ref()
435            .map(|c| c.cumulative_pass_nr());
436        self.set_hover(source, item, pass.or(Some(0)));
437    }
438
439    /// Hovers an item until said otherwise (an agent's), or none.
440    pub fn hover_until_changed(&self, item: Option<&SelectionItem>, source: &str) {
441        let item = item.cloned();
442        let owner = source.to_string();
443        self.change(source, false, move |s| {
444            s.hovered = item.map(|item| Hover {
445                item,
446                source: owner,
447                pass: None,
448            });
449        });
450    }
451
452    fn set_hover(&self, source: &str, item: Option<&SelectionItem>, pass: Option<u64>) {
453        {
454            let mut s = self.lock();
455            match (&mut s.hovered, item) {
456                // The same: only its pass moves, no change.
457                (Some(h), Some(i)) if h.item == *i => {
458                    h.source = source.to_string();
459                    h.pass = pass;
460                    return;
461                }
462                (Some(h), None) if h.source != source => return,
463                (None, None) => return,
464                _ => {}
465            }
466        }
467        let item = item.cloned();
468        let owner = source.to_string();
469        self.change(source, false, move |s| {
470            s.hovered = item.map(|item| Hover {
471                item,
472                source: owner,
473                pass,
474            });
475        });
476    }
477
478    /// Clears a widget's hover not said since pass `before` (the widget
479    /// is no longer drawn). The plugin calls it every pass.
480    pub fn expire_hover(&self, before: u64) {
481        let stale = self
482            .lock()
483            .hovered
484            .as_ref()
485            .and_then(|h| h.pass.filter(|p| *p < before).map(|_| h.source.clone()));
486        if let Some(source) = stale {
487            self.set_hover(&source, None, None);
488        }
489    }
490
491    /// Whether there is a selection to go back to.
492    pub fn can_back(&self) -> bool {
493        !self.lock().back.is_empty()
494    }
495
496    /// Whether there is a selection to go forward to.
497    pub fn can_forward(&self) -> bool {
498        !self.lock().forward.is_empty()
499    }
500
501    /// Back to the selection before; `false` when there is none.
502    pub fn back(&self, source: &str) -> bool {
503        self.walk(source, true)
504    }
505
506    /// Forward to the selection gone back from; `false` when there is
507    /// none.
508    pub fn forward(&self, source: &str) -> bool {
509        self.walk(source, false)
510    }
511
512    fn walk(&self, source: &str, back: bool) -> bool {
513        let listeners;
514        let change;
515        {
516            let mut s = self.lock();
517            let to = if back { s.back.pop() } else { s.forward.pop() };
518            let Some(to) = to else { return false };
519            let from = std::mem::take(&mut s.items);
520            if back {
521                s.forward.push(from);
522            } else {
523                s.back.push(from);
524            }
525            s.anchor = to.last().cloned();
526            s.assign(to);
527            s.revision += 1;
528            s.source = source.to_string();
529            listeners = s
530                .listeners
531                .iter()
532                .map(|(_, l)| l.clone())
533                .collect::<Vec<_>>();
534            change = describe_change(&s, true, source);
535        }
536        self.notify(listeners, &change);
537        true
538    }
539
540    /// Applies `f`; when the selected items (or, `selection` false, the
541    /// hovered one) changed, bumps the revision, keeps the history and
542    /// tells the subscribers. Returns whether anything changed.
543    fn change(&self, source: &str, selection: bool, f: impl FnOnce(&mut Inner)) -> bool {
544        let listeners;
545        let change;
546        {
547            let mut s = self.lock();
548            let before = s.items.clone();
549            let hovered = s.hovered.as_ref().map(|h| h.item.clone());
550            f(&mut s);
551            if selection {
552                if s.items == before {
553                    return false;
554                }
555                s.back.push(before);
556                if s.back.len() > HISTORY_CAP {
557                    s.back.remove(0);
558                }
559                s.forward.clear();
560                s.revision += 1;
561                s.source = source.to_string();
562            } else {
563                if s.hovered.as_ref().map(|h| &h.item) == hovered.as_ref() {
564                    return false;
565                }
566                s.hover_revision += 1;
567            }
568            listeners = s
569                .listeners
570                .iter()
571                .map(|(_, l)| l.clone())
572                .collect::<Vec<_>>();
573            change = describe_change(&s, selection, source);
574        }
575        self.notify(listeners, &change);
576        true
577    }
578
579    fn notify(&self, listeners: Vec<Listener>, change: &Change) {
580        for l in listeners {
581            l(change);
582        }
583        if let Some(ctx) = self.egui.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
584            ctx.request_repaint();
585        }
586    }
587
588    /// The selection as the collector shows it.
589    pub fn describe(&self) -> Json {
590        let s = self.lock();
591        json!({
592            "items": s.items,
593            "count": s.items.len(),
594            "hovered": s.hovered.as_ref().map(|h| &h.item),
595            "hovered_by": s.hovered.as_ref().map(|h| &h.source),
596            "anchor": s.anchor,
597            "revision": s.revision,
598            "source": s.source,
599            "back": s.back.len(),
600            "forward": s.forward.len(),
601        })
602    }
603
604    /// The revisions not published yet, marked published.
605    fn unpublished(&self) -> Option<Change> {
606        let mut s = self.lock();
607        let now = (s.revision, s.hover_revision);
608        if s.published == now {
609            return None;
610        }
611        let selection = s.published.0 != now.0;
612        s.published = now;
613        let source = s.source.clone();
614        Some(describe_change(&s, selection, &source))
615    }
616}
617
618fn describe_change(s: &Inner, selection: bool, source: &str) -> Change {
619    Change {
620        items: s.items.clone(),
621        hovered: s.hovered.as_ref().map(|h| h.item.clone()),
622        revision: s.revision,
623        selection,
624        source: source.to_string(),
625    }
626}
627
628/// The items of `order` from `a` to `b`, both included, in that order's
629/// direction; `None` when either is not in it.
630fn range(
631    order: &[SelectionItem],
632    a: &SelectionItem,
633    b: &SelectionItem,
634) -> Option<Vec<SelectionItem>> {
635    let i = order.iter().position(|x| x == a)?;
636    let j = order.iter().position(|x| x == b)?;
637    let (lo, hi) = if i <= j { (i, j) } else { (j, i) };
638    Some(order[lo..=hi].to_vec())
639}
640
641/// Draws `add` in the selection's focus surface ([`SURFACE`]): a widget
642/// of the application's bound to the selection (a canvas) opens it so
643/// Alt+Left and Alt+Right walk the selection's history while it has the
644/// focus.
645pub fn surface<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
646    egui_pop_core::focus::scope(ui, SURFACE, &[], add)
647}
648
649/// Sets the context keys and publishes what changed since the last call.
650pub fn sync(app: &AppHandle) {
651    let Some(s) = app.service(&SELECTION) else {
652        return;
653    };
654    let say = |b: bool| if b { "true" } else { "false" };
655    app.set_context(CONTEXT_HAS, say(!s.is_empty()));
656    app.set_context(CONTEXT_COUNT, &s.len().to_string());
657    app.set_context(CONTEXT_CAN_BACK, say(s.can_back()));
658    app.set_context(CONTEXT_CAN_FORWARD, say(s.can_forward()));
659    if let Some(change) = s.unpublished() {
660        app.publish(
661            "egui_pop.selection",
662            None,
663            EVENT_CHANGED,
664            serde_json::to_value(&change).unwrap_or(Json::Null),
665        );
666    }
667}
668
669/// The application's selection, or why there is none.
670fn service(app: &AppHandle) -> Result<Arc<SelectionService>, String> {
671    app.service(&SELECTION)
672        .ok_or_else(|| "the selection plugin is not connected".to_string())
673}
674
675/// The `items` argument: a list of ids (a single id is taken too).
676fn items_arg(args: &Json) -> Result<Vec<SelectionItem>, String> {
677    match args.get("items") {
678        Some(Json::Array(a)) => a
679            .iter()
680            .map(|v| {
681                v.as_str()
682                    .map(SelectionItem::from)
683                    .ok_or_else(|| format!("`items`: {v} is not a string"))
684            })
685            .collect(),
686        Some(Json::String(s)) => Ok(vec![SelectionItem::from(s.as_str())]),
687        Some(Json::Null) | None => Err("`items` is missing".into()),
688        Some(v) => Err(format!("`items`: {v} is not a list of ids")),
689    }
690}
691
692/// The application-wide selection: its service, commands, keys, context
693/// keys and collector.
694#[derive(Debug, Default)]
695pub struct SelectionPlugin;
696
697impl Plugin for SelectionPlugin {
698    fn id(&self) -> PluginId {
699        SELECTION_PLUGIN
700    }
701
702    fn title(&self) -> String {
703        "Selection".into()
704    }
705
706    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
707        const CAT: &str = "Selection";
708        let provided = SelectionService::new();
709        provided.set_egui(&ctx.app().egui());
710        ctx.service(&SELECTION, provided)?;
711        let shared = ctx.app().service(&SELECTION).expect("just provided");
712        let done = |call: &crate::Call<'_>, changed: bool| -> Result<Json, String> {
713            sync(call.app);
714            let s = service(call.app)?;
715            Ok(json!({ "changed": changed, "items": s.items(), "count": s.len() }))
716        };
717        ctx.command(
718            CommandSpec::new(CMD_BACK, "Back to the previous selection", CAT)
719                .icon("chevron-left")
720                .description("Selects again what was selected before the last change.")
721                .when(CONTEXT_CAN_BACK)
722                .key_with("Alt+Left", BindOptions::surface(SURFACE)),
723            move |call| {
724                let changed = service(call.app)?.back("history");
725                done(call, changed)
726            },
727        )?
728        .command(
729            CommandSpec::new(CMD_FORWARD, "Forward to the next selection", CAT)
730                .icon("chevron-right")
731                .description("Selects again what was selected before going back.")
732                .when(CONTEXT_CAN_FORWARD)
733                .key_with("Alt+Right", BindOptions::surface(SURFACE)),
734            move |call| {
735                let changed = service(call.app)?.forward("history");
736                done(call, changed)
737            },
738        )?
739        .command(
740            CommandSpec::new(CMD_SET, "Select items", CAT)
741                .description("Selects these items (`items`, their ids), and only them.")
742                .hidden()
743                .args(json!({ "items": ["photos/2024/0012.raw"] })),
744            move |call| {
745                let items = items_arg(call.args)?;
746                let changed = service(call.app)?.set(items, SOURCE_COMMAND);
747                done(call, changed)
748            },
749        )?
750        .command(
751            CommandSpec::new(CMD_ADD, "Add items to the selection", CAT)
752                .description("Adds these items (`items`, their ids) to the selection.")
753                .hidden()
754                .args(json!({ "items": ["photos/2024/0013.raw"] })),
755            move |call| {
756                let items = items_arg(call.args)?;
757                let changed = service(call.app)?.add(items, SOURCE_COMMAND);
758                done(call, changed)
759            },
760        )?
761        .command(
762            CommandSpec::new(CMD_CLEAR, "Clear the selection", CAT)
763                .description("Selects nothing.")
764                .hidden(),
765            move |call| {
766                let changed = service(call.app)?.clear(SOURCE_COMMAND);
767                done(call, changed)
768            },
769        )?
770        .command(
771            CommandSpec::new(CMD_HOVER, "Hover an item", CAT)
772                .description("Hovers an item (`item`, its id; null for none) in every widget showing it, until a widget or another call hovers something else.")
773                .hidden()
774                .args(json!({ "item": "photos/2024/0012.raw" })),
775            move |call| {
776                let item = match call.args.get("item") {
777                    Some(Json::String(s)) => Some(SelectionItem::from(s.as_str())),
778                    Some(Json::Null) | None => None,
779                    Some(v) => return Err(format!("`item`: {v} is not an id")),
780                };
781                let s = service(call.app)?;
782                s.hover_until_changed(item.as_ref(), SOURCE_COMMAND);
783                sync(call.app);
784                Ok(json!({ "hovered": s.hovered() }))
785            },
786        )?;
787        ctx.collector(
788            egui_pop_core::debug::FnCollector::new(
789                "selection",
790                "The application-wide selection: the items selected (ids, in the order selected), their count, the item hovered and by which widget, the anchor of a range, the revision, who made the last change, and how many selections back and forward go to.",
791            )
792            .snapshot(move |_| shared.describe()),
793        )?;
794        sync(&ctx.app());
795        ctx.on(On::Pass, |app, _| {
796            if let Some(s) = app.service(&SELECTION) {
797                // A hover not said this pass or the last: its widget is gone.
798                let pass = app.egui().cumulative_pass_nr();
799                s.expire_hover(pass.saturating_sub(1));
800            }
801            sync(app);
802        });
803        Ok(())
804    }
805}
806
807#[cfg(test)]
808mod tests {
809    use super::*;
810
811    /// `SelectionItem` moved to `egui_pop_model::selection` and is
812    /// re-exported here; everything egui-pop-api 0.10.0 offered on it
813    /// still works through this path (cargo-semver-checks cannot follow
814    /// the re-export across crates, see the crate's Cargo.toml).
815    #[test]
816    fn selection_item_keeps_its_0_10_surface() {
817        use std::collections::HashSet;
818        use std::sync::Arc;
819
820        let a = SelectionItem::new(Arc::<str>::from("a"));
821        let b: SelectionItem = String::from("b").into();
822        assert_eq!(SelectionItem::from("a"), a.clone());
823        assert_eq!(SelectionItem::from_key(&12).as_str(), "12");
824        assert_eq!(SelectionItem::from_key("x").as_str(), "x");
825        assert!(a < b);
826        assert_eq!(format!("{a} {b:?}"), "a \"b\"");
827        assert_eq!(HashSet::from([a.clone(), a.clone()]).len(), 1);
828        let text = serde_json::to_string(&a).unwrap();
829        assert_eq!(text, "\"a\"");
830        assert_eq!(serde_json::from_str::<SelectionItem>(&text).unwrap(), a);
831    }
832
833    fn items(ids: &[&str]) -> Vec<SelectionItem> {
834        ids.iter().map(|s| SelectionItem::from(*s)).collect()
835    }
836
837    #[test]
838    fn gestures_replace_toggle_and_range() {
839        let s = SelectionService::new();
840        let order = items(&["a", "b", "c", "d", "e"]);
841        s.click(&order[1], Gesture::Replace, &order, "t");
842        s.click(&order[3], Gesture::Range, &order, "t");
843        assert_eq!(s.items(), items(&["b", "c", "d"]));
844        // Shift again ranges from the same anchor.
845        s.click(&order[0], Gesture::Range, &order, "t");
846        assert_eq!(s.items(), items(&["a", "b"]));
847        s.click(&order[4], Gesture::Toggle, &order, "t");
848        assert_eq!(s.items(), items(&["a", "b", "e"]));
849        s.click(&order[0], Gesture::Toggle, &order, "t");
850        assert_eq!(s.items(), items(&["b", "e"]));
851        // Ctrl+Shift adds the range from the anchor (`a`, the last toggled).
852        s.click(&order[2], Gesture::AddRange, &order, "t");
853        assert_eq!(s.items(), items(&["b", "e", "a", "c"]));
854        // An anchor outside this order: the item alone.
855        let other = items(&["x", "y"]);
856        s.click(&other[1], Gesture::Range, &other, "t");
857        assert_eq!(s.items(), items(&["y"]));
858        assert_eq!(Gesture::of(Modifiers::COMMAND), Gesture::Toggle);
859        assert_eq!(Gesture::of(Modifiers::SHIFT), Gesture::Range);
860        assert_eq!(Gesture::of(Modifiers::NONE), Gesture::Replace);
861    }
862
863    #[test]
864    fn history_goes_back_and_forward_and_a_change_drops_forward() {
865        let s = SelectionService::new();
866        s.set(items(&["a"]), "t");
867        s.set(items(&["b"]), "t");
868        s.set(items(&["c"]), "t");
869        assert!(s.back("h"));
870        assert_eq!(s.items(), items(&["b"]));
871        assert!(s.back("h"));
872        assert_eq!(s.items(), items(&["a"]));
873        assert!(s.forward("h"));
874        assert_eq!(s.items(), items(&["b"]));
875        assert!(s.can_forward());
876        s.set(items(&["d"]), "t");
877        assert!(!s.can_forward());
878        assert!(!s.forward("h"));
879        assert!(s.back("h"));
880        assert_eq!(s.items(), items(&["b"]));
881        // The same selection again is no change and no step.
882        let rev = s.revision();
883        assert!(!s.set(items(&["b"]), "t"));
884        assert_eq!(s.revision(), rev);
885    }
886
887    #[test]
888    fn hover_belongs_to_the_widget_that_said_it() {
889        let s = SelectionService::new();
890        let a = SelectionItem::from("a");
891        s.hover("tree", Some(&a));
892        assert!(s.is_hovered(&a));
893        // Another widget hovering nothing leaves it.
894        s.hover("list", None);
895        assert_eq!(s.hovered(), Some(a.clone()));
896        s.hover("tree", None);
897        assert_eq!(s.hovered(), None);
898        // Not said again: it expires.
899        s.set_hover("tree", Some(&a), Some(4));
900        s.expire_hover(4);
901        assert!(s.is_hovered(&a));
902        s.expire_hover(5);
903        assert_eq!(s.hovered(), None);
904        // An agent's stays.
905        s.hover_until_changed(Some(&a), "command");
906        s.expire_hover(1000);
907        assert!(s.is_hovered(&a));
908    }
909
910    #[test]
911    fn subscribers_hear_each_change_once() {
912        let s = SelectionService::new();
913        let heard = Arc::new(Mutex::new(Vec::new()));
914        let h = heard.clone();
915        let sub = s.subscribe(move |c| h.lock().unwrap().push((c.selection, c.items.len())));
916        s.set(items(&["a", "b"]), "t");
917        s.set(items(&["a", "b"]), "t");
918        s.hover("t", Some(&SelectionItem::from("a")));
919        s.unsubscribe(sub);
920        s.clear("t");
921        assert_eq!(*heard.lock().unwrap(), vec![(true, 2), (false, 2)]);
922    }
923
924    #[test]
925    fn items_of_keys() {
926        assert_eq!(SelectionItem::from_key("a/b").as_str(), "a/b");
927        assert_eq!(SelectionItem::from_key(&12u32).as_str(), "12");
928        assert_eq!(SelectionItem::from_key(&(1, 2)).as_str(), "[1,2]");
929    }
930}