monospace-core 0.1.0

Core library for Monospace: parsing, layout and ASCII rendering of diagrams
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! The box: corners, border runs and an interior, placed correctly. See _The initial set_ in
//! [`docs/model.md`](../../../docs/model.md).

use crate::cell::Side;
use crate::shape::fragment::border::Border;
use crate::shape::fragment::corner::Corner;
use crate::shape::fragment::fill::Fill;
use crate::{Glyph, Pos, Shape, Size, Stroke, Surface};

/// A box: a position, a size and a stroke, with a fill as an option.
///
/// A **complete** shape in the sense of _Complete and fragment_ in
/// [`docs/model.md`](../../../docs/model.md): what a library user sees. Its decomposition depends
/// on `size` rather than on its kind — a 2×2 box is four corners and nothing else — and below 2
/// in either dimension it draws nothing at all, per _Degenerate arrangements_.
#[derive(Debug)]
pub struct BoxShape {
    /// The box's top-left corner.
    pub at: Pos,
    /// The box's width and height, in cells.
    pub size: Size,
    /// The stroke every cell this box writes is drawn in.
    pub stroke: Stroke,
    /// The glyph that fills the interior, or `None` for no fill at all.
    pub fill: Option<Glyph>,
}

impl Shape for BoxShape {
    fn draw(&self, surface: &mut dyn Surface) {
        let Size { width, height } = self.size;
        if width < 2 || height < 2 {
            return;
        }
        let (Some(x1), Some(y1)) = (
            self.at.x.checked_add_unsigned(width - 1),
            self.at.y.checked_add_unsigned(height - 1),
        ) else {
            return;
        };
        let x0 = self.at.x;
        let y0 = self.at.y;
        let stroke = || self.stroke.clone();
        let closes_interior = self.fill.is_some();

        Corner {
            at: Pos { x: x0, y: y0 },
            opens: (Side::Right, Side::Bottom),
            stroke: stroke(),
        }
        .draw(surface);
        Corner {
            at: Pos { x: x1, y: y0 },
            opens: (Side::Bottom, Side::Left),
            stroke: stroke(),
        }
        .draw(surface);
        Corner {
            at: Pos { x: x1, y: y1 },
            opens: (Side::Top, Side::Left),
            stroke: stroke(),
        }
        .draw(surface);
        Corner {
            at: Pos { x: x0, y: y1 },
            opens: (Side::Top, Side::Right),
            stroke: stroke(),
        }
        .draw(surface);

        if width > 2 {
            Border {
                from: Pos { x: x0 + 1, y: y0 },
                len: width - 2,
                side: Side::Top,
                stroke: stroke(),
                closes_interior,
            }
            .draw(surface);
            Border {
                from: Pos { x: x0 + 1, y: y1 },
                len: width - 2,
                side: Side::Bottom,
                stroke: stroke(),
                closes_interior,
            }
            .draw(surface);
        }
        if height > 2 {
            Border {
                from: Pos { x: x0, y: y0 + 1 },
                len: height - 2,
                side: Side::Left,
                stroke: stroke(),
                closes_interior,
            }
            .draw(surface);
            Border {
                from: Pos { x: x1, y: y0 + 1 },
                len: height - 2,
                side: Side::Right,
                stroke: stroke(),
                closes_interior,
            }
            .draw(surface);
        }
        if width > 2
            && height > 2
            && let Some(glyph) = &self.fill
        {
            Fill {
                at: Pos {
                    x: x0 + 1,
                    y: y0 + 1,
                },
                size: Size {
                    width: width - 2,
                    height: height - 2,
                },
                glyph: glyph.clone(),
            }
            .draw(surface);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::BoxShape;
    use crate::shape::counting::CountingSurface;
    use crate::{Buffer, GlyphCatalog, Window};
    use crate::{FigureLayer, Glyph, Pos, Shape, Size, StampMode, Stroke, render};

    fn light() -> Stroke {
        Stroke::from("light")
    }

    /// A 6×3 box renders its border exactly.
    #[test]
    fn a_6x3_box_renders_its_border() {
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 6,
            height: 3,
        };
        let mut buffer = Buffer::new(Window { origin, size });
        BoxShape {
            at: origin,
            size,
            stroke: light(),
            fill: None,
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));

        let text = render(&buffer, &GlyphCatalog::light(), buffer.window());

        assert_eq!(text, "┌────┐\n│    │\n└────┘\n");
    }

    /// The same box filled keeps its border and fills exactly its 4×1
    /// interior.
    #[test]
    fn a_6x3_box_filled_keeps_its_border_and_fills_only_its_interior() {
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 6,
            height: 3,
        };
        let mut buffer = Buffer::new(Window { origin, size });
        BoxShape {
            at: origin,
            size,
            stroke: light(),
            fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));

        let text = render(&buffer, &GlyphCatalog::light(), buffer.window());

        assert_eq!(text, "┌────┐\n│░░░░│\n└────┘\n");
    }

    /// A 2×2 box is four corners and nothing else.
    #[test]
    fn a_2x2_box_is_four_corners_and_nothing_else() {
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 2,
            height: 2,
        };
        let mut buffer = Buffer::new(Window { origin, size });
        BoxShape {
            at: origin,
            size,
            stroke: light(),
            fill: None,
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));

        let text = render(&buffer, &GlyphCatalog::light(), buffer.window());

        assert_eq!(text, "┌┐\n└┘\n");
    }

    /// Below 2 in either dimension, nothing is drawn at all.
    #[test]
    fn a_box_below_2_in_either_dimension_draws_nothing() {
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 2,
            height: 2,
        };

        for degenerate in [
            Size {
                width: 1,
                height: 2,
            },
            Size {
                width: 2,
                height: 1,
            },
            Size {
                width: 0,
                height: 2,
            },
        ] {
            let mut buffer = Buffer::new(Window { origin, size });
            BoxShape {
                at: origin,
                size: degenerate,
                stroke: light(),
                fill: None,
            }
            .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));

            let text = render(&buffer, &GlyphCatalog::light(), buffer.window());

            assert_eq!(text, "  \n  \n", "size {degenerate:?}");
        }
    }

    /// None of the boxes above writes any position more than once.
    #[test]
    fn no_box_above_writes_any_position_more_than_once() {
        for (size, fill) in [
            (
                Size {
                    width: 6,
                    height: 3,
                },
                None,
            ),
            (
                Size {
                    width: 6,
                    height: 3,
                },
                Some(Glyph::new("░").expect("\"░\" is one glyph")),
            ),
            (
                Size {
                    width: 2,
                    height: 2,
                },
                None,
            ),
        ] {
            let mut surface = CountingSurface::default();
            BoxShape {
                at: Pos { x: 0, y: 0 },
                size,
                stroke: light(),
                fill,
            }
            .draw(&mut surface);

            assert!(
                surface.max_writes() <= 1,
                "size {size:?} wrote a position more than once"
            );
        }
    }

    /// Two unfilled boxes positioned so one's border
    /// crosses into the other's interior render a crossing (`┼`) at every cell where that
    /// happens, not a closed junction.
    #[test]
    fn two_unfilled_boxes_render_a_crossing_at_every_cell_their_borders_overlap() {
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 9,
            height: 5,
        };
        let mut buffer = Buffer::new(Window { origin, size });

        BoxShape {
            at: Pos { x: 0, y: 0 },
            size: Size {
                width: 6,
                height: 4,
            },
            stroke: light(),
            fill: None,
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));
        BoxShape {
            at: Pos { x: 4, y: 2 },
            size: Size {
                width: 6,
                height: 4,
            },
            stroke: light(),
            fill: None,
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));

        let text = render(&buffer, &GlyphCatalog::light(), buffer.window());

        assert_eq!(
            text,
            "┌────┐   \n│    │   \n│   ┌┼───\n└───┼┘   \n    │    \n"
        );
    }

    /// A fill keeps closing its own interior side, even
    /// while an unfilled box elsewhere still lets a crossing show through.
    #[test]
    fn a_filled_box_among_unfilled_ones_still_closes_its_interior() {
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 9,
            height: 5,
        };
        let mut buffer = Buffer::new(Window { origin, size });

        BoxShape {
            at: Pos { x: 0, y: 0 },
            size: Size {
                width: 6,
                height: 4,
            },
            stroke: light(),
            fill: None,
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));
        BoxShape {
            at: Pos { x: 4, y: 2 },
            size: Size {
                width: 6,
                height: 4,
            },
            stroke: light(),
            fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));

        let text = render(&buffer, &GlyphCatalog::light(), buffer.window());

        assert_eq!(
            text,
            "┌────┐   \n│    │   \n│   ┌┴───\n└───┤░░░░\n    │░░░░\n"
        );
    }

    /// Two unfilled boxes at the same row, overlapping horizontally by two columns, merge cleanly
    /// into T-junctions at both cells where one's corner lands on the other's border — an
    /// unfilled shape's interior side stays open to whatever else needs that cell, here as much
    /// as at the diagonal overlap the bug was reported against.
    #[test]
    fn two_unfilled_boxes_overlapping_horizontally_merge_into_t_junctions() {
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 6,
            height: 3,
        };
        let mut buffer = Buffer::new(Window { origin, size });

        BoxShape {
            at: Pos { x: 0, y: 0 },
            size: Size {
                width: 4,
                height: 3,
            },
            stroke: light(),
            fill: None,
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));
        BoxShape {
            at: Pos { x: 2, y: 0 },
            size: Size {
                width: 4,
                height: 3,
            },
            stroke: light(),
            fill: None,
        }
        .draw(&mut FigureLayer::new(&mut buffer, StampMode::Above));

        let text = render(&buffer, &GlyphCatalog::light(), buffer.window());

        assert_eq!(text, "┌─┬┬─┐\n│ ││ │\n└─┴┴─┘\n");
    }
}