Skip to main content

egui_pop_core/
state.rs

1//! The state egui-pop keeps in egui's memory, through typed slots.
2//!
3//! A [`Slot`] names a value of one type kept in a context's temporary
4//! memory (`egui::Memory::data`): per context (`Slot::new`), or per
5//! instance (`slot.keyed(widget_id)`, one value per key). Every write
6//! registers the slot in the context, so the debug bridge's `state`
7//! collector lists what egui-pop holds: each slot's name, type, scope,
8//! how many entries it has and a one-line summary of its values.
9//!
10//! ```
11//! use egui_pop_core::state::Slot;
12//!
13//! // Declared once, beside the code that uses it; the name is unique.
14//! const CLICKS: Slot<u32> = Slot::new("example.clicks");
15//!
16//! let ctx = egui::Context::default();
17//! CLICKS.update(&ctx, |n| *n += 1);
18//! assert_eq!(CLICKS.get(&ctx), Some(1));
19//! // Per instance: one value per key.
20//! let widget = egui::Id::new("a button");
21//! CLICKS.keyed(widget).set(&ctx, 7);
22//! assert_eq!(CLICKS.keyed(widget).get(&ctx), Some(7));
23//! assert_eq!(CLICKS.get(&ctx), Some(1));
24//! ```
25//!
26//! egui's context is locked while its memory is read or written, and
27//! taking the lock again from inside (`ctx.viewport_id()`,
28//! `ctx.input(..)`, another slot) deadlocks. A slot takes the lock
29//! itself and only hands its value to the closure of [`Slot::update`];
30//! build every key and read every other state *before* calling it. A
31//! slot touched from inside another slot's `update` panics with a
32//! message instead of deadlocking.
33
34use std::any::TypeId;
35use std::cell::Cell;
36use std::collections::{BTreeMap, HashSet};
37use std::fmt::{self, Debug, Write as _};
38use std::hash::Hash;
39use std::marker::PhantomData;
40use std::sync::{Arc, Mutex, MutexGuard, PoisonError, TryLockError};
41
42use egui::util::id_type_map::RawKey;
43use egui::{Context, Id};
44use serde::Serialize;
45
46/// Locks a mutex, ignoring poisoning (a panic caught by a fault boundary
47/// must not make the framework's own state unusable).
48pub fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
49    m.lock().unwrap_or_else(PoisonError::into_inner)
50}
51
52/// The longest summary of a value, in characters.
53pub const SUMMARY_MAX: usize = 160;
54
55/// A value of type `T` kept in a context's temporary memory, by name.
56///
57/// Per context by default; [`Slot::keyed`] gives one value per key (a
58/// widget's id, a viewport). Names are unique across egui-pop and the
59/// application, prefixed by the crate (`core.slider.typing`).
60pub struct Slot<T> {
61    name: &'static str,
62    key: Option<Id>,
63    summary: fn(&T) -> String,
64    _t: PhantomData<fn() -> T>,
65}
66
67impl<T> Clone for Slot<T> {
68    fn clone(&self) -> Self {
69        *self
70    }
71}
72
73impl<T> Copy for Slot<T> {}
74
75impl<T> Debug for Slot<T> {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.debug_struct("Slot")
78            .field("name", &self.name)
79            .field("key", &self.key)
80            .finish()
81    }
82}
83
84/// Where a slot's value lives.
85#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
86#[serde(rename_all = "lowercase")]
87pub enum Scope {
88    /// One value per context.
89    Context,
90    /// One value per key (a widget, a viewport, a document).
91    Instance,
92}
93
94thread_local! {
95    /// A slot's closure is running: egui's context is locked.
96    static LOCKED: Cell<Option<&'static str>> = const { Cell::new(None) };
97}
98
99/// Runs `f` with the context marked locked by slot `name`, refusing a
100/// slot touched from inside another's closure (it would deadlock).
101fn guarded<R>(name: &'static str, f: impl FnOnce() -> R) -> R {
102    if let Some(outer) = LOCKED.get() {
103        panic!(
104            "slot `{name}` touched inside slot `{outer}`'s closure: egui's context is locked there; read it before"
105        );
106    }
107    struct Reset;
108    impl Drop for Reset {
109        fn drop(&mut self) {
110            LOCKED.set(None);
111        }
112    }
113    LOCKED.set(Some(name));
114    let _reset = Reset;
115    f()
116}
117
118impl<T: Clone + Send + Sync + 'static> Slot<T> {
119    /// A slot per context, its values summarised by their `Debug` form.
120    pub const fn new(name: &'static str) -> Self
121    where
122        T: Debug,
123    {
124        Self {
125            name,
126            key: None,
127            summary: debug_summary::<T>,
128            _t: PhantomData,
129        }
130    }
131
132    /// A slot per context whose values say themselves what the debug
133    /// bridge should read, when their `Debug` form would not fit in a
134    /// summary.
135    pub const fn summarised(name: &'static str, summary: fn(&T) -> String) -> Self {
136        Self {
137            name,
138            key: None,
139            summary,
140            _t: PhantomData,
141        }
142    }
143
144    /// A slot per context whose values have no `Debug` form (handles,
145    /// trait objects): summarised by their type.
146    pub const fn opaque(name: &'static str) -> Self {
147        Self {
148            name,
149            key: None,
150            summary: opaque_summary::<T>,
151            _t: PhantomData,
152        }
153    }
154
155    /// The same slot, one value per `key` (a widget's id, a viewport).
156    pub fn keyed(self, key: impl Hash + Debug) -> Self {
157        Self {
158            key: Some(Id::unique(key)),
159            ..self
160        }
161    }
162
163    /// The slot's name.
164    pub fn name(&self) -> &'static str {
165        self.name
166    }
167
168    /// Per context or per instance.
169    pub fn scope(&self) -> Scope {
170        if self.key.is_some() {
171            Scope::Instance
172        } else {
173            Scope::Context
174        }
175    }
176
177    /// The id the value is kept under in egui's memory.
178    pub fn id(&self) -> Id {
179        let base = base_id(self.name);
180        match self.key {
181            Some(k) => base.with(k),
182            None => base,
183        }
184    }
185
186    /// The value, cloned.
187    pub fn get(&self, ctx: &Context) -> Option<T> {
188        let id = self.id();
189        guarded(self.name, || ctx.data(|d| d.get_temp::<T>(id)))
190    }
191
192    /// The value, or `T::default()` (nothing is stored).
193    pub fn get_or_default(&self, ctx: &Context) -> T
194    where
195        T: Default,
196    {
197        self.get(ctx).unwrap_or_default()
198    }
199
200    /// Whether a value is stored.
201    pub fn exists(&self, ctx: &Context) -> bool {
202        let raw = RawKey::new::<T>(self.id());
203        guarded(self.name, || ctx.data(|d| d.get_temp_raw(raw).is_some()))
204    }
205
206    /// Stores a value.
207    pub fn set(&self, ctx: &Context, value: T) {
208        let id = self.id();
209        self.register(ctx, id);
210        guarded(self.name, || ctx.data_mut(|d| d.insert_temp(id, value)));
211    }
212
213    /// Removes the value; what it was.
214    pub fn remove(&self, ctx: &Context) -> Option<T> {
215        let id = self.id();
216        let raw = RawKey::new::<T>(id);
217        let old = guarded(self.name, || ctx.data_mut(|d| d.remove_temp_raw(raw)));
218        self.unregister(ctx, id);
219        old.and_then(|b| b.downcast::<T>().ok()).map(|b| *b)
220    }
221
222    /// The value, created by `make` when there is none. `make` runs
223    /// outside egui's lock: it may read the context.
224    pub fn get_or_insert_with(&self, ctx: &Context, make: impl FnOnce() -> T) -> T {
225        if let Some(v) = self.get(ctx) {
226            return v;
227        }
228        let v = make();
229        self.set(ctx, v.clone());
230        v
231    }
232
233    /// Changes the value in place (`T::default()` when there is none)
234    /// and returns what `f` returns. `f` runs under egui's lock: it must
235    /// not touch the context (no `ctx.viewport_id()`, no other slot).
236    pub fn update<R>(&self, ctx: &Context, f: impl FnOnce(&mut T) -> R) -> R
237    where
238        T: Default,
239    {
240        let id = self.id();
241        self.register(ctx, id);
242        guarded(self.name, || {
243            ctx.data_mut(|d| f(d.get_temp_mut_or_default::<T>(id)))
244        })
245    }
246
247    fn register(&self, ctx: &Context, id: Id) {
248        let reg = registry(ctx);
249        let mut r = lock(&reg);
250        let e = r
251            .slots
252            .entry((self.name, TypeId::of::<T>()))
253            .or_insert_with(|| Entry::new::<T>(self.summary));
254        if self.key.is_some() {
255            e.keyed = true;
256            e.ids.insert(id);
257        } else {
258            e.context = true;
259        }
260    }
261
262    fn unregister(&self, ctx: &Context, id: Id) {
263        if self.key.is_none() {
264            return;
265        }
266        let reg = registry(ctx);
267        if let Some(e) = lock(&reg).slots.get_mut(&(self.name, TypeId::of::<T>())) {
268            e.ids.remove(&id);
269        }
270    }
271}
272
273fn base_id(name: &'static str) -> Id {
274    Id::unique(("egui_pop::slot", name))
275}
276
277/// A value's `Debug` form, on one line, cut at [`SUMMARY_MAX`].
278fn debug_summary<T: Debug>(v: &T) -> String {
279    let mut out = Bounded(String::new());
280    // Stops early (an error) once the summary is full.
281    let _ = write!(out, "{v:?}");
282    let mut s: String = out.0.split_whitespace().collect::<Vec<_>>().join(" ");
283    if s.chars().count() >= SUMMARY_MAX {
284        s = s.chars().take(SUMMARY_MAX - 1).collect();
285        s.push('…');
286    }
287    s
288}
289
290fn opaque_summary<T>(_: &T) -> String {
291    format!("<{}>", short_type_name::<T>())
292}
293
294/// A writer refusing more than a summary's length, so a large value is
295/// not formatted whole.
296struct Bounded(String);
297
298impl fmt::Write for Bounded {
299    fn write_str(&mut self, s: &str) -> fmt::Result {
300        // Bytes: at least as many as the characters kept.
301        let room = (4 * SUMMARY_MAX).saturating_sub(self.0.len());
302        if s.len() <= room {
303            self.0.push_str(s);
304            Ok(())
305        } else {
306            let mut end = room;
307            while !s.is_char_boundary(end) {
308                end -= 1;
309            }
310            self.0.push_str(&s[..end]);
311            Err(fmt::Error)
312        }
313    }
314}
315
316/// A type's name without its module paths.
317fn short_type_name<T>() -> String {
318    let full = std::any::type_name::<T>();
319    let mut out = String::with_capacity(full.len());
320    let mut word = String::new();
321    for c in full.chars() {
322        if c.is_alphanumeric() || c == '_' || c == ':' {
323            word.push(c);
324        } else {
325            out.push_str(word.rsplit("::").next().unwrap_or(&word));
326            word.clear();
327            out.push(c);
328        }
329    }
330    out.push_str(word.rsplit("::").next().unwrap_or(&word));
331    out
332}
333
334type Present = fn(&Context, Id) -> bool;
335type Summarise = Arc<dyn Fn(&Context, Id) -> Option<String> + Send + Sync>;
336
337/// What the registry knows of a slot.
338struct Entry {
339    type_name: String,
340    /// Written without a key.
341    context: bool,
342    /// Written with a key.
343    keyed: bool,
344    /// The keyed entries written and not removed.
345    ids: HashSet<Id>,
346    present: Present,
347    summarise: Summarise,
348}
349
350impl Entry {
351    fn new<T: Clone + Send + Sync + 'static>(summary: fn(&T) -> String) -> Self {
352        Self {
353            type_name: short_type_name::<T>(),
354            context: false,
355            keyed: false,
356            ids: HashSet::new(),
357            present: |ctx, id| {
358                let raw = RawKey::new::<T>(id);
359                ctx.data(|d| d.get_temp_raw(raw).is_some())
360            },
361            // Cloned out, then formatted outside egui's lock.
362            summarise: Arc::new(move |ctx, id| {
363                let v = ctx.data(|d| d.get_temp::<T>(id));
364                v.map(|v| summary(&v))
365            }),
366        }
367    }
368}
369
370#[derive(Default)]
371struct Registry {
372    slots: BTreeMap<(&'static str, TypeId), Entry>,
373}
374
375fn registry(ctx: &Context) -> Arc<Mutex<Registry>> {
376    let id = Id::unique("egui_pop::slot::registry");
377    guarded("registry", || {
378        ctx.data_mut(|d| {
379            d.get_temp_mut_or_insert_with(id, || Arc::new(Mutex::new(Registry::default())))
380                .clone()
381        })
382    })
383}
384
385/// A slot as the debug bridge reports it.
386#[derive(Clone, Debug, PartialEq, Serialize)]
387pub struct SlotReport {
388    pub name: String,
389    #[serde(rename = "type")]
390    pub type_name: String,
391    pub scope: Scope,
392    /// Values held: 0 or 1 per context, one per key per instance.
393    pub entries: usize,
394    /// The first values' summaries (the value's, per context).
395    pub summaries: Vec<String>,
396}
397
398/// Every slot written in a context, by name, with its entries still
399/// held (keys removed since are forgotten). At most `samples`
400/// summaries per slot.
401pub fn report(ctx: &Context, samples: usize) -> Vec<SlotReport> {
402    // Copied out of the registry: reading values takes egui's lock, and
403    // a summary may lock what it summarises.
404    struct Seen {
405        name: &'static str,
406        type_id: TypeId,
407        type_name: String,
408        context: bool,
409        keyed: bool,
410        ids: Vec<Id>,
411        present: Present,
412        summarise: Summarise,
413    }
414    let reg = registry(ctx);
415    let seen: Vec<Seen> = lock(&reg)
416        .slots
417        .iter()
418        .map(|((name, type_id), e)| Seen {
419            name,
420            type_id: *type_id,
421            type_name: e.type_name.clone(),
422            context: e.context,
423            keyed: e.keyed,
424            ids: e.ids.iter().copied().collect(),
425            present: e.present,
426            summarise: e.summarise.clone(),
427        })
428        .collect();
429    let mut out = Vec::new();
430    for s in seen {
431        if s.context {
432            let base = base_id(s.name);
433            let held = (s.present)(ctx, base);
434            let summaries = if held && samples > 0 {
435                (s.summarise)(ctx, base).into_iter().collect()
436            } else {
437                Vec::new()
438            };
439            out.push(SlotReport {
440                name: s.name.into(),
441                type_name: s.type_name.clone(),
442                scope: Scope::Context,
443                entries: usize::from(held),
444                summaries,
445            });
446        }
447        if s.keyed {
448            let (mut held, gone): (Vec<Id>, Vec<Id>) =
449                s.ids.into_iter().partition(|id| (s.present)(ctx, *id));
450            if !gone.is_empty()
451                && let Some(e) = lock(&reg).slots.get_mut(&(s.name, s.type_id))
452            {
453                for id in &gone {
454                    e.ids.remove(id);
455                }
456            }
457            held.sort_by_key(Id::value);
458            let summaries = held
459                .iter()
460                .take(samples)
461                .filter_map(|id| (s.summarise)(ctx, *id))
462                .collect();
463            out.push(SlotReport {
464                name: s.name.into(),
465                type_name: s.type_name,
466                scope: Scope::Instance,
467                entries: held.len(),
468                summaries,
469            });
470        }
471    }
472    out
473}
474
475/// Shared state of type `T` in a context, created on first use.
476pub(crate) fn shared<T: Default + Debug + Send + 'static>(
477    ctx: &Context,
478    name: &'static str,
479) -> Arc<Mutex<T>> {
480    Slot::<Shared<T>>::new(name)
481        .get_or_insert_with(ctx, || Shared(Arc::new(Mutex::new(T::default()))))
482        .0
483}
484
485/// Shared state of type `T` for the window being drawn (egui's current
486/// viewport), created on first use: the main window's is [`shared`]'s,
487/// each other window has its own (the focus chain, the overlay stack:
488/// egui keeps focus and modals per window, and each window counts its
489/// own passes).
490pub(crate) fn shared_in_window<T: Default + Debug + Send + 'static>(
491    ctx: &Context,
492    name: &'static str,
493) -> Arc<Mutex<T>> {
494    let viewport = ctx.viewport_id();
495    shared_of_window(ctx, name, viewport)
496}
497
498/// A window's shared state of type `T` (see [`shared_in_window`]).
499pub(crate) fn shared_of_window<T: Default + Debug + Send + 'static>(
500    ctx: &Context,
501    name: &'static str,
502    viewport: egui::ViewportId,
503) -> Arc<Mutex<T>> {
504    if viewport == egui::ViewportId::ROOT {
505        return shared(ctx, name);
506    }
507    Slot::<Shared<T>>::new(name)
508        .keyed(viewport)
509        .get_or_insert_with(ctx, || Shared(Arc::new(Mutex::new(T::default()))))
510        .0
511}
512
513/// Forgets a window's shared state of type `T` (the window closed); the
514/// main window's is kept.
515pub(crate) fn forget_window<T: Debug + Send + 'static>(
516    ctx: &Context,
517    name: &'static str,
518    viewport: egui::ViewportId,
519) {
520    if viewport != egui::ViewportId::ROOT {
521        Slot::<Shared<T>>::new(name).keyed(viewport).remove(ctx);
522    }
523}
524
525/// A shared value, summarised by what it holds.
526struct Shared<T>(Arc<Mutex<T>>);
527
528impl<T> Clone for Shared<T> {
529    fn clone(&self) -> Self {
530        Self(self.0.clone())
531    }
532}
533
534impl<T: Debug> Debug for Shared<T> {
535    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536        match self.0.try_lock() {
537            Ok(v) => v.fmt(f),
538            Err(TryLockError::Poisoned(p)) => p.into_inner().fmt(f),
539            Err(TryLockError::WouldBlock) => f.write_str("<in use>"),
540        }
541    }
542}
543
544/// The pass being drawn.
545pub(crate) fn pass(ctx: &Context) -> u64 {
546    ctx.cumulative_pass_nr()
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    const COUNT: Slot<u32> = Slot::new("test.count");
554    const TEXT: Slot<String> = Slot::new("test.text");
555
556    #[test]
557    fn per_context_and_per_instance_values_are_apart() {
558        let ctx = Context::default();
559        assert_eq!(COUNT.get(&ctx), None);
560        COUNT.set(&ctx, 3);
561        COUNT.keyed(1).set(&ctx, 10);
562        COUNT.keyed(2).set(&ctx, 20);
563        assert_eq!(COUNT.get(&ctx), Some(3));
564        assert_eq!(COUNT.keyed(1).get(&ctx), Some(10));
565        assert_eq!(COUNT.update(&ctx, |n| std::mem::replace(n, 4)), 3);
566        assert_eq!(COUNT.remove(&ctx), Some(4));
567        assert!(!COUNT.exists(&ctx));
568        assert_eq!(COUNT.keyed(2).remove(&ctx), Some(20));
569    }
570
571    #[test]
572    fn the_report_counts_held_entries_and_summarises_them() {
573        let ctx = Context::default();
574        TEXT.set(&ctx, "x".repeat(1000));
575        for k in 0..5 {
576            COUNT.keyed(k).set(&ctx, k);
577        }
578        COUNT.keyed(0).remove(&ctx);
579        // Removed behind the slot's back: forgotten by the next report.
580        let gone = COUNT.keyed(1).id();
581        ctx.data_mut(|d| d.remove::<u32>(gone));
582        let r = report(&ctx, 2);
583        let count = r.iter().find(|s| s.name == "test.count").unwrap();
584        assert_eq!((count.scope, count.entries), (Scope::Instance, 3));
585        assert_eq!(count.summaries.len(), 2);
586        assert_eq!(count.type_name, "u32");
587        let text = r.iter().find(|s| s.name == "test.text").unwrap();
588        assert_eq!((text.scope, text.entries), (Scope::Context, 1));
589        assert_eq!(text.summaries[0].chars().count(), SUMMARY_MAX);
590        assert!(text.summaries[0].ends_with('…'));
591    }
592
593    #[test]
594    fn opaque_values_are_summarised_by_their_type() {
595        let ctx = Context::default();
596        let s: Slot<Arc<dyn Fn() + Send + Sync>> = Slot::opaque("test.opaque");
597        s.set(&ctx, Arc::new(|| {}));
598        let r = report(&ctx, 1);
599        let o = r.iter().find(|s| s.name == "test.opaque").unwrap();
600        assert_eq!(o.summaries, ["<Arc<dyn Fn() + Send + Sync>>"]);
601    }
602
603    #[test]
604    fn the_debug_bridge_lists_the_slots() {
605        let ctx = Context::default();
606        COUNT.keyed("a").set(&ctx, 1);
607        let mut bridge = crate::debug::DebugBridge::with_core_collectors();
608        let snap = bridge.snapshot_of(&ctx, "state").unwrap();
609        let slot = snap["slots"]
610            .as_array()
611            .unwrap()
612            .iter()
613            .find(|s| s["name"] == "test.count")
614            .unwrap();
615        assert_eq!(slot["scope"], "instance");
616        assert_eq!(slot["entries"], 1);
617        let f = bridge.call(
618            &ctx,
619            "state",
620            "slot",
621            &serde_json::json!({ "name": "test.count" }),
622        );
623        assert!(f.ok && !f.mutates, "{}", f.message);
624        assert_eq!(f.data[0]["summaries"][0], "1");
625        let f = bridge.call(
626            &ctx,
627            "state",
628            "slot",
629            &serde_json::json!({ "name": "nothing" }),
630        );
631        assert!(!f.ok);
632    }
633
634    #[test]
635    #[should_panic(expected = "touched inside slot `test.count`")]
636    fn a_slot_inside_another_s_closure_panics_instead_of_deadlocking() {
637        let ctx = Context::default();
638        COUNT.update(&ctx, |_| TEXT.get(&ctx));
639    }
640}