Skip to main content

egui_pop_model/
ids.rs

1//! Typed ids (ADR 0002): one newtype per namespace, sharing one syntax,
2//! serialized as plain strings.
3//!
4//! ```
5//! use egui_pop_model::ids::{CommandId, ZoneId};
6//!
7//! const SIDEBAR: ZoneId = ZoneId::from_static("app.sidebar");
8//! let palette = CommandId::new("view.palette").unwrap();
9//! assert_eq!(palette.as_str(), "view.palette");
10//! assert_eq!(serde_json::to_string(&SIDEBAR).unwrap(), "\"app.sidebar\"");
11//! assert!(CommandId::new("has space").is_err());
12//! ```
13//!
14//! An invalid literal in `from_static` is a compile error when used in a
15//! constant:
16//!
17//! ```compile_fail
18//! use egui_pop_model::ids::ZoneId;
19//! const BAD: ZoneId = ZoneId::from_static("no spaces allowed");
20//! ```
21
22use std::borrow::Cow;
23use std::fmt;
24
25/// The longest id, in bytes.
26pub const MAX_ID_LEN: usize = 128;
27
28/// Why a text is not an id.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct IdError {
31    /// The namespace (`CommandId`, `ZoneId`...).
32    pub kind: &'static str,
33    pub text: String,
34    pub reason: &'static str,
35}
36
37impl fmt::Display for IdError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "`{}` is not a {}: {}", self.text, self.kind, self.reason)
40    }
41}
42
43impl std::error::Error for IdError {}
44
45/// Checks the shared syntax: ASCII letters, digits and `. _ - / :`, not
46/// empty, at most [`MAX_ID_LEN`] bytes. `Err` holds the reason.
47pub const fn check(text: &str) -> Result<(), &'static str> {
48    let b = text.as_bytes();
49    if b.is_empty() {
50        return Err("it is empty");
51    }
52    if b.len() > MAX_ID_LEN {
53        return Err("it is longer than 128 bytes");
54    }
55    let mut i = 0;
56    while i < b.len() {
57        let c = b[i];
58        let ok = c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-' | b'/' | b':');
59        if !ok {
60            return Err("only ASCII letters, digits and `. _ - / :` are allowed");
61        }
62        i += 1;
63    }
64    Ok(())
65}
66
67/// Checks a panel id: the shared syntax ([`check`]), and an instance's
68/// `#<n>` after it (`app.gallery#2`, ADR 0002's panel instances), `n` a
69/// number from 2 without leading zeros (the panel declared is instance 1).
70pub const fn check_panel(text: &str) -> Result<(), &'static str> {
71    let b = text.as_bytes();
72    let mut hash = b.len();
73    let mut i = 0;
74    while i < b.len() {
75        if b[i] == b'#' {
76            hash = i;
77            break;
78        }
79        i += 1;
80    }
81    if hash == b.len() {
82        return check(text);
83    }
84    if b.len() > MAX_ID_LEN {
85        return Err("it is longer than 128 bytes");
86    }
87    if hash == 0 {
88        return Err("an instance's `#<n>` follows a panel's id");
89    }
90    let digits = b.len() - hash - 1;
91    if digits == 0 || digits > 9 || b[hash + 1] == b'0' {
92        return Err("an instance's `#<n>` is a number from 2, without leading zeros");
93    }
94    let mut j = hash + 1;
95    while j < b.len() {
96        if !b[j].is_ascii_digit() {
97            return Err("an instance's `#<n>` is a number from 2, without leading zeros");
98        }
99        j += 1;
100    }
101    if digits == 1 && b[hash + 1] == b'1' {
102        return Err("instance 1 is the panel itself: its id has no `#1`");
103    }
104    // The kind before `#`: the shared syntax.
105    let mut k = 0;
106    while k < hash {
107        let c = b[k];
108        let ok = c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-' | b'/' | b':');
109        if !ok {
110            return Err("only ASCII letters, digits and `. _ - / :` are allowed");
111        }
112        k += 1;
113    }
114    Ok(())
115}
116
117macro_rules! typed_id {
118    ($(#[$doc:meta])* $name:ident) => {
119        typed_id!($(#[$doc])* $name, check);
120    };
121    ($(#[$doc:meta])* $name:ident, $check:ident) => {
122        $(#[$doc])*
123        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
124        pub struct $name(Cow<'static, str>);
125
126        impl $name {
127            /// From a literal, checked at compile time when used in a
128            /// constant (and panicking otherwise).
129            pub const fn from_static(text: &'static str) -> Self {
130                match $check(text) {
131                    Ok(()) => $name(Cow::Borrowed(text)),
132                    Err(_) => panic!(concat!("invalid ", stringify!($name), " literal")),
133                }
134            }
135
136            /// From any text, checked.
137            pub fn new(text: impl Into<String>) -> Result<Self, IdError> {
138                let text = text.into();
139                match $check(&text) {
140                    Ok(()) => Ok($name(Cow::Owned(text))),
141                    Err(reason) => Err(IdError {
142                        kind: stringify!($name),
143                        text,
144                        reason,
145                    }),
146                }
147            }
148
149            pub fn as_str(&self) -> &str {
150                &self.0
151            }
152
153            /// This id with a suffix (`panel.focus` from `panel`),
154            /// checked.
155            pub fn join(&self, suffix: &str) -> Result<Self, IdError> {
156                Self::new(format!("{}.{suffix}", self.0))
157            }
158        }
159
160        impl fmt::Debug for $name {
161            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162                write!(f, "{}({:?})", stringify!($name), &*self.0)
163            }
164        }
165
166        impl fmt::Display for $name {
167            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168                f.write_str(&self.0)
169            }
170        }
171
172        impl AsRef<str> for $name {
173            fn as_ref(&self) -> &str {
174                &self.0
175            }
176        }
177
178        impl std::str::FromStr for $name {
179            type Err = IdError;
180
181            fn from_str(s: &str) -> Result<Self, IdError> {
182                Self::new(s)
183            }
184        }
185
186        impl TryFrom<&str> for $name {
187            type Error = IdError;
188
189            fn try_from(s: &str) -> Result<Self, IdError> {
190                Self::new(s)
191            }
192        }
193
194        impl TryFrom<String> for $name {
195            type Error = IdError;
196
197            fn try_from(s: String) -> Result<Self, IdError> {
198                Self::new(s)
199            }
200        }
201
202        impl serde::Serialize for $name {
203            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
204                s.serialize_str(&self.0)
205            }
206        }
207
208        impl<'de> serde::Deserialize<'de> for $name {
209            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
210                let text = String::deserialize(d)?;
211                Self::new(text).map_err(serde::de::Error::custom)
212            }
213        }
214    };
215}
216
217typed_id!(
218    /// A command: `view.palette`, `file.save`.
219    CommandId
220);
221typed_id!(
222    /// A menu: `app.main`, `panel.tab`.
223    MenuId
224);
225typed_id!(
226    /// A panel: `app.log`; an instance of a panel declared with several
227    /// (`PanelSpec::instances`) adds `#<n>`: `app.gallery#2`.
228    PanelId,
229    check_panel
230);
231
232impl PanelId {
233    /// The panel declared this id is an instance of: itself for the
234    /// panel declared (instance 1), `app.gallery` for `app.gallery#2`.
235    ///
236    /// ```
237    /// use egui_pop_model::ids::PanelId;
238    /// let second = PanelId::new("app.gallery#2").unwrap();
239    /// assert_eq!(second.kind().as_str(), "app.gallery");
240    /// assert_eq!(second.instance_number(), 2);
241    /// assert_eq!(second.kind().instance_number(), 1);
242    /// assert_eq!(second.kind().instance(2).unwrap(), second);
243    /// assert!(PanelId::new("app.gallery#1").is_err());
244    /// assert!(PanelId::new("app.gallery#02").is_err());
245    /// ```
246    pub fn kind(&self) -> PanelId {
247        match self.0.split_once('#') {
248            Some((kind, _)) => PanelId(Cow::Owned(kind.to_string())),
249            None => self.clone(),
250        }
251    }
252
253    /// Its instance's number: 1 for the panel declared.
254    pub fn instance_number(&self) -> u32 {
255        self.0
256            .split_once('#')
257            .and_then(|(_, n)| n.parse().ok())
258            .unwrap_or(1)
259    }
260
261    /// Whether it names an instance other than the panel declared
262    /// (`#<n>`).
263    pub fn is_instance(&self) -> bool {
264        self.0.contains('#')
265    }
266
267    /// The id of this panel's instance `n` (its kind's): the kind itself
268    /// for 1.
269    pub fn instance(&self, n: u32) -> Result<PanelId, IdError> {
270        let kind = self.kind();
271        if n <= 1 {
272            return Ok(kind);
273        }
274        PanelId::new(format!("{kind}#{n}"))
275    }
276}
277typed_id!(
278    /// A zone where blocks are drawn: `app.sidebar`.
279    ZoneId
280);
281typed_id!(
282    /// A block in a zone.
283    BlockId
284);
285typed_id!(
286    /// A plugin: `gallery.overview`.
287    PluginId
288);
289typed_id!(
290    /// Who registered something: a plugin's id, `framework`, `user`.
291    OwnerId
292);
293typed_id!(
294    /// A setting, also its path in the value store under `settings/`.
295    SettingId
296);
297
298/// Where settings live in the value store: a setting `id` is at
299/// `settings/<id>` ([`SettingId::path`]).
300pub const SETTINGS_PREFIX: &str = "settings/";
301
302impl SettingId {
303    /// The setting's path in the value store: `settings/<id>`.
304    ///
305    /// ```
306    /// use egui_pop_model::ids::SettingId;
307    /// let id = SettingId::from_static("swatch.show_code");
308    /// assert_eq!(id.path(), "settings/swatch.show_code");
309    /// ```
310    pub fn path(&self) -> String {
311        format!("{SETTINGS_PREFIX}{}", self.0)
312    }
313}
314typed_id!(
315    /// A service plugins share.
316    ServiceId
317);
318typed_id!(
319    /// A hook point declarations are altered at.
320    HookId
321);
322typed_id!(
323    /// A gallery story.
324    StoryId
325);
326typed_id!(
327    /// A step of a feature's life that plugins may watch, veto, replace
328    /// or extend: `frame.close`, `workbench.detach`.
329    StepId
330);
331
332typed_id!(
333    /// A frame of the context stack (ADR 0012): a place (`demo.album`)
334    /// or a mode (`demo.orientation.culling`).
335    FrameId
336);
337typed_id!(
338    /// A group of modes, one active at a time (`orientation`): the
339    /// context key `mode.<group>`, so letters, digits, `_` and `.`.
340    GroupId
341);
342typed_id!(
343    /// A history (ADR 0014): one undo line, a document's edit, a
344    /// collection's marks, the settings window (`app`, `settings`).
345    ScopeId
346);
347
348impl OwnerId {
349    /// The framework itself.
350    pub const FRAMEWORK: OwnerId = OwnerId::from_static("framework");
351    /// The user (their keymap, their settings).
352    pub const USER: OwnerId = OwnerId::from_static("user");
353}
354
355impl From<&PluginId> for OwnerId {
356    fn from(p: &PluginId) -> OwnerId {
357        OwnerId(p.0.clone())
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    #[test]
366    fn ids_check_their_syntax_and_round_trip_as_strings() {
367        for good in ["a", "view.palette", "app/sidebar", "x:y-z_1"] {
368            assert!(CommandId::new(good).is_ok(), "{good}");
369        }
370        for bad in ["", "a b", "é", &"x".repeat(129)] {
371            let e = CommandId::new(bad).unwrap_err();
372            assert_eq!(e.kind, "CommandId");
373            assert!(e.to_string().contains("is not a CommandId"), "{e}");
374        }
375        const Z: ZoneId = ZoneId::from_static("app.main");
376        let json = serde_json::to_string(&Z).unwrap();
377        assert_eq!(json, "\"app.main\"");
378        assert_eq!(serde_json::from_str::<ZoneId>(&json).unwrap(), Z);
379        assert!(serde_json::from_str::<ZoneId>("\"a b\"").is_err());
380        assert_eq!(format!("{Z:?}"), "ZoneId(\"app.main\")");
381        assert_eq!(Z.join("focus").unwrap().as_str(), "app.main.focus");
382        assert_eq!(
383            OwnerId::from(&PluginId::from_static("p")),
384            OwnerId::new("p").unwrap()
385        );
386    }
387}