rust_widgets 2.9.2

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
//! `Legend` — a reusable chart legend with optional series toggling.

use crate::compat::{String, ToString, Vec};
use crate::core::{Color, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::impl_draw_bridge;
use crate::impl_widget_property_hooks;
use crate::property_names_of;
use crate::render::RenderContext;
use crate::signal::{EventSignalRef, Signal1};
use crate::widget::capability::coercion::{expect_bool, expect_string};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::effective_font;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};

use super::helpers::{expect_color, expect_token, surface_ink};

// ---------------------------------------------------------------------------
// COMP-07 Legend
// ---------------------------------------------------------------------------

/// How a legend lays its entries out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LegendOrientation {
    /// Entries flow left to right.
    Horizontal,
    /// Entries stack top to bottom.
    #[default]
    Vertical,
}

impl LegendOrientation {
    /// The published token.
    pub fn as_str(self) -> &'static str {
        match self {
            LegendOrientation::Horizontal => "horizontal",
            LegendOrientation::Vertical => "vertical",
        }
    }
    /// Parses the published token.
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "horizontal" => Some(LegendOrientation::Horizontal),
            "vertical" => Some(LegendOrientation::Vertical),
            _ => None,
        }
    }
}

/// Where a legend sits relative to the plot it describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LegendPosition {
    /// Above the plot.
    #[default]
    Top,
    /// Right of the plot.
    Right,
    /// Below the plot.
    Bottom,
    /// Left of the plot.
    Left,
    /// Outside the plot's own surface (a detached legend).
    Outside,
}

impl LegendPosition {
    /// The published token.
    pub fn as_str(self) -> &'static str {
        match self {
            LegendPosition::Top => "top",
            LegendPosition::Right => "right",
            LegendPosition::Bottom => "bottom",
            LegendPosition::Left => "left",
            LegendPosition::Outside => "outside",
        }
    }
    /// Parses the published token.
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "top" => Some(LegendPosition::Top),
            "right" => Some(LegendPosition::Right),
            "bottom" => Some(LegendPosition::Bottom),
            "left" => Some(LegendPosition::Left),
            "outside" => Some(LegendPosition::Outside),
            _ => None,
        }
    }
}

/// One legend row: its series label, colour, and whether that series is shown.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegendEntry {
    /// Series label.
    pub label: String,
    /// Series colour.
    pub color: Color,
    /// Whether the series is currently visible.
    pub visible: bool,
}

impl LegendEntry {
    /// Creates a visible entry.
    pub fn new(label: impl Into<String>, color: Color) -> Self {
        Self { label: label.into(), color, visible: true }
    }
    /// Sets the initial visibility.
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }
}

/// Inset around a legend's entries.
const LEGEND_INSET: u32 = 4;
/// Size of the colour marker before a label.
const LEGEND_MARKER: u32 = 9;

/// A legend that can be mounted beside a chart or a custom canvas.
///
/// A checkable legend owns the visibility bit and reports every toggle through
/// [`Self::series_toggled`]; a non-checkable legend only reports clicks.
pub struct Legend {
    base: BaseWidget,
    entries: Vec<LegendEntry>,
    orientation: LegendOrientation,
    checkable: bool,
    position: LegendPosition,
    /// Emitted with the entry index on any click.
    pub entry_clicked: Signal1<usize>,
    /// Emitted with `(index, visible)` after a checkable entry toggles.
    pub series_toggled: Signal1<(usize, bool)>,
}

impl Legend {
    /// Creates an empty vertical legend.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Legend, geometry, "Legend"),
            entries: Vec::new(),
            orientation: LegendOrientation::Vertical,
            checkable: false,
            position: LegendPosition::Top,
            entry_clicked: Signal1::new(),
            series_toggled: Signal1::new(),
        }
    }

    /// Replaces the entries.
    pub fn set_entries(&mut self, entries: Vec<LegendEntry>) {
        self.entries = entries;
        self.base.request_redraw();
    }

    /// Returns the entries.
    pub fn entries(&self) -> &[LegendEntry] {
        &self.entries
    }

    /// Shows or hides one series, publishing the change when it actually moved.
    ///
    /// Returns `false` for an index outside the entry list.
    pub fn set_entry_visible(&mut self, index: usize, visible: bool) -> bool {
        let Some(entry) = self.entries.get_mut(index) else {
            return false;
        };
        if entry.visible == visible {
            return true;
        }
        entry.visible = visible;
        self.base.request_redraw();
        self.series_toggled.emit((index, visible));
        true
    }

    /// Sets the layout orientation.
    pub fn set_orientation(&mut self, orientation: LegendOrientation) {
        if self.orientation != orientation {
            self.orientation = orientation;
            self.base.request_redraw();
        }
    }

    /// Returns the layout orientation.
    pub fn orientation(&self) -> LegendOrientation {
        self.orientation
    }

    /// Enables or disables click-to-toggle.
    pub fn set_checkable(&mut self, checkable: bool) {
        self.checkable = checkable;
    }

    /// Returns whether entries are checkable.
    pub fn is_checkable(&self) -> bool {
        self.checkable
    }

    /// Sets the position hint (layout is the host's business).
    pub fn set_position(&mut self, position: LegendPosition) {
        self.position = position;
    }

    /// Returns the position hint.
    pub fn position(&self) -> LegendPosition {
        self.position
    }

    /// The rectangle of one entry, in window coordinates.
    fn entry_rect(&self, index: usize) -> Option<Rect> {
        if index >= self.entries.len() {
            return None;
        }
        let rect = self.geometry();
        let count = self.entries.len() as u32;
        let inner_width = rect.width.saturating_sub(LEGEND_INSET * 2);
        let inner_height = rect.height.saturating_sub(LEGEND_INSET * 2);
        match self.orientation {
            LegendOrientation::Horizontal => {
                let width = (inner_width / count.max(1)).max(1);
                Some(Rect::new(
                    rect.x + LEGEND_INSET as i32 + index as u32 as i32 * width as i32,
                    rect.y + LEGEND_INSET as i32,
                    width,
                    inner_height,
                ))
            }
            LegendOrientation::Vertical => {
                let height = (inner_height / count.max(1)).max(1);
                Some(Rect::new(
                    rect.x + LEGEND_INSET as i32,
                    rect.y + LEGEND_INSET as i32 + index as u32 as i32 * height as i32,
                    inner_width,
                    height,
                ))
            }
        }
    }

    /// The entry under `pos`, if any.
    fn entry_at(&self, pos: Point) -> Option<usize> {
        (0..self.entries.len())
            .find(|&index| self.entry_rect(index).is_some_and(|rect| rect.contains(pos)))
    }
}

impl EventHandler for Legend {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        if let Event::MousePress { pos, button: 1, .. } = event {
            if let Some(index) = self.entry_at(*pos) {
                self.entry_clicked.emit(index);
                if self.checkable {
                    let visible = !self.entries[index].visible;
                    self.set_entry_visible(index, visible);
                }
            }
        }
    }
}

impl Draw for Legend {
    fn draw(&mut self, context: &mut RenderContext) {
        let style = self.style();
        let (surface, ink) = surface_ink(style);
        let font = effective_font(style);
        context.fill_rect(self.geometry(), surface);
        for index in 0..self.entries.len() {
            let Some(cell) = self.entry_rect(index) else {
                continue;
            };
            let entry = &self.entries[index];
            let marker = Rect::new(
                cell.x + 4,
                cell.y + (cell.height.saturating_sub(LEGEND_MARKER) / 2) as i32,
                LEGEND_MARKER.min(cell.width),
                LEGEND_MARKER.min(cell.height),
            );
            let marker_color = if entry.visible { entry.color } else { entry.color.with_alpha(60) };
            context.fill_rect(marker, marker_color);
            let label_color = if entry.visible { ink } else { surface.blend(&ink, 0.45) };
            let label = Rect::new(
                marker.x + LEGEND_MARKER as i32 + 4,
                cell.y,
                cell.width.saturating_sub(LEGEND_MARKER + 8),
                cell.height,
            );
            context.draw_text_fitted(
                label,
                &entry.label,
                font,
                label_color,
                crate::core::HorizontalAlignment::Left,
            );
        }
    }
}

impl Widget for Legend {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }
    fn size_hint(&self) -> Size {
        match self.orientation {
            LegendOrientation::Horizontal => {
                Size::new((self.entries.len() as u32 * 80).max(80), 24)
            }
            LegendOrientation::Vertical => Size::new(140, (self.entries.len() as u32 * 22).max(22)),
        }
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
    fn event_signal_dyn(&self, name: &str) -> Option<EventSignalRef> {
        match name {
            "entry_clicked" => {
                Some(EventSignalRef::mapped("entry_clicked", &self.entry_clicked, |value| {
                    CapabilityValue::UInt(*value as u64)
                }))
            }
            "series_toggled" => {
                Some(EventSignalRef::mapped("series_toggled", &self.series_toggled, |value| {
                    CapabilityValue::Tuple(vec![
                        CapabilityValue::UInt(value.0 as u64),
                        CapabilityValue::Bool(value.1),
                    ])
                }))
            }
            _ => None,
        }
    }
}

/// Encodes one legend entry as `[label, colour, visible]`.
fn legend_entry_value(entry: &LegendEntry) -> CapabilityValue {
    CapabilityValue::Tuple(vec![
        CapabilityValue::String(entry.label.clone()),
        CapabilityValue::Color(entry.color),
        CapabilityValue::Bool(entry.visible),
    ])
}

/// Decodes the entry-list property.
fn expect_legend_entries(
    value: CapabilityValue,
) -> Result<Vec<LegendEntry>, CapabilityAccessError> {
    let CapabilityValue::Tuple(items) = value else {
        return Err(CapabilityAccessError::TypeMismatch);
    };
    let mut entries = Vec::with_capacity(items.len());
    for item in items {
        let CapabilityValue::Tuple(parts) = item else {
            return Err(CapabilityAccessError::TypeMismatch);
        };
        if parts.len() != 3 {
            return Err(CapabilityAccessError::TypeMismatch);
        }
        let mut parts = parts.into_iter();
        let label = expect_string(parts.next().ok_or(CapabilityAccessError::TypeMismatch)?)?;
        let color = expect_color(parts.next().ok_or(CapabilityAccessError::TypeMismatch)?)?;
        let visible = expect_bool(parts.next().ok_or(CapabilityAccessError::TypeMismatch)?)?;
        entries.push(LegendEntry { label, color, visible });
    }
    Ok(entries)
}

impl WidgetProperties for Legend {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "entries" => {
                Ok(CapabilityValue::Tuple(self.entries.iter().map(legend_entry_value).collect()))
            }
            "orientation" => Ok(CapabilityValue::String(self.orientation.as_str().to_string())),
            "checkable" => Ok(CapabilityValue::Bool(self.checkable)),
            "position" => Ok(CapabilityValue::String(self.position.as_str().to_string())),
            _ => base_property_get(self, name),
        }
    }
    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "entries" => {
                self.set_entries(expect_legend_entries(value)?);
                Ok(())
            }
            "orientation" => {
                self.set_orientation(expect_token(value, LegendOrientation::from_name)?);
                Ok(())
            }
            "checkable" => {
                self.set_checkable(expect_bool(value)?);
                Ok(())
            }
            "position" => {
                self.set_position(expect_token(value, LegendPosition::from_name)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }
    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["entries", "orientation", "checkable", "position", BASE_PROPERTY_NAMES]
    }
}

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

    #[test]
    fn toggling_an_entry_reports_the_series_and_refuses_a_stale_index() {
        let mut legend = Legend::new(Rect::new(0, 0, 240, 80));
        legend.set_entries(crate::compat::Vec::from([
            LegendEntry::new("Revenue", Color::PRIMARY),
            LegendEntry::new("Cost", Color::ERROR),
        ]));
        assert_eq!(legend.entries().len(), 2);
        assert!(legend.set_entry_visible(1, false));
        assert!(!legend.entries()[1].visible);
        // An entry that was already visible is reported as a no-op success rather than a toggle.
        assert!(legend.set_entry_visible(0, true));
        assert!(legend.entries()[0].visible);
        assert!(!legend.set_entry_visible(5, false));
    }
}