number-loom 0.5.0

Multipurpose GUI and CLI tool for constructing nonograms
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
use anyhow::{Context, bail};
use image::{DynamicImage, GenericImageView, Pixel, Rgba};
use std::{
    char::from_digit,
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    io::Cursor,
    io::Read,
    iter::FromIterator,
    path::PathBuf,
};

use crate::{
    formats::woven::from_woven,
    geometry::{GridKind, Square, Tri},
    puzzle::{
        self, BACKGROUND, ClueStyle, Color, ColorInfo, Corner, Document, DynPuzzle, DynSolution,
        Nono, NonogramFormat, Puzzle, Solution, Triano,
    },
};

pub fn load_path(path: &PathBuf, format: Option<NonogramFormat>) -> anyhow::Result<Document> {
    let mut bytes = vec![];
    if path == &PathBuf::from("-") {
        std::io::stdin().read_to_end(&mut bytes)?;
    } else {
        bytes = std::fs::read(path)?;
    }

    load(
        path.to_str().context("path is not valid UTF-8")?,
        bytes,
        format,
    )
}

pub fn load(
    filename: &str,
    bytes: Vec<u8>,
    format: Option<NonogramFormat>,
) -> anyhow::Result<Document> {
    use crate::formats::webpbn::webpbn_to_document;

    let input_format = puzzle::infer_format(filename, format);

    Ok(match input_format {
        NonogramFormat::Html => {
            bail!("HTML input is not supported.")
        }
        NonogramFormat::Image => {
            let img = image::load_from_memory(&bytes).context("could not decode image")?;
            let solution = image_to_solution(&img);
            Document::from_solution(DynSolution::Square(solution), filename.to_string())
        }
        NonogramFormat::Webpbn => {
            let webpbn_string = String::from_utf8(bytes).context("file is not valid UTF-8 text")?;
            let mut doc = webpbn_to_document(&webpbn_string)?;
            doc.file = filename.to_string();
            doc
        }
        NonogramFormat::CharGrid => {
            let grid_string = String::from_utf8(bytes).context("file is not valid UTF-8 text")?;
            let solution = char_grid_to_solution(&grid_string);
            Document::from_solution(DynSolution::Square(solution), filename.to_string())
        }
        NonogramFormat::Woven => {
            let woven_string = String::from_utf8(bytes).context("file is not valid UTF-8 text")?;
            from_woven(&woven_string, filename.to_string())?
        }
        NonogramFormat::Olsak => {
            let olsak_string = String::from_utf8(bytes).context("file is not valid UTF-8 text")?;
            let puzzle = olsak_to_puzzle(&olsak_string)?;
            Document::from_puzzle(puzzle, filename.to_string())
        }
    })
}

pub fn image_to_solution(image: &DynamicImage) -> Solution<Square> {
    let (width, height) = image.dimensions();

    let mut palette = HashMap::<image::Rgba<u8>, ColorInfo>::new();
    let mut grid: Vec<Vec<Color>> = vec![vec![BACKGROUND; height as usize]; width as usize];

    // pbnsolve output looks weird if the default color isn't called "white".
    palette.insert(
        image::Rgba::<u8>([255, 255, 255, 255]),
        ColorInfo::default_bg(),
    );

    let mut next_char = 'a';
    let mut next_color_idx: u8 = 1; // BACKGROUND is 0

    // Gather the palette
    for y in 0..height {
        for x in 0..width {
            let pixel: Rgba<u8> = image.get_pixel(x, y);
            let color = palette.entry(pixel).or_insert_with(|| {
                let this_char = next_char;
                let [r, g, b] = pixel.channels()[0..3] else {
                    panic!("Image with fewer than three channels?")
                };
                let this_color = Color(next_color_idx);

                // Don't crash for too many colors, but the quality check should complain:
                next_color_idx = next_color_idx.wrapping_add(1);

                if r == 0 && g == 0 && b == 0 {
                    return ColorInfo::default_fg(this_color);
                }

                next_char = (next_char as u8).wrapping_add(1) as char;

                ColorInfo {
                    ch: this_char,
                    name: format!("{}{:02X}{:02X}{:02X}", this_char, r, g, b),
                    rgb: (r, g, b),
                    color: this_color,
                    corner: None,
                }
            });

            grid[x as usize][y as usize] = color.color;
        }
    }

    Solution::from_columns(
        ClueStyle::Nono, // Images can't have triangular pixels!
        palette
            .into_values()
            .map(|color_info| (color_info.color, color_info))
            .collect(),
        grid,
    )
}

pub fn char_grid_to_solution(char_grid: &str) -> Solution<Square> {
    let mut palette = HashMap::<char, ColorInfo>::new();

    let mut any_uppercase = false;
    // We want deterministic behavior
    let mut unused_chars = BTreeSet::<char>::new();
    for ch in char_grid.chars() {
        if ch == '\n' {
            continue;
        }
        unused_chars.insert(ch);
        if ch.is_ascii_uppercase() {
            // the characters this matters for are in ASCII
            any_uppercase = true;
        }
    }

    let mut bg_ch: Option<char> = None;

    // Look for a character that seems to represent a white background.
    for possible_bg in [' ', '.', '_', 'w', 'W', '·', '', '0', 'x', ''] {
        if unused_chars.contains(&possible_bg) {
            bg_ch = Some(possible_bg);
        }
    }

    // But we need to *some* color as background to proceed!
    let bg_ch = match bg_ch {
        Some(x) => x,
        None => {
            eprintln!(
                "number-loom: Warning: unable to guess which character is supposed to be the background; using the upper-left corner"
            );
            char_grid.trim_start().chars().next().unwrap()
        }
    };

    palette.insert(
        bg_ch,
        ColorInfo {
            ch: bg_ch,
            ..ColorInfo::default_bg()
        },
    );
    unused_chars.remove(&bg_ch);

    let mut next_color: u8 = 1;

    // Look for a character that might be black (but it's not required to exist).
    for possible_black in ['#', '.', '', '', '1', '', 'B', 'b'] {
        if unused_chars.contains(&possible_black) {
            palette.insert(possible_black, ColorInfo::default_fg(Color(next_color)));
            next_color += 1;
            unused_chars.remove(&possible_black);
            break;
        }
    }

    let lower_right_tri = HashSet::<char>::from_iter(['', '🮞', '']);
    let lower_left_tri = HashSet::<char>::from_iter(['', '🮟', '']);
    let upper_left_tri = HashSet::<char>::from_iter(['', '🮜', '']);
    let upper_right_tri = HashSet::<char>::from_iter(['', '🮝', '']);
    let mut any_tri = HashSet::<char>::new();
    any_tri.extend(lower_right_tri.iter());
    any_tri.extend(lower_left_tri.iter());
    any_tri.extend(upper_left_tri.iter());
    any_tri.extend(upper_right_tri.iter());

    // By default, use primary and secondary colors:
    let mut unused_colors = BTreeMap::<char, (u8, u8, u8)>::new();
    if any_uppercase {
        unused_colors.insert('R', (255, 0, 0));
        unused_colors.insert('G', (0, 255, 0));
        unused_colors.insert('B', (0, 0, 255));

        unused_colors.insert('Y', (255, 255, 0));
        unused_colors.insert('C', (0, 255, 255));
        unused_colors.insert('M', (255, 0, 255));
    } else {
        unused_colors.insert('r', (255, 0, 0));
        unused_colors.insert('g', (0, 255, 0));
        unused_colors.insert('b', (0, 0, 255));

        unused_colors.insert('y', (255, 255, 0));
        unused_colors.insert('c', (0, 255, 255));
        unused_colors.insert('m', (255, 0, 255));
    }
    // Using '🟥' and 'r' in the same puzzle (etc.) will cause a warning.
    unused_colors.insert('🟥', (255, 0, 0));
    unused_colors.insert('🟩', (0, 255, 0));
    unused_colors.insert('🟦', (0, 0, 255));
    unused_colors.insert('🟨', (255, 255, 0));
    unused_colors.insert('🟧', (255, 165, 0));
    unused_colors.insert('🟪', (128, 0, 128));
    unused_colors.insert('🟫', (139, 69, 19));

    for ch in unused_chars {
        if unused_colors.is_empty() {
            // If desperate, use grays and dark colors:
            for i in 1_u8..5_u8 {
                unused_colors.insert(from_digit(i.into(), 10).unwrap(), (44 * i, 44 * i, 44 * i));
            }
            unused_colors.insert('R', (127, 0, 0));
            unused_colors.insert('G', (0, 127, 0));
            unused_colors.insert('B', (0, 0, 127));

            unused_colors.insert('Y', (127, 127, 0));
            unused_colors.insert('C', (0, 127, 127));
            unused_colors.insert('M', (127, 0, 127));
        }
        let rgb = unused_colors
            .remove(&ch)
            .unwrap_or_else(|| unused_colors.pop_first().unwrap().1);

        palette.insert(
            ch,
            ColorInfo {
                ch,
                name: ch.to_string(),
                rgb,
                color: Color(next_color),
                corner: if any_tri.contains(&ch) {
                    Some(Corner {
                        upper: upper_left_tri.contains(&ch) || upper_right_tri.contains(&ch),
                        left: lower_left_tri.contains(&ch) || upper_left_tri.contains(&ch),
                    })
                } else {
                    None
                },
            },
        );
        next_color += 1;
    }

    let mut grid: Vec<Vec<Color>> = vec![];

    // TODO: check that rows are the same length!
    for (y, row) in char_grid
        .split("\n")
        .filter(|line| !line.is_empty())
        .enumerate()
    {
        for (x, ch) in row.chars().enumerate() {
            // There's probably a better way than this...
            grid.resize(std::cmp::max(grid.len(), x + 1), vec![]);
            let new_height = std::cmp::max(grid[x].len(), y + 1);
            grid[x].resize(new_height, BACKGROUND);

            grid[x][y] = palette[&ch].color;
        }
    }

    let has_triangles = palette.values().any(|ci| ci.corner.is_some());

    let clue_style = if has_triangles {
        // Let's assume triano clues are black-and-white; fix the palette!
        for color_info in palette.values_mut() {
            if color_info.color == BACKGROUND {
                continue;
            }
            color_info.rgb = (0, 0, 0);
        }

        ClueStyle::Triano
    } else {
        ClueStyle::Nono
    };

    Solution::from_columns(
        clue_style,
        palette
            .into_values()
            .map(|color_info| (color_info.color, color_info))
            .collect(),
        grid,
    )
}

/// Assemble a triddler from Olsak's six data groups.
///
/// Olsak labels the hexagon's sides `A`..`F` counterclockwise from the upper left:
///
/// ```text
///          F
///       -------
///    A /       \ E
///     /        /
///     \       / D
///    B \     /
///       -----
///         C
/// ```
///
/// so `A`=topleft, `B`=bottomleft, `C`=bottom, `D`=bottomright, `E`=topright, `F`=top. Because the
/// traversal is counterclockwise, `A`/`B` and `C`/`D` list their lines in increasing lane order,
/// but `E`/`F` run the other way around the hexagon and so are listed in *decreasing* lane order.
///
/// The `C`/`D` blocks are written in the reverse of our order, which is what Olsak's own warning
/// about reading columns that "begin at the bottom of hexagonal ... from underneath upstairs"
/// refers to. (Note that these two facts were confirmed empirically: of the 1024 readings that fit
/// `tkocka.g`'s line lengths, only two solve it completely, and this is the one that also matches
/// the documented side diagram. The other is its mirror image.)
///
/// A blank line inside a group is significant — it means "no blocks in this line" — so unlike most
/// of this format, trailing blank lines must *not* be trimmed.
///
/// Olsak also documents two identities the side lengths must satisfy (`E = A + B - D` and
/// `F = C + D - A`); those hold automatically for any real outline, so rather than checking them
/// we just recover the outline from the six lengths and let that fail if they're inconsistent.
fn olsak_triddler(
    palette: HashMap<Color, ColorInfo>,
    mut groups: Vec<Vec<Vec<Nono>>>,
) -> anyhow::Result<Puzzle<Nono, Tri>> {
    use crate::geometry::{ClueSet, ClueSetCounts, Geometry, Outline};

    let counts = ClueSetCounts {
        topleft: groups[0].len(),
        bottomleft: groups[1].len(),
        bottom: groups[2].len(),
        bottomright: groups[3].len(),
        topright: groups[4].len(),
        top: groups[5].len(),
    };
    let outline = Outline::from_clue_set_counts(counts)?;
    let geometry = Geometry::<Tri>::new(outline);

    let mut lines = vec![vec![]; geometry.lane_map().lane_count()];
    // Group index, its clue set, whether Olsak lists that side's lines backwards, and whether the
    // blocks within each line are written in the opposite order to ours.
    let assignment = [
        (0, ClueSet::TopLeft, false, false),
        (1, ClueSet::BottomLeft, false, false),
        (2, ClueSet::Bottom, false, true),
        (3, ClueSet::BottomRight, false, true),
        (4, ClueSet::TopRight, true, false),
        (5, ClueSet::Top, true, false),
    ];
    for (group_idx, clue_set, lines_reversed, blocks_reversed) in assignment {
        let mut group_lines = std::mem::take(&mut groups[group_idx]);
        if lines_reversed {
            group_lines.reverse();
        }
        for (lane, mut clue_line) in geometry
            .lanes_in_clue_set(clue_set)
            .into_iter()
            .zip(group_lines)
        {
            if blocks_reversed {
                clue_line.reverse();
            }
            lines[lane] = clue_line;
        }
    }

    Ok(Puzzle::triangular(palette, outline, lines))
}

#[derive(Debug, PartialEq, Eq)]
enum OlsakStanza {
    Preamble,
    Palette,
    Dimension(usize),
}

#[derive(Debug, PartialEq, Eq, Hash)]
enum Glue {
    NoGlue,
    Left,
    Right,
}

pub fn olsak_to_puzzle(olsak: &str) -> anyhow::Result<DynPuzzle> {
    use Glue::*;
    use OlsakStanza::*;
    let mut cur_stanza = Preamble;

    let mut next_color: u8 = 1;

    let named_colors = BTreeMap::<&str, (u8, u8, u8)>::from([
        ("white", (255, 255, 255)),
        ("black", (0, 0, 0)),
        ("red", (255, 0, 0)),
        ("green", (0, 255, 0)),
        ("blue", (0, 0, 255)),
        ("pink", (255, 128, 128)),
        ("yellow", (255, 255, 0)),
        ("r", (255, 0, 0)),
        ("g", (0, 255, 0)),
        ("b", (0, 0, 255)),
    ]);

    let mut olsak_palette = HashMap::<char, ColorInfo>::new();
    // For each dimension, store the "glued" colors (the caps):
    let mut olsak_glued_palettes = [
        HashMap::<(char, Glue), ColorInfo>::new(),
        HashMap::<(char, Glue), ColorInfo>::new(),
    ];
    let mut clue_style = ClueStyle::Nono;
    // `#t`/`#T` declares a triddler, which has six data groups rather than two.
    let mut triddler = false;

    // Dimension > Position > Clue index
    let mut nono_clues: Vec<Vec<Vec<Nono>>> = vec![vec![]; 6];
    let mut triano_clues: Vec<Vec<Vec<Triano>>> = vec![vec![], vec![]];

    let rrggbb = regex::Regex::new(r"^#(..)(..)(..)$").unwrap();
    let palette_line = regex::Regex::new(r"^\s*(\S):(.)\s+(\S+)\s*(.*)$").unwrap();

    for line in olsak.lines() {
        if let Some(palette_ch) = line.strip_prefix("#") {
            if cur_stanza != Preamble {
                bail!("Palette initiator (line beginning with '#') must be the first content");
            }

            let palette_ch = palette_ch.to_lowercase();

            // `#t`/`#T` only declares that this is a triddler; the palette (if any) is still
            // introduced by a separate `#d`, and comments may sit between the two. A triddler
            // with no colors has no `#d` at all.
            if palette_ch.starts_with("t") {
                triddler = true;
            } else if palette_ch.starts_with("d") {
                cur_stanza = Palette;
            } else {
                bail!("unrecognized directive: #{palette_ch}");
            }
        } else if line.starts_with(":") {
            cur_stanza = Dimension(if let Dimension(n) = cur_stanza {
                n + 1
            } else {
                0
            });
        } else if cur_stanza == Preamble {
            /* Just comments */
        } else if cur_stanza == Palette {
            if line.trim().is_empty() {
                continue;
            }
            let captures = palette_line
                .captures(line)
                .ok_or(anyhow::anyhow!("Malformed palette line {line}"))?;

            let (_, [input_ch, unique_ch, color_name, comment]) = captures.extract();

            let parse_glue = |c| match c {
                '>' => Right,
                '<' => Left,
                _ => NoGlue,
            };

            let rising = color_name.contains('/');

            let (corner, unique_ch) = match (color_name.split_once(['/', '\\']), rising) {
                (None, _) => (None, unique_ch.chars().next().unwrap()),
                (Some(("white", "black")), true) => (
                    Some(Corner {
                        upper: false,
                        left: false,
                    }),
                    '',
                ),
                (Some(("white", "black")), false) => (
                    Some(Corner {
                        upper: true,
                        left: false,
                    }),
                    '',
                ),
                (Some(("black", "white")), true) => (
                    Some(Corner {
                        upper: true,
                        left: true,
                    }),
                    '',
                ),
                (Some(("black", "white")), false) => (
                    Some(Corner {
                        upper: false,
                        left: true,
                    }),
                    '',
                ),
                (Some((_, _)), _) => {
                    eprintln!("Unsupported triangle color combination: {color_name}");
                    (None, unique_ch.chars().next().unwrap())
                }
            };

            let rgb =
                if let Some((_, [rs, gs, bs])) = rrggbb.captures(color_name).map(|c| c.extract()) {
                    (
                        u8::from_str_radix(rs, 16).context("expected hex digits in color")?,
                        u8::from_str_radix(gs, 16).context("expected hex digits in color")?,
                        u8::from_str_radix(bs, 16).context("expected hex digits in color")?,
                    )
                } else if corner.is_some() {
                    (0, 0, 0) // Assumes Triano puzzles are black-and-white!
                } else if let Some((r, g, b)) = named_colors.get(color_name) {
                    (*r, *g, *b)
                } else if let Some((r, g, b)) = named_colors.get(input_ch) {
                    (*r, *g, *b)
                } else {
                    // TODO: generate nice colors, like for chargrid (probably less critical here)
                    (128, 128, 128)
                };

            let dim_0_glue = comment.chars().next().map(parse_glue).unwrap_or(NoGlue);
            let dim_1_glue = comment.chars().nth(1).map(parse_glue).unwrap_or(NoGlue);

            if dim_0_glue != NoGlue || dim_1_glue != NoGlue {
                clue_style = ClueStyle::Triano;
            }

            let color = if input_ch == "0" {
                BACKGROUND
            } else {
                Color(next_color)
            };

            let color_info = ColorInfo {
                ch: unique_ch,
                name: color_name.to_string(),
                rgb,
                color,
                corner,
            };
            let input_ch = input_ch.chars().next().unwrap();

            if dim_0_glue == NoGlue && dim_1_glue == NoGlue {
                olsak_palette.insert(input_ch, color_info);
            } else {
                assert!(dim_0_glue != NoGlue && dim_1_glue != NoGlue);
                olsak_glued_palettes[0].insert((input_ch, dim_0_glue), color_info.clone());
                olsak_glued_palettes[1].insert((input_ch, dim_1_glue), color_info);
            }

            next_color += 1;
        } else if let Dimension(d) = cur_stanza {
            olsak_palette.entry('1').or_insert_with(|| ColorInfo {
                ch: '#',
                name: "black".to_string(),
                rgb: (0, 0, 0),
                color: Color(next_color),
                corner: None,
            });

            if d >= if triddler { 6 } else { 2 } {
                // There can be comments after the end!
                continue;
            }
            let clue_strs = line.split_whitespace();
            match clue_style {
                ClueStyle::Nono => {
                    let mut clues = vec![];
                    for clue_str in clue_strs {
                        if let Ok(count) = clue_str.parse::<u16>() {
                            clues.push(Nono {
                                color: olsak_palette[&'1'].color,
                                count,
                            })
                        } else {
                            let count: u8 = clue_str
                                .trim_end_matches(|c: char| !c.is_numeric())
                                .parse()?;
                            let input_ch = clue_str.chars().last().unwrap();
                            let color = olsak_palette
                                .get(&input_ch)
                                .with_context(|| format!("undefined color: {input_ch}"))?
                                .color;
                            clues.push(Nono {
                                color,
                                count: count as u16,
                            })
                        }
                    }
                    nono_clues[d].push(clues);
                }
                ClueStyle::Triano => {
                    let mut clues = vec![];

                    for clue_str in clue_strs {
                        let mut chars: Vec<char> = clue_str.chars().collect();
                        let front_cap = chars.first().and_then(|c| {
                            olsak_glued_palettes[d].get(&(*c, Left)).map(|c| c.color)
                        });
                        if front_cap.is_some() {
                            chars.remove(0);
                        }
                        let back_cap = chars.last().and_then(|c| {
                            olsak_glued_palettes[d].get(&(*c, Right)).map(|c| c.color)
                        });
                        if back_cap.is_some() {
                            chars.pop();
                        }
                        let last_char = *chars.last().context("clue has no body")?;
                        let body_color = if !last_char.is_numeric() {
                            let body_ch = chars.pop().unwrap();
                            olsak_palette
                                .get(&body_ch)
                                .with_context(|| format!("undefined color: {body_ch}"))?
                                .color
                        } else {
                            olsak_palette[&'1'].color
                        };

                        let body_len = chars.iter().collect::<String>().parse::<u16>()?
                            - (front_cap.is_some() as u16 + back_cap.is_some() as u16);

                        clues.push(Triano {
                            front_cap,
                            body_len,
                            body_color,
                            back_cap,
                        });
                    }
                    triano_clues[d].push(clues);
                }
            }
        }
    }
    olsak_palette
        .entry('0')
        .or_insert_with(ColorInfo::default_bg);

    let mut palette: HashMap<Color, ColorInfo> = olsak_palette
        .into_values()
        .map(|ci| (ci.color, ci))
        .collect();
    for glued_palette in olsak_glued_palettes {
        for (_, ci) in glued_palette.iter() {
            palette.insert(ci.color, ci.clone());
        }
    }

    if triddler {
        if clue_style == ClueStyle::Triano {
            bail!("a puzzle can't be both a triddler and a trianogram");
        }
        return Ok(olsak_triddler(palette, nono_clues)?.into());
    }

    Ok(match clue_style {
        ClueStyle::Nono => {
            Puzzle::<Nono, Square>::square(palette, nono_clues[0].clone(), nono_clues[1].clone())
                .into()
        }
        ClueStyle::Triano => Puzzle::<Triano, Square>::square(
            palette,
            triano_clues[0].clone(),
            triano_clues[1].clone(),
        )
        .into(),
    })
}

pub fn solution_to_triano_puzzle(solution: &Solution<Square>) -> Puzzle<Triano, Square> {
    let width = solution.x_size();
    let height = solution.y_size();

    let mut rows: Vec<Vec<Triano>> = Vec::new();
    let mut cols: Vec<Vec<Triano>> = Vec::new();

    let blank_clue = Triano {
        front_cap: None,
        body_color: BACKGROUND,
        body_len: 0,
        back_cap: None,
    };

    // Generate row clues
    for y in 0..height {
        let mut clues = Vec::<Triano>::new();
        let mut cur_clue = blank_clue;

        for x in 0..width {
            let color = solution[(x, y)];
            let color_info = &solution.palette[&color];

            // For example `!left` means ◢ or ◥:
            if color_info.corner.is_some_and(|c| !c.left) {
                // Only a blank clue can accept a front cap:
                if cur_clue != blank_clue {
                    clues.push(cur_clue);
                    cur_clue = blank_clue
                }
                cur_clue.front_cap = Some(color);
            } else if color_info.corner.is_some_and(|c| c.left) {
                // The back cap is always none...
                cur_clue.back_cap = Some(color);
                // ...because we finish right after setting it
                clues.push(cur_clue);
                cur_clue = blank_clue;
            } else if color == BACKGROUND {
                if cur_clue != blank_clue {
                    clues.push(cur_clue);
                    cur_clue = blank_clue;
                }
            } else {
                // Since the back cap is always none, the only obstacle to continuing is if the
                // body color is wrong.
                if cur_clue.body_color != BACKGROUND && cur_clue.body_color != color {
                    clues.push(cur_clue);
                    cur_clue = blank_clue;
                }
                cur_clue.body_color = color;
                cur_clue.body_len += 1;
            }
        }
        if cur_clue != blank_clue {
            clues.push(cur_clue);
        }

        rows.push(clues);
    }

    // Generate column clues
    for x in 0..width {
        let mut clues = Vec::<Triano>::new();
        let mut cur_clue = blank_clue;

        for y in 0..height {
            let color = solution[(x, y)];
            let color_info = &solution.palette[&color];

            if color_info.corner.is_some_and(|c| !c.upper) {
                // Only a blank clue can accept a front cap:
                if cur_clue != blank_clue {
                    clues.push(cur_clue);
                    cur_clue = blank_clue
                }
                cur_clue.front_cap = Some(color);
            } else if color_info.corner.is_some_and(|c| c.upper) {
                // The back cap is always none...
                cur_clue.back_cap = Some(color);
                // ...because we finish right after setting it
                clues.push(cur_clue);
                cur_clue = blank_clue;
            } else if color == BACKGROUND {
                if cur_clue != blank_clue {
                    clues.push(cur_clue);
                    cur_clue = blank_clue;
                }
            } else {
                // Since the back cap is always none, the only obstacle to continuing is if the
                // body color is wrong.
                if cur_clue.body_color != BACKGROUND && cur_clue.body_color != color {
                    clues.push(cur_clue);
                    cur_clue = blank_clue;
                }
                cur_clue.body_color = color;
                cur_clue.body_len += 1;
            }
        }
        if cur_clue != blank_clue {
            clues.push(cur_clue);
        }

        cols.push(clues);
    }

    Puzzle::square(solution.palette.clone(), rows, cols)
}

/// Read off nonogram clues for one lane: maximal runs of a single non-background color.
fn clues_along_lane<K: GridKind>(solution: &Solution<K>, cells: &[u32]) -> Vec<Nono> {
    let mut clues = Vec::<Nono>::new();

    let mut prev_color: Option<Color> = None;
    let mut run = 1;
    // One extra step past the end, so the final run gets flushed.
    for i in 0..cells.len() + 1 {
        let color = cells.get(i).map(|c| solution.cells[*c as usize]);
        if prev_color == color {
            run += 1;
            continue;
        }
        match prev_color {
            None => {}
            Some(color) if color == BACKGROUND => {}
            Some(color) => clues.push(Nono { color, count: run }),
        }
        prev_color = color;
        run = 1;
    }
    clues
}

/// Derive a puzzle's clues from a finished picture, for any geometry.
pub fn solution_to_nono_puzzle<K: GridKind>(solution: &Solution<K>) -> Puzzle<Nono, K> {
    let lanes = solution.geometry.lane_map();
    let lines = (0..lanes.lane_count())
        .map(|lane| clues_along_lane(solution, &lanes.lane(lane).cells))
        .collect();

    Puzzle {
        palette: solution.palette.clone(),
        geometry: solution.geometry.clone(),
        lines,
    }
}

pub fn solution_to_puzzle(solution: &Solution<Square>) -> Puzzle<Nono, Square> {
    solution_to_nono_puzzle(solution)
}

pub fn solution_to_tri_puzzle(solution: &Solution<Tri>) -> Puzzle<Nono, Tri> {
    solution_to_nono_puzzle(solution)
}

pub fn bw_palette() -> HashMap<Color, ColorInfo> {
    let mut palette = HashMap::new();
    palette.insert(BACKGROUND, ColorInfo::default_bg());
    palette.insert(Color(1), ColorInfo::default_fg(Color(1)));
    palette
}

// It's impossible to get released assests from GitHub for CORS reasons (!?), so
// we grab the raw files:
pub async fn puzzles_from_github() -> anyhow::Result<Vec<Document>> {
    let client = reqwest::Client::new();

    let puzzles_url =
        "https://api.github.com/repos/paulstansifer/number-loom/contents/puzzles?ref=main";

    let contents = client
        .get(puzzles_url)
        .header("User-Agent", "number-loom")
        .send()
        .await?
        .bytes()
        .await?;

    let files: Vec<serde_json::Value> = serde_json::from_slice(&contents)?;

    let mut res: Vec<Document> = vec![];

    for file in files {
        if file["type"] == "file" {
            let name = file["name"].as_str().unwrap();
            let download_url = file["download_url"].as_str().unwrap();

            let content = client.get(download_url).send().await?.bytes().await?;

            res.push(load(name, content.to_vec(), None)?);
        }
    }

    Ok(res)
}

pub async fn load_zip_from_url(url: &str) -> anyhow::Result<Vec<Document>> {
    let response = reqwest::get(url).await?;
    let zip_bytes = response.bytes().await?;
    let zip_cursor = Cursor::new(zip_bytes);

    let mut archive = zip::ZipArchive::new(zip_cursor)?;
    let mut documents = vec![];

    for i in 0..archive.len() {
        let mut file = archive.by_index(i)?;
        let filename = file.name().to_string();

        if file.is_dir() {
            continue;
        }

        let mut bytes = vec![];
        file.read_to_end(&mut bytes)?;
        documents.push(load(&filename, bytes, None)?);
    }

    Ok(documents)
}

pub fn triano_palette() -> HashMap<Color, ColorInfo> {
    let mut palette = HashMap::new();
    palette.insert(BACKGROUND, ColorInfo::default_bg());
    palette.insert(Color(1), ColorInfo::default_fg(Color(1)));

    palette.insert(
        Color(3),
        ColorInfo {
            ch: '',
            name: r#"black/white"#.to_string(),
            rgb: (0, 0, 0),
            color: Color(3),
            corner: Some(Corner {
                upper: true,
                left: true,
            }),
        },
    );
    palette.insert(
        Color(4),
        ColorInfo {
            ch: '',
            name: r#"white\black"#.to_string(),
            rgb: (0, 0, 0),
            color: Color(4),
            corner: Some(Corner {
                upper: true,
                left: false,
            }),
        },
    );
    palette.insert(
        Color(5),
        ColorInfo {
            ch: '',
            name: r#"black\white"#.to_string(),
            rgb: (0, 0, 0),
            color: Color(5),
            corner: Some(Corner {
                upper: false,
                left: true,
            }),
        },
    );
    palette.insert(
        Color(6),
        ColorInfo {
            ch: '',
            name: r#"white/black"#.to_string(),
            rgb: (0, 0, 0),
            color: Color(6),
            corner: Some(Corner {
                upper: false,
                left: false,
            }),
        },
    );

    palette
}