embedded-charts 0.3.0

A rich graph framework for embedded systems using embedded-graphics with std/no_std support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Core traits for legend implementations.

use crate::error::ChartResult;
use embedded_graphics::{prelude::*, primitives::Rectangle};

#[cfg(feature = "std")]
use std::vec::Vec;

#[cfg(all(feature = "no_std", not(feature = "std")))]
extern crate alloc;

#[cfg(all(feature = "no_std", not(feature = "std")))]
use alloc::vec::Vec;

/// Main trait for legend implementations
pub trait Legend<C: PixelColor> {
    /// The type of legend entries this legend contains
    type Entry: LegendEntry<C>;

    /// Get all legend entries
    fn entries(&self) -> &[Self::Entry];

    /// Get mutable access to legend entries
    fn entries_mut(&mut self) -> &mut [Self::Entry];

    /// Add a new entry to the legend
    fn add_entry(&mut self, entry: Self::Entry) -> ChartResult<()>;

    /// Remove an entry by index
    fn remove_entry(&mut self, index: usize) -> ChartResult<()>;

    /// Clear all entries
    fn clear_entries(&mut self);

    /// Get the legend position
    fn position(&self) -> crate::legend::position::LegendPosition;

    /// Set the legend position
    fn set_position(&mut self, position: crate::legend::position::LegendPosition);

    /// Get the legend orientation
    fn orientation(&self) -> crate::legend::types::LegendOrientation;

    /// Set the legend orientation
    fn set_orientation(&mut self, orientation: crate::legend::types::LegendOrientation);

    /// Calculate the required size for this legend
    fn calculate_size(&self) -> Size;

    /// Check if the legend is empty
    fn is_empty(&self) -> bool {
        self.entries().is_empty()
    }

    /// Get the number of visible entries
    fn visible_entry_count(&self) -> usize {
        self.entries().iter().filter(|e| e.is_visible()).count()
    }
}

/// Trait for rendering legends to a display target
pub trait LegendRenderer<C: PixelColor> {
    /// The legend type this renderer can handle
    type Legend: Legend<C>;

    /// Render the legend to the target display
    ///
    /// # Arguments
    /// * `legend` - The legend to render
    /// * `viewport` - The area to render the legend in
    /// * `target` - The display target to render to
    fn render<D>(
        &self,
        legend: &Self::Legend,
        viewport: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>;

    /// Calculate the layout for legend entries within the viewport
    ///
    /// # Arguments
    /// * `legend` - The legend to calculate layout for
    /// * `viewport` - The available area for the legend
    fn calculate_layout(
        &self,
        legend: &Self::Legend,
        viewport: Rectangle,
    ) -> ChartResult<heapless::Vec<Rectangle, 8>>;

    /// Render a single legend entry
    ///
    /// # Arguments
    /// * `entry` - The legend entry to render
    /// * `bounds` - The area to render the entry in
    /// * `target` - The display target to render to
    fn render_entry<D>(
        &self,
        entry: &<Self::Legend as Legend<C>>::Entry,
        bounds: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>;
}

/// Trait for individual legend entries
pub trait LegendEntry<C: PixelColor> {
    /// Get the label text for this entry
    fn label(&self) -> &str;

    /// Set the label text for this entry
    fn set_label(&mut self, label: &str) -> ChartResult<()>;

    /// Get the entry type (determines the symbol)
    fn entry_type(&self) -> &crate::legend::types::LegendEntryType<C>;

    /// Set the entry type
    fn set_entry_type(&mut self, entry_type: crate::legend::types::LegendEntryType<C>);

    /// Check if this entry is visible
    fn is_visible(&self) -> bool;

    /// Set the visibility of this entry
    fn set_visible(&mut self, visible: bool);

    /// Calculate the required size for this entry
    fn calculate_size(&self, style: &crate::legend::style::LegendStyle<C>) -> Size;

    /// Render the symbol for this entry
    fn render_symbol<D>(
        &self,
        bounds: Rectangle,
        style: &crate::legend::style::SymbolStyle<C>,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>;
}

/// Trait for legends that can automatically generate entries from chart data
pub trait AutoLegend<C: PixelColor>: Legend<C> {
    /// The type of data series this legend can generate entries for
    type DataSeries;

    /// Generate legend entries from data series
    fn generate_from_series(&mut self, series: &[Self::DataSeries]) -> ChartResult<()>;

    /// Generate a single entry from a data series
    fn generate_entry_from_series(
        &self,
        series: &Self::DataSeries,
        index: usize,
    ) -> ChartResult<Self::Entry>;

    /// Update existing entries to match current data series
    fn update_from_series(&mut self, series: &[Self::DataSeries]) -> ChartResult<()>;
}

/// Trait for legends that support interactive features
pub trait InteractiveLegend<C: PixelColor>: Legend<C> {
    /// Event type for legend interactions
    type Event;
    /// Response type for legend interactions
    type Response;

    /// Handle an interaction event
    ///
    /// # Arguments
    /// * `event` - The interaction event
    /// * `viewport` - The legend viewport
    fn handle_event(
        &mut self,
        event: Self::Event,
        viewport: Rectangle,
    ) -> ChartResult<Self::Response>;

    /// Check if a point is within a legend entry
    ///
    /// # Arguments
    /// * `point` - The point to check
    /// * `viewport` - The legend viewport
    fn hit_test(&self, point: Point, viewport: Rectangle) -> Option<usize>;

    /// Toggle the visibility of an entry
    fn toggle_entry(&mut self, index: usize) -> ChartResult<()>;

    /// Get the currently selected entry index
    fn selected_entry(&self) -> Option<usize>;

    /// Set the selected entry
    fn set_selected_entry(&mut self, index: Option<usize>);
}

/// Default legend renderer implementation
#[derive(Debug, Clone)]
pub struct DefaultLegendRenderer<C: PixelColor> {
    _phantom: core::marker::PhantomData<C>,
}

impl<C: PixelColor> DefaultLegendRenderer<C> {
    /// Create a new default legend renderer
    pub fn new() -> Self {
        Self {
            _phantom: core::marker::PhantomData,
        }
    }
}

impl<C: PixelColor> Default for DefaultLegendRenderer<C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C: PixelColor + From<embedded_graphics::pixelcolor::Rgb565>> LegendRenderer<C>
    for DefaultLegendRenderer<C>
{
    type Legend = crate::legend::DefaultLegend<C>;

    fn render<D>(
        &self,
        legend: &Self::Legend,
        viewport: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        if legend.entries.is_empty() {
            return Ok(());
        }

        let entry_bounds = self.calculate_layout(legend, viewport)?;

        // Render background if configured
        if let Some(bg_color) = legend.style.background.color {
            use embedded_graphics::primitives::PrimitiveStyle;
            use embedded_graphics::primitives::Rectangle as EgRectangle;

            EgRectangle::new(viewport.top_left, viewport.size)
                .into_styled(PrimitiveStyle::with_fill(bg_color))
                .draw(target)
                .map_err(|_| crate::error::ChartError::RenderingError)?;
        }

        // Render each visible entry
        for (entry, bounds) in legend
            .entries
            .iter()
            .filter(|e| e.visible)
            .zip(entry_bounds.iter())
        {
            self.render_entry(entry, *bounds, target)?;
        }

        Ok(())
    }

    fn calculate_layout(
        &self,
        legend: &Self::Legend,
        viewport: Rectangle,
    ) -> ChartResult<heapless::Vec<Rectangle, 8>> {
        let mut layouts = heapless::Vec::new();
        let visible_entries: Vec<_> = legend.entries.iter().filter(|e| e.visible).collect();

        if visible_entries.is_empty() {
            return Ok(layouts);
        }

        match legend.orientation {
            crate::legend::types::LegendOrientation::Vertical => {
                let entry_height = legend.style.text.line_height;
                let spacing = legend.style.spacing.entry_spacing;

                for (i, _) in visible_entries.iter().enumerate() {
                    let y_offset = i as u32 * (entry_height + spacing);
                    let bounds = Rectangle::new(
                        Point::new(viewport.top_left.x, viewport.top_left.y + y_offset as i32),
                        Size::new(viewport.size.width, entry_height),
                    );
                    if layouts.push(bounds).is_err() {
                        return Err(crate::error::ChartError::ConfigurationError);
                    }
                }
            }
            crate::legend::types::LegendOrientation::Horizontal => {
                let mut x_offset = 0u32;
                let entry_height = legend.style.text.line_height;

                for entry in visible_entries.iter() {
                    let entry_width = legend.style.spacing.symbol_width
                        + legend.style.spacing.symbol_text_gap
                        + entry.label.len() as u32 * legend.style.text.char_width;

                    let bounds = Rectangle::new(
                        Point::new(viewport.top_left.x + x_offset as i32, viewport.top_left.y),
                        Size::new(entry_width, entry_height),
                    );
                    if layouts.push(bounds).is_err() {
                        return Err(crate::error::ChartError::ConfigurationError);
                    }

                    x_offset += entry_width + legend.style.spacing.entry_spacing;
                }
            }
        }

        /// Standard legend renderer implementation
        #[derive(Debug, Clone)]
        pub struct StandardLegendRenderer<C: PixelColor> {
            _phantom: core::marker::PhantomData<C>,
        }

        impl<C: PixelColor> StandardLegendRenderer<C> {
            /// Create a new standard legend renderer
            pub fn new() -> Self {
                Self {
                    _phantom: core::marker::PhantomData,
                }
            }
        }

        impl<C: PixelColor> Default for StandardLegendRenderer<C> {
            fn default() -> Self {
                Self::new()
            }
        }

        impl<C: PixelColor + From<embedded_graphics::pixelcolor::Rgb565>> LegendRenderer<C>
            for StandardLegendRenderer<C>
        {
            type Legend = crate::legend::types::StandardLegend<C>;

            fn render<D>(
                &self,
                legend: &Self::Legend,
                viewport: Rectangle,
                target: &mut D,
            ) -> ChartResult<()>
            where
                D: DrawTarget<Color = C>,
            {
                if legend.entries().is_empty() {
                    return Ok(());
                }

                let entry_bounds = self.calculate_layout(legend, viewport)?;

                // Render background if configured
                if let Some(bg_color) = legend.style().background.color {
                    use embedded_graphics::primitives::PrimitiveStyle;
                    use embedded_graphics::primitives::Rectangle as EgRectangle;

                    EgRectangle::new(viewport.top_left, viewport.size)
                        .into_styled(PrimitiveStyle::with_fill(bg_color))
                        .draw(target)
                        .map_err(|_| crate::error::ChartError::RenderingError)?;
                }

                // Render each visible entry
                for (entry, bounds) in legend
                    .entries()
                    .iter()
                    .filter(|e| e.is_visible())
                    .zip(entry_bounds.iter())
                {
                    self.render_entry(entry, *bounds, target)?;
                }

                Ok(())
            }

            fn calculate_layout(
                &self,
                legend: &Self::Legend,
                viewport: Rectangle,
            ) -> ChartResult<heapless::Vec<Rectangle, 8>> {
                let mut layouts = heapless::Vec::new();
                let visible_entries: Vec<_> =
                    legend.entries().iter().filter(|e| e.is_visible()).collect();

                if visible_entries.is_empty() {
                    return Ok(layouts);
                }

                match legend.orientation() {
                    crate::legend::types::LegendOrientation::Vertical => {
                        let entry_height = legend.style().text.line_height;
                        let spacing = legend.style().spacing.entry_spacing;

                        for (i, _) in visible_entries.iter().enumerate() {
                            let y_offset = i as u32 * (entry_height + spacing);
                            let bounds = Rectangle::new(
                                Point::new(
                                    viewport.top_left.x,
                                    viewport.top_left.y + y_offset as i32,
                                ),
                                Size::new(viewport.size.width, entry_height),
                            );
                            if layouts.push(bounds).is_err() {
                                return Err(crate::error::ChartError::ConfigurationError);
                            }
                        }
                    }
                    crate::legend::types::LegendOrientation::Horizontal => {
                        let mut x_offset = 0u32;
                        let entry_height = legend.style().text.line_height;

                        for entry in visible_entries.iter() {
                            let entry_width = legend.style().spacing.symbol_width
                                + legend.style().spacing.symbol_text_gap
                                + entry.label().len() as u32 * legend.style().text.char_width;

                            let bounds = Rectangle::new(
                                Point::new(
                                    viewport.top_left.x + x_offset as i32,
                                    viewport.top_left.y,
                                ),
                                Size::new(entry_width, entry_height),
                            );
                            if layouts.push(bounds).is_err() {
                                return Err(crate::error::ChartError::ConfigurationError);
                            }

                            x_offset += entry_width + legend.style().spacing.entry_spacing;
                        }
                    }
                }

                Ok(layouts)
            }

            fn render_entry<D>(
                &self,
                entry: &crate::legend::types::StandardLegendEntry<C>,
                bounds: Rectangle,
                target: &mut D,
            ) -> ChartResult<()>
            where
                D: DrawTarget<Color = C>,
            {
                // Render symbol
                let symbol_bounds = Rectangle::new(
                    bounds.top_left,
                    Size::new(bounds.size.width.min(20), bounds.size.height),
                );
                entry.render_symbol(
                    symbol_bounds,
                    &crate::legend::style::SymbolStyle::default(),
                    target,
                )?;

                // Render text (simplified - would need proper text rendering in full implementation)
                // For now, we'll skip text rendering as it requires font support

                Ok(())
            }
        }

        Ok(layouts)
    }

    fn render_entry<D>(
        &self,
        entry: &crate::legend::DefaultLegendEntry<C>,
        bounds: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        // Render symbol
        let symbol_bounds = Rectangle::new(
            bounds.top_left,
            Size::new(bounds.size.width.min(20), bounds.size.height),
        );
        entry.render_symbol(
            symbol_bounds,
            &crate::legend::style::SymbolStyle::default(),
            target,
        )?;

        // Render text label
        let text_x = bounds.top_left.x + 25; // Symbol width + gap
        let text_y = bounds.top_left.y + (bounds.size.height as i32 / 2);

        // Use embedded-graphics text rendering
        use embedded_graphics::{
            mono_font::{ascii::FONT_6X10, MonoTextStyle},
            text::{Baseline, Text},
        };

        let text_style = MonoTextStyle::new(
            &FONT_6X10,
            C::from(embedded_graphics::pixelcolor::Rgb565::BLACK),
        );

        Text::with_baseline(
            entry.label(),
            Point::new(text_x, text_y),
            text_style,
            Baseline::Middle,
        )
        .draw(target)
        .map_err(|_| crate::error::ChartError::RenderingError)?;

        Ok(())
    }
}

/// Standard legend renderer implementation
#[derive(Debug, Clone)]
pub struct StandardLegendRenderer<C: PixelColor> {
    _phantom: core::marker::PhantomData<C>,
}

impl<C: PixelColor> StandardLegendRenderer<C> {
    /// Create a new standard legend renderer
    pub fn new() -> Self {
        Self {
            _phantom: core::marker::PhantomData,
        }
    }
}

impl<C: PixelColor> Default for StandardLegendRenderer<C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C: PixelColor + From<embedded_graphics::pixelcolor::Rgb565>> LegendRenderer<C>
    for StandardLegendRenderer<C>
{
    type Legend = crate::legend::types::StandardLegend<C>;

    fn render<D>(
        &self,
        legend: &Self::Legend,
        viewport: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        if legend.entries().is_empty() {
            return Ok(());
        }

        let entry_bounds = self.calculate_layout(legend, viewport)?;

        // Render background if configured
        if let Some(bg_color) = legend.style().background.color {
            use embedded_graphics::primitives::PrimitiveStyle;
            use embedded_graphics::primitives::Rectangle as EgRectangle;

            EgRectangle::new(viewport.top_left, viewport.size)
                .into_styled(PrimitiveStyle::with_fill(bg_color))
                .draw(target)
                .map_err(|_| crate::error::ChartError::RenderingError)?;
        }

        // Render each visible entry
        for (entry, bounds) in legend
            .entries()
            .iter()
            .filter(|e| e.is_visible())
            .zip(entry_bounds.iter())
        {
            self.render_entry(entry, *bounds, target)?;
        }

        Ok(())
    }

    fn calculate_layout(
        &self,
        legend: &Self::Legend,
        viewport: Rectangle,
    ) -> ChartResult<heapless::Vec<Rectangle, 8>> {
        let mut layouts = heapless::Vec::new();
        let visible_entries: Vec<_> = legend.entries().iter().filter(|e| e.is_visible()).collect();

        if visible_entries.is_empty() {
            return Ok(layouts);
        }

        match legend.orientation() {
            crate::legend::types::LegendOrientation::Vertical => {
                let entry_height = legend.style().text.line_height;
                let spacing = legend.style().spacing.entry_spacing;

                for (i, _) in visible_entries.iter().enumerate() {
                    let y_offset = i as u32 * (entry_height + spacing);
                    let bounds = Rectangle::new(
                        Point::new(viewport.top_left.x, viewport.top_left.y + y_offset as i32),
                        Size::new(viewport.size.width, entry_height),
                    );
                    if layouts.push(bounds).is_err() {
                        return Err(crate::error::ChartError::ConfigurationError);
                    }
                }
            }
            crate::legend::types::LegendOrientation::Horizontal => {
                let mut x_offset = 0u32;
                let entry_height = legend.style().text.line_height;

                for entry in visible_entries.iter() {
                    let entry_width = legend.style().spacing.symbol_width
                        + legend.style().spacing.symbol_text_gap
                        + entry.label().len() as u32 * legend.style().text.char_width;

                    let bounds = Rectangle::new(
                        Point::new(viewport.top_left.x + x_offset as i32, viewport.top_left.y),
                        Size::new(entry_width, entry_height),
                    );
                    if layouts.push(bounds).is_err() {
                        return Err(crate::error::ChartError::ConfigurationError);
                    }

                    x_offset += entry_width + legend.style().spacing.entry_spacing;
                }
            }
        }

        Ok(layouts)
    }

    fn render_entry<D>(
        &self,
        entry: &crate::legend::types::StandardLegendEntry<C>,
        bounds: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        // Render symbol
        let symbol_bounds = Rectangle::new(
            bounds.top_left,
            Size::new(bounds.size.width.min(20), bounds.size.height),
        );
        entry.render_symbol(
            symbol_bounds,
            &crate::legend::style::SymbolStyle::default(),
            target,
        )?;

        // Render text label
        let text_x = bounds.top_left.x + 25; // Symbol width + gap
        let text_y = bounds.top_left.y + (bounds.size.height as i32 / 2);

        // Use embedded-graphics text rendering
        use embedded_graphics::{
            mono_font::{ascii::FONT_6X10, MonoTextStyle},
            text::{Baseline, Text},
        };

        let text_style = MonoTextStyle::new(
            &FONT_6X10,
            C::from(embedded_graphics::pixelcolor::Rgb565::BLACK),
        );

        Text::with_baseline(
            entry.label(),
            Point::new(text_x, text_y),
            text_style,
            Baseline::Middle,
        )
        .draw(target)
        .map_err(|_| crate::error::ChartError::RenderingError)?;

        Ok(())
    }
}