Skip to main content

egui_pop_fit/
dump.rs

1//! A plain-text picture of a layout, for snapshot tests and debugging.
2
3use crate::layout::{Layout, Status};
4use core::fmt::Write;
5
6const LABELS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
7
8fn label(logical: usize) -> char {
9    LABELS.get(logical).map_or('#', |&b| b as char)
10}
11
12fn gcd(a: u32, b: u32) -> u32 {
13    if b == 0 { a } else { gcd(b, a % b) }
14}
15
16impl Layout {
17    /// Draws the layout as an ASCII grid, then lists every element.
18    ///
19    /// Each element is drawn with a letter for its logical index (`a` is the
20    /// first), empty room with `.`. One character spans the largest number
21    /// of twelfths that divides every edge, so a grid of whole rows prints
22    /// one line per row. The list gives, in logical order, the form, the
23    /// orientation, the slot in twelfths and the status.
24    ///
25    /// With groups, a gutter left of the picture draws each group's band,
26    /// one column per nesting depth (`/` its first line, `|` the middle
27    /// ones, `\\` its last, `[` a one-line group), and one line per group
28    /// precedes the elements' list: its key, its parent's, its band and
29    /// the row its members start at.
30    pub fn dump(&self) -> String {
31        let rects: Vec<_> = self
32            .placements
33            .iter()
34            .filter_map(|p| p.rect.map(|r| (p.logical, r)))
35            .collect();
36        let (mut sx, mut sy) = (gcd(12, self.columns), gcd(12, self.rows));
37        for (_, r) in &rects {
38            sx = gcd(gcd(sx, r.x), r.w);
39            sy = gcd(gcd(sy, r.y), r.h);
40        }
41        let (sx, sy) = (sx.max(1), sy.max(1));
42        let (cols, rows) = ((self.columns / sx) as usize, (self.rows / sy) as usize);
43        let mut out = String::new();
44        let _ = writeln!(
45            out,
46            "grid {}x{} twelfths, one char = {}x{}",
47            self.columns, self.rows, sx, sy
48        );
49        let mut grid = vec![vec!['.'; cols]; rows];
50        for (logical, r) in &rects {
51            for line in grid
52                .iter_mut()
53                .take(((r.y + r.h) / sy) as usize)
54                .skip((r.y / sy) as usize)
55            {
56                for cell in line
57                    .iter_mut()
58                    .take(((r.x + r.w) / sx) as usize)
59                    .skip((r.x / sx) as usize)
60                {
61                    *cell = label(*logical);
62                }
63            }
64        }
65        let depth = |mut g: usize| {
66            let mut d = 0;
67            while let Some(p) = self.groups[g].parent {
68                (d, g) = (d + 1, p);
69            }
70            d
71        };
72        let framed: Vec<(usize, usize, u32, u32)> = self
73            .groups
74            .iter()
75            .enumerate()
76            .filter_map(|(g, gp)| gp.rect.map(|r| (g, depth(g), r.y / sy, r.bottom() / sy)))
77            .collect();
78        let gutter = framed.iter().map(|f| f.1 + 1).max().unwrap_or(0);
79        for (n, line) in grid.into_iter().enumerate() {
80            if gutter > 0 {
81                let n = n as u32;
82                for d in 0..gutter {
83                    let mark = framed
84                        .iter()
85                        .find(|f| f.1 == d && f.2 <= n && n < f.3)
86                        .map_or(' ', |&(_, _, first, end)| {
87                            match (n == first, n + 1 == end) {
88                                (true, true) => '[',
89                                (true, false) => '/',
90                                (false, true) => '\\',
91                                (false, false) => '|',
92                            }
93                        });
94                    out.push(mark);
95                }
96                out.push(' ');
97            }
98            out.extend(line);
99            out.push('\n');
100        }
101        for g in &self.groups {
102            let _ = write!(out, "group key={}", g.key);
103            if let Some(p) = g.parent {
104                let _ = write!(out, " in key={}", self.groups[p].key);
105            }
106            let _ = match (g.ignored, g.rect) {
107                (true, _) => writeln!(out, " ignored"),
108                (false, None) => writeln!(out, " empty"),
109                (false, Some(r)) => writeln!(
110                    out,
111                    " at {},{} size {}x{} body at row {}",
112                    r.x, r.y, r.w, r.h, g.body_top
113                ),
114            };
115        }
116        for p in &self.placements {
117            let _ = write!(
118                out,
119                "{} key={} form={} {}",
120                label(p.logical),
121                p.key,
122                p.form,
123                p.orientation
124            );
125            if let Some(r) = p.rect {
126                let _ = write!(out, " at {},{} size {}x{}", r.x, r.y, r.w, r.h);
127            }
128            let _ = match p.status {
129                Status::Placed => writeln!(out),
130                Status::Unpinned(reason) => writeln!(out, " unpinned({reason})"),
131                Status::Overflow(reason) => writeln!(out, " overflow({reason})"),
132            };
133        }
134        out
135    }
136}