hephaestus 0.2.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
//! Codec for the plot layer: projections, axis and legend specs, the
//! layout extents a composition's tracks are made of, the composition
//! template, and the plots themselves.
//!
//! Three shapes of impl appear here, in ascending order of care:
//!
//! - **Plain data with reachable fields** — projections, legend specs,
//!   layout extents. One [`impl_codec`] line each. `Legend`'s fields are
//!   `pub(crate)`, which is enough from inside the crate.
//! - **Encapsulated types** — [`PolarProjection`] and
//!   [`Axis`](crate::plot::Axis) keep their fields private, so they are
//!   read through accessors and rebuilt through builders, exactly as
//!   [`Scale`](crate::plot::Scale) is in [`super::impls_scale`].
//! - **Aggregates** — a `Plot` is reassembled by replaying the calls
//!   that built it. Its geoms come back through the kind tag and the
//!   factory table in [`super::ReadContext`].
//!
//! One deliberate lossiness: `GeomId` / `AxisId` / `LegendId` are not
//! carried. They are handles for later `update_geom`-style calls, not
//! anything drawing depends on — draw order is vector order, which is
//! preserved — and a handle can't outlive the process that issued it
//! anyway. Replaying through `add_geom` / `add_axis` / `add_legend`
//! renumbers from zero, which differs from the original only where the
//! original had gaps.

use std::collections::HashMap;

use super::codec::impl_codec;
#[cfg(feature = "document-read")]
use super::codec::{Decode, Reader};
#[cfg(feature = "document-write")]
use super::codec::{Encode, Writer};
#[cfg(feature = "document-read")]
use super::DocumentError;
use crate::layout::Axis as LayoutAxis;
use crate::layout::{CellId, Extent, Inset, Placement, Track};
use crate::plot::chrome::axis::{Axis, AxisPlacement, PolarRing};
use crate::plot::chrome::legend::{
    AestheticSource, BinSpacing, ColorbarSpec, Legend, LegendBody, LegendKey, LegendKeySpec,
    StackBody,
};
use crate::plot::geom::Channel;
use crate::plot::projection::{
    ChromeStrategy, CustomProjection, PolarEdgeStyle, PolarProjection, Projection,
};
use crate::scales::chrome::{Anchor, AxisSide, LegendSide};

// ─── Layout extents ──────────────────────────────────────────────────────────

impl_codec! {
    enum LayoutAxis {
        0 => Width,
        1 => Height,
    }

    newtype CellId;

    enum Extent {
        0 => Sum { px, inches, percent },
        1 => Min(a, b),
        2 => Max(a, b),
        // `grid` is a `CellId` handed out by the layout solver, so it
        // means nothing in another process. The wire form exists so the
        // format needn't change if track references ever become
        // portable; the write-side validation pass refuses a document
        // that would depend on one.
        3 => TrackOf { grid, axis, track, span },
    }

    enum Track {
        0 => Fixed(extent),
        1 => Fr(share),
        2 => Auto,
    }

    struct Inset { left, right, top, bottom, width, height }
    struct Placement { row, col, row_span, col_span, inset }
}

// ─── Projections ─────────────────────────────────────────────────────────────

impl_codec! {
    enum ChromeStrategy {
        0 => PatchSlots,
        1 => InsidePanel,
    }

    enum PolarEdgeStyle {
        0 => Geodesic,
        1 => Chord,
    }

    struct CustomProjection { outline, x_major, x_minor, y_major, y_minor, x_channel, y_channel }

    enum Projection {
        0 => Cartesian,
        1 => Polar(p),
        2 => Custom(p),
    }
}

// `PolarProjection` keeps its fields private; every one has both an
// accessor and a builder, so it round-trips through the same calls that
// would have configured it by hand — including whatever clamping those
// builders apply.
#[cfg(feature = "document-write")]
impl Encode for PolarProjection {
    fn encode(&self, w: &mut Writer) {
        self.angle_channel().encode(w);
        self.radius_channel().encode(w);
        self.theta_start().encode(w);
        self.theta_end().encode(w);
        self.inner_radius_frac().encode(w);
        self.outer_radius_frac().encode(w);
        self.edge_style().encode(w);
        self.theta_break_fracs().to_vec().encode(w);
        self.is_fit_to_bbox().encode(w);
    }
}

#[cfg(feature = "document-read")]
impl Decode for PolarProjection {
    fn decode(r: &mut Reader<'_>) -> Result<Self, DocumentError> {
        let angle = String::decode(r)?;
        let radius = String::decode(r)?;
        let theta_start = f64::decode(r)?;
        let theta_end = f64::decode(r)?;
        let inner = f64::decode(r)?;
        let outer = f64::decode(r)?;
        let edges = PolarEdgeStyle::decode(r)?;
        let breaks = Vec::<f64>::decode(r)?;
        let fit = bool::decode(r)?;
        Ok(PolarProjection::full_circle()
            .channels(angle, radius)
            .theta_range(theta_start, theta_end)
            .inner_radius(inner)
            .outer_radius(outer)
            .edges(edges)
            .theta_breaks(breaks)
            .fit_to_bbox(fit))
    }
}

// ─── Axis chrome ─────────────────────────────────────────────────────────────

impl_codec! {
    enum AxisSide {
        0 => Left,
        1 => Right,
        2 => Bottom,
        3 => Top,
    }

    enum PolarRing {
        0 => Outer,
        1 => Inner,
    }

    enum AxisPlacement {
        0 => Cartesian(side),
        1 => PolarRadius { theta_frac },
        2 => PolarAngular(ring),
    }
}

// An axis is either a rail or title-only, which is what the two
// constructors express; the private fields are reached through the
// matching accessors.
#[cfg(feature = "document-write")]
impl Encode for Axis {
    fn encode(&self, w: &mut Writer) {
        self.scale_name().map(str::to_string).encode(w);
        self.placement().encode(w);
        self.title_ref().map(str::to_string).encode(w);
    }
}

#[cfg(feature = "document-read")]
impl Decode for Axis {
    fn decode(r: &mut Reader<'_>) -> Result<Self, DocumentError> {
        let scale_name = Option::<String>::decode(r)?;
        let placement = AxisPlacement::decode(r)?;
        let title = Option::<String>::decode(r)?;
        let axis = match (scale_name, &title) {
            (Some(name), _) => Axis::rail(name, placement),
            // A rail-less axis still reserves its title slot, and
            // `title_only` is the only way to build one.
            (None, Some(t)) => Axis::title_only(t.clone(), placement),
            (None, None) => Axis::title_only(String::new(), placement),
        };
        Ok(match title {
            Some(t) => axis.title(t),
            None => axis,
        })
    }
}

// ─── Legends ─────────────────────────────────────────────────────────────────

impl_codec! {
    enum Anchor {
        0 => TopLeft,
        1 => TopCenter,
        2 => TopRight,
        3 => CenterLeft,
        4 => Center,
        5 => CenterRight,
        6 => BottomLeft,
        7 => BottomCenter,
        8 => BottomRight,
    }

    enum LegendSide {
        0 => Left,
        1 => Right,
        2 => Top,
        3 => Bottom,
        4 => InPanel { anchor, inset_pt },
    }

    enum LegendKey {
        0 => Point,
        1 => Line,
        2 => Rect,
        3 => Text,
    }

    enum AestheticSource {
        0 => Scaled(scale_name),
        1 => Fixed(value),
    }

    struct LegendKeySpec { kind, bindings }
    struct StackBody { keys, binned }
    struct ColorbarSpec { samples, stepped, bindings }

    enum LegendBody {
        0 => Stack(body),
        1 => Colorbar(spec),
    }

    enum BinSpacing {
        0 => Proportional,
        1 => Equal,
    }

    struct Legend {
        side,
        title,
        domain_scale,
        body,
        open_lower,
        open_upper,
        bin_spacing,
        theme_variant,
        merge,
    }
}

// ─── Geoms ───────────────────────────────────────────────────────────────────

impl_codec! {
    enum Channel {
        0 => Constant(v),
        1 => Data(col),
        2 => RawConstant(v),
        3 => RawData(col),
    }
}

/// A geom's whole serializable state: its kind tag plus the parts a
/// [`GeomBuilder`](crate::plot::GeomBuilder) would have been given.
///
/// Everything else a concrete geom holds — mark layouts, orientation,
/// the declared-channel list, the diff snapshot — is derived, and
/// `build_from` recomputes all of it.
#[cfg(any(feature = "document-read", feature = "document-write"))]
pub(crate) struct GeomParts {
    pub(crate) kind: String,
    pub(crate) keys: Option<crate::scales::value::DataColumn>,
    pub(crate) channels: HashMap<String, Channel>,
}

#[cfg(feature = "document-write")]
impl Encode for GeomParts {
    fn encode(&self, w: &mut Writer) {
        self.kind.encode(w);
        self.keys.encode(w);
        self.channels.encode(w);
    }
}

#[cfg(feature = "document-read")]
impl Decode for GeomParts {
    fn decode(r: &mut Reader<'_>) -> Result<Self, DocumentError> {
        Ok(GeomParts {
            kind: String::decode(r)?,
            keys: Option::decode(r)?,
            channels: HashMap::decode(r)?,
        })
    }
}

#[cfg(feature = "document-read")]
impl GeomParts {
    /// Rebuild the geom, resolving the kind tag through `r`'s context.
    pub(crate) fn build(self, r: &Reader<'_>) -> Result<Box<dyn crate::plot::Geom>, DocumentError> {
        let factory =
            r.ctx()
                .geom_factory(&self.kind)
                .ok_or_else(|| DocumentError::UnknownGeom {
                    kind: self.kind.clone(),
                })?;
        Ok(factory(self.keys, self.channels))
    }
}

/// Read a geom's parts off a live geom, or `None` when it can't be
/// named on the wire.
#[cfg(feature = "document-write")]
pub(crate) fn geom_parts(g: &dyn crate::plot::Geom) -> Option<GeomParts> {
    let kind = g.kind()?.to_string();
    let state = g.state();
    Some(GeomParts {
        kind,
        // The builder's view of keys: an explicit column, or `None` for
        // synthesised positional ones. This mirrors what each geom's
        // `update` carries forward, so replaying reproduces the same
        // state the live geom had.
        keys: match &state.keys {
            crate::plot::Keys::Explicit(col) => Some(col.clone()),
            crate::plot::Keys::Positional(_) => None,
        },
        channels: state.channels.clone(),
    })
}

// ─── Composition template ────────────────────────────────────────────────────

impl_codec! {
    struct Span { rows, cols }

    enum ElementTemplate {
        0 => NamedPatch(id),
        1 => Spacer,
        2 => Composition(nested),
    }

    struct PlacementTemplate { row, col, span, element }

    struct CompositionTemplate {
        id,
        rows,
        cols,
        widths,
        heights,
        aspect,
        margin,
        padding,
        placements,
    }

    struct CompositionChrome {
        title,
        subtitle,
        caption,
        axis_titles,
        legends,
        next_legend_id,
    }
}

use crate::composition::Span;
use crate::plot::composition::{
    CompositionChrome, CompositionTemplate, ElementTemplate, PlacementTemplate,
};

// ─── Plot ────────────────────────────────────────────────────────────────────

#[cfg(feature = "document-write")]
impl Encode for Plot {
    fn encode(&self, w: &mut Writer) {
        self.patch_id().to_string().encode(w);

        let mut bindings: Vec<(&str, &str)> = self.bindings().collect();
        bindings.sort_unstable_by_key(|(channel, _)| *channel);
        w.varint(bindings.len() as u64);
        for (channel, scale) in bindings {
            channel.encode(w);
            scale.encode(w);
        }

        self.title_ref().map(str::to_string).encode(w);
        self.subtitle_ref().map(str::to_string).encode(w);
        self.caption_ref().map(str::to_string).encode(w);

        // Strips are indexed by side, so the array position carries the
        // meaning and no side tag is needed.
        let strips: [Option<String>; 4] = [
            AxisSide::Left,
            AxisSide::Right,
            AxisSide::Bottom,
            AxisSide::Top,
        ]
        .map(|side| self.strip_at(side).map(str::to_string));
        strips.encode(w);

        self.axes().to_vec().encode(w);
        self.legends().to_vec().encode(w);
        self.projection_ref().encode(w);
        self.is_clipped().encode(w);
        self.tracks_identity().encode(w);
        self.aspect_ratio_ref().encode(w);
        self.aspect_mode_ref().encode(w);
        self.theme_override_ref().cloned().encode(w);

        // Only the geoms that can name themselves. A geom returning
        // `None` from `kind` has already been reported by the write-side
        // validation pass, so skipping it here can't silently drop one.
        let parts: Vec<GeomParts> = self.geoms().filter_map(|(_, g)| geom_parts(g)).collect();
        parts.encode(w);
    }
}

/// Rebuild a plot bound to `patch_id`, which the caller has already
/// checked against the composition.
///
/// Not a [`Decode`] impl: a `Plot` can only be constructed against a
/// `Composition` that contains its patch, so the composition has to be
/// built first and passed in.
#[cfg(feature = "document-read")]
pub(crate) fn decode_plot(
    r: &mut Reader<'_>,
    composition: &crate::composition::Composition,
) -> Result<Plot, DocumentError> {
    let patch_id = String::decode(r)?;
    let mut plot = Plot::try_new(composition, &patch_id).map_err(|e| DocumentError::Invalid {
        what: "plot patch binding",
        why: e.to_string(),
    })?;

    let bindings = r.count()?;
    for _ in 0..bindings {
        let channel = String::decode(r)?;
        let scale = String::decode(r)?;
        plot.set_binding(channel, scale);
    }

    if let Some(t) = Option::<String>::decode(r)? {
        plot.set_title(t);
    }
    if let Some(t) = Option::<String>::decode(r)? {
        plot = plot.subtitle(t);
    }
    if let Some(t) = Option::<String>::decode(r)? {
        plot = plot.caption(t);
    }

    let strips = <[Option<String>; 4]>::decode(r)?;
    for (side, text) in [
        AxisSide::Left,
        AxisSide::Right,
        AxisSide::Bottom,
        AxisSide::Top,
    ]
    .into_iter()
    .zip(strips)
    {
        plot.set_strip(side, text);
    }

    for axis in Vec::<Axis>::decode(r)? {
        plot.add_axis(axis);
    }
    for legend in Vec::<Legend>::decode(r)? {
        plot.add_legend(legend);
    }

    plot = plot.projection(Projection::decode(r)?);
    plot = plot.clip(bool::decode(r)?);
    plot = plot.track_identity(bool::decode(r)?);
    if let Some(ratio) = Option::<f64>::decode(r)? {
        plot = plot.aspect_ratio(ratio);
    }
    plot = plot.aspect_mode(crate::plot::AspectMode::decode(r)?);
    plot.set_theme_override(Option::decode(r)?);

    let parts = Vec::<GeomParts>::decode(r)?;
    let geoms: Vec<Box<dyn crate::plot::Geom>> = parts
        .into_iter()
        .map(|p| p.build(r))
        .collect::<Result<_, _>>()?;
    for geom in geoms {
        plot.add_boxed_geom(geom);
    }

    Ok(plot)
}

impl_codec! {
    enum AspectMode {
        0 => Panel,
        1 => Range,
    }
}

use crate::plot::{AspectMode, Plot};