1use 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
46pub fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
49 m.lock().unwrap_or_else(PoisonError::into_inner)
50}
51
52pub const SUMMARY_MAX: usize = 160;
54
55pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
86#[serde(rename_all = "lowercase")]
87pub enum Scope {
88 Context,
90 Instance,
92}
93
94thread_local! {
95 static LOCKED: Cell<Option<&'static str>> = const { Cell::new(None) };
97}
98
99fn 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 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 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 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 pub fn keyed(self, key: impl Hash + Debug) -> Self {
157 Self {
158 key: Some(Id::unique(key)),
159 ..self
160 }
161 }
162
163 pub fn name(&self) -> &'static str {
165 self.name
166 }
167
168 pub fn scope(&self) -> Scope {
170 if self.key.is_some() {
171 Scope::Instance
172 } else {
173 Scope::Context
174 }
175 }
176
177 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 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 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 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 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 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 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 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(®);
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(®).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
277fn debug_summary<T: Debug>(v: &T) -> String {
279 let mut out = Bounded(String::new());
280 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
294struct Bounded(String);
297
298impl fmt::Write for Bounded {
299 fn write_str(&mut self, s: &str) -> fmt::Result {
300 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
316fn 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
337struct Entry {
339 type_name: String,
340 context: bool,
342 keyed: bool,
344 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 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#[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 pub entries: usize,
394 pub summaries: Vec<String>,
396}
397
398pub fn report(ctx: &Context, samples: usize) -> Vec<SlotReport> {
402 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(®)
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(®).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
475pub(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
485pub(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
498pub(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
513pub(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
525struct 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
544pub(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 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}