1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum DiagnosticKind {
22 IdCollision,
24 UnbalancedScope,
26 NoLayoutSpace,
28 PopupWithoutAnchor,
30 InvalidValue,
32 InvalidModel,
34 InvalidUsage,
37 MissingAccessibleName,
40 InvalidShader,
43 External,
46}
47
48#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub struct DebugOverlay {
62 pub issues: bool,
64 pub bounds: bool,
66 pub clip: bool,
68 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#[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 pub fn diagnostics(&self) -> &[Diagnostic] {
131 &self.diagnostics.published
132 }
133
134 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 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 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 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}