rizzma 1.8.1

A Rust reimplementation of the good parts of matplotlib/pyplot, with first-class wasm support.
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
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
//! Portable-figure tests.
//!
//! The load-bearing test is [`round_trip_is_pixel_identical`]: for a battery of
//! figures covering every artist, scale, and decoration, exporting and
//! re-importing must render a byte-identical PNG. That one assertion
//! transitively pins the entire wire model — a field dropped anywhere in the
//! spec shows up as a pixel difference.
//!
//! The rest of the suite covers what pixel identity cannot see: that bulk data
//! really travels in the binary chunk (and survives values JSON cannot express),
//! that an imported figure is still *live* under interaction, and that every
//! way an artifact can be malformed produces an error rather than a wrong
//! figure or a panic.

use crate::axis::ticker::{
    EngFormatter, FixedLocator, FuncFormatter, LogLocator, MultipleLocator, PercentFormatter,
    StrMethodFormatter,
};
use crate::core::color::Rgba;
use crate::core::{Bbox, Path, RcParams};
use crate::figure::{Axes, Event, Figure, Interactor, MouseButton};
use crate::portable::{Limits, PortableConfig, PortableError, SCHEMA_VERSION};

/// Deterministic pseudo-random values in `0.0..1.0` (no rand dependency).
fn rng(seed: u64) -> impl FnMut() -> f64 {
    let mut state = seed;
    move || {
        state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
        ((state >> 33) as f64) / ((1u64 << 31) as f64)
    }
}

fn linspace(a: f64, b: f64, n: usize) -> Vec<f64> {
    (0..n)
        .map(|i| a + (b - a) * i as f64 / (n - 1).max(1) as f64)
        .collect()
}

/// One figure per interesting corner of the model, each named for failure
/// messages. Every artist type, every scale, and the figure- and axes-level
/// decorations appear at least once.
fn fixtures() -> Vec<(&'static str, Figure)> {
    let mut out: Vec<(&'static str, Figure)> = Vec::new();

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(0.0, 6.0, 64), &linspace(-1.0, 1.0, 64));
    out.push(("line", fig));

    let mut fig = Figure::new(5.0, 3.5);
    let ax = fig.add_subplot(1, 1, 1);
    let x = linspace(0.0, 10.0, 200);
    let y: Vec<f64> = x.iter().map(|v| v.sin() * v).collect();
    ax.plot(&x, &y);
    ax.set_title("decay $\\alpha$");
    ax.set_xlabel("time [s]");
    ax.set_ylabel("amplitude");
    ax.grid(true);
    ax.legend(vec![(Rgba::rgb(0.1, 0.4, 0.8), "signal".to_string())]);
    fig.suptitle("figure title");
    out.push(("styled_line", fig));

    let mut fig = Figure::new(4.0, 4.0);
    let ax = fig.add_subplot(1, 1, 1);
    let mut r = rng(7);
    let xs: Vec<f64> = (0..300).map(|_| r()).collect();
    let ys: Vec<f64> = (0..300).map(|_| r()).collect();
    ax.scatter(&xs, &ys);
    out.push(("scatter", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.bar(&[0.0, 1.0, 2.0, 3.0], &[3.0, 1.0, 4.0, 1.5]);
    out.push(("bar_patches", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let data: Vec<f64> = (0..(16 * 16)).map(|i| (i as f64 * 0.13).sin()).collect();
    ax.imshow(&data, 16, 16);
    fig.colorbar("viridis", -1.0, 1.0);
    out.push(("image_colorbar", fig));

    let mut fig = Figure::new(4.5, 3.5);
    let ax = fig.add_subplot(1, 1, 1);
    let z: Vec<f64> = (0..(20 * 24))
        .map(|i| {
            let (r, c) = (i / 24, i % 24);
            (r as f64 * 0.3).sin() * (c as f64 * 0.2).cos()
        })
        .collect();
    ax.pcolormesh(&z, 20, 24);
    out.push(("quadmesh", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.loglog(&linspace(1.0, 1000.0, 50), &linspace(1.0, 1e6, 50));
    out.push(("loglog", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(-100.0, 100.0, 80), &linspace(-100.0, 100.0, 80));
    ax.set_xscale_symlog(10.0, 2.0);
    ax.set_yscale_asinh(1.0);
    out.push(("symlog_asinh", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(0.01, 0.99, 40), &linspace(0.01, 0.99, 40));
    ax.set_xscale_logit();
    out.push(("logit", fig));

    let mut fig = Figure::new(5.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0, 2.0], &[1.0, 3.0, 2.0]);
    ax.xaxis_mut()
        .set_locator(Box::new(MultipleLocator::with_offset(0.5, 0.1)));
    ax.xaxis_mut()
        .set_formatter(Box::new(StrMethodFormatter::new("{x}")));
    ax.yaxis_mut()
        .set_locator(Box::new(FixedLocator::new(vec![1.0, 2.0, 3.0])));
    ax.yaxis_mut().set_formatter(Box::new(EngFormatter::new()));
    out.push(("custom_tickers", fig));

    let mut fig = Figure::new(5.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.semilogx(&linspace(1.0, 1e4, 40), &linspace(0.0, 1.0, 40));
    ax.xaxis_mut()
        .set_locator(Box::new(LogLocator::with_subs(10.0, vec![1.0, 2.0, 5.0])));
    ax.yaxis_mut()
        .set_formatter(Box::new(PercentFormatter::fraction()));
    out.push(("log_subs_percent", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.axhline(0.5);
    ax.axvspan(0.2, 0.4);
    ax.annotate("peak", (0.5, 0.5), (0.7, 0.8));
    ax.text(0.1, 0.9, "note");
    out.push(("spans_annotations", fig));

    let mut fig = Figure::new(5.0, 4.0).with_rcparams(RcParams::dark());
    let ax = fig.add_subplot(2, 1, 1);
    ax.plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 0.5]);
    let ax = fig.add_subplot(2, 1, 2);
    ax.plot(&[0.0, 1.0, 2.0], &[2.0, 0.0, 1.0]);
    out.push(("dark_two_subplots", fig));

    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1)
        .plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
    fig.twinx(0);
    out.push(("twinx", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let z: Vec<f64> = (0..(30 * 30))
        .map(|i| {
            let (r, c) = ((i / 30) as f64 * 0.2 - 3.0, (i % 30) as f64 * 0.2 - 3.0);
            (-(r * r + c * c) / 4.0).exp()
        })
        .collect();
    ax.contour(&z, 30, 30);
    ax.clabel();
    out.push(("contour_labels", fig));

    out
}

#[test]
fn round_trip_is_pixel_identical() {
    for (name, fig) in fixtures() {
        let bytes = fig
            .to_portable()
            .unwrap_or_else(|e| panic!("{name}: export failed: {e}"));
        let restored =
            Figure::from_portable(&bytes).unwrap_or_else(|e| panic!("{name}: import failed: {e}"));

        let want = fig.encode_png().expect("reference png");
        let got = restored.encode_png().expect("restored png");
        assert_eq!(
            got.len(),
            want.len(),
            "{name}: restored figure rendered a different-sized png"
        );
        assert!(
            got == want,
            "{name}: restored figure is not pixel-identical"
        );
    }
}

#[test]
fn round_trip_preserves_svg_and_pdf_too() {
    // The wire model is backend-agnostic: it restores the scene, not a raster.
    let (_, fig) = fixtures()
        .into_iter()
        .find(|(n, _)| *n == "styled_line")
        .unwrap();
    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert_eq!(restored.to_svg(), fig.to_svg());
    assert_eq!(restored.to_pdf(), fig.to_pdf());
}

#[test]
fn imported_figure_is_still_interactive() {
    // The point of carrying data rather than geometry: the restored figure can
    // be panned and zoomed, revealing data the original viewport never showed,
    // and it lands in exactly the same place as the original would.
    let mut fig = Figure::new(5.0, 4.0);
    let ax = fig.add_subplot(1, 1, 1);
    let x = linspace(0.0, 20.0, 500);
    let y: Vec<f64> = x.iter().map(|v| v.sin()).collect();
    ax.plot(&x, &y);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();

    let drive = |figure: Figure| {
        let mut it = Interactor::new(figure);
        it.handle(Event::Wheel {
            x: 240.0,
            y: 180.0,
            dy: -3.0,
        });
        it.handle(Event::MouseDown {
            x: 240.0,
            y: 180.0,
            button: MouseButton::Left,
        });
        it.handle(Event::MouseMove { x: 300.0, y: 150.0 });
        it.handle(Event::MouseUp {
            x: 300.0,
            y: 150.0,
            button: MouseButton::Left,
        });
        let limits = it.figure().axes()[0].effective_limits();
        (limits, it.figure().encode_png().expect("png"))
    };

    let (want_limits, want_png) = drive(fig);
    let (got_limits, got_png) = drive(restored);
    assert_eq!(
        got_limits, want_limits,
        "zoom/pan diverged after a round trip"
    );
    assert!(
        got_png == want_png,
        "interacted figures rendered differently"
    );
}

#[test]
fn bulk_data_travels_in_the_binary_chunk() {
    // Vertices must not be spelled out as JSON floats: the JSON chunk should
    // stay tiny while the binary chunk carries the samples.
    let mut fig = Figure::new(4.0, 3.0);
    let x = linspace(0.0, 1.0, 20_000);
    fig.add_subplot(1, 1, 1).plot(&x, &x);

    let bytes = fig.to_portable().unwrap();
    let (json, bin) = split(&bytes);
    assert!(
        bin.len() >= 20_000 * 2 * 8,
        "expected both coordinate arrays in the binary chunk, got {} bytes",
        bin.len()
    );
    assert!(
        json.len() < 8_000,
        "json chunk should stay small, got {} bytes",
        json.len()
    );
}

#[test]
fn non_finite_samples_survive_the_round_trip() {
    // JSON cannot express NaN or infinity; the binary chunk can, and gaps in a
    // series are meaningful data, not noise.
    let mut fig = Figure::new(4.0, 3.0);
    let x = vec![0.0, 1.0, 2.0, 3.0, 4.0];
    let y = vec![0.0, f64::NAN, 2.0, f64::INFINITY, -1.0];
    fig.add_subplot(1, 1, 1).plot(&x, &y);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn colormap_sampled_colors_round_trip_exactly() {
    // Mesh face colors come from a colormap as f64 channels; snapping them to
    // 8-bit hex on the way out would shift pixels.
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let z: Vec<f64> = (0..(6 * 8)).map(|i| i as f64 / 47.0).collect();
    ax.pcolormesh(&z, 6, 8);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn save_and_load_a_file() {
    let dir = std::env::temp_dir().join("rizzma-portable-test");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("figure.riz");

    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[1.0, 0.0]);
    fig.save_portable(&path).expect("save");

    let restored = Figure::from_portable(&std::fs::read(&path).expect("read")).expect("load");
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
    std::fs::remove_file(&path).ok();
}

#[test]
fn func_formatter_fails_export_loudly() {
    // A closure cannot cross the wire. Substituting a default formatter would
    // silently relabel every tick, so export refuses instead.
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.xaxis_mut()
        .set_formatter(Box::new(FuncFormatter::from_fn(|v, _| format!("<{v}>"))));

    match fig.to_portable() {
        Err(PortableError::Unsupported(msg)) => {
            assert!(msg.contains("FuncFormatter"), "unhelpful message: {msg}");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

/// The `JSON` and `BIN ` payloads of an artifact, for tests that rewrite one
/// and reframe the other unchanged.
fn split(bytes: &[u8]) -> (&[u8], &[u8]) {
    use crate::portable::container;
    let dir = container::directory(bytes, &Limits::default()).expect("valid container");
    (
        container::chunk(bytes, &dir, container::TAG_JSON).expect("json chunk"),
        container::chunk(bytes, &dir, container::TAG_BIN).unwrap_or(&[]),
    )
}

/// Reframe a (possibly doctored) spec and binary payload into an artifact.
fn reframe(json: &[u8], bin: &[u8]) -> Vec<u8> {
    use crate::portable::container;
    container::write(&[(container::TAG_JSON, json), (container::TAG_BIN, bin)])
}

/// Import `bytes` and discard the figure, so a wrongly-accepted artifact
/// formats in a panic message (`Figure` is deliberately not `Debug`).
fn import(bytes: &[u8]) -> Result<(), PortableError> {
    Figure::from_portable(bytes).map(|_| ())
}

#[test]
fn the_poster_is_what_the_renderer_would_draw() {
    // The poster is a byproduct of a figure the exporter already holds, so it
    // must be exactly the PNG that figure renders — not an approximation.
    let mut fig = Figure::new(5.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(0.0, 6.0, 50), &linspace(0.0, 1.0, 50));
    ax.set_title("decay");

    let bytes = fig.to_portable().expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");
    let poster = info.poster(&bytes).expect("a poster by default");

    assert_eq!(&poster[..8], b"\x89PNG\r\n\x1a\n", "poster must be a PNG");
    assert!(
        poster == fig.encode_png().expect("png").as_slice(),
        "poster differs from the figure's own render"
    );
    let meta = info.meta.expect("schema 2 carries meta");
    assert_eq!(meta.poster.expect("poster ref").bytes, poster.len());
}

#[test]
fn inspect_sizes_a_card_without_a_renderer() {
    // What a host reads before deciding to fetch 370 KB of wasm: the exact box
    // to reserve, the text to announce, and something to show meanwhile.
    let mut fig = Figure::new(6.4, 4.8).with_dpi(100.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.set_title("step response");

    let cfg = PortableConfig::default().with_alt("step response rising to one");
    let bytes = fig.to_portable_with(&cfg).expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");

    assert!(info.renderable(), "this build must render its own schema");
    let meta = info.meta.expect("meta");
    assert_eq!((meta.width_px, meta.height_px), (640, 480));
    assert_eq!(meta.alt.as_deref(), Some("step response rising to one"));
    assert_eq!(meta.title.as_deref(), Some("step response"));
    assert!(!meta.animated);
    assert_eq!(info.generator.rizzma, env!("CARGO_PKG_VERSION"));
}

#[test]
fn the_poster_can_be_turned_off() {
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[1.0, 0.0]);

    let with = fig.to_portable().expect("export");
    let without = fig
        .to_portable_with(&PortableConfig::default().with_poster(false))
        .expect("export");
    assert!(
        without.len() < with.len(),
        "dropping the poster should shrink the artifact"
    );

    let info = crate::portable::inspect(&without, &Limits::default()).expect("inspect");
    assert!(info.poster(&without).is_none());
    assert!(info.meta.expect("meta").poster.is_none());
    // Still a complete figure: the poster is a fallback, not the content.
    let restored = Figure::from_portable(&without).expect("import");
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn schema_1_artifacts_still_load() {
    // Artifacts written by 1.7.x carry no `meta` and no poster. Refusing them
    // would break every figure already archived, so the field is optional for
    // as long as SCHEMA_MIN is 1.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1)
        .plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
    let current = fig.to_portable().expect("export");

    // Rewrite it as a schema-1 document: drop `meta` and the poster chunk.
    let (json, bin) = split(&current);
    let mut spec: serde_json::Value = serde_json::from_slice(json).expect("json");
    spec["schema"] = serde_json::json!(1);
    spec.as_object_mut().expect("object").remove("meta");
    let legacy = reframe(spec.to_string().as_bytes(), bin);

    let info = crate::portable::inspect(&legacy, &Limits::default()).expect("inspect");
    assert_eq!(info.schema, 1);
    assert!(info.schema_supported, "1 is still within the range");
    assert!(info.meta.is_none());

    let restored = Figure::from_portable(&legacy).expect("schema 1 must still import");
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn import_enforces_caller_budgets() {
    let bytes = sample_bytes();
    let tight = Limits::default().with_max_total_bytes(128);
    match Figure::from_portable_limited(&bytes, &tight).map(|_| ()) {
        Err(PortableError::Budget(msg)) => assert!(msg.contains("128"), "{msg}"),
        other => panic!("expected Budget, got {other:?}"),
    }
    // The default budget admits an ordinary figure.
    assert!(Figure::from_portable_limited(&bytes, &Limits::default()).is_ok());
}

/// A valid artifact to mutate in the rejection tests below.
fn sample_bytes() -> Vec<u8> {
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1)
        .plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
    fig.to_portable().expect("export")
}

/// Re-frame `spec_json` into a container with an empty binary chunk.
fn container_with_json(json: &str) -> Vec<u8> {
    reframe(json.as_bytes(), &[])
}

/// The artifact's spec JSON as a mutable `serde_json` value.
fn sample_spec() -> serde_json::Value {
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    serde_json::from_slice(json).unwrap()
}

#[test]
fn rejects_bad_magic() {
    let mut bytes = sample_bytes();
    bytes[0] = b'X';
    assert!(matches!(
        Figure::from_portable(&bytes),
        Err(PortableError::Malformed(_))
    ));
}

#[test]
fn rejects_truncation() {
    let bytes = sample_bytes();
    for cut in [0, 4, 11, 20, bytes.len() / 2, bytes.len() - 1] {
        assert!(
            Figure::from_portable(&bytes[..cut]).is_err(),
            "truncating to {cut} bytes should not load"
        );
    }
}

#[test]
fn rejects_a_future_schema() {
    let mut spec = sample_spec();
    spec["schema"] = serde_json::json!(SCHEMA_VERSION + 1);
    let bytes = container_with_json(&spec.to_string());
    match import(&bytes) {
        Err(PortableError::Schema { found, max, .. }) => {
            assert_eq!(found, SCHEMA_VERSION + 1);
            assert_eq!(max, SCHEMA_VERSION);
        }
        other => panic!("expected Schema, got {other:?}"),
    }
}

#[test]
fn rejects_unknown_fields() {
    // Forward compatibility by skipping is wrong for a figure: an artist a
    // newer schema introduced would vanish without a trace.
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["lines"][0]["glow"] = serde_json::json!(true);
    let bytes = container_with_json(&spec.to_string());
    assert!(matches!(
        Figure::from_portable(&bytes),
        Err(PortableError::Json(_))
    ));
}

#[test]
fn rejects_unknown_enum_variants() {
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["xscale"] = serde_json::json!({ "hyperbolic": { "k": 2.0 } });
    let bytes = container_with_json(&spec.to_string());
    assert!(matches!(
        Figure::from_portable(&bytes),
        Err(PortableError::Json(_))
    ));
}

#[test]
fn rejects_out_of_bounds_accessors() {
    let mut spec = sample_spec();
    spec["accessors"][0]["count"] = serde_json::json!(1_000_000);
    let bytes = sample_bytes();
    let (_, bin) = split(&bytes);
    let bin = bin.to_vec();
    let reframed = reframe(spec.to_string().as_bytes(), &bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("accessor"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_a_dangling_accessor_index() {
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["lines"][0]["x"] = serde_json::json!({ "acc": 999 });
    let bytes = sample_bytes();
    let (_, bin) = split(&bytes);
    let reframed = reframe(spec.to_string().as_bytes(), bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("999"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_inconsistent_array_lengths() {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let data: Vec<f64> = (0..12).map(|i| i as f64).collect();
    ax.imshow(&data, 3, 4);
    let bytes = fig.to_portable().unwrap();

    let (json, bin) = split(&bytes);
    let mut spec: serde_json::Value = serde_json::from_slice(json).unwrap();
    // Claim a 5x4 grid over the same 12 samples.
    spec["figure"]["axes"][0]["images"][0]["nrows"] = serde_json::json!(5);
    let reframed = reframe(spec.to_string().as_bytes(), bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("samples"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_hostile_locator_parameters() {
    // A zero step would trip a constructor assertion; the importer turns it
    // into an error rather than letting a malformed artifact panic the process.
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["xaxis"]["locator"] =
        serde_json::json!({ "multiple": { "step": 0.0, "offset": 0.0 } });
    let bytes = sample_bytes();
    let (_, bin) = split(&bytes);
    let reframed = reframe(spec.to_string().as_bytes(), bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("step"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_self_contained_chunks_this_build_cannot_honor() {
    // FONT/WASM chunks belong to a later phase; ignoring them would render
    // with the wrong font or the wrong renderer.
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    let mut framed = reframe(json, &[]);
    // Append a FONT chunk and fix up the declared total length.
    let payload = b"not-a-font";
    framed.extend_from_slice(&(payload.len() as u32).to_le_bytes());
    framed.extend_from_slice(b"FONT");
    framed.extend_from_slice(payload);
    while !framed.len().is_multiple_of(8) {
        framed.push(0);
    }
    let total = framed.len() as u32;
    framed[8..12].copy_from_slice(&total.to_le_bytes());

    match import(&framed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("FONT"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_a_duplicate_chunk() {
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    let mut framed = reframe(json, &[]);
    let start = framed.len();
    framed.extend_from_slice(&(json.len() as u32).to_le_bytes());
    framed.extend_from_slice(b"JSON");
    framed.extend_from_slice(json);
    while !framed.len().is_multiple_of(8) {
        framed.push(0);
    }
    assert!(framed.len() > start);
    let total = framed.len() as u32;
    framed[8..12].copy_from_slice(&total.to_le_bytes());

    match import(&framed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("duplicate"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_an_unknown_path_code() {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.add_patch(crate::artist::Patch::new(Path::from_polyline(&[
        [0.0, 0.0],
        [1.0, 0.0],
        [1.0, 1.0],
    ])));
    ax.scatter(&[0.5], &[0.5]);
    let bytes = fig.to_portable().unwrap();
    let (json, bin) = split(&bytes);
    let spec: serde_json::Value = serde_json::from_slice(json).unwrap();

    // Find a u8 (path-code) accessor and corrupt its first byte.
    let mut bin = bin.to_vec();
    let offset = spec["accessors"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["dtype"] == "u8")
        .map(|a| a["offset"].as_u64().unwrap() as usize)
        .expect("a path-code accessor");
    bin[offset] = 200;

    let reframed = reframe(json, &bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("path code"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn error_messages_name_the_problem() {
    // These strings are what a user sees when an artifact will not load, so
    // they are part of the contract.
    let schema = PortableError::Schema {
        found: 9,
        min: 1,
        max: 2,
    };
    let text = schema.to_string();
    assert!(text.contains('9') && text.contains("1..=2"), "{text}");
    assert!(text.contains("drop content"), "{text}");
}

#[test]
fn spec_bytes_are_stable_across_a_round_trip() {
    // Export → import → export must reproduce the artifact byte-for-byte:
    // nothing is invented, reordered, or lost on the way through.
    let first = sample_bytes();
    let second = Figure::from_portable(&first)
        .unwrap()
        .to_portable()
        .unwrap();
    assert_eq!(first, second);
}

#[test]
fn json_scalars_round_trip_bit_exactly() {
    // Scalars (limits, positions, colors) travel as JSON numbers, and
    // serde_json only parses them back to the same bits with its
    // `float_roundtrip` feature enabled — without it, values land one ULP off
    // and a re-exported artifact silently differs from its original. This test
    // pins that dependency feature; it is not hypothetical, it fired once.
    let awkward = [
        0.109_999_999_999_999_99_f64,
        1.0 / 3.0,
        f64::MIN_POSITIVE,
        f64::MAX,
        std::f64::consts::PI * 1e-7,
    ];
    for v in awkward {
        let text = serde_json::to_string(&v).expect("serialize");
        let back: f64 = serde_json::from_str(&text).expect("parse");
        assert_eq!(
            back.to_bits(),
            v.to_bits(),
            "{v} did not survive a JSON round trip ({text})"
        );
    }
}

#[test]
fn declares_its_schema_and_generator() {
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    let spec: serde_json::Value = serde_json::from_slice(json).unwrap();
    assert_eq!(spec["schema"], SCHEMA_VERSION);
    assert_eq!(spec["generator"]["rizzma"], env!("CARGO_PKG_VERSION"));
    assert_eq!(spec["renderer"]["version"], env!("CARGO_PKG_VERSION"));
}

#[test]
fn an_empty_figure_round_trips() {
    let fig = Figure::new(3.0, 2.0).with_facecolor(Rgba::rgb(0.2, 0.3, 0.4));
    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn axes_added_by_rect_keep_their_position() {
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_axes(0.2, 0.3, 0.5, 0.4);
    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    let want: Bbox = fig.axes()[0].position();
    let got: Bbox = restored.axes()[0].position();
    assert_eq!(
        (got.x0, got.y0, got.x1, got.y1),
        (want.x0, want.y0, want.x1, want.y1)
    );
}

#[test]
fn axes_helper_is_reachable_for_every_artist_vec() {
    // Guards against a new artist Vec being added to `Axes` without a matching
    // wire field: the spec's own struct is exhaustive, so this compiles only
    // while the two agree.
    let mut fig = Figure::new(4.0, 3.0);
    let ax: &mut Axes = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.scatter(&[0.5], &[0.5]);
    ax.bar(&[0.0], &[1.0]);
    ax.imshow(&[1.0, 2.0, 3.0, 4.0], 2, 2);
    ax.pcolormesh(&[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], 2, 3);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

// ---------------------------------------------------------------------------
// Inspection: reading an artifact without building a figure from it.
//
// These build artifacts by hand rather than through the exporter, so a
// malformed or future-schema document can be exercised directly — cases the
// exporter cannot produce.
// ---------------------------------------------------------------------------

use crate::portable::container::{self, TAG_BIN, TAG_JSON, TAG_PSTR};
use crate::portable::inspect;

/// A minimal but valid schema-2 spec document.
fn spec_json(poster_bytes: usize) -> String {
    let poster = if poster_bytes > 0 {
        format!(r#","poster":{{"chunk":"PSTR","mime":"image/png","bytes":{poster_bytes}}}"#)
    } else {
        r#","poster":null"#.to_string()
    };
    format!(
        r#"{{"schema":{SCHEMA_VERSION},
            "generator":{{"rizzma":"1.8.0"}},
            "renderer":{{"version":"1.8.0","sha256":"9f2c"}},
            "meta":{{"width_px":640,"height_px":480,"alt":"a figure",
                     "title":"demo"{poster},"animated":false}},
            "figure":{{"ignored":true}},
            "accessors":[]}}"#
    )
}

fn artifact(poster: &[u8], bin: &[u8]) -> Vec<u8> {
    let json = spec_json(poster.len());
    let mut chunks: Vec<([u8; 4], &[u8])> = vec![(TAG_JSON, json.as_bytes())];
    if !poster.is_empty() {
        chunks.push((TAG_PSTR, poster));
    }
    if !bin.is_empty() {
        chunks.push((TAG_BIN, bin));
    }
    container::write(&chunks)
}

#[test]
fn reads_metadata_without_the_bulk_payload() {
    // The point of the crate: learn the figure's size, alt text, and poster
    // without touching a megabyte of samples.
    let bin = vec![7u8; 1_000_000];
    let bytes = artifact(b"fake-png", &bin);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");

    assert_eq!(info.schema, SCHEMA_VERSION);
    assert!(info.schema_supported && info.renderable());
    assert_eq!(info.generator.rizzma, "1.8.0");
    assert_eq!(info.renderer.version, "1.8.0");
    let meta = info.meta.as_ref().expect("schema 2 carries meta");
    assert_eq!((meta.width_px, meta.height_px), (640, 480));
    assert_eq!(meta.alt.as_deref(), Some("a figure"));
    assert_eq!(info.poster(&bytes), Some(&b"fake-png"[..]));
    assert_eq!(info.total_bytes, bytes.len());
    assert_eq!(info.chunks.len(), 3);
}

#[test]
fn a_schema_1_artifact_still_inspects() {
    // Artifacts written before the meta block must not become unreadable:
    // no size, no poster, but provenance and renderability still resolve.
    let json = r#"{"schema":1,"generator":{"rizzma":"1.7.0"},
                   "renderer":{"version":"1.7.0","sha256":null},
                   "figure":{},"accessors":[]}"#;
    let bytes = container::write(&[(TAG_JSON, json.as_bytes())]);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");
    assert_eq!(info.schema, 1);
    assert!(info.schema_supported);
    assert!(info.meta.is_none());
    assert!(info.poster(&bytes).is_none());
}

#[test]
fn an_unsupported_schema_is_reported_not_refused() {
    // A host still wants the size and poster of a figure it cannot draw, so a
    // future schema is a flag rather than an error.
    let json = format!(
        r#"{{"schema":{},"generator":{{"rizzma":"9.9.9"}},
             "renderer":{{"version":"9.9.9","sha256":null}},
             "meta":{{"width_px":640,"height_px":480,"alt":null,"title":null,
                      "poster":null,"animated":true}}}}"#,
        SCHEMA_VERSION + 1
    );
    let bytes = container::write(&[(TAG_JSON, json.as_bytes())]);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");
    assert_eq!(info.schema, SCHEMA_VERSION + 1);
    assert!(!info.schema_supported, "must not claim it can render this");
    assert!(!info.renderable());
    assert!(info.meta.expect("meta").animated);
}

#[test]
fn budgets_are_enforced_before_allocating() {
    let bytes = artifact(b"fake-png", &vec![0u8; 4096]);

    let tiny = Limits::default().with_max_total_bytes(64);
    match inspect(&bytes, &tiny) {
        Err(PortableError::Budget(msg)) => assert!(msg.contains("over the 64 byte limit"), "{msg}"),
        other => panic!("expected Budget, got {other:?}"),
    }

    let json_capped = Limits::default().with_max_json_bytes(10);
    assert!(matches!(
        inspect(&bytes, &json_capped),
        Err(PortableError::Budget(_))
    ));

    let pixel_capped = Limits::default().with_max_canvas_pixels(1000);
    match inspect(&bytes, &pixel_capped) {
        Err(PortableError::Budget(msg)) => assert!(msg.contains("640x480"), "{msg}"),
        other => panic!("expected Budget, got {other:?}"),
    }
}

#[test]
fn a_lying_poster_length_is_malformed() {
    // The spec says 8 bytes; the chunk holds 4. Trusting the spec would hand a
    // truncated image to a decoder.
    let json = spec_json(8);
    let bytes = container::write(&[(TAG_JSON, json.as_bytes()), (TAG_PSTR, b"abcd")]);
    match inspect(&bytes, &Limits::default()) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("poster"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn structural_corruption_is_rejected() {
    let good = artifact(b"png", b"bin");

    let mut bad_magic = good.clone();
    bad_magic[0] = b'X';
    assert!(matches!(
        inspect(&bad_magic, &Limits::default()),
        Err(PortableError::Malformed(_))
    ));

    for cut in [0, 8, 11, good.len() / 2, good.len() - 1] {
        assert!(
            inspect(&good[..cut], &Limits::default()).is_err(),
            "truncating to {cut} bytes must not inspect"
        );
    }

    // A duplicate chunk is ambiguous, so it is refused rather than guessed.
    let json = spec_json(0);
    let mut dup = container::write(&[(TAG_JSON, json.as_bytes()), (TAG_JSON, json.as_bytes())]);
    let total = dup.len() as u32;
    dup[8..12].copy_from_slice(&total.to_le_bytes());
    match inspect(&dup, &Limits::default()) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("duplicate"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn json_and_poster_precede_bulk_payloads() {
    // Writers order chunks so a partial read can paint a card; readers must
    // still tolerate any order, which the duplicate/lookup tests exercise.
    let bytes = artifact(b"png", &vec![0u8; 2048]);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");
    let tags: Vec<String> = info.chunks.iter().map(container::ChunkRef::name).collect();
    assert_eq!(tags, vec!["JSON", "PSTR", "BIN "]);
}

#[test]
fn missing_json_chunk_is_refused() {
    let bytes = container::write(&[(TAG_PSTR, b"png")]);
    match inspect(&bytes, &Limits::default()) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("JSON"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}