charton 0.6.0

A high-performance, layered charting system for Rust, featuring a flexible data core and multi-backend rendering.
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
use crate::Precision;
use crate::coordinate::{AxisVisibility, CoordinateTrait, Rect, cartesian::Cartesian2D};
use crate::core::layer::{LineConfig, PathConfig, PathTopology, RenderBackend, TextConfig};
use crate::error::ChartonError;
use crate::scale::ExplicitTick;
use crate::theme::Theme;

/// Orchestrates the visual rendering of both horizontal and vertical axes for a panel.
///
/// This function is "Panel-aware": it renders axes relative to the `Rect` provided
/// in the `PanelContext`. In a faceted chart, this is called for each individual panel.
#[allow(clippy::too_many_arguments)]
pub fn render_cartesian_axes(
    backend: &mut dyn RenderBackend, // A generic backend for rendering.
    theme: &Theme,
    panel: &Rect,
    coord: &Cartesian2D,
    x_label: &str,
    x_explicit: Option<&[ExplicitTick]>,
    y_label: &str,
    y_explicit: Option<&[ExplicitTick]>,
    visibility: AxisVisibility,
) -> Result<(), ChartonError> {
    // Determine which data label belongs to which physical position based on flip state.
    // If flipped, the Y-scale data is projected onto the visual Bottom axis.
    let (bottom_label, left_label) = if coord.is_flipped() {
        (y_label, x_label)
    } else {
        (x_label, y_label)
    };

    // Determine which explicit ticks belongs to which physical position based on flip state.
    let bottom_explicit = if coord.is_flipped() {
        y_explicit
    } else {
        x_explicit
    };
    let left_explicit = if coord.is_flipped() {
        x_explicit
    } else {
        y_explicit
    };

    // 1. Process the Physical Bottom Axis (X-axis in standard, Y-axis in flipped)
    if visibility.show_x {
        draw_axis_line(backend, theme, panel, true)?;
        draw_ticks_and_labels(backend, theme, panel, coord, true, bottom_explicit)?;
        draw_axis_title(backend, theme, panel, coord, bottom_label, true)?;
    }

    // 2. Process the Physical Left Axis (Y-axis in standard, X-axis in flipped)
    if visibility.show_y {
        draw_axis_line(backend, theme, panel, false)?;
        draw_ticks_and_labels(backend, theme, panel, coord, false, left_explicit)?;
        draw_axis_title(backend, theme, panel, coord, left_label, false)?;
    }

    Ok(())
}

/// Renders the straight line (spine) of the axis.
fn draw_axis_line(
    backend: &mut dyn RenderBackend,
    theme: &Theme,
    panel: &Rect,
    is_bottom: bool,
) -> Result<(), ChartonError> {
    let (x1, y1, x2, y2) = if is_bottom {
        // Horizontal line at the bottom edge of the panel
        (
            panel.x,
            panel.y + panel.height,
            panel.x + panel.width,
            panel.y + panel.height,
        )
    } else {
        // Vertical line at the left edge of the panel
        (panel.x, panel.y, panel.x, panel.y + panel.height)
    };

    // Using PathConfig to draw the single line segment of the axis spine
    backend.draw_path(PathConfig {
        points: vec![
            (x1 as Precision, y1 as Precision),
            (x2 as Precision, y2 as Precision),
        ],
        fill: "none".into(),
        stroke: theme.axes_color,
        stroke_width: theme.axis_width as Precision,
        opacity: 1.0,
        dash: vec![], // Solid line
        topology: PathTopology::Simple,
    });

    Ok(())
}

/// Renders the individual ticks and their associated labels.
fn draw_ticks_and_labels(
    backend: &mut dyn RenderBackend,
    theme: &Theme,
    panel: &Rect,
    coord: &dyn CoordinateTrait,
    is_bottom: bool,
    explicit_ticks: Option<&[ExplicitTick]>,
) -> Result<(), ChartonError> {
    let is_flipped = coord.is_flipped();

    // 1. Select logical scale based on coordinate orientation
    let target_scale = if is_flipped {
        if is_bottom {
            coord.get_y_scale()
        } else {
            coord.get_x_scale()
        }
    } else if is_bottom {
        coord.get_x_scale()
    } else {
        coord.get_y_scale()
    };

    // 2. Generate ticks based on available pixel space
    let ticks = match explicit_ticks {
        Some(explicit) => target_scale.create_explicit_ticks(explicit),
        None => {
            let available_space = if is_bottom { panel.width } else { panel.height };
            target_scale.suggest_ticks(theme.suggest_tick_count(available_space))
        }
    };

    let tick_len = 6.0;

    // 3. Resolve rotation angle for tick labels
    let angle = if is_bottom {
        if is_flipped {
            theme.y_tick_label_angle
        } else {
            theme.x_tick_label_angle
        }
    } else if is_flipped {
        theme.x_tick_label_angle
    } else {
        theme.y_tick_label_angle
    };

    for tick in ticks {
        let norm_pos = target_scale.normalize(tick.value);

        let (px, py) = if is_bottom {
            (panel.x + norm_pos * panel.width, panel.y + panel.height)
        } else {
            (panel.x, panel.y + (1.0 - norm_pos) * panel.height)
        };

        // --- DRAW TICK LINE ---
        let (x2, y2) = if is_bottom {
            (px, py + tick_len)
        } else {
            (px - tick_len, py)
        };

        backend.draw_path(PathConfig {
            points: vec![
                (px as Precision, py as Precision),
                (x2 as Precision, y2 as Precision),
            ],
            fill: "none".into(),
            stroke: theme.tick_color,
            stroke_width: theme.tick_width as Precision,
            opacity: 1.0,
            dash: vec![],
            topology: PathTopology::Simple,
        });

        // --- DRAW TICK LABEL ---
        let (dx, dy, anchor, baseline) = if is_bottom {
            let x_anchor = if angle == 0.0 { "middle" } else { "end" };
            (
                0.0,
                tick_len + theme.tick_label_padding,
                x_anchor,
                "hanging",
            )
        } else {
            (
                -(tick_len + theme.tick_label_padding + 1.0),
                0.0,
                "end",
                "central",
            )
        };

        backend.draw_text(TextConfig {
            text: tick.label.clone(),
            x: (px + dx) as Precision,
            y: (py + dy) as Precision,
            font_size: theme.tick_label_size as Precision,
            font_family: theme.tick_label_family.clone(),
            color: theme.tick_label_color,
            text_anchor: anchor.to_string(),
            dominant_baseline: baseline.to_string(),
            font_weight: "normal".to_string(), // Ticks usually use normal weight
            opacity: 1.0,
            angle: angle as Precision,
        });
    }
    Ok(())
}

/// Renders the axis title, calculating offsets based on the bounding box of rotated tick labels.
fn draw_axis_title(
    backend: &mut dyn RenderBackend,
    theme: &Theme,
    panel: &Rect,
    coord: &dyn CoordinateTrait,
    label: &str,
    is_bottom: bool,
) -> Result<(), ChartonError> {
    if label.is_empty() {
        return Ok(());
    }

    let is_flipped = coord.is_flipped();
    let tick_line_len = 6.0;
    let title_gap = 5.0;

    // Resolve which angle and scale are mapped to this physical axis.
    let (angle_rad, target_scale) = if is_flipped {
        if is_bottom {
            (theme.y_tick_label_angle.to_radians(), coord.get_y_scale())
        } else {
            (theme.x_tick_label_angle.to_radians(), coord.get_x_scale())
        }
    } else if is_bottom {
        (theme.x_tick_label_angle.to_radians(), coord.get_x_scale())
    } else {
        (theme.y_tick_label_angle.to_radians(), coord.get_y_scale())
    };

    let available_space = if is_bottom { panel.width } else { panel.height };
    let final_count = theme.suggest_tick_count(available_space);
    let ticks = target_scale.suggest_ticks(final_count);

    if is_bottom {
        let x = panel.x + panel.width / 2.0;

        // Calculate the maximum vertical extension (Descent) of the labels to avoid overlap.
        let max_tick_height = ticks
            .iter()
            .map(|t| {
                let w = crate::core::utils::estimate_text_width(&t.label, theme.tick_label_size);
                let h = theme.tick_label_size;
                w.abs() * angle_rad.sin().abs() + h * angle_rad.cos().abs()
            })
            .fold(0.0, f64::max);

        // Compute total vertical offset from the panel edge.
        let v_offset = tick_line_len + max_tick_height + theme.label_padding + title_gap;
        let y = panel.y + panel.height + v_offset;

        backend.draw_text(TextConfig {
            x: x as Precision,
            y: y as Precision,
            text: label.to_string(),
            font_size: theme.label_size as Precision,
            font_family: theme.label_family.clone(),
            color: theme.label_color,
            text_anchor: "middle".to_string(),
            dominant_baseline: "hanging".to_string(),
            font_weight: "bold".to_string(),
            opacity: 1.0,
            angle: 0.0,
        });
    } else {
        let y = panel.y + panel.height / 2.0;

        // Calculate the maximum horizontal extension for the left axis to prevent clipping.
        let max_tick_width = ticks
            .iter()
            .map(|t| {
                let w = crate::core::utils::estimate_text_width(&t.label, theme.tick_label_size);
                let h = theme.tick_label_size;
                w.abs() * angle_rad.cos().abs() + h * angle_rad.sin().abs()
            })
            .fold(0.0, f64::max);

        // Total horizontal offset for vertical axis title.
        let h_offset = tick_line_len
            + max_tick_width
            + theme.label_padding
            + title_gap
            + (theme.label_size / 2.0)
            + 3.0;
        let x = panel.x - h_offset;

        backend.draw_text(TextConfig {
            x: x as Precision,
            y: y as Precision,
            text: label.to_string(),
            font_size: theme.label_size as Precision,
            font_family: theme.label_family.clone(),
            color: theme.label_color,
            text_anchor: "middle".to_string(),
            dominant_baseline: "middle".to_string(),
            font_weight: "bold".to_string(),
            opacity: 1.0,
            angle: -90.0, // Rotate Counter-Clockwise(CCW) for vertical alignment
        });
    }

    Ok(())
}

/// Renders the underlying grid lines for a 2D Cartesian coordinate system.
///
/// This must be called before `layer.render_marks` to keep grid lines in the background.
#[allow(clippy::too_many_arguments)]
pub fn render_cartesian_grid(
    backend: &mut dyn RenderBackend,
    theme: &Theme,
    panel: &Rect,
    coord: &Cartesian2D,
    x_explicit: Option<&[ExplicitTick]>,
    y_explicit: Option<&[ExplicitTick]>,
) -> Result<(), ChartonError> {
    let is_flipped = coord.is_flipped();

    // ------------------------------------------------------------------------
    // 1. Render vertical grid lines (Bottom axis ticks)
    // ------------------------------------------------------------------------
    let bottom_scale = if is_flipped {
        coord.get_y_scale()
    } else {
        coord.get_x_scale()
    };
    let bottom_explicit = if is_flipped { y_explicit } else { x_explicit };

    let x_ticks = match bottom_explicit {
        Some(explicit) => bottom_scale.create_explicit_ticks(explicit),
        None => bottom_scale.suggest_ticks(theme.suggest_tick_count(panel.width)),
    };

    for tick in x_ticks {
        let norm_pos = bottom_scale.normalize(tick.value);
        let canvas_x = panel.x + norm_pos * panel.width;

        // Vertical line: spans from the top edge to the bottom edge of the panel
        // Stack-allocated LineConfig avoids iterative heap allocations
        backend.draw_line(LineConfig {
            x1: canvas_x as Precision,
            y1: panel.y as Precision,
            x2: canvas_x as Precision,
            y2: (panel.y + panel.height) as Precision,
            color: theme.grid_color,
            width: theme.grid_width as Precision,
            opacity: 0.5,
            dash: vec![], // Can be replaced with theme.grid_dash.clone() if customized
        });
    }

    // ------------------------------------------------------------------------
    // 2. Render horizontal grid lines (Left axis ticks)
    // ------------------------------------------------------------------------
    let left_scale = if is_flipped {
        coord.get_x_scale()
    } else {
        coord.get_y_scale()
    };
    let left_explicit = if is_flipped { x_explicit } else { y_explicit };

    let y_ticks = match left_explicit {
        Some(explicit) => left_scale.create_explicit_ticks(explicit),
        None => left_scale.suggest_ticks(theme.suggest_tick_count(panel.height)),
    };

    for tick in y_ticks {
        let norm_pos = left_scale.normalize(tick.value);
        let canvas_y = panel.y + (1.0 - norm_pos) * panel.height; // Invert Y for screen space

        // Horizontal line: spans from the left edge to the right edge of the panel
        backend.draw_line(LineConfig {
            x1: panel.x as Precision,
            y1: canvas_y as Precision,
            x2: (panel.x + panel.width) as Precision,
            y2: canvas_y as Precision,
            color: theme.grid_color,
            width: theme.grid_width as Precision,
            opacity: 0.5,
            dash: vec![],
        });
    }

    // Close the grid at the panel boundary even when the first or last tick
    // does not land exactly on a scale endpoint.
    let right = panel.x + panel.width;
    let bottom = panel.y + panel.height;
    for (x1, y1, x2, y2) in [
        (panel.x, panel.y, right, panel.y),
        (right, panel.y, right, bottom),
        (right, bottom, panel.x, bottom),
        (panel.x, bottom, panel.x, panel.y),
    ] {
        backend.draw_line(LineConfig {
            x1: x1 as Precision,
            y1: y1 as Precision,
            x2: x2 as Precision,
            y2: y2 as Precision,
            color: theme.grid_color,
            width: theme.grid_width as Precision,
            opacity: 0.5,
            dash: vec![],
        });
    }

    Ok(())
}