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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! A gallery of every figure, one snapshot per level: each entry is the value, then the
//! picture, then the table of cells that produced it.
//!
//! The gap this fills is that nothing in the repository shows what a figure writes at a glance.
//! The model's prose says a border run is `Set` along it, `Unset` outward and `Closed` facing
//! the interior when the figure closes it, and four tests in `border.rs` assert it, and neither
//! is readable side by side. Nor is anything visible in a picture: a `Border` with
//! `closes_interior` true and with it false render the same `───`, because `Closed` and `Unset`
//! are one thing to the renderer and different things only to whatever composes into the cell
//! afterwards. Each block here puts the picture and the rule under it, so the difference the
//! picture cannot show is readable anyway.
//!
//! Nothing in a block is written by hand. The label is `format!("{value:?}")`, so it cannot
//! disagree with the value it names, and every other line comes out of the buffer or the
//! renderer. The one piece of prose is the `description` every file carries.
//!
//! **This promises no completeness, and cannot.** `Shape` here is an open trait and the model
//! has no central list of figures to check a gallery against, by design — `docs/model.md` says
//! defining a new kind of shape touches no existing shape because there is no such list. The
//! diagram crate above can promise it, and does, by matching over its closed set of kinds.
//!
//! A gallery rather than a `<!-- render: -->` marker, because a marker is a description a
//! subprocess reads and the fragments above are crate-private, so nothing a subprocess can name
//! reaches them; a gallery draws the values themselves, which is the only way to see what a
//! fragment stamps.

use std::fmt::Write as _;

use crate::cell::Side;
use crate::shape::fragment::border::Border;
use crate::shape::fragment::corner::Corner;
use crate::shape::fragment::end::End;
use crate::shape::fragment::fill::Fill;
use crate::shape::fragment::literal::Literal;
use crate::shape::fragment::segment::Segment;
use crate::shape::fragment::symbol::NamedSymbol;
use crate::shape::route::Route;
use crate::stroke::Stroke;
use crate::{
    Arm, BoxShape, Buffer, Cell, CellReader, Connector, Direction, Endpoint, FigureLayer, Glyph,
    GlyphCatalog, Line, Orientation, Pos, Size, StampMode, Surface, Symbol, SymbolCell,
    SymbolStyleName, Terminal, Window, render,
};

/// One description for every file, so the prose is written once rather than per level — and
/// once rather than per block, which is what the arms table made necessary.
const WHAT: &str = concat!(
    "A gallery: a chosen set of examples, one block each, for reading rather than for coverage. ",
    "Each label is derived from the value that drew the block, so it cannot disagree with it. ",
    "Under each picture is the surface that picture came from: a count of the positions the ",
    "figure wrote, then a row for each of them, saying what that position renders, what each of ",
    "its four arms holds, and the base stroke every Set arm is drawn in. A Set arm names the ",
    "stroke; Unset and Closed are the model's own two words for the other two. A position the ",
    "figure left unwritten is a hole in the picture rather than a row here, and the count is how ",
    "many there are. A literal or a symbol has no arms, so its arm columns are empty. A block ",
    "moving means a figure changed, and what moved is the thing to look at — the same acceptance a ",
    "characterization gets, without its claim of covering a range.",
);

/// The columns of the arms table, in the order the model's four sides are named, then the base
/// stroke every `Set` arm is drawn in.
const COLUMNS: [&str; 7] = ["at", "glyph", "top", "right", "bottom", "left", "base"];

fn arm_text(arm: &Arm) -> String {
    match arm {
        Arm::Set(stroke) => stroke.0.clone(),
        Arm::Closed => "Closed".to_string(),
        Arm::Unset => "Unset".to_string(),
    }
}

fn draw(size: Size, body: impl FnOnce(&mut dyn Surface)) -> (String, String) {
    let origin = Pos { x: 0, y: 0 };
    let mut buffer = Buffer::new(Window { origin, size });
    body(&mut FigureLayer::new(&mut buffer, StampMode::Above));
    let picture = render(&buffer, &catalog(), buffer.window());
    (picture, surface(&buffer, size))
}

/// The catalog the gallery reads and renders with: the core's arm table and its symbol table, so
/// a cell naming a symbol reads as the glyph it draws rather than as a hole. A miss is still a
/// miss — `?` in the table and a space in the picture — because that is what the catalog answers.
fn catalog() -> GlyphCatalog {
    GlyphCatalog::union([GlyphCatalog::light(), GlyphCatalog::solid()])
}

/// The surface as a Markdown table: one row per position the figure wrote, padded to the widest
/// cell in each column so the file reads as a table. A position it left unwritten is a hole in
/// the picture above, and the count says how many there were.
fn surface(buffer: &Buffer, size: Size) -> String {
    let catalog = catalog();
    let mut rows: Vec<[String; 7]> = Vec::new();
    let total = size.width as usize * size.height as usize;

    for y in 0..size.height.cast_signed() {
        for x in 0..size.width.cast_signed() {
            let cell = buffer.cell(Pos { x, y });
            let (glyph, top, right, bottom, left, base) = match &cell {
                None => continue,
                Some(Cell::Literal(g)) => (
                    g.as_str().to_string(),
                    String::new(),
                    String::new(),
                    String::new(),
                    String::new(),
                    String::new(),
                ),
                Some(Cell::Symbol(s)) => (
                    catalog
                        .symbol(s)
                        .map_or("?".to_string(), |g| g.as_str().to_string()),
                    String::new(),
                    String::new(),
                    String::new(),
                    String::new(),
                    String::new(),
                ),
                Some(Cell::Strokes(s)) => (
                    catalog
                        .glyph(&s.key())
                        .map_or("?".to_string(), |g| g.as_str().to_string()),
                    arm_text(&s.top),
                    arm_text(&s.right),
                    arm_text(&s.bottom),
                    arm_text(&s.left),
                    s.base.0.clone(),
                ),
            };
            rows.push([format!("{x},{y}"), glyph, top, right, bottom, left, base]);
        }
    }

    let widths: Vec<usize> = (0..COLUMNS.len())
        .map(|column| {
            rows.iter()
                .map(|row| row[column].chars().count())
                .chain(std::iter::once(COLUMNS[column].len()))
                .max()
                .unwrap_or(0)
        })
        .collect();

    let line = |cells: &[String]| {
        let padded: Vec<String> = cells
            .iter()
            .zip(&widths)
            .map(|(cell, width)| format!("{cell:<width$}"))
            .collect();
        format!("  | {} |", padded.join(" | "))
    };

    let mut out = format!("  wrote {} of {total} positions\n", rows.len());
    let header: Vec<String> = COLUMNS.iter().map(|name| (*name).to_string()).collect();
    let _ = writeln!(out, "{}", line(&header));
    let rule: Vec<String> = widths.iter().map(|width| "-".repeat(*width)).collect();
    let _ = writeln!(out, "  | {} |", rule.join(" | "));
    for row in &rows {
        let _ = writeln!(out, "{}", line(row));
    }
    out
}

/// One entry: the value, then the picture, then the surface. Every label is `format!("{value:?}")`
/// and every other line comes from the buffer or the renderer.
type Entry = (String, Size, Box<dyn Fn(&mut dyn Surface)>);

fn one<T: std::fmt::Debug + crate::Shape + 'static>(value: T, size: Size) -> Entry {
    let label = format!("{value:?}");
    (
        label,
        size,
        Box::new(move |s: &mut dyn Surface| value.draw(s)),
    )
}

fn gallery(entries: Vec<Entry>) -> String {
    let mut out = String::new();
    for (label, size, entry) in entries {
        let _ = writeln!(out, "{label}");
        let (picture, surface) = draw(size, |s| entry(s));
        // The indent is trimmed off a line the picture left empty, or the gate's
        // `editorconfig-checker` step rejects the snapshot once it is tracked, since `render` pads
        // every line to the window's width.
        for line in picture.lines() {
            let _ = writeln!(out, "{}", format!("  {line}").trim_end());
        }
        let _ = write!(out, "{surface}");
        let _ = writeln!(out);
    }
    out
}

/// Writes one snapshot. The path is set rather than left to `insta`'s default, which puts a
/// snapshot beside the source that wrote it — the characterization does the same, and the two
/// kinds are kept apart by directory.
fn snap(name: &str, body: &str) {
    let mut settings = insta::Settings::clone_current();
    settings.set_snapshot_path(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/snapshots/gallery"
    ));
    settings.set_description(WHAT);
    settings.bind(|| insta::assert_snapshot!(name, body));
}

fn window(width: u16, height: u16) -> Size {
    Size { width, height }
}

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

fn glyph(text: &str) -> Glyph {
    Glyph::new(text).expect("one glyph")
}

// ------------------------------------------------------ level 1b: the connector and its route

/// The head glyph the model's own tests fix for a picture: opposite the leaving direction.
fn head(leaving: Direction) -> Glyph {
    glyph(match leaving {
        Direction::Up => "▼",
        Direction::Right => "◄",
        Direction::Down => "▲",
        Direction::Left => "►",
    })
}

fn at(x: i16, y: i16) -> Pos {
    Pos { x, y }
}

fn glyph_end(x: i16, y: i16, leaving: Direction) -> Endpoint {
    Endpoint {
        at: at(x, y),
        leaving,
        terminal: Terminal::Glyph {
            glyph: head(leaving),
        },
    }
}

fn arm_end(x: i16, y: i16, leaving: Direction) -> Endpoint {
    Endpoint {
        at: at(x, y),
        leaving,
        terminal: Terminal::Arm,
    }
}

/// A terminal naming a style instead of spelling a head: the symbol follows from `leaving`, so
/// the picture shows which head that style draws for that direction.
fn symbol_end(x: i16, y: i16, leaving: Direction) -> Endpoint {
    Endpoint {
        at: at(x, y),
        leaving,
        terminal: Terminal::Symbol {
            style: SymbolStyleName::from("solid"),
        },
    }
}

fn connector(from: Endpoint, to: Endpoint) -> Connector {
    Connector {
        from,
        to,
        stroke: light(),
    }
}

/// The route a connector derived for the arrangement the test named. `from` and `to` are carried
/// because the route's outermost positions need to know which side faces the head beside them.
fn route(from: Pos, to: Pos, positions: Vec<Pos>) -> Route {
    Route {
        from,
        to,
        positions,
        stroke: light(),
    }
}

#[test]
fn level_1_connector() {
    let entries = vec![
        one(
            connector(
                glyph_end(0, 0, Direction::Down),
                glyph_end(4, 3, Direction::Left),
            ),
            window(5, 4),
        ),
        one(
            connector(
                glyph_end(0, 0, Direction::Right),
                glyph_end(4, 3, Direction::Up),
            ),
            window(5, 4),
        ),
        one(
            connector(
                glyph_end(0, 0, Direction::Right),
                glyph_end(6, 0, Direction::Left),
            ),
            window(7, 1),
        ),
        one(
            connector(
                glyph_end(0, 0, Direction::Right),
                glyph_end(6, 2, Direction::Left),
            ),
            window(7, 3),
        ),
        one(
            connector(
                glyph_end(2, 0, Direction::Right),
                glyph_end(8, 2, Direction::Left),
            ),
            window(9, 3),
        ),
        one(
            connector(
                glyph_end(2, 0, Direction::Left),
                glyph_end(8, 2, Direction::Right),
            ),
            window(10, 3),
        ),
        one(
            connector(
                glyph_end(2, 0, Direction::Left),
                glyph_end(8, 2, Direction::Down),
            ),
            window(9, 4),
        ),
        one(
            connector(
                glyph_end(2, 0, Direction::Right),
                glyph_end(4, 1, Direction::Left),
            ),
            window(5, 2),
        ),
        one(
            connector(
                glyph_end(2, 0, Direction::Left),
                glyph_end(3, 2, Direction::Right),
            ),
            window(5, 3),
        ),
        one(
            connector(
                arm_end(0, 0, Direction::Right),
                arm_end(6, 0, Direction::Left),
            ),
            window(7, 1),
        ),
        one(
            connector(
                arm_end(0, 0, Direction::Down),
                arm_end(4, 3, Direction::Left),
            ),
            window(5, 4),
        ),
        one(
            connector(
                glyph_end(2, 1, Direction::Right),
                glyph_end(2, 1, Direction::Left),
            ),
            window(5, 3),
        ),
        one(
            connector(
                symbol_end(0, 0, Direction::Down),
                symbol_end(4, 3, Direction::Left),
            ),
            window(5, 4),
        ),
    ];
    snap("level_1_connector", &gallery(entries));
}

#[test]
fn level_1_route() {
    let entries = vec![
        one(
            route(
                at(0, 0),
                at(6, 0),
                vec![at(1, 0), at(2, 0), at(3, 0), at(4, 0), at(5, 0)],
            ),
            window(7, 1),
        ),
        one(
            route(
                at(0, 0),
                at(4, 3),
                vec![at(0, 1), at(0, 2), at(0, 3), at(1, 3), at(2, 3), at(3, 3)],
            ),
            window(5, 4),
        ),
        one(
            route(
                at(2, 0),
                at(8, 2),
                vec![
                    at(1, 0),
                    at(1, 1),
                    at(2, 1),
                    at(3, 1),
                    at(4, 1),
                    at(5, 1),
                    at(6, 1),
                    at(7, 1),
                    at(8, 1),
                    at(9, 1),
                    at(9, 2),
                ],
            ),
            window(10, 3),
        ),
    ];
    snap("level_1_route", &gallery(entries));
}

// ---------------------------------------------------------------- level 2: the fragments

#[test]
fn level_2_fragments() {
    let entries = vec![
        one(
            Border {
                from: Pos { x: 0, y: 0 },
                len: 3,
                side: Side::Top,
                stroke: light(),
                closes_interior: true,
            },
            window(3, 1),
        ),
        one(
            Border {
                from: Pos { x: 0, y: 0 },
                len: 3,
                side: Side::Top,
                stroke: light(),
                closes_interior: false,
            },
            window(3, 1),
        ),
        one(
            Border {
                from: Pos { x: 0, y: 0 },
                len: 3,
                side: Side::Left,
                stroke: light(),
                closes_interior: true,
            },
            window(3, 1),
        ),
        one(
            Corner {
                at: Pos { x: 1, y: 0 },
                opens: (Side::Right, Side::Bottom),
                stroke: light(),
            },
            window(3, 1),
        ),
        one(
            End {
                at: Pos { x: 1, y: 0 },
                side: Side::Right,
                stroke: light(),
            },
            window(3, 1),
        ),
        one(
            End {
                at: Pos { x: 1, y: 0 },
                side: Side::Top,
                stroke: light(),
            },
            window(3, 1),
        ),
        one(
            Segment {
                from: Pos { x: 0, y: 0 },
                len: 3,
                orientation: Orientation::Horizontal,
                stroke: light(),
            },
            window(3, 1),
        ),
        one(
            Fill {
                at: Pos { x: 0, y: 0 },
                size: window(3, 1),
                glyph: glyph("."),
            },
            window(3, 1),
        ),
        one(
            Literal {
                at: Pos { x: 1, y: 0 },
                glyph: glyph(">"),
            },
            window(3, 1),
        ),
        one(
            NamedSymbol {
                at: Pos { x: 1, y: 0 },
                cell: SymbolCell {
                    symbol: Symbol::DirectionUp,
                    style: SymbolStyleName::from("solid"),
                },
            },
            window(3, 1),
        ),
    ];
    snap("level_2_fragments", &gallery(entries));
}

// ------------------------------------------------------------ level 1: the complete shapes

#[test]
fn level_1_complete_shapes() {
    let entries = vec![
        one(
            BoxShape {
                at: Pos { x: 0, y: 0 },
                size: window(6, 3),
                stroke: light(),
                fill: None,
            },
            window(6, 3),
        ),
        one(
            BoxShape {
                at: Pos { x: 0, y: 0 },
                size: window(6, 3),
                stroke: light(),
                fill: Some(glyph(".")),
            },
            window(6, 3),
        ),
        one(
            BoxShape {
                at: Pos { x: 0, y: 0 },
                size: window(2, 2),
                stroke: light(),
                fill: None,
            },
            window(2, 2),
        ),
        one(
            Line {
                at: Pos { x: 0, y: 0 },
                len: 5,
                orientation: Orientation::Horizontal,
                stroke: light(),
            },
            window(5, 1),
        ),
        one(
            Line {
                at: Pos { x: 0, y: 0 },
                len: 0,
                orientation: Orientation::Horizontal,
                stroke: light(),
            },
            window(5, 1),
        ),
    ];
    snap("level_1_complete_shapes", &gallery(entries));
}