hephaestus 0.1.0

Backend-agnostic 2D scene renderer for data visualization.
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
//! `RectGeom` — vectorised axis-aligned rectangles drawn at scaled
//! `(x, y) – (x2, y2)` diagonal corners.
//!
//! One rectangle per row (PointGeom-style: row == mark). The user
//! supplies two opposite corners; the geom computes `min`/`max`
//! internally so corner ordering doesn't matter.
//!
//! Channels consumed:
//!
//! - `"x"`, `"y"` — one corner of the rect (required; data; numeric).
//! - `"x2"`, `"y2"` — the opposite corner (required; data; numeric).
//! - `"x_offset"`, `"y_offset"`, `"x2_offset"`, `"y2_offset"` —
//!   absolute pt offsets added per edge after scale resolution.
//! - `"x_band"`, `"y_band"`, `"x2_band"`, `"y2_band"` — band-fraction
//!   offsets folded into the scale's `map_with_offset` per edge.
//!   **Defaults**: `x_band = -0.5`, `x2_band = +0.5`, `y_band = 0.0`,
//!   `y2_band = 0.0`. The non-zero x defaults give the canonical
//!   "bar fills its band" behaviour for discrete x scales: bind both
//!   `x` and `x2` to the same category column, and each mark fills
//!   the full band. Continuous x scales have `band_width = 0` so the
//!   defaults are no-ops there.
//! - `"corner_radius"` — uniform corner radius in pt (per-mark;
//!   default 0pt = sharp corners). Clamped by kurbo to at most half
//!   the shorter side.
//! - `"fill"`, `"stroke"`, `"fill_opacity"`, `"stroke_opacity"`,
//!   `"linewidth"`, `"linetype"`, `"dash_offset"`, `"cap"`, `"join"`
//!   — same styling set as LineGeom / PointGeom.
//! - `"angle"` — rotation in **radians** around the rect centre,
//!   mathematical CCW (positive rotates the rect counter-clockwise in
//!   the rendered image). Default `0.0` (no rotation). Band offsets
//!   are resolved **before** rotation, so a band-aligned bar rotated
//!   by `π/4` keeps its band-aligned bbox but the rect's corners poke
//!   beyond the band visually — expected behaviour, not a bug.
//!
//! Stroke is drawn around the rect outline. Fill and stroke are
//! independent — set one, the other, or both.
//!
//! ## Non-linear projections (Polar / future Ternary)
//!
//! Under non-linear projections the geom switches to a **polygon
//! fallback path**: walks the four channel-space corners
//! `(x, y)` / `(x2, y)` / `(x2, y2)` / `(x, y2)` in CCW order,
//! projects each, and densifies each edge via
//! [`Projection::interpolate_segment`](crate::plot::projection::Projection::interpolate_segment)
//! so the polygon outline follows
//! the projected geodesic. Under polar this turns a "rect" into the
//! correct annular wedge or sector.
//!
//! Limitations under non-linear projections:
//!
//! - `"corner_radius"` is ignored (sharp corners on the resulting
//!   polygon).
//! - `"expand"` is ignored — an arbitrary polygon has no single
//!   "outward" direction without a polygon-offset pass.
//! - Rotation pivots on the densified polygon's centroid rather than
//!   the user-rect centre.
//!
//! For typical use cases (bar charts in polar, annular sectors) the
//! limitations don't bite. Plotting code that needs full fidelity
//! under non-linear projections should reach for `PolygonGeom`
//! directly.

use crate::brush::Brush;
use crate::geometry::{Affine, Point, Rect};
use crate::path::FillRule;
use crate::primitives::{polygon as polygon_path, rect as rect_path, rounded_rect, PolygonOptions};
use crate::scene::SceneBuilder;

use super::resolve::{
    draw_stroke_with_linetype, override_alpha, pt_to_px, resolve_angle_channel,
    resolve_cap_channel, resolve_color_channel_or_theme, resolve_join_channel,
    resolve_linetype_channel, resolve_number_channel, resolve_number_channel_or, resolve_pick_id,
    resolve_position,
};
use super::state::{finalize_state, require_x_and_siblings, GeomState, KeysStrategy};
use super::{BuildableGeom, Channel, ExpectedOutput, Geom, GeomBuilder, GeomContext};

// ─── Defaults ────────────────────────────────────────────────────────────────

// Style defaults (linewidth, cap, join) live on `theme.geom.rect`.

/// Default band offset for `"x"`: `-0.5` so the left edge sits at the
/// band's left side on discrete x scales. No effect on continuous scales.
const DEFAULT_X_BAND: f64 = -0.5;
/// Default band offset for `"x2"`: `+0.5` so the right edge sits at the
/// band's right side on discrete x scales.
const DEFAULT_X2_BAND: f64 = 0.5;
/// Default band offset for `"y"`: `0.0`. Users on discrete y scales who
/// want band-filling bars set this explicitly.
const DEFAULT_Y_BAND: f64 = 0.0;
const DEFAULT_Y2_BAND: f64 = 0.0;

const CHANNELS: &[(&str, ExpectedOutput)] = &[
    ("x", ExpectedOutput::Numbers),
    ("y", ExpectedOutput::Numbers),
    ("x2", ExpectedOutput::Numbers),
    ("y2", ExpectedOutput::Numbers),
    ("x_offset", ExpectedOutput::Numbers),
    ("y_offset", ExpectedOutput::Numbers),
    ("x2_offset", ExpectedOutput::Numbers),
    ("y2_offset", ExpectedOutput::Numbers),
    ("x_band", ExpectedOutput::Numbers),
    ("y_band", ExpectedOutput::Numbers),
    ("x2_band", ExpectedOutput::Numbers),
    ("y2_band", ExpectedOutput::Numbers),
    ("corner_radius", ExpectedOutput::Numbers),
    ("fill", ExpectedOutput::Colors),
    ("stroke", ExpectedOutput::Colors),
    ("fill_opacity", ExpectedOutput::Numbers),
    ("stroke_opacity", ExpectedOutput::Numbers),
    ("linewidth", ExpectedOutput::Numbers),
    ("linetype", ExpectedOutput::Linetypes),
    ("dash_offset", ExpectedOutput::Numbers),
    ("cap", ExpectedOutput::Strings),
    ("join", ExpectedOutput::Strings),
    ("expand", ExpectedOutput::Numbers),
    ("angle", ExpectedOutput::Numbers),
    ("pick_id", ExpectedOutput::Numbers),
];

// ─── RectGeom ────────────────────────────────────────────────────────────────

/// A vectorised rectangle geom. One rect per row.
pub struct RectGeom {
    pub(crate) state: GeomState,
}

crate::impl_geom_inherents!(RectGeom);

// ─── BuildableGeom impl ──────────────────────────────────────────────────────

impl BuildableGeom for RectGeom {
    fn build_from(builder: GeomBuilder<Self>) -> Self {
        let (keys_opt, channels) = builder.into_parts();
        let n = require_x_and_siblings(&channels, &["y", "x2", "y2"], "RectGeom");
        let state = finalize_state(
            keys_opt,
            channels,
            n,
            KeysStrategy::PerRow,
            CHANNELS,
            "RectGeom",
        );
        RectGeom { state }
    }
}

// ─── Geom impl ───────────────────────────────────────────────────────────────

impl Geom for RectGeom {
    fn state(&self) -> &GeomState {
        &self.state
    }

    fn state_mut(&mut self) -> &mut GeomState {
        &mut self.state
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn draw(&self, scene: &mut dyn SceneBuilder, ctx: &GeomContext<'_>) {
        let panel = ctx.panel_rect;
        let panel_w = panel.x1 - panel.x0;
        let panel_h = panel.y1 - panel.y0;
        if panel_w <= 0.0 || panel_h <= 0.0 {
            return;
        }
        let n = self.len();
        if n == 0 {
            return;
        }

        let x_scale_bound = ctx.scale_for("x");
        let y_scale_bound = ctx.scale_for("y");
        let x2_scale_bound = ctx.scale_for("x2").or(x_scale_bound);
        let y2_scale_bound = ctx.scale_for("y2").or(y_scale_bound);
        let x_offset_scale = ctx.scale_for("x_offset");
        let y_offset_scale = ctx.scale_for("y_offset");
        let x2_offset_scale = ctx.scale_for("x2_offset");
        let y2_offset_scale = ctx.scale_for("y2_offset");
        let x_band_scale = ctx.scale_for("x_band");
        let y_band_scale = ctx.scale_for("y_band");
        let x2_band_scale = ctx.scale_for("x2_band");
        let y2_band_scale = ctx.scale_for("y2_band");
        let corner_radius_scale = ctx.scale_for("corner_radius");
        let fill_scale = ctx.scale_for("fill");
        let stroke_scale = ctx.scale_for("stroke");
        let fill_opacity_scale = ctx.scale_for("fill_opacity");
        let stroke_opacity_scale = ctx.scale_for("stroke_opacity");
        let linewidth_scale = ctx.scale_for("linewidth");
        let linetype_scale = ctx.scale_for("linetype");
        let dash_offset_scale = ctx.scale_for("dash_offset");
        let cap_scale = ctx.scale_for("cap");
        let join_scale = ctx.scale_for("join");
        let pick_id_scale = ctx.scale_for("pick_id");
        let expand_scale = ctx.scale_for("expand");
        let angle_scale = ctx.scale_for("angle");

        let channels = &self.state.channels;
        let (x_col, x_scale) = match channels.get("x") {
            Some(Channel::Data(c)) => (c, x_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };
        let (y_col, y_scale) = match channels.get("y") {
            Some(Channel::Data(c)) => (c, y_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };
        let (x2_col, x2_scale) = match channels.get("x2") {
            Some(Channel::Data(c)) => (c, x2_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };
        let (y2_col, y2_scale) = match channels.get("y2") {
            Some(Channel::Data(c)) => (c, y2_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };

        let x_offset_ch = channels.get("x_offset");
        let y_offset_ch = channels.get("y_offset");
        let x2_offset_ch = channels.get("x2_offset");
        let y2_offset_ch = channels.get("y2_offset");
        let x_band_ch = channels.get("x_band");
        let y_band_ch = channels.get("y_band");
        let x2_band_ch = channels.get("x2_band");
        let y2_band_ch = channels.get("y2_band");
        let corner_radius_ch = channels.get("corner_radius");
        let fill_ch = channels.get("fill");
        let stroke_ch = channels.get("stroke");
        let fill_opacity_ch = channels.get("fill_opacity");
        let stroke_opacity_ch = channels.get("stroke_opacity");
        let linewidth_ch = channels.get("linewidth");
        let linetype_ch = channels.get("linetype");
        let dash_offset_ch = channels.get("dash_offset");
        let cap_ch = channels.get("cap");
        let join_ch = channels.get("join");
        let pick_id_ch = channels.get("pick_id");
        let expand_ch = channels.get("expand");
        let angle_ch = channels.get("angle");

        for i in 0..n {
            // ── Resolve the four corner positions. ──
            let x_band = resolve_number_channel_or(x_band_ch, x_band_scale, i, DEFAULT_X_BAND);
            let x2_band = resolve_number_channel_or(x2_band_ch, x2_band_scale, i, DEFAULT_X2_BAND);
            let y_band = resolve_number_channel_or(y_band_ch, y_band_scale, i, DEFAULT_Y_BAND);
            let y2_band = resolve_number_channel_or(y2_band_ch, y2_band_scale, i, DEFAULT_Y2_BAND);

            let x_frac = resolve_position(x_col.get(i), x_scale, x_band);
            let x2_frac = resolve_position(x2_col.get(i), x2_scale, x2_band);
            let y_frac = resolve_position(y_col.get(i), y_scale, y_band);
            let y2_frac = resolve_position(y2_col.get(i), y2_scale, y2_band);
            if !x_frac.is_finite()
                || !x2_frac.is_finite()
                || !y_frac.is_finite()
                || !y2_frac.is_finite()
            {
                continue;
            }

            // Per-corner pixel offsets — same logic in both linear and
            // non-linear paths. Y is subtracted because screen y is
            // down while the user's offset convention is positive-up.
            let x_off_px = resolve_number_channel(x_offset_ch, x_offset_scale, i)
                .map(|o| pt_to_px(o, ctx.dpi))
                .unwrap_or(0.0);
            let x2_off_px = resolve_number_channel(x2_offset_ch, x2_offset_scale, i)
                .map(|o| pt_to_px(o, ctx.dpi))
                .unwrap_or(0.0);
            let y_off_px = resolve_number_channel(y_offset_ch, y_offset_scale, i)
                .map(|o| pt_to_px(o, ctx.dpi))
                .unwrap_or(0.0);
            let y2_off_px = resolve_number_channel(y2_offset_ch, y2_offset_scale, i)
                .map(|o| pt_to_px(o, ctx.dpi))
                .unwrap_or(0.0);

            // Project the two diagonal corners. Always needed: the
            // linear path uses these directly for the axis-aligned
            // rect; the non-linear path uses them as two of the four
            // polygon vertices.
            let (px0, py0) = ctx.projection.project_to_panel_px(panel, &[x_frac, y_frac]);
            let (px20, py20) = ctx
                .projection
                .project_to_panel_px(panel, &[x2_frac, y2_frac]);
            let px = px0 + x_off_px;
            let py = py0 - y_off_px;
            let px2 = px20 + x2_off_px;
            let py2 = py20 - y2_off_px;

            // `expand` (pt → px) inflates the linear axis-aligned rect.
            // Under non-linear projections this knob is ignored — an
            // arbitrary polygon has no single "outward" direction
            // without a polygon-offset pass (clipper2).
            let expand_px = pt_to_px(
                resolve_number_channel_or(expand_ch, expand_scale, i, 0.0),
                ctx.dpi,
            );

            // Build the normalised linear rect (robust to corner
            // ordering and y axis flip). Reused by both branches: the
            // linear path uses it as the path; the non-linear path
            // uses its centre as a fallback rotation pivot if the
            // polygon centroid degenerates.
            let x0 = px.min(px2) - expand_px;
            let y0 = py.min(py2) - expand_px;
            let x1 = px.max(px2) + expand_px;
            let y1 = py.max(py2) + expand_px;
            let r = Rect::new(x0, y0, x1, y1);
            let is_linear = ctx.projection.is_linear();
            // A zero-width/height rect is degenerate only for the axis-aligned
            // (linear) path, where `r` *is* the drawn shape. Under a non-linear
            // projection `r` is built from just two of the four polygon corners,
            // which may legitimately share a pixel coordinate (e.g. a 180° polar
            // wedge whose diagonal endpoints both lie on one diameter → zero px
            // width); there `r` only supplies a fallback rotation pivot, so guard
            // finiteness alone and let the polygon path draw.
            if !r.is_finite() || (is_linear && (r.width() <= 0.0 || r.height() <= 0.0)) {
                continue;
            }

            // ── Resolve styling. ──
            let fill_color = override_alpha(
                resolve_color_channel_or_theme(
                    fill_ch,
                    fill_scale,
                    i,
                    ctx.theme.geom.rect.fill.as_ref(),
                    &ctx.theme.palette,
                ),
                resolve_number_channel(fill_opacity_ch, fill_opacity_scale, i),
            );
            let stroke_color = override_alpha(
                resolve_color_channel_or_theme(
                    stroke_ch,
                    stroke_scale,
                    i,
                    ctx.theme.geom.rect.stroke.as_ref(),
                    &ctx.theme.palette,
                ),
                resolve_number_channel(stroke_opacity_ch, stroke_opacity_scale, i),
            );
            let linewidth_pt = resolve_number_channel_or(
                linewidth_ch,
                linewidth_scale,
                i,
                ctx.theme.geom.rect.linewidth_pt,
            );
            let linewidth_px = pt_to_px(linewidth_pt, ctx.dpi);
            let corner_radius_pt =
                resolve_number_channel_or(corner_radius_ch, corner_radius_scale, i, 0.0);
            let corner_radius_px = pt_to_px(corner_radius_pt, ctx.dpi).max(0.0);
            let dash_pattern_pt = resolve_linetype_channel(linetype_ch, linetype_scale, i);
            let dash_offset_pt =
                resolve_number_channel_or(dash_offset_ch, dash_offset_scale, i, 0.0);
            let cap = resolve_cap_channel(cap_ch, cap_scale, i, ctx.theme.geom.rect.cap);
            let join = resolve_join_channel(join_ch, join_scale, i, ctx.theme.geom.rect.join);

            // ── Build the path. ──
            //
            // Linear projection (Cartesian): axis-aligned kurbo rect,
            // honouring corner_radius. The fast path.
            //
            // Non-linear projection (Polar / future Ternary): walk the
            // four channel-space corners, project each, densify each
            // edge via `interpolate_segment`, and build a closed
            // polygon. `corner_radius_px` is ignored in this path
            // (sharp corners on the resulting polygon); `expand_px`
            // was likewise ignored above.
            let (path, rotation_centre) = if is_linear {
                let p = if corner_radius_px > 0.0 {
                    rounded_rect(r, corner_radius_px)
                } else {
                    rect_path(r)
                };
                let centre = Point::new(0.5 * (x0 + x1), 0.5 * (y0 + y1));
                (p, centre)
            } else {
                // Four corners in channel space, in CCW order, plus
                // the per-corner offsets that apply to each.
                let corners: [([f64; 2], f64, f64); 4] = [
                    ([x_frac, y_frac], x_off_px, y_off_px),
                    ([x2_frac, y_frac], x2_off_px, y_off_px),
                    ([x2_frac, y2_frac], x2_off_px, y2_off_px),
                    ([x_frac, y2_frac], x_off_px, y2_off_px),
                ];
                let mut pts: Vec<Point> = Vec::with_capacity(16);
                let mut interior: Vec<(f64, f64)> = Vec::new();
                for k in 0..4 {
                    let (curr, x_off, y_off) = corners[k];
                    let next_channels = corners[(k + 1) % 4].0;
                    let (cpx, cpy) = ctx.projection.project_to_panel_px(panel, &curr);
                    pts.push(Point::new(cpx + x_off, cpy - y_off));
                    // Densify the edge to the next corner. Interior
                    // points sit on the un-offset geodesic — matches
                    // the policy in LineGeom / PolygonGeom.
                    interior.clear();
                    ctx.projection
                        .interpolate_segment(panel, &curr, &next_channels, &mut interior);
                    for (ipx, ipy) in &interior {
                        pts.push(Point::new(*ipx, *ipy));
                    }
                }
                let n_pts = pts.len() as f64;
                let cx = pts.iter().map(|p| p.x).sum::<f64>() / n_pts;
                let cy = pts.iter().map(|p| p.y).sum::<f64>() / n_pts;
                let p = polygon_path(&[&pts], PolygonOptions::default());
                (p, Point::new(cx, cy))
            };

            let pick = resolve_pick_id(pick_id_ch, pick_id_scale, i);

            // Rotation around the rect centre (linear) / polygon
            // centroid (non-linear). Math CCW from the user → negate
            // for kurbo (screen y-down). Identity when angle == 0
            // keeps the recording byte-identical for unrotated rects.
            let angle = resolve_angle_channel(angle_ch, angle_scale, i);
            let xform = if angle == 0.0 {
                Affine::IDENTITY
            } else {
                Affine::rotate_about(-angle, rotation_centre)
            };

            if let Some(fc) = fill_color {
                scene.fill(
                    FillRule::NonZero,
                    xform,
                    &Brush::Solid(fc),
                    None,
                    &path,
                    pick,
                );
            }
            if let Some(sc) = stroke_color {
                draw_stroke_with_linetype(
                    scene,
                    &path,
                    /* closed */ true,
                    sc,
                    sc,
                    linewidth_px,
                    linewidth_pt,
                    cap,
                    join,
                    &dash_pattern_pt,
                    dash_offset_pt,
                    xform,
                    pick,
                    ctx.shapes,
                    ctx.theme.geom.marker_outline_pt,
                    ctx.dpi,
                );
            }
        }
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;

    use crate::color::Color;
    use crate::geometry::Rect as GeomRect;
    use crate::geometry::Shape as _;
    use crate::plot::geom::{linetype, DirectScaleResolver, Raw};
    use crate::plot::scale;
    use crate::plot::value::Value;
    use crate::scene::recording::{Op, RecordingScene};

    fn shapes() -> crate::shape::ShapeRegistry {
        crate::shape::ShapeRegistry::with_builtins()
    }

    fn ctx<'a>(
        panel: GeomRect,
        registry: &'a crate::shape::ShapeRegistry,
        scales: &'a DirectScaleResolver<'a>,
    ) -> GeomContext<'a> {
        GeomContext::new(panel, 96.0, registry, scales)
    }

    fn red() -> Color {
        Color::new([1.0, 0.0, 0.0, 1.0])
    }

    // ── build() validation ──

    #[test]
    fn builder_requires_all_four_positions() {
        let r = std::panic::catch_unwind(|| {
            RectGeom::builder()
                .set("x", vec![0.0_f64, 1.0])
                .set("y", vec![0.0_f64, 1.0])
                .set("x2", vec![0.5_f64, 1.5])
                // y2 missing
                .build()
        });
        assert!(r.is_err());
    }

    #[test]
    #[should_panic(expected = "must be data, not constant")]
    fn builder_x_constant_panics() {
        RectGeom::builder()
            .set("x", 0.0_f64)
            .set("y", vec![0.0_f64])
            .set("x2", vec![1.0_f64])
            .set("y2", vec![1.0_f64])
            .build();
    }

    #[test]
    #[should_panic(expected = "does not match")]
    fn builder_x2_length_mismatch_panics() {
        RectGeom::builder()
            .set("x", vec![0.0_f64, 1.0, 2.0])
            .set("y", vec![0.0_f64, 1.0, 2.0])
            .set("x2", vec![0.5_f64, 1.5]) // wrong length
            .set("y2", vec![1.0_f64, 2.0, 3.0])
            .build();
    }

    // ── Drawing ──

    fn first_fill_rect(scene: &RecordingScene) -> Option<GeomRect> {
        for op in &scene.ops {
            if let Op::Fill { path, .. } = op {
                let bbox = path.bounding_box();
                return Some(GeomRect::new(bbox.x0, bbox.y0, bbox.x1, bbox.y1));
            }
        }
        None
    }

    #[test]
    fn fill_only_at_continuous_corners() {
        // 100x100 panel, scaleless: fractions are values directly. A rect
        // from x=0.1..x2=0.4 and y=0.1..y2=0.4 should fill a 30x30 box
        // somewhere in the panel.
        let g = RectGeom::builder()
            .set("x", vec![0.1_f64])
            .set("y", vec![0.1_f64])
            .set("x2", vec![0.4_f64])
            .set("y2", vec![0.4_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let r = first_fill_rect(&scene).expect("fill");
        // Without scale binding, band defaults apply: x_band=-0.5,
        // x2_band=+0.5 with band_width = 0 (no scale) ⇒ no effect. So
        // x_frac = 0.1, x2_frac = 0.4.
        assert!((r.width() - 30.0).abs() < 1e-6, "width = {}", r.width());
        assert!((r.height() - 30.0).abs() < 1e-6, "height = {}", r.height());
    }

    #[test]
    fn band_fill_default_on_discrete_x_scale() {
        // Two categories, panel 100 wide → each band is 50 px. With
        // x and x2 both bound to "B" and default bands -0.5/+0.5, the
        // rect should span band B exactly (50 px wide).
        let x = scale::discrete(["A", "B"].into_iter().map(|s| Value::String(Arc::from(s))));
        let resolver = DirectScaleResolver::new().with("x", &x).with("x2", &x);
        let g = RectGeom::builder()
            .set("x", vec!["B"])
            .set("x2", vec!["B"])
            .set("y", vec![0.2_f64])
            .set("y2", vec![0.8_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &resolver),
        );
        let r = first_fill_rect(&scene).expect("fill");
        // Band B: x range [50, 100]. Width 50.
        assert!((r.width() - 50.0).abs() < 1e-6, "width = {}", r.width());
        assert!((r.x0 - 50.0).abs() < 1e-6, "x0 = {}", r.x0);
        assert!((r.x1 - 100.0).abs() < 1e-6, "x1 = {}", r.x1);
    }

    #[test]
    fn dodge_within_band_via_per_row_bands() {
        // Two groups in band B, side by side. group 0: [-0.5, 0.0],
        // group 1: [0.0, +0.5]. Each should be 25 px wide.
        let x = scale::discrete(["A", "B"].into_iter().map(|s| Value::String(Arc::from(s))));
        let resolver = DirectScaleResolver::new().with("x", &x).with("x2", &x);
        let g = RectGeom::builder()
            .set("x", vec!["B", "B"])
            .set("x2", vec!["B", "B"])
            .set("y", vec![0.2_f64, 0.2])
            .set("y2", vec![0.8_f64, 0.8])
            .set("x_band", vec![-0.5_f64, 0.0])
            .set("x2_band", vec![0.0_f64, 0.5])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &resolver),
        );
        let widths: Vec<f64> = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Fill { path, .. } => {
                    let bb = path.bounding_box();
                    Some(bb.x1 - bb.x0)
                }
                _ => None,
            })
            .collect();
        assert_eq!(widths.len(), 2);
        for w in &widths {
            assert!((w - 25.0).abs() < 1e-6, "width = {w}");
        }
    }

    #[test]
    fn continuous_scale_band_defaults_have_no_effect() {
        // band_width on continuous scale = 0, so the -0.5/+0.5 defaults
        // contribute 0 to the fraction. The rect spans [x, x2] verbatim.
        let x = scale::continuous(0.0..=10.0);
        let resolver = DirectScaleResolver::new().with("x", &x).with("x2", &x);
        let g = RectGeom::builder()
            .set("x", vec![2.0_f64])
            .set("y", vec![0.0_f64])
            .set("x2", vec![8.0_f64])
            .set("y2", vec![1.0_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &resolver),
        );
        let r = first_fill_rect(&scene).expect("fill");
        // x: 2/10 = 0.2 → 20 px; x2: 8/10 = 0.8 → 80 px.
        assert!((r.x0 - 20.0).abs() < 1e-6);
        assert!((r.x1 - 80.0).abs() < 1e-6);
    }

    #[test]
    fn diagonal_corner_order_doesnt_matter() {
        // x > x2, y > y2 — geom should still produce the same rect via
        // internal min/max.
        let g = RectGeom::builder()
            .set("x", vec![0.4_f64])
            .set("x2", vec![0.1_f64])
            .set("y", vec![0.4_f64])
            .set("y2", vec![0.1_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let r = first_fill_rect(&scene).expect("fill");
        assert!((r.width() - 30.0).abs() < 1e-6);
        assert!((r.height() - 30.0).abs() < 1e-6);
    }

    #[test]
    fn rect_with_corner_radius_uses_rounded_path() {
        let g = RectGeom::builder()
            .set("x", vec![0.1_f64])
            .set("y", vec![0.1_f64])
            .set("x2", vec![0.5_f64])
            .set("y2", vec![0.5_f64])
            .set("fill", red())
            .set("corner_radius", 4.0_f64)
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        // Rounded paths contain curves; sharp rects are line-only.
        let curves = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Fill { path, .. } => Some(path.elements().iter().any(|el| {
                    matches!(
                        el,
                        crate::path::PathEl::CurveTo(_, _, _) | crate::path::PathEl::QuadTo(_, _)
                    )
                })),
                _ => None,
            })
            .next();
        assert_eq!(curves, Some(true), "rounded rect should contain curves");
    }

    #[test]
    fn no_fill_no_stroke_emits_nothing() {
        let g = RectGeom::builder()
            .set("x", vec![0.1_f64])
            .set("y", vec![0.1_f64])
            .set("x2", vec![0.5_f64])
            .set("y2", vec![0.5_f64])
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        assert!(scene.ops.is_empty());
    }

    #[test]
    fn stroke_uses_linewidth_pt_to_px() {
        let g = RectGeom::builder()
            .set("x", vec![0.1_f64])
            .set("y", vec![0.1_f64])
            .set("x2", vec![0.5_f64])
            .set("y2", vec![0.5_f64])
            .set("stroke", red())
            .set("linewidth", 2.0_f64) // 2pt at 96dpi = 8/3 px
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let widths: Vec<f64> = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Stroke { stroke, .. } => Some(stroke.width),
                _ => None,
            })
            .collect();
        assert_eq!(widths.len(), 1);
        assert!((widths[0] - 2.0 * 96.0 / 72.0).abs() < 1e-9);
    }

    #[test]
    fn linetype_dashes_stroke() {
        let g = RectGeom::builder()
            .set("x", vec![0.1_f64])
            .set("y", vec![0.1_f64])
            .set("x2", vec![0.5_f64])
            .set("y2", vec![0.5_f64])
            .set("stroke", red())
            .set("linetype", Value::Linetype(linetype::dashed()))
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let dashed = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Stroke { stroke, .. } => Some(!stroke.dash_pattern.is_empty()),
                _ => None,
            })
            .any(|b| b);
        assert!(dashed);
    }

    #[test]
    fn x_offset_translates_left_edge_in_pt() {
        let g = RectGeom::builder()
            .set("x", vec![0.2_f64])
            .set("y", vec![0.0_f64])
            .set("x2", vec![0.8_f64])
            .set("y2", vec![1.0_f64])
            .set("fill", red())
            .set("x_offset", 9.0_f64) // 12 px right
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let r = first_fill_rect(&scene).expect("fill");
        // x_frac=0.2 → 20 px; +12 px offset → 32 px. x2_frac=0.8 → 80 px.
        assert!((r.x0 - 32.0).abs() < 1e-6, "x0 = {}", r.x0);
        assert!((r.x1 - 80.0).abs() < 1e-6, "x1 = {}", r.x1);
    }

    #[test]
    fn nonfinite_position_skips_row() {
        let g = RectGeom::builder()
            .set("x", vec![0.1_f64, f64::NAN])
            .set("y", vec![0.1_f64, 0.1])
            .set("x2", vec![0.5_f64, 0.5])
            .set("y2", vec![0.5_f64, 0.5])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(GeomRect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let fills = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Fill { .. }))
            .count();
        assert_eq!(fills, 1);
    }

    #[test]
    fn declared_channels_alphabetical() {
        let g = RectGeom::builder()
            .set("x", vec![0.0_f64])
            .set("y", vec![0.0_f64])
            .set("x2", vec![1.0_f64])
            .set("y2", vec![1.0_f64])
            .set("fill", red())
            .build();
        let names: Vec<&str> = g.declared_channels().iter().map(|d| d.name).collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
    }

    #[test]
    fn expand_grows_rect_on_all_sides() {
        use crate::geometry::Shape as _;
        // Rect from (20, 20) → (80, 80) in panel-fraction Raw, so
        // pixel bbox is 20..80 = 60 wide. expand = 3pt = 4 px → bbox
        // 16..84 = 68 wide.
        let g = RectGeom::builder()
            .set("x", Raw(vec![0.2_f64]))
            .set("y", Raw(vec![0.2_f64]))
            .set("x2", Raw(vec![0.8_f64]))
            .set("y2", Raw(vec![0.8_f64]))
            .set("fill", red())
            .set("expand", 3.0_f64)
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let bb = scene
            .ops
            .iter()
            .find_map(|op| match op {
                Op::Fill { path, .. } => Some(path.bounding_box()),
                _ => None,
            })
            .expect("fill");
        let expand_px = 3.0 * 96.0 / 72.0;
        let expected = 60.0 + 2.0 * expand_px;
        assert!((bb.width() - expected).abs() < 0.5);
        assert!((bb.height() - expected).abs() < 0.5);
    }

    #[test]
    fn negative_expand_shrinks_rect() {
        use crate::geometry::Shape as _;
        let g = RectGeom::builder()
            .set("x", Raw(vec![0.2_f64]))
            .set("y", Raw(vec![0.2_f64]))
            .set("x2", Raw(vec![0.8_f64]))
            .set("y2", Raw(vec![0.8_f64]))
            .set("fill", red())
            .set("expand", -3.0_f64)
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let bb = scene
            .ops
            .iter()
            .find_map(|op| match op {
                Op::Fill { path, .. } => Some(path.bounding_box()),
                _ => None,
            })
            .expect("fill");
        let expand_px = 3.0 * 96.0 / 72.0;
        let expected = 60.0 - 2.0 * expand_px;
        assert!((bb.width() - expected).abs() < 0.5);
    }
}