Skip to main content

egui_pop_model/
selection.rs

1//! The selection's item: a string id an application chooses, the same in
2//! every widget showing it, without egui or an application (ADR 0012).
3//! The application-wide selection that holds these items is
4//! `egui_pop_api::selection`; a widget used alone keys its own selection by
5//! them.
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9
10use std::fmt;
11use std::sync::Arc;
12
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14use serde_json::Value as Json;
15
16/// An item of the selection: a string id the application chooses, the
17/// same in every widget showing the item (a path, `kind:id`, a number).
18///
19/// A string rather than a typed key: widgets with different key types (a
20/// tree by path, a table by row id, a canvas by entity) meet on it, it
21/// goes through the journal, the history and the agents' commands as it
22/// is, and it clones for the cost of a reference count.
23///
24/// It serialises as its string. The impls are written by hand: deriving
25/// them over `Arc<str>` needs serde's `rc` feature, which this crate does
26/// not turn on (it would build only beside a crate that does).
27#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
28pub struct SelectionItem(Arc<str>);
29
30impl Serialize for SelectionItem {
31    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
32        serializer.serialize_str(&self.0)
33    }
34}
35
36impl<'de> Deserialize<'de> for SelectionItem {
37    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
38        String::deserialize(deserializer).map(Self::from)
39    }
40}
41
42impl SelectionItem {
43    pub fn new(id: impl Into<Arc<str>>) -> Self {
44        Self(id.into())
45    }
46
47    /// The item of a widget's key: a string key as it is, any other its
48    /// JSON text (`12`, `[1,2]`).
49    pub fn from_key<K: Serialize + ?Sized>(key: &K) -> Self {
50        match serde_json::to_value(key) {
51            Ok(Json::String(s)) => Self::new(s),
52            Ok(v) => Self::new(v.to_string()),
53            Err(_) => Self::new(""),
54        }
55    }
56
57    pub fn as_str(&self) -> &str {
58        &self.0
59    }
60}
61
62impl fmt::Debug for SelectionItem {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        fmt::Debug::fmt(&*self.0, f)
65    }
66}
67
68impl fmt::Display for SelectionItem {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_str(&self.0)
71    }
72}
73
74impl From<&str> for SelectionItem {
75    fn from(s: &str) -> Self {
76        Self::new(s)
77    }
78}
79
80impl From<String> for SelectionItem {
81    fn from(s: String) -> Self {
82        Self::new(s)
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn serialises_as_its_string() {
92        let item = SelectionItem::from("photos/a.jpg");
93        let text = serde_json::to_string(&item).unwrap();
94        assert_eq!(text, "\"photos/a.jpg\"");
95        assert_eq!(serde_json::from_str::<SelectionItem>(&text).unwrap(), item);
96    }
97}