1use 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
65pub const SELECTION_PLUGIN: PluginId = PluginId::from_static("egui_pop.selection");
67
68pub const SELECTION: ServiceToken<SelectionService> = ServiceToken::new("egui_pop.selection");
70
71pub const SURFACE: &str = "selection";
75
76pub const CONTEXT_HAS: &str = "hasSelection";
78pub const CONTEXT_COUNT: &str = "selectionCount";
80pub const CONTEXT_CAN_BACK: &str = "selectionCanBack";
82pub const CONTEXT_CAN_FORWARD: &str = "selectionCanForward";
84
85pub const CMD_BACK: CommandId = CommandId::from_static("selection.back");
87pub const CMD_FORWARD: CommandId = CommandId::from_static("selection.forward");
89pub const CMD_SET: CommandId = CommandId::from_static("selection.set");
91pub const CMD_ADD: CommandId = CommandId::from_static("selection.add");
93pub const CMD_CLEAR: CommandId = CommandId::from_static("selection.clear");
95pub const CMD_HOVER: CommandId = CommandId::from_static("selection.hover");
97
98pub const EVENT_CHANGED: &str = "selection.changed";
101
102pub const HISTORY_CAP: usize = 100;
104
105pub const SOURCE_COMMAND: &str = "command";
107
108pub use egui_pop_model::selection::SelectionItem;
109
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum Gesture {
113 Replace,
115 Toggle,
117 Range,
120 AddRange,
122}
123
124impl Gesture {
125 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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
138pub struct Change {
139 pub items: Vec<SelectionItem>,
141 pub hovered: Option<SelectionItem>,
142 pub revision: u64,
144 pub selection: bool,
146 pub source: String,
148}
149
150#[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 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 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
193pub 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 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 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 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 pub fn anchor(&self) -> Option<SelectionItem> {
258 self.lock().anchor.clone()
259 }
260
261 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 pub fn revision(&self) -> u64 {
276 self.lock().revision
277 }
278
279 pub fn hover_revision(&self) -> u64 {
281 self.lock().hover_revision
282 }
283
284 pub fn source(&self) -> String {
286 self.lock().source.clone()
287 }
288
289 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 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 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 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 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 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 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 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 s.anchor = anchor.clone().or_else(|| Some(item.clone()));
420 })
421 }
422 }
423 }
424
425 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 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 (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 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 pub fn can_back(&self) -> bool {
493 !self.lock().back.is_empty()
494 }
495
496 pub fn can_forward(&self) -> bool {
498 !self.lock().forward.is_empty()
499 }
500
501 pub fn back(&self, source: &str) -> bool {
503 self.walk(source, true)
504 }
505
506 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 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 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 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
628fn 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
641pub 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
649pub 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
669fn 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
675fn 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#[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 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 #[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 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 s.click(&order[2], Gesture::AddRange, &order, "t");
853 assert_eq!(s.items(), items(&["b", "e", "a", "c"]));
854 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 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 s.hover("list", None);
895 assert_eq!(s.hovered(), Some(a.clone()));
896 s.hover("tree", None);
897 assert_eq!(s.hovered(), None);
898 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 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}