use crate::*;
pub(crate) fn register(ctx: &Context) {
ctx.on_end_frame("debug_text", std::sync::Arc::new(State::end_frame));
}
#[track_caller]
pub fn print(ctx: &Context, text: impl Into<WidgetText>) {
if !cfg!(debug_assertions) {
return;
}
let location = std::panic::Location::caller();
let location = format!("{}:{}", location.file(), location.line());
ctx.data_mut(|data| {
let state = data.get_temp_mut_or_default::<State>(Id::NULL);
state.entries.push(Entry {
location,
text: text.into(),
});
});
}
#[derive(Clone)]
struct Entry {
location: String,
text: WidgetText,
}
#[derive(Clone, Default)]
struct State {
entries: Vec<Entry>,
}
impl State {
fn end_frame(ctx: &Context) {
let state = ctx.data_mut(|data| data.remove_temp::<Self>(Id::NULL));
if let Some(state) = state {
state.paint(ctx);
}
}
fn paint(self, ctx: &Context) {
let Self { entries } = self;
if entries.is_empty() {
return;
}
let mut pos = ctx
.input(|i| i.pointer.latest_pos())
.unwrap_or_else(|| ctx.screen_rect().center())
+ 8.0 * Vec2::Y;
let painter = ctx.debug_painter();
let where_to_put_background = painter.add(Shape::Noop);
let mut bounding_rect = Rect::from_points(&[pos]);
let color = Color32::GRAY;
let font_id = FontId::new(10.0, FontFamily::Proportional);
for Entry { location, text } in entries {
{
let location_galley =
ctx.fonts(|f| f.layout(location, font_id.clone(), color, f32::INFINITY));
let location_rect =
Align2::RIGHT_TOP.anchor_size(pos - 4.0 * Vec2::X, location_galley.size());
painter.galley(location_rect.min, location_galley, color);
bounding_rect = bounding_rect.union(location_rect);
}
{
let wrap = true;
let available_width = ctx.screen_rect().max.x - pos.x;
let galley = text.into_galley_impl(
ctx,
&ctx.style(),
wrap,
available_width,
font_id.clone().into(),
Align::TOP,
);
let rect = Align2::LEFT_TOP.anchor_size(pos, galley.size());
painter.galley(rect.min, galley, color);
bounding_rect = bounding_rect.union(rect);
}
pos.y = bounding_rect.max.y + 4.0;
}
painter.set(
where_to_put_background,
Shape::rect_filled(
bounding_rect.expand(4.0),
2.0,
Color32::from_black_alpha(192),
),
);
}
}