use std::fmt::{self, Write};
use nadir_core::{Color, FastHashSet, Handle, Rect, UVec2, Vec2};
use nadir_render::{
Font, SortMode, SpriteDraw, TextDraw, Texture, UiList, UiScale, UiSpace, UiView,
};
use crate::edit::Caret;
use crate::id::{Id, split};
use crate::input::{DebugInput, Taken};
use crate::{Style, TextMetrics, Ui};
const LAYER: u8 = u8::MAX;
const ROWS_A_LINE: f32 = 3.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Chrome {
Collapse,
Grip,
Thumb,
Bar,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Geometry {
rect: Rect,
bar: Rect,
collapse: Rect,
drag: Rect,
view: Rect,
track: Rect,
grip: Rect,
scrollable: bool,
range: f32,
thumb_height: f32,
room: f32,
}
impl Geometry {
fn thumb(&self, scroll: f32) -> Rect {
let share = if self.range > 0.0 {
scroll / self.range
} else {
0.0
};
Rect::from_min_size(
Vec2::new(self.track.min.x, self.track.min.y + share * self.room),
Vec2::new(self.track.width(), self.thumb_height),
)
}
}
impl Chrome {
fn geometry(rect: Rect, row: f32, size: f32, content: f32) -> Geometry {
let bar = Rect::new(rect.min, Vec2::new(rect.max.x, rect.min.y + row));
let collapse = Rect::from_min_size(rect.min, Vec2::splat(row));
let view = Rect::new(Vec2::new(rect.min.x, bar.max.y), rect.max);
let track = Rect::new(
Vec2::new(rect.max.x - size, bar.max.y),
Vec2::new(rect.max.x, rect.max.y - size),
);
let scrollable = content > view.height();
let thumb_height = if scrollable {
(view.height() / content * track.height()).max(size)
} else {
0.0
};
Geometry {
rect,
bar,
collapse,
drag: Rect::new(Vec2::new(collapse.max.x, bar.min.y), bar.max),
view,
track,
grip: Rect::new(rect.max - Vec2::splat(size), rect.max),
scrollable,
range: (content - view.height()).max(0.0),
thumb_height,
room: (track.height() - thumb_height).max(0.0),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Part {
clip: Rect,
left: f32,
width: f32,
top: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Layer {
Window(Id),
Popup,
}
#[derive(Clone, Debug, PartialEq)]
struct WindowState {
id: Id,
key: String,
rect: Rect,
collapsed: bool,
scroll: f32,
content: f32,
drawn: bool,
shown: bool,
hit: Rect,
next_y: f32,
part: Option<Part>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Active {
pub(crate) id: Id,
pub(crate) seen: bool,
pub(crate) from: Vec2,
pub(crate) last: Vec2,
pub(crate) start: Rect,
pub(crate) start_value: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Focus {
pub(crate) id: Id,
pub(crate) seen: bool,
pub(crate) caret: Caret,
pub(crate) scroll: f32,
pub(crate) len: usize,
pub(crate) hash: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Popup {
pub(crate) id: Id,
pub(crate) seen: bool,
pub(crate) anchor: Rect,
pub(crate) rect: Rect,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Owner {
Nobody,
Ui,
Game,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Shape {
Rect {
rect: Rect,
color: Color,
},
Title {
rect: Rect,
},
Text {
at: Vec2,
start: u32,
end: u32,
color: Color,
},
Line {
from: Vec2,
to: Vec2,
color: Color,
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Cmd {
layer: Layer,
clip: Rect,
shape: Shape,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Interaction {
pub(crate) hovered: bool,
pub(crate) pressed: bool,
pub(crate) held: bool,
pub(crate) released: bool,
pub(crate) clicked: bool,
}
pub struct DebugUi {
pub(crate) style: Style,
font: Handle<Font>,
white: Handle<Texture>,
pub(crate) metrics: Box<dyn TextMetrics>,
windows: Vec<WindowState>,
pub(crate) active: Option<Active>,
pub(crate) focus: Option<Focus>,
pub(crate) lost: Option<Id>,
pub(crate) focus_next: bool,
pub(crate) open: FastHashSet<Id>,
pub(crate) popup: Option<Popup>,
owner: Owner,
drawn_any: bool,
wants_mouse: bool,
wants_keyboard: bool,
revision: u64,
pub(crate) frames: u64,
pub(crate) space: UiSpace,
pub(crate) input: Taken,
pub(crate) pointer: Vec2,
pub(crate) press: Option<Vec2>,
pub(crate) release: Option<(Vec2, bool)>,
pub(crate) down: bool,
hover_layer: Option<Layer>,
press_layer: Option<Layer>,
cmds: Vec<Cmd>,
pub(crate) text: String,
scratch: String,
order: Vec<(u32, u32)>,
pub(crate) values: Vec<f32>,
}
impl DebugUi {
pub fn new(
font: Handle<Font>,
metrics: impl TextMetrics + 'static,
white: Handle<Texture>,
) -> Self {
Self {
style: Style::default(),
font,
white,
metrics: Box::new(metrics),
windows: Vec::new(),
active: None,
focus: None,
lost: None,
focus_next: false,
open: FastHashSet::default(),
popup: None,
owner: Owner::Nobody,
drawn_any: false,
wants_mouse: false,
wants_keyboard: false,
frames: 0,
revision: 0,
space: UiSpace::new(UiScale::Free(1.0), UVec2::ONE, UVec2::ZERO),
input: Taken::default(),
pointer: Vec2::ZERO,
press: None,
release: None,
down: false,
hover_layer: None,
press_layer: None,
cmds: Vec::new(),
text: String::new(),
scratch: String::new(),
order: Vec::new(),
values: Vec::new(),
}
}
pub fn set_font(&mut self, font: Handle<Font>, metrics: impl TextMetrics + 'static) {
self.font = font;
self.metrics = Box::new(metrics);
}
pub fn style(&self) -> &Style {
&self.style
}
pub fn style_mut(&mut self) -> &mut Style {
&mut self.style
}
pub fn wants_mouse(&self) -> bool {
self.wants_mouse
}
pub fn is_over(&self, at: Vec2) -> bool {
self.layer_at(self.space.to_ui(at)).is_some()
}
pub fn wants_keyboard(&self) -> bool {
self.wants_keyboard
}
pub fn places(&self) -> impl ExactSizeIterator<Item = WindowPlace<'_>> + '_ {
self.windows.iter().map(|window| WindowPlace {
title: &window.key,
rect: window.rect,
collapsed: window.collapsed,
})
}
pub fn set_place(&mut self, title: &str, rect: Rect, collapsed: bool) {
let finite = [rect.min.x, rect.min.y, rect.max.x, rect.max.y]
.iter()
.all(|v| v.is_finite());
if !finite {
return;
}
let (_, key) = split(title);
let rect = Rect::from_min_size(rect.min, rect.size().max(self.style.min_size));
let index = self.window_index(Id::ROOT.with(key), key, rect);
let window = &mut self.windows[index];
window.rect = rect;
window.collapsed = collapsed;
}
pub fn places_revision(&self) -> u64 {
self.revision
}
pub fn frame(
&mut self,
input: &mut DebugInput,
virtual_resolution: UVec2,
output_size: UVec2,
) -> Frame<'_> {
input.take(&mut self.input);
self.frames += 1;
let space = UiSpace::new(self.style.scale, virtual_resolution, output_size);
self.space = space;
self.pointer = space.to_ui(self.input.pointer);
self.press = self.input.press.map(|at| space.to_ui(at));
self.release = self
.input
.release
.map(|(at, cancelled)| (space.to_ui(at), cancelled));
self.down = self.input.down;
self.cmds.clear();
self.text.clear();
for window in &mut self.windows {
window.shown = false;
}
if let Some(active) = &mut self.active {
active.seen = false;
}
if let Some(focus) = &mut self.focus {
focus.seen = false;
}
if let Some(popup) = &mut self.popup {
popup.seen = false;
}
self.hover_layer = self.layer_at(self.pointer);
self.press_layer = None;
if let Some(at) = self.press {
let layer = self.layer_at(at);
self.press_layer = layer;
self.owner = if layer.is_some() {
Owner::Ui
} else {
Owner::Game
};
if self
.popup
.is_some_and(|popup| !popup.rect.contains(at) && !popup.anchor.contains(at))
{
self.popup = None;
}
if let Some(Layer::Window(id)) = layer {
self.bring_to_front(id);
}
}
if self.owner == Owner::Game {
self.hover_layer = None;
self.press_layer = None;
}
Frame { ui: self }
}
fn layer_at(&self, at: Vec2) -> Option<Layer> {
if self.popup.is_some_and(|popup| popup.rect.contains(at)) {
return Some(Layer::Popup);
}
self.windows
.iter()
.rev()
.find(|window| window.drawn && window.hit.contains(at))
.map(|window| Layer::Window(window.id))
}
fn bring_to_front(&mut self, id: Id) {
if let Some(index) = self.windows.iter().position(|window| window.id == id) {
let window = self.windows.remove(index);
self.windows.push(window);
}
}
fn window_index(&mut self, id: Id, key: &str, rect: Rect) -> usize {
if let Some(index) = self.windows.iter().position(|window| window.id == id) {
return index;
}
self.windows.push(WindowState {
id,
key: key.to_string(),
rect,
collapsed: false,
scroll: 0.0,
content: 0.0,
drawn: false,
shown: false,
hit: Rect::default(),
next_y: 0.0,
part: None,
});
self.windows.len() - 1
}
pub(crate) fn row_height(&self) -> f32 {
self.metrics.line_height() + 2.0 * self.style.padding
}
pub(crate) fn width(&self, text: &str) -> f32 {
self.metrics.caret_x(text, text.len())
}
pub(crate) fn interact(&mut self, layer: Layer, clip: Rect, id: Id, rect: Rect) -> Interaction {
let inside = |at: Vec2| rect.contains(at) && clip.contains(at);
let mut out = Interaction::default();
if let Some(active) = self.active.as_mut().filter(|active| active.id == id) {
active.seen = true;
}
let free = self.active.is_none_or(|active| active.id == id);
out.hovered = free && self.hover_layer == Some(layer) && inside(self.pointer);
if let Some(at) = self.press
&& self.active.is_none()
&& self.press_layer == Some(layer)
&& inside(at)
{
self.active = Some(Active {
id,
seen: true,
from: at,
last: at,
start: Rect::default(),
start_value: 0.0,
});
out.pressed = true;
}
if self.active.is_some_and(|active| active.id == id) {
out.held = true;
if let Some((at, cancelled)) = self.release {
out.released = true;
out.clicked = !cancelled && inside(at);
}
}
out
}
pub(crate) fn wheel_over(&self, layer: Layer, clip: Rect, rect: Rect) -> f32 {
let at = self.pointer;
if self.hover_layer == Some(layer) && rect.contains(at) && clip.contains(at) {
self.input.wheel.y
} else {
0.0
}
}
pub(crate) fn active_mut(&mut self, id: Id) -> Option<&mut Active> {
self.active.as_mut().filter(|active| active.id == id)
}
pub(crate) fn rect(&mut self, layer: Layer, clip: Rect, rect: Rect, color: Color) {
self.push(layer, clip, Shape::Rect { rect, color });
}
pub(crate) fn text_at(
&mut self,
layer: Layer,
clip: Rect,
at: Vec2,
(start, end): (u32, u32),
color: Color,
) {
self.push(
layer,
clip,
Shape::Text {
at,
start,
end,
color,
},
);
}
pub(crate) fn line(&mut self, layer: Layer, clip: Rect, from: Vec2, to: Vec2, color: Color) {
self.push(layer, clip, Shape::Line { from, to, color });
}
pub(crate) fn push(&mut self, layer: Layer, clip: Rect, shape: Shape) {
if !clip.is_empty() {
self.cmds.push(Cmd { layer, clip, shape });
}
}
pub(crate) fn format(&mut self, text: impl fmt::Display) -> (u32, u32) {
let start = self.text.len() as u32;
if write!(self.text, "{text}").is_err() {
self.text.truncate(start as usize);
}
(start, self.text.len() as u32)
}
pub(crate) fn text(&self, (start, end): (u32, u32)) -> &str {
&self.text[start as usize..end as usize]
}
fn emit(&mut self, out: &mut UiList) {
self.order.clear();
let z = |layer: Layer, windows: &[WindowState]| match layer {
Layer::Popup => u32::MAX,
Layer::Window(id) => windows
.iter()
.position(|window| window.id == id)
.map_or(0, |index| index as u32),
};
for (seq, cmd) in (0u32..).zip(&self.cmds) {
self.order.push((z(cmd.layer, &self.windows), seq));
}
self.order.sort_unstable();
let front = self
.windows
.iter()
.rev()
.find(|window| window.shown)
.map(|window| Layer::Window(window.id));
let before = out.view();
let base = UiView::new(self.style.scale);
let mut clip = None;
for &(_, seq) in &self.order {
let cmd = self.cmds[seq as usize];
if clip != Some(cmd.clip) {
out.set_view(base.clipped(cmd.clip));
clip = Some(cmd.clip);
}
match cmd.shape {
Shape::Rect { rect, color } => {
out.sprite(self.sprite(rect.min, rect.size(), color));
}
Shape::Title { rect } => {
let color = if front == Some(cmd.layer) {
self.style.title_front
} else {
self.style.title
};
out.sprite(self.sprite(rect.min, rect.size(), color));
}
Shape::Text {
at,
start,
end,
color,
} => {
let mut draw = TextDraw::new(self.font, at);
draw.layout.markup = false;
draw.color = color;
draw.layer = LAYER;
draw.sort = SortMode::Fixed(u32::MAX);
out.text(draw, &self.text[start as usize..end as usize]);
}
Shape::Line { from, to, color } => {
let along = to - from;
let length = along.length();
if length > 0.0 && length.is_finite() {
let mut sprite = self.sprite(from, Vec2::new(length, 1.0), color);
sprite.pivot = Vec2::new(0.0, 0.5);
sprite.rotation = along.y.atan2(along.x);
out.sprite(sprite);
}
}
}
}
out.set_view(before);
}
fn sprite(&self, at: Vec2, size: Vec2, color: Color) -> SpriteDraw {
let mut sprite = SpriteDraw::new(self.white, at, size);
sprite.pivot = Vec2::ZERO;
sprite.color = color;
sprite.layer = LAYER;
sprite.sort = SortMode::Fixed(u32::MAX);
sprite
}
fn end(&mut self) {
if self.release.is_some() || self.active.is_some_and(|active| !active.seen) {
self.active = None;
}
if self.focus.is_some_and(|focus| !focus.seen) {
self.focus = None;
}
if self.popup.is_some_and(|popup| !popup.seen) {
self.popup = None;
}
for window in &mut self.windows {
window.drawn = window.shown;
}
self.drawn_any = self.windows.iter().any(|window| window.drawn);
let pointer = self.pointer;
let over = self.popup.is_some_and(|popup| popup.rect.contains(pointer))
|| self
.windows
.iter()
.any(|window| window.drawn && window.hit.contains(pointer));
self.wants_mouse = match self.owner {
Owner::Game => false,
Owner::Ui => true,
Owner::Nobody => over || self.active.is_some(),
};
self.wants_keyboard = self.focus.is_some();
if !self.down {
self.owner = Owner::Nobody;
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowPlace<'a> {
pub title: &'a str,
pub rect: Rect,
pub collapsed: bool,
}
pub struct Frame<'a> {
ui: &'a mut DebugUi,
}
impl Frame<'_> {
pub fn window(
&mut self,
title: impl fmt::Display,
first: Rect,
add: impl FnOnce(&mut Ui<'_>),
) -> bool {
let core = &mut *self.ui;
let screen = core.space.size;
if !(screen.x > 0.0 && screen.y > 0.0) {
return false;
}
core.scratch.clear();
let _ = write!(core.scratch, "{title}");
let scratch = std::mem::take(&mut core.scratch);
let (shown, key) = split(&scratch);
let id = Id::ROOT.with(key);
let first = sanitize(first, core.style.min_size);
let mut index = core.window_index(id, key, first);
let title_range = {
let start = core.text.len() as u32;
core.text.push_str(shown);
(start, core.text.len() as u32)
};
core.scratch = scratch;
let style = core.style;
let row = core.row_height();
let layer = Layer::Window(id);
if core.windows[index].shown {
let window = &core.windows[index];
let (collapsed, part, next_y) = (window.collapsed, window.part, window.next_y);
let Some(part) = part.filter(|_| !collapsed) else {
return !collapsed;
};
let mut ui = Ui::new(core, layer, id, part.clip, part.left, part.width, next_y);
add(&mut ui);
let end = ui.y();
let window = &mut core.windows[index];
window.next_y = end;
window.content = end - part.top + 2.0 * style.padding;
return true;
}
if !core.windows[index].drawn && core.drawn_any {
core.bring_to_front(id);
index = core.windows.len() - 1;
}
let (stored, mut collapsed, mut scroll, content) = {
let window = &core.windows[index];
(window.rect, window.collapsed, window.scroll, window.content)
};
let content = if content.is_finite() { content } else { 0.0 };
let size = style.scrollbar;
let was = Chrome::geometry(on_screen(stored, screen, row), row, size, content);
let mut place = stored;
let pointer = core.pointer;
let chrome = |part: Chrome| id.with(part);
if core
.interact(layer, was.rect, chrome(Chrome::Collapse), was.collapse)
.clicked
{
collapsed = !collapsed;
core.revision += 1;
}
if !collapsed {
let held = core.interact(layer, was.rect, chrome(Chrome::Grip), was.grip);
let mut start = None;
if let Some(active) = core.active_mut(chrome(Chrome::Grip)) {
if held.pressed {
active.start = was.rect;
}
let grown = (active.start.size() + pointer - active.from).max(style.min_size);
place = Rect::from_min_size(active.start.min, grown);
start = Some(active.start);
}
if held.released && start.is_some_and(|start| start != place) {
core.revision += 1;
}
if was.scrollable {
let thumb = was.thumb(scroll);
let held = core.interact(layer, was.rect, chrome(Chrome::Thumb), thumb);
if let Some(active) = core.active_mut(chrome(Chrome::Thumb)) {
if held.pressed {
active.start_value = scroll;
}
if was.room > 0.0 {
scroll =
active.start_value + (pointer.y - active.from.y) * was.range / was.room;
}
}
}
}
let held = core.interact(layer, was.rect, chrome(Chrome::Bar), was.drag);
let mut start = None;
if let Some(active) = core.active_mut(chrome(Chrome::Bar)) {
if held.pressed {
active.start = was.rect;
}
let moved = pointer - active.from;
place = Rect::new(active.start.min + moved, active.start.max + moved);
start = Some(active.start);
}
if held.released && start.is_some_and(|start| start != place) {
core.revision += 1;
}
if core.hover_layer == Some(layer) && was.view.contains(pointer) {
scroll -= core.input.wheel.y * ROWS_A_LINE * row;
}
let now = Chrome::geometry(on_screen(place, screen, row), row, size, content);
scroll = if scroll.is_nan() {
0.0
} else {
scroll.min(now.range).max(0.0)
};
if !collapsed {
core.rect(layer, now.rect, now.rect, style.panel);
}
core.push(layer, now.rect, Shape::Title { rect: now.bar });
let mark = core.format(if collapsed { "+" } else { "-" });
let mark_at =
now.collapse.min + Vec2::new((row - core.width(core.text(mark))) * 0.5, style.padding);
core.text_at(layer, now.collapse, mark_at, mark, style.text);
let title_at = Vec2::new(now.collapse.max.x, now.bar.min.y + style.padding);
core.text_at(layer, now.drag, title_at, title_range, style.text);
let mut part = None;
let mut next_y = 0.0;
let mut measured = content;
if !collapsed {
let width = if now.scrollable {
now.view.width() - size
} else {
now.view.width()
};
let clip =
Rect::from_min_size(now.view.min, Vec2::new(width.max(0.0), now.view.height()));
let laid = Part {
clip,
left: now.view.min.x + style.padding,
width: width - 2.0 * style.padding,
top: now.view.min.y + style.padding - scroll,
};
let mut ui = Ui::new(core, layer, id, laid.clip, laid.left, laid.width, laid.top);
add(&mut ui);
next_y = ui.y();
measured = next_y - laid.top + 2.0 * style.padding;
part = Some(laid);
if now.scrollable {
core.rect(layer, now.rect, now.track, style.dim);
core.rect(layer, now.rect, now.thumb(scroll), style.widget);
}
core.rect(layer, now.rect, now.grip, style.dim);
}
let window = &mut core.windows[index];
window.rect = place;
window.collapsed = collapsed;
window.scroll = scroll;
window.hit = if collapsed { now.bar } else { now.rect };
window.content = measured;
window.next_y = next_y;
window.part = part;
window.shown = true;
!collapsed
}
pub fn finish(self, out: &mut UiList) {
self.ui.emit(out);
}
}
impl Drop for Frame<'_> {
fn drop(&mut self) {
self.ui.end();
}
}
fn sanitize(rect: Rect, min: Vec2) -> Rect {
let finite = [rect.min.x, rect.min.y, rect.max.x, rect.max.y]
.iter()
.all(|v| v.is_finite());
let rect = if finite {
rect
} else {
Rect::from_min_size(Vec2::ZERO, min)
};
Rect::from_min_size(rect.min, rect.size().max(min))
}
fn on_screen(rect: Rect, screen: Vec2, bar: f32) -> Rect {
let size = rect.size();
let keep = (2.0 * bar).min(size.x);
let x = rect.min.x.max(keep - size.x).min(screen.x - keep);
let y = rect.min.y.min(screen.y - bar).max(0.0);
Rect::from_min_size(Vec2::new(x, y), size)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_window_is_kept_with_its_title_bar_on_screen() {
let screen = Vec2::new(100.0, 80.0);
let rect = |x: f32, y: f32| Rect::from_min_size(Vec2::new(x, y), Vec2::new(40.0, 30.0));
assert_eq!(on_screen(rect(10.0, 10.0), screen, 10.0), rect(10.0, 10.0));
assert_eq!(on_screen(rect(500.0, 10.0), screen, 10.0).min.x, 80.0);
assert_eq!(on_screen(rect(-500.0, 10.0), screen, 10.0).min.x, -20.0);
assert_eq!(on_screen(rect(10.0, 500.0), screen, 10.0).min.y, 70.0);
assert_eq!(on_screen(rect(10.0, -5.0), screen, 10.0).min.y, 0.0);
assert_eq!(
on_screen(rect(500.0, 500.0), screen, 10.0).size(),
Vec2::new(40.0, 30.0)
);
}
#[test]
fn a_rect_that_is_not_finite_or_too_small_is_made_a_window_s() {
let min = Vec2::new(60.0, 40.0);
let nan = Rect::new(Vec2::new(f32::NAN, 0.0), Vec2::ONE);
assert_eq!(sanitize(nan, min), Rect::from_min_size(Vec2::ZERO, min));
let small = Rect::from_min_size(Vec2::new(5.0, 5.0), Vec2::new(10.0, 100.0));
assert_eq!(sanitize(small, min).size(), Vec2::new(60.0, 100.0));
}
}