Skip to main content

zaxis/context/
diagnostics.rs

1//! Usage diagnostics: problems in how the library is driven, found while the
2//! UI is built. Detection is free in steady state (it only records when
3//! something is wrong); reporting is a query on [`Context`], an optional
4//! handler, and an opt-in overlay. Nothing is logged or printed.
5
6use super::{Context, HitAction, HitRegion, Id};
7use crate::Rect;
8use std::{
9    cell::RefCell,
10    collections::HashSet,
11    hash::{Hash, Hasher},
12    panic::Location,
13};
14
15const MAX_PER_PASS: usize = 64;
16const MAX_REMEMBERED: usize = 1024;
17
18/// What went wrong. New kinds may be added.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum DiagnosticKind {
22    /// Two interactive widgets used the same [`Id`] in one pass.
23    IdCollision,
24    /// A scope (scroll area, placement, visual group) was left open at the end of a pass.
25    UnbalancedScope,
26    /// An interactive widget was given an empty or non-finite rect.
27    NoLayoutSpace,
28    /// A popup had a non-finite anchor or no room to open.
29    PopupWithoutAnchor,
30    /// A builder argument was out of range and was replaced by a valid value.
31    InvalidValue,
32    /// A data model passed to a component is inconsistent, for example a tree cycle.
33    InvalidModel,
34    /// An API contract was broken and the call was made harmless, for example an
35    /// extra Grid cell or an unknown panel id.
36    InvalidUsage,
37    /// A control that a screen reader announces by name has none. Found while the
38    /// accessibility tree is collected; see `Context::set_accessibility_active`.
39    MissingAccessibleName,
40    /// A material was rejected: invalid WGSL, a parameter schema that does not fit, or too
41    /// many materials. Draws with it use their fallback.
42    InvalidShader,
43    /// A system resource failed and the app would otherwise never know: the
44    /// clipboard, a native window drag or resize, an image that could not be decoded.
45    External,
46}
47
48/// One usage problem. `rect` is where it happened when that is known.
49#[derive(Clone, Debug, PartialEq)]
50pub struct Diagnostic {
51    pub kind: DiagnosticKind,
52    pub id: Option<Id>,
53    pub rect: Option<Rect>,
54    pub message: String,
55}
56
57/// Debug drawing above all layers; everything is off by default and costs
58/// nothing while off. Enabling it never changes layout, hit testing or the
59/// geometry cache of the application's own elements.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub struct DebugOverlay {
62    /// A frame and a short message on the rect of every current diagnostic.
63    pub issues: bool,
64    /// Bounds of the topmost hit region under the cursor.
65    pub bounds: bool,
66    /// Clip rectangle of that region.
67    pub clip: bool,
68    /// Every hit region under the cursor, with its kind.
69    pub hits: bool,
70}
71
72impl DebugOverlay {
73    pub const OFF: Self = Self {
74        issues: false,
75        bounds: false,
76        clip: false,
77        hits: false,
78    };
79    pub const ISSUES: Self = Self {
80        issues: true,
81        ..Self::OFF
82    };
83    pub const ALL: Self = Self {
84        issues: true,
85        bounds: true,
86        clip: true,
87        hits: true,
88    };
89    pub(crate) fn active(self) -> bool {
90        self != Self::OFF
91    }
92}
93
94type Handler = Box<dyn FnMut(&Diagnostic)>;
95
96#[derive(Default)]
97pub(crate) struct Diagnostics {
98    current: Vec<Diagnostic>,
99    pub(super) published: Vec<Diagnostic>,
100    remembered: HashSet<u64>,
101    handler: Option<Handler>,
102    pub(super) overlay: DebugOverlay,
103}
104
105struct Invalid {
106    what: &'static str,
107    detail: String,
108    at: &'static Location<'static>,
109}
110thread_local! {
111    static INVALID: RefCell<Vec<Invalid>> = const { RefCell::new(Vec::new()) };
112}
113
114/// Record a builder argument that was replaced; delivered by the next pass.
115#[track_caller]
116pub(crate) fn invalid_value(what: &'static str, detail: String) {
117    let at = Location::caller();
118    INVALID.with(|list| {
119        let mut list = list.borrow_mut();
120        if list.len() < MAX_PER_PASS {
121            list.push(Invalid { what, detail, at });
122        }
123    });
124}
125
126impl Context {
127    /// Problems found during the last completed pass. Empty when the UI is
128    /// used correctly. Out-of-range builder values appear here too, for as
129    /// long as they are still passed in.
130    pub fn diagnostics(&self) -> &[Diagnostic] {
131        &self.diagnostics.published
132    }
133
134    /// Called once for each distinct problem, the first time it is seen, so a
135    /// misconfigured widget does not report every frame. Replaces the previous handler.
136    pub fn set_diagnostic_handler(&mut self, handler: Option<Handler>) {
137        self.diagnostics.handler = handler;
138    }
139
140    pub fn set_debug_overlay(&mut self, overlay: DebugOverlay) {
141        if self.diagnostics.overlay != overlay {
142            self.diagnostics.overlay = overlay;
143            self.request_repaint();
144        }
145    }
146
147    pub fn debug_overlay(&self) -> DebugOverlay {
148        self.diagnostics.overlay
149    }
150
151    pub(crate) fn report(
152        &mut self,
153        kind: DiagnosticKind,
154        id: Option<Id>,
155        rect: Option<Rect>,
156        message: impl FnOnce() -> String,
157    ) {
158        let list = &mut self.diagnostics.current;
159        if list.len() >= MAX_PER_PASS
160            || list
161                .iter()
162                .any(|d| d.kind == kind && d.id == id && id.is_some())
163        {
164            return;
165        }
166        list.push(Diagnostic {
167            kind,
168            id,
169            rect,
170            message: message(),
171        });
172    }
173
174    /// Final hit regions of controls that were laid out with no area. Measuring
175    /// passes never reach this list, so only widgets that really stayed empty show up.
176    pub(super) fn report_empty_hits(&mut self) {
177        let mut empty = Vec::new();
178        for hit in &self.interaction.hits {
179            let interactive = !matches!(
180                hit.action,
181                HitAction::Block
182                    | HitAction::ContextMenu
183                    | HitAction::Move
184                    | HitAction::Resize
185                    | HitAction::Semantic
186            );
187            if interactive && (hit.rect.is_empty() || !hit.rect.is_finite()) {
188                empty.push((hit.id, hit.rect));
189            }
190        }
191        for (id, rect) in empty {
192            self.report(DiagnosticKind::NoLayoutSpace, Some(id), Some(rect), || {
193                "no layout space: the widget rect is empty".into()
194            });
195        }
196    }
197
198    /// Two painted elements share an ID. A widget collision already reported through
199    /// its hit region collides in its parts too, so those add nothing.
200    pub(super) fn report_paint_collision(&mut self, id: Id) {
201        if !self
202            .diagnostics
203            .current
204            .iter()
205            .any(|d| d.kind == DiagnosticKind::IdCollision)
206        {
207            self.report(DiagnosticKind::IdCollision, Some(id), None, || {
208                "duplicate id: use Ui::push_id or an explicit id_source".into()
209            });
210        }
211    }
212
213    pub(super) fn note_hit_collision(&mut self, hit: &HitRegion) {
214        self.report(
215            DiagnosticKind::IdCollision,
216            Some(hit.id),
217            Some(hit.rect),
218            || "duplicate id: give each widget a unique id_source or push_id scope".into(),
219        );
220    }
221
222    /// End of pass: collect builder reports, check scopes, publish, notify, draw.
223    pub(super) fn finish_diagnostics(&mut self) {
224        self.report_empty_hits();
225        INVALID.with(|list| {
226            for item in list.borrow_mut().drain(..) {
227                let message = format!(
228                    "{}: {} ({}:{})",
229                    item.what,
230                    item.detail,
231                    item.at.file(),
232                    item.at.line()
233                );
234                let mut hasher = std::collections::hash_map::DefaultHasher::new();
235                (item.what, item.at.file(), item.at.line(), item.at.column()).hash(&mut hasher);
236                self.report(
237                    DiagnosticKind::InvalidValue,
238                    Some(Id::new(hasher.finish())),
239                    None,
240                    || message,
241                );
242            }
243        });
244        if !self.scrolling.stack.is_empty()
245            || !self.placements.stack.is_empty()
246            || self.placements.outstanding > 0
247            || self.visuals.depth > 0
248            || !self.visuals.clips.is_empty()
249        {
250            self.report(DiagnosticKind::UnbalancedScope, None, None, || {
251                "scope left open at the end of the pass; its closure did not return".into()
252            });
253            self.scrolling.stack.clear();
254            self.placements.stack.clear();
255            self.placements.outstanding = 0;
256            self.visuals.depth = 0;
257            self.visuals.clips.clear();
258        }
259        let diagnostics = &mut self.diagnostics;
260        std::mem::swap(&mut diagnostics.published, &mut diagnostics.current);
261        diagnostics.current.clear();
262        if !diagnostics.published.is_empty() {
263            if let Some(handler) = diagnostics.handler.as_mut() {
264                if diagnostics.remembered.len() > MAX_REMEMBERED {
265                    diagnostics.remembered.clear();
266                }
267                for diagnostic in &diagnostics.published {
268                    let mut hasher = std::collections::hash_map::DefaultHasher::new();
269                    (diagnostic.kind, diagnostic.id, &diagnostic.message).hash(&mut hasher);
270                    if diagnostics.remembered.insert(hasher.finish()) {
271                        handler(diagnostic);
272                    }
273                }
274            }
275        }
276        if self.diagnostics.overlay.active() {
277            self.paint_debug_overlay();
278        }
279    }
280}