rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! BarChart widget — a vertical bar chart for visualizing categorical data.
//!
//! The BarChart widget draws axes, optional grid lines, vertical bars with
//! optional value labels on top. Each bar can have its own color, or all bars
//! share a default color.
//!
//! # Rendering path
//!
//! With the `chart` feature enabled, the plot area, axes, grid and tick labels
//! are produced by the shared chart engine in [`crate::widget::chart_widgets`], so this widget
//! and the SVG chart renderer share one implementation (see `plot_rect` below).
//!
//! Without that feature — `tablet` and `mobile` do not enable it — the widget
//! falls back to its own compact plot-area and grid loop. That path is kept
//! deliberately small so the two never diverge in the parts that matter: both
//! use the same bar geometry, labels and colors.

use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::widget::capability::coercion::expect_f32;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
#[cfg(feature = "chart")]
use crate::widget::chart_widgets::adapter::ChartContextAdapter;
#[cfg(feature = "chart")]
use crate::widget::chart_widgets::charts::{
    compute_cartesian_layout, draw_y_ticks, CartesianLayout,
};
// The chrome derivation is shared with the engine-backed path deliberately: the
// `not(feature = "chart")` backdrop used to write its own light-chart literals, so a
// tablet/mobile build in the dark appearance drew a near-invisible chart. One
// derivation, both paths.
use crate::widget::chart_widgets::charts::{axis_chrome, axis_chrome_color};
#[cfg(feature = "chart")]
use crate::widget::chart_widgets::types::ChartContext;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Converts the shared engine's float plot area into the integer [`Rect`] this
/// widget positions bars in.
///
/// `CartesianLayout` stores `f32` geometry because it is shared with the SVG
/// backend; bar placement is pixel-exact, so the conversion happens once here
/// rather than at every use site.
#[cfg(feature = "chart")]
fn plot_rect(layout: &CartesianLayout) -> Rect {
    Rect::new(
        layout.plot_x().round() as i32,
        layout.plot_y().round() as i32,
        layout.plot_w().round().max(1.0) as u32,
        layout.plot_h().round().max(1.0) as u32,
    )
}

/// A single bar entry in the bar chart.
#[derive(Clone, Debug)]
pub struct BarEntry {
    /// Label displayed below the bar (X-axis category).
    pub label: String,
    /// Numeric value determining the bar height.
    pub value: f64,
    /// Optional per-bar color. Falls back to the chart's bar_color if None.
    pub color: Option<Color>,
}

impl BarEntry {
    /// Creates a new bar entry with the given label and value.
    pub fn new(label: impl Into<String>, value: f64) -> Self {
        Self { label: label.into(), value, color: None }
    }

    /// Sets a custom color for this bar entry.
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }
}

/// A vertical bar chart widget for categorical data.
pub struct BarChart {
    base: BaseWidget,
    bars: Vec<BarEntry>,
    bar_color: Color,
    bar_spacing: f32,
    show_values: bool,
    show_grid: bool,
    min_value: Option<f64>,
    max_value: Option<f64>,
}

/// Font size of the value label drawn above each bar, in points.
const LABEL_FONT_SIZE: f32 = 10.0;

/// Font size of the category label drawn below the axis, in points.
const CATEGORY_FONT_SIZE: f32 = 9.0;

/// Distance between a bar's top edge and the bottom edge of its value label.
const LABEL_GAP: i32 = 4;

/// Distance from the plot baseline down to the top of the category label row.
const LABEL_ROW_TOP: i32 = 12;

impl BarChart {
    /// Creates a new BarChart widget with the given geometry.
    ///
    /// Defaults: blue bars, spacing 0.2 (20% of bar slot), values shown, grid enabled.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::BarChart, geometry, "BarChart"),
            bars: Vec::new(),
            bar_color: Color::PRIMARY,
            bar_spacing: 0.2,
            show_values: true,
            show_grid: true,
            min_value: None,
            max_value: None,
        }
    }

    /// Sets the bars to display. Clears any previous bars.
    pub fn set_bars(&mut self, entries: Vec<BarEntry>) {
        self.bars = entries;
        self.base.request_redraw();
    }

    /// Adds a single bar entry to the chart.
    pub fn add_bar(&mut self, entry: BarEntry) {
        self.bars.push(entry);
        self.base.request_redraw();
    }

    /// Removes the bar at the given index.
    /// Returns `true` if the bar was removed, `false` if the index was out of bounds.
    pub fn remove_bar(&mut self, index: usize) -> bool {
        if index < self.bars.len() {
            self.bars.remove(index);
            self.base.request_redraw();
            true
        } else {
            false
        }
    }

    /// Removes all bars from the chart.
    pub fn clear_bars(&mut self) {
        self.bars.clear();
        self.base.request_redraw();
    }

    /// Returns the number of bars.
    pub fn bar_count(&self) -> usize {
        self.bars.len()
    }

    /// Returns a reference to the current bar entries.
    pub fn bars(&self) -> &[BarEntry] {
        &self.bars
    }

    /// Sets the default bar color for all bars (used when BarEntry.color is None).
    pub fn set_bar_color(&mut self, color: Color) {
        self.bar_color = color;
        self.base.request_redraw();
    }

    /// Returns the current default bar color.
    pub fn bar_color(&self) -> Color {
        self.bar_color
    }

    /// Sets the spacing between bars as a fraction of the bar slot width.
    pub fn set_bar_spacing(&mut self, spacing: f32) {
        self.bar_spacing = spacing.clamp(0.0, 0.8);
        self.base.request_redraw();
    }

    /// Returns the current bar spacing fraction.
    pub fn bar_spacing(&self) -> f32 {
        self.bar_spacing
    }

    /// Enables or disables showing value labels on top of bars.
    pub fn set_show_values(&mut self, show: bool) {
        self.show_values = show;
        self.base.request_redraw();
    }

    /// Returns whether value labels are shown on top of bars.
    pub fn show_values(&self) -> bool {
        self.show_values
    }

    /// Enables or disables grid lines.
    pub fn set_show_grid(&mut self, show: bool) {
        self.show_grid = show;
        self.base.request_redraw();
    }

    /// Returns whether grid lines are shown.
    pub fn show_grid(&self) -> bool {
        self.show_grid
    }

    /// Sets manual min/max value range. Pass `None` for auto-compute.
    pub fn set_value_range(&mut self, min: Option<f64>, max: Option<f64>) {
        self.min_value = min;
        self.max_value = max;
        self.base.request_redraw();
    }

    /// Returns the configured value minimum (if manually set).
    pub fn min_value(&self) -> Option<f64> {
        self.min_value
    }

    /// Returns the configured value maximum (if manually set).
    pub fn max_value(&self) -> Option<f64> {
        self.max_value
    }

    /// Resolves the Y range for the chart.
    fn resolve_y_range(&self) -> (f64, f64) {
        match (self.min_value, self.max_value) {
            (Some(min), Some(max)) => (min, max),
            _ => {
                if self.bars.is_empty() {
                    return (0.0, 10.0);
                }
                let min = self.bars.iter().map(|b| b.value).fold(f64::INFINITY, f64::min).min(0.0);
                let max = self.bars.iter().map(|b| b.value).fold(f64::NEG_INFINITY, f64::max);
                if (max - min).abs() < f64::EPSILON {
                    return (0.0, max.max(1.0) + 1.0);
                }
                let padding = (max - min) * 0.1;
                (min - padding, max + padding)
            }
        }
    }

    /// Plot area used when the `chart` feature is unavailable.
    ///
    /// `tablet` and `mobile` do not enable the shared chart engine, so they keep
    /// this compact margin calculation. It mirrors the engine's left margin (for
    /// Y labels) and bottom margin (for X categories) so a chart looks the same
    /// across profiles.
    #[cfg(not(feature = "chart"))]
    fn plot_area(&self) -> Rect {
        let rect = self.base.geometry();
        let margin_left = 50;
        let margin_right = 10;
        let margin_top = if self.show_values { 30 } else { 10 };
        let margin_bottom = if !self.bars.is_empty() { 30 } else { 10 };
        let x = rect.x + margin_left;
        let y = rect.y + margin_top;
        let w = (rect.width as i32 - margin_left - margin_right).max(10) as u32;
        let h = (rect.height as i32 - margin_top - margin_bottom).max(10) as u32;
        Rect::new(x, y, w, h)
    }
}

impl Widget for BarChart {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        crate::core::Size::new(400, 300)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `BarChart`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, including
/// the `f32` → `f64` widening on read.
impl WidgetProperties for BarChart {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "bar_spacing" => Ok(CapabilityValue::Float(self.bar_spacing() as f64)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "bar_spacing" => {
                self.set_bar_spacing(expect_f32(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["bar_spacing", BASE_PROPERTY_NAMES]
    }
}

impl Draw for BarChart {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.base.geometry();
        if rect.width == 0 || rect.height == 0 {
            return;
        }

        let (y_min, y_max) = self.resolve_y_range();
        let is_enabled = self.base.is_enabled();
        let disabled_color = Color::DISABLED_FOREGROUND;

        // ── Backdrop: axes, grid and tick labels ──
        //
        // With the `chart` feature this is the shared engine, so the widget and
        // the SVG chart renderer cannot drift apart. Without it (tablet/mobile)
        // a compact local preamble runs instead — see `draw_backdrop_without_engine`.
        #[cfg(feature = "chart")]
        let plot_area = {
            let layout = compute_cartesian_layout(rect, true, true, 0);
            let plot_area = plot_rect(&layout);
            let mut adapter = ChartContextAdapter::new(context);

            let axis_color = if is_enabled { axis_chrome().0 } else { disabled_color };
            let bottom = layout.plot_y() + layout.plot_h();
            adapter.draw_line(
                Point::new(layout.plot_x() as i32, layout.plot_y() as i32),
                Point::new(layout.plot_x() as i32, bottom as i32),
                1.0,
                axis_color,
            );
            adapter.draw_line(
                Point::new(layout.plot_x() as i32, bottom as i32),
                Point::new((layout.plot_x() + layout.plot_w()) as i32, bottom as i32),
                1.0,
                axis_color,
            );

            // `draw_y_ticks` emits the grid lines *and* their value labels, so the
            // tick density is no longer hard-coded in this widget.
            draw_y_ticks(&mut adapter, &layout, y_min, y_max, 4, self.show_grid);
            plot_area
        };

        #[cfg(not(feature = "chart"))]
        let plot_area = self.draw_backdrop_without_engine(context, is_enabled, disabled_color);

        // ── Bars ──
        if self.bars.is_empty() {
            return;
        }

        let plot_width = plot_area.width as f32;
        let n = self.bars.len();
        let total_slots = n as f32;
        let spacing_pixels = (plot_width * self.bar_spacing) / total_slots;
        let bar_slot_width = (plot_width - spacing_pixels * (total_slots + 1.0)) / total_slots;
        let bar_width = bar_slot_width.max(1.0);

        let baseline_y = plot_area.y + plot_area.height as i32;
        let height_range = plot_area.height as f64;
        let value_span = (y_max - y_min).max(f64::EPSILON);

        for (i, bar) in self.bars.iter().enumerate() {
            let bar_color = bar.color.unwrap_or(self.bar_color);
            let effective_color = if is_enabled { bar_color } else { disabled_color };

            let bar_x = plot_area.x
                + (spacing_pixels * (i as f32 + 1.0) + bar_slot_width * i as f32) as i32;
            let bar_height = ((bar.value - y_min) / value_span * height_range) as i32;
            let bar_y = baseline_y - bar_height;

            if bar_height > 0 {
                context.fill_rect(
                    Rect::new(bar_x, bar_y, bar_width as u32, bar_height as u32),
                    effective_color,
                );
            }

            // ── Value label on top of the bar ──
            //
            // Placed as a **line box sitting above the bar**, not at `bar_y - 4`. The literal
            // gap had no relation to the label's own height, so a 10 px line began 4 px above
            // the bar's top with its glyph box still overlapping the bar, which the vertical
            // audit reads as PUSHED-DOWN. Building the box from the measured line height and
            // anchoring its bottom edge to the bar's top is what makes the gap actually four
            // pixels, and it scales with the label font.
            if self.show_values && is_enabled {
                let label = format!("{:.1}", bar.value);
                let label_x = bar_x.max(plot_area.x) + (bar_width as i32 / 2).min(12);
                let font = Font::simple("sans-serif", LABEL_FONT_SIZE);
                let line_height = context.measure_text("M", &font).height.max(1) as i32;
                let label_band = Rect {
                    x: label_x,
                    y: (bar_y - LABEL_GAP - line_height).max(plot_area.y),
                    width: bar_width as u32,
                    height: line_height as u32,
                };
                draw_label(context, &label, label_band, &font);
            }

            // ── Category label below the axis ──
            if is_enabled {
                let label_x = bar_x.max(plot_area.x) + (bar_width as i32 / 2).min(12);
                // Same treatment, anchored below the baseline: the line box starts where the
                // axis label row starts, so the gap under the axis is `LABEL_ROW_TOP`, not a
                // second hand-tuned offset that happened to equal it.
                let font = Font::simple("sans-serif", CATEGORY_FONT_SIZE);
                let line_height = context.measure_text("M", &font).height.max(1) as i32;
                let label_band = Rect {
                    x: label_x,
                    y: baseline_y + LABEL_ROW_TOP,
                    width: (plot_area.width as i32 - (label_x - plot_area.x)).max(0) as u32,
                    height: line_height as u32,
                };
                draw_label(context, &bar.label, label_band, &font);
            }
        }
    }
}

/// Draws a single-line label with the chart's shared styling.
///
/// The colour is derived from the active surface rather than written as `DARK_GRAY`:
/// that literal is a *light* chart's ink, so on the dark appearance the value labels
/// above the bars and the category labels below the axis rendered at **1.8:1** against
/// their own background — present in the pixel census, unreadable to a person. The
/// series colours are unchanged; only the framing text moves (rule #108 ③).
fn draw_label(context: &mut RenderContext, text: &str, band: Rect, font: &Font) {
    // Fitted to the band, so a long category name cannot run into the bar beside it — the
    // caller already knows each label's column, which is why the band is passed rather than a
    // point.
    context.draw_text_fitted(
        band,
        text,
        font,
        axis_chrome_color(0.70),
        HorizontalAlignment::Center,
    );
}

/// Fallback backdrop for builds without the `chart` feature (tablet/mobile).
///
/// Kept intentionally minimal and structurally identical to what the shared
/// engine produces: same axes, same grid spacing, so a chart is recognisable
/// across profiles rather than looking like a different widget.
#[cfg(not(feature = "chart"))]
impl BarChart {
    fn draw_backdrop_without_engine(
        &self,
        context: &mut RenderContext,
        is_enabled: bool,
        disabled_color: Color,
    ) -> Rect {
        let plot_area = self.plot_area();
        let (axis_color, _, grid_color) = axis_chrome();
        let axis_color = if is_enabled { axis_color } else { disabled_color };
        let bottom = plot_area.y + plot_area.height as i32;

        context.draw_line_stroke(
            Point::new(plot_area.x, plot_area.y),
            Point::new(plot_area.x, bottom),
            axis_color,
            1,
        );
        context.draw_line_stroke(
            Point::new(plot_area.x, bottom),
            Point::new(plot_area.x + plot_area.width as i32, bottom),
            axis_color,
            1,
        );

        if self.show_grid {
            let grid_color = if is_enabled { grid_color } else { disabled_color };
            for tick in 0..=4 {
                let t = tick as f64 / 4.0;
                let gy = plot_area.y + (plot_area.height as f64 * (1.0 - t)) as i32;
                context.draw_line_aa(
                    Point::new(plot_area.x + 1, gy),
                    Point::new(plot_area.x + plot_area.width as i32 - 1, gy),
                    grid_color,
                );
            }
        }

        plot_area
    }
}

impl EventHandler for BarChart {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::svg::render_to_svg;

    #[test]
    fn bar_chart_default_creation() {
        let bc = BarChart::new(Rect::new(0, 0, 300, 200));
        assert_eq!(bc.kind(), WidgetKind::BarChart);
        assert_eq!(bc.bar_count(), 0);
        assert_eq!(bc.bar_color(), Color::PRIMARY);
        assert!((bc.bar_spacing() - 0.2).abs() < f32::EPSILON);
        assert!(bc.show_values());
        assert!(bc.show_grid());
    }

    #[test]
    fn bar_chart_set_bars() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        let entries =
            vec![BarEntry::new("A", 10.0), BarEntry::new("B", 20.0), BarEntry::new("C", 15.0)];
        bc.set_bars(entries);
        assert_eq!(bc.bar_count(), 3);
        assert_eq!(bc.bars()[0].label, "A");
        assert!((bc.bars()[1].value - 20.0).abs() < f64::EPSILON);
    }

    #[test]
    fn bar_chart_add_and_remove() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.add_bar(BarEntry::new("X", 5.0));
        bc.add_bar(BarEntry::new("Y", 10.0));
        bc.add_bar(BarEntry::new("Z", 15.0));
        assert_eq!(bc.bar_count(), 3);

        assert!(bc.remove_bar(1)); // Remove "Y"
        assert_eq!(bc.bar_count(), 2);
        assert_eq!(bc.bars()[1].label, "Z");

        assert!(!bc.remove_bar(5)); // Out of bounds
        assert_eq!(bc.bar_count(), 2);
    }

    #[test]
    fn bar_chart_clear_bars() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.add_bar(BarEntry::new("A", 1.0));
        bc.add_bar(BarEntry::new("B", 2.0));
        bc.clear_bars();
        assert_eq!(bc.bar_count(), 0);
    }

    #[test]
    fn bar_chart_bar_color_and_spacing() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.set_bar_color(Color::WARNING);
        assert_eq!(bc.bar_color(), Color::WARNING);
        bc.set_bar_spacing(0.5);
        assert!((bc.bar_spacing() - 0.5).abs() < f32::EPSILON);
        bc.set_bar_spacing(1.5); // clamp
        assert!((bc.bar_spacing() - 0.8).abs() < f32::EPSILON);
    }

    #[test]
    fn bar_chart_show_values_and_grid() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        assert!(bc.show_values());
        bc.set_show_values(false);
        assert!(!bc.show_values());
        assert!(bc.show_grid());
        bc.set_show_grid(false);
        assert!(!bc.show_grid());
    }

    #[test]
    fn bar_chart_with_custom_colors() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.add_bar(BarEntry::new("A", 10.0).with_color(Color::ERROR));
        bc.add_bar(BarEntry::new("B", 20.0)); // Uses default bar_color
        assert_eq!(bc.bar_count(), 2);
        assert_eq!(bc.bars()[0].color, Some(Color::ERROR));
        assert!(bc.bars()[1].color.is_none());
    }

    #[test]
    fn bar_chart_svg_output() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.add_bar(BarEntry::new("A", 10.0));
        bc.add_bar(BarEntry::new("B", 20.0));
        bc.add_bar(BarEntry::new("C", 15.0));
        let svg = render_to_svg(&mut bc);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
    }

    #[test]
    fn bar_chart_empty_bars_no_crash() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        let svg = render_to_svg(&mut bc);
        assert!(svg.starts_with("<svg"));
    }

    #[test]
    fn bar_chart_event_forwarding() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.handle_event(&Event::MouseMove { pos: Point::new(10, 10) });
        bc.handle_event(&Event::MousePress { pos: Point::new(10, 10), button: 1 });
    }

    /// One ink box per text `<path>`, in document order.
    ///
    /// # Why the geometry and not the string
    ///
    /// Text leaves the backend as the `font8x8` rectangles the software rasteriser fills — one
    /// axis-aligned `<path>` subpath per set bitmap bit — so the rendered string is **not in the
    /// document in any form** and `svg.contains("100.0")` can never be true. A run can only be
    /// located by *where it is*: the union of one `<path>`'s subpaths is its ink box.
    ///
    /// # Why subpaths are not de-duplicated
    ///
    /// When a glyph box is wider than 8 pixels two bitmap columns map onto the same pixel via
    /// integer division, so the same rectangle is emitted twice. That is the rasteriser's own
    /// geometry — it fills that pixel twice — so collapsing it here would make this disagree with
    /// the drawing.
    #[cfg(feature = "chart")]
    fn ink_paths(svg: &str) -> Vec<(i32, i32, i32, i32)> {
        let mut runs = Vec::new();
        for line in svg.lines() {
            let Some(path_at) = line.find("<path ") else { continue };
            let Some(d_at) = line[path_at..].find("d=\"") else { continue };
            let start = path_at + d_at + 3;
            let Some(end) = line[start..].find('"') else { continue };
            let mut bounds: Option<(i32, i32, i32, i32)> = None;
            for subpath in line[start..start + end].split('M').skip(1) {
                let numbers: Vec<i32> = subpath
                    .split(|c: char| !c.is_ascii_digit() && c != '-')
                    .filter(|part| !part.is_empty())
                    .filter_map(|part| part.parse().ok())
                    .collect();
                if numbers.len() < 4 {
                    continue;
                }
                let (x, y, w, h) = (numbers[0], numbers[1], numbers[2], numbers[3]);
                bounds = Some(match bounds {
                    None => (x, y, x + w, y + h),
                    Some((left, top, right, bottom)) => {
                        (left.min(x), top.min(y), right.max(x + w), bottom.max(y + h))
                    }
                });
            }
            if let Some(bounds) = bounds {
                runs.push(bounds);
            }
        }
        runs
    }

    /// The widget must render through the shared chart engine rather than its
    /// own copy of the axis/tick math — that duplication is what this refactor
    /// removed.
    ///
    /// Observable proof: `draw_y_ticks` emits a numeric value label for every
    /// tick, which the widget's previous hand-rolled grid loop did not draw. The labels are not
    /// searchable as strings — they are `font8x8` rectangles now — so the check is on where the
    /// ink landed. `draw_text` anchors every y-tick label's glyph box at `plot_x - 44 = 20`, and
    /// the value decides how much ink follows: `100.0` is 17 px wide, `0.0` is 29 px because a
    /// three-character label is ellipsised to `0…` in the 29 px-wide `bar_width` band. A widget
    /// drawing only bars produces no run on that anchor at all.
    ///
    /// Gated on the feature, like `ink_paths` and the module's other `chart`-dependent items:
    /// a build without `chart` compiles this test module and the engine it exercises is absent.
    #[cfg(feature = "chart")]
    #[test]
    fn bar_chart_renders_axis_value_labels_from_the_shared_engine() {
        // Holds the crate-wide theme guard: this test renders, and a concurrent
        // test that switches the appearance would otherwise change a later frame.
        let _theme_guard = crate::style::theme_test_guard();
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.set_bars(vec![BarEntry::new("A", 0.0), BarEntry::new("B", 100.0)]);
        bc.set_value_range(Some(0.0), Some(100.0));

        let svg = render_to_svg(&mut bc);
        let runs = ink_paths(&svg);

        // `draw_y_ticks` walks `tick_count = 4` plus the inclusive upper bound, so five labels
        // are painted. The bars' own `{:.1}` value labels are here too, which is why the
        // assertion picks the runs out by geometry rather than by count.
        assert!(
            runs.len() >= 8,
            "the shared tick engine must label every tick (bars included), got {} runs",
            runs.len()
        );
        let (left, _, right, _) = runs[0];
        assert_eq!(left, 20, "the topmost y-tick label starts at the engine's `plot_x - 44`");
        assert_eq!(right - left, 17, "...and `100.0` is five characters of ink, not the bar label");
        let (short_left, _, short_right, _) = runs[4];
        assert_eq!(
            (short_left, short_right - short_left),
            (20, 29),
            "the bottom y-tick label is `0.0`, which the 29 px bar band ellipsises to `0…`"
        );
        assert!(
            runs.iter().any(|run| run.0 == 20 && run.2 - run.0 == 17),
            "at least one five-character label sits on the y-axis anchor"
        );
        // The two runs differ, so the engine drew a *value* label rather than repeating one
        // string at every tick: a widget that lost the tick loop's `min_y + span * t` would
        // paint five identical boxes.
        assert_ne!(runs[0], runs[4], "the ticks carry different values, so different ink");
    }

    /// Grid toggling must reach the shared engine: `draw_y_ticks` adds grid lines
    /// when asked, so enabling the grid must increase the line count.
    #[test]
    fn bar_chart_grid_toggle_changes_rendered_line_count() {
        let mut bc = BarChart::new(Rect::new(0, 0, 300, 200));
        bc.set_bars(vec![BarEntry::new("A", 10.0), BarEntry::new("B", 20.0)]);

        bc.set_show_grid(false);
        let without_grid = render_to_svg(&mut bc).matches("<line").count();

        bc.set_show_grid(true);
        let with_grid = render_to_svg(&mut bc).matches("<line").count();

        assert!(
            with_grid > without_grid,
            "grid must add lines through the shared engine (off={without_grid}, on={with_grid})"
        );
    }
}