embedded_menu/
lib.rs

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
#![cfg_attr(not(test), no_std)]

pub mod adapters;
pub mod builder;
pub mod collection;
pub mod interaction;
pub mod items;
pub mod selection_indicator;
pub mod theme;

mod margin;

use crate::{
    builder::MenuBuilder,
    collection::MenuItemCollection,
    interaction::{
        programmed::Programmed, Action, InputAdapter, InputAdapterSource, InputResult, InputState,
        Interaction, Navigation,
    },
    selection_indicator::{
        style::{line::Line as LineIndicator, IndicatorStyle},
        AnimatedPosition, Indicator, SelectionIndicatorController, State as IndicatorState,
        StaticPosition,
    },
    theme::Theme,
};
use core::marker::PhantomData;
use embedded_graphics::{
    draw_target::DrawTarget,
    geometry::{AnchorPoint, AnchorX, AnchorY},
    mono_font::{ascii::FONT_6X10, MonoFont, MonoTextStyle},
    pixelcolor::BinaryColor,
    prelude::{Dimensions, DrawTargetExt, Point},
    primitives::{Line, Primitive, PrimitiveStyle, Rectangle},
    Drawable,
};
use embedded_layout::{layout::linear::LinearLayout, prelude::*, view_group::ViewGroup};
use embedded_text::{
    style::{HeightMode, TextBoxStyle},
    TextBox,
};

pub use embedded_menu_macros::SelectValue;

#[derive(Copy, Clone, Debug)]
pub enum DisplayScrollbar {
    Display,
    Hide,
    Auto,
}

#[derive(Copy, Clone, Debug)]
pub struct MenuStyle<S, IT, P, R, T> {
    pub(crate) theme: T,
    pub(crate) scrollbar: DisplayScrollbar,
    pub(crate) font: &'static MonoFont<'static>,
    pub(crate) title_font: &'static MonoFont<'static>,
    pub(crate) input_adapter: IT,
    pub(crate) indicator: Indicator<P, S>,
    _marker: PhantomData<R>,
}

impl<R> Default for MenuStyle<LineIndicator, Programmed, StaticPosition, R, BinaryColor> {
    fn default() -> Self {
        Self::new(BinaryColor::On)
    }
}

impl<T, R> MenuStyle<LineIndicator, Programmed, StaticPosition, R, T>
where
    T: Theme,
{
    pub const fn new(theme: T) -> Self {
        Self {
            theme,
            scrollbar: DisplayScrollbar::Auto,
            font: &FONT_6X10,
            title_font: &FONT_6X10,
            input_adapter: Programmed,
            indicator: Indicator {
                style: LineIndicator,
                controller: StaticPosition,
            },
            _marker: PhantomData,
        }
    }
}

impl<S, IT, P, R, T> MenuStyle<S, IT, P, R, T>
where
    S: IndicatorStyle,
    IT: InputAdapterSource<R>,
    P: SelectionIndicatorController,
    T: Theme,
{
    pub const fn with_font(self, font: &'static MonoFont<'static>) -> Self {
        Self { font, ..self }
    }

    pub const fn with_title_font(self, title_font: &'static MonoFont<'static>) -> Self {
        Self { title_font, ..self }
    }

    pub const fn with_scrollbar_style(self, scrollbar: DisplayScrollbar) -> Self {
        Self { scrollbar, ..self }
    }

    pub const fn with_selection_indicator<S2>(
        self,
        indicator_style: S2,
    ) -> MenuStyle<S2, IT, P, R, T>
    where
        S2: IndicatorStyle,
    {
        MenuStyle {
            theme: self.theme,
            scrollbar: self.scrollbar,
            font: self.font,
            title_font: self.title_font,
            input_adapter: self.input_adapter,
            indicator: Indicator {
                style: indicator_style,
                controller: self.indicator.controller,
            },
            _marker: PhantomData,
        }
    }

    pub const fn with_input_adapter<IT2>(self, input_adapter: IT2) -> MenuStyle<S, IT2, P, R, T>
    where
        IT2: InputAdapterSource<R>,
    {
        MenuStyle {
            theme: self.theme,
            input_adapter,
            scrollbar: self.scrollbar,
            font: self.font,
            title_font: self.title_font,
            indicator: self.indicator,
            _marker: PhantomData,
        }
    }

    pub const fn with_animated_selection_indicator(
        self,
        frames: i32,
    ) -> MenuStyle<S, IT, AnimatedPosition, R, T> {
        MenuStyle {
            theme: self.theme,
            input_adapter: self.input_adapter,
            scrollbar: self.scrollbar,
            font: self.font,
            title_font: self.title_font,
            indicator: Indicator {
                style: self.indicator.style,
                controller: AnimatedPosition::new(frames),
            },
            _marker: PhantomData,
        }
    }

    pub fn text_style(&self) -> MonoTextStyle<'static, BinaryColor> {
        MonoTextStyle::new(self.font, BinaryColor::On)
    }

    pub fn title_style(&self) -> MonoTextStyle<'static, T::Color> {
        MonoTextStyle::new(self.title_font, self.theme.text_color())
    }
}

pub struct NoItems;

pub struct MenuState<IT, P, S>
where
    IT: InputAdapter,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
{
    selected: usize,
    list_offset: i32,
    interaction_state: IT::State,
    indicator_state: IndicatorState<P, S>,
    last_input_state: InputState,
}

impl<IT, P, S> Default for MenuState<IT, P, S>
where
    IT: InputAdapter,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
{
    fn default() -> Self {
        Self {
            selected: 0,
            list_offset: Default::default(),
            interaction_state: Default::default(),
            indicator_state: Default::default(),
            last_input_state: InputState::Idle,
        }
    }
}

impl<IT, P, S> Clone for MenuState<IT, P, S>
where
    IT: InputAdapter,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<IT, P, S> Copy for MenuState<IT, P, S>
where
    IT: InputAdapter,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
{
}

impl<IT, P, S> MenuState<IT, P, S>
where
    IT: InputAdapter,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
{
    pub fn reset_interaction(&mut self) {
        self.interaction_state = Default::default();
    }

    fn set_selected_item<ITS, R, T>(
        &mut self,
        selected: usize,
        items: &impl MenuItemCollection<R>,
        style: &MenuStyle<S, ITS, P, R, T>,
    ) where
        ITS: InputAdapterSource<R, InputAdapter = IT>,
        T: Theme,
    {
        let selected =
            Navigation::JumpTo(selected)
                .calculate_selection(self.selected, items.count(), |i| items.selectable(i));
        self.selected = selected;

        let selected_offset = items.bounds_of(selected).top_left.y;

        style
            .indicator
            .change_selected_item(selected_offset, &mut self.indicator_state);
    }
}

pub struct Menu<T, IT, VG, R, P, S, C>
where
    T: AsRef<str>,
    IT: InputAdapterSource<R>,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
    C: Theme,
{
    _return_type: PhantomData<R>,
    title: T,
    items: VG,
    style: MenuStyle<S, IT, P, R, C>,
    state: MenuState<IT::InputAdapter, P, S>,
}

impl<T, R, S, C> Menu<T, Programmed, NoItems, R, StaticPosition, S, C>
where
    T: AsRef<str>,
    S: IndicatorStyle,
    C: Theme,
{
    /// Creates a new menu builder with the given title.
    pub fn build(title: T) -> MenuBuilder<T, Programmed, NoItems, R, StaticPosition, S, C>
    where
        MenuStyle<S, Programmed, StaticPosition, R, C>: Default,
    {
        Self::with_style(title, MenuStyle::default())
    }
}

impl<T, IT, R, P, S, C> Menu<T, IT, NoItems, R, P, S, C>
where
    T: AsRef<str>,
    S: IndicatorStyle,
    IT: InputAdapterSource<R>,
    P: SelectionIndicatorController,
    C: Theme,
{
    /// Creates a new menu builder with the given title and style.
    pub fn with_style(
        title: T,
        style: MenuStyle<S, IT, P, R, C>,
    ) -> MenuBuilder<T, IT, NoItems, R, P, S, C> {
        MenuBuilder::new(title, style)
    }
}

impl<T, IT, VG, R, P, S, C> Menu<T, IT, VG, R, P, S, C>
where
    T: AsRef<str>,
    IT: InputAdapterSource<R>,
    VG: MenuItemCollection<R>,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
    C: Theme,
{
    pub fn interact(&mut self, input: <IT::InputAdapter as InputAdapter>::Input) -> Option<R> {
        let input = self
            .style
            .input_adapter
            .adapter()
            .handle_input(&mut self.state.interaction_state, input);

        self.state.last_input_state = match input {
            InputResult::Interaction(_) => InputState::Idle,
            InputResult::StateUpdate(state) => state,
        };

        match input {
            InputResult::Interaction(interaction) => match interaction {
                Interaction::Navigation(navigation) => {
                    let count = self.items.count();
                    let new_selected =
                        navigation.calculate_selection(self.state.selected, count, |i| {
                            self.items.selectable(i)
                        });
                    if new_selected != self.state.selected {
                        self.state
                            .set_selected_item(new_selected, &self.items, &self.style);
                    }
                    None
                }
                Interaction::Action(Action::Select) => {
                    let value = self.items.interact_with(self.state.selected);
                    Some(value)
                }
                Interaction::Action(Action::Return(value)) => Some(value),
            },
            _ => None,
        }
    }

    pub fn state(&self) -> MenuState<IT::InputAdapter, P, S> {
        self.state
    }
}

impl<T, IT, VG, R, P, S, C> Menu<T, IT, VG, R, P, S, C>
where
    T: AsRef<str>,
    R: Copy,
    IT: InputAdapterSource<R>,
    VG: MenuItemCollection<R>,
    C: Theme,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
{
    pub fn selected_value(&self) -> R {
        self.items.value_of(self.state.selected)
    }
}

impl<T, IT, VG, R, C, P, S> Menu<T, IT, VG, R, P, S, C>
where
    T: AsRef<str>,
    IT: InputAdapterSource<R>,
    VG: ViewGroup + MenuItemCollection<R>,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
    C: Theme,
{
    fn header<'t>(
        &self,
        title: &'t str,
        display_area: Rectangle,
    ) -> Option<impl View + 't + Drawable<Color = C::Color>>
    where
        C: Theme + 't,
    {
        if title.is_empty() {
            return None;
        }

        let text_style = self.style.title_style();
        let thin_stroke = PrimitiveStyle::with_stroke(self.style.theme.text_color(), 1);
        let header = LinearLayout::vertical(
            Chain::new(TextBox::with_textbox_style(
                title,
                display_area,
                text_style,
                TextBoxStyle::with_height_mode(HeightMode::FitToText),
            ))
            .append(
                // Bottom border
                Line::new(
                    display_area.top_left,
                    display_area.anchor_point(AnchorPoint::TopRight),
                )
                .into_styled(thin_stroke),
            ),
        )
        .arrange();

        Some(header)
    }

    fn top_offset(&self) -> i32 {
        self.style.indicator.offset(&self.state.indicator_state) - self.state.list_offset
    }

    pub fn update(&mut self, display: &impl Dimensions) {
        // animations
        self.style
            .indicator
            .update(self.state.last_input_state, &mut self.state.indicator_state);

        // Ensure selection indicator is always visible by moving the menu list.
        let top_distance = self.top_offset();

        let list_offset_change = if top_distance > 0 {
            let display_area = display.bounding_box();
            let display_height = display_area.size().height as i32;

            let header_height = if let Some(header) = self.header(self.title.as_ref(), display_area)
            {
                header.size().height as i32
            } else {
                0
            };

            let selected_height = MenuItemCollection::bounds_of(&self.items, self.state.selected)
                .size()
                .height as i32;
            let indicator_height = self
                .style
                .indicator
                .item_height(selected_height, &self.state.indicator_state);

            // Indicator is below display top. We only have to
            // move if indicator bottom is below display bottom.
            (top_distance + indicator_height + header_height - display_height).max(0)
        } else {
            // We need to move up
            top_distance
        };

        // Move menu list.
        self.state.list_offset += list_offset_change;
    }
}

impl<T, IT, VG, R, C, P, S> Drawable for Menu<T, IT, VG, R, P, S, C>
where
    T: AsRef<str>,
    IT: InputAdapterSource<R>,
    VG: ViewGroup + MenuItemCollection<R>,
    P: SelectionIndicatorController,
    S: IndicatorStyle,
    C: Theme,
{
    type Color = C::Color;
    type Output = ();

    fn draw<D>(&self, display: &mut D) -> Result<(), D::Error>
    where
        D: DrawTarget<Color = C::Color>,
    {
        let display_area = display.bounding_box();

        let header = self.header(self.title.as_ref(), display_area);
        let content_area = if let Some(header) = header {
            header.draw(display)?;
            display_area.resized_height(
                display_area.size().height - header.size().height,
                AnchorY::Bottom,
            )
        } else {
            display_area
        };

        let menu_height = content_area.size().height as i32;
        let list_height = self.items.bounds().size().height as i32;

        let draw_scrollbar = match self.style.scrollbar {
            DisplayScrollbar::Display => true,
            DisplayScrollbar::Hide => false,
            DisplayScrollbar::Auto => list_height > menu_height,
        };

        let menu_display_area = if draw_scrollbar {
            let scrollbar_area = content_area.resized_width(2, AnchorX::Right);
            let thin_stroke = PrimitiveStyle::with_stroke(self.style.theme.text_color(), 1);

            let scale = |value| value * menu_height / list_height;

            let scrollbar_height = scale(menu_height).max(1);
            let mut scrollbar_display = display.cropped(&scrollbar_area);

            // Start scrollbar from y=1, so we have a margin on top instead of bottom
            Line::new(Point::new(0, 1), Point::new(0, scrollbar_height))
                .into_styled(thin_stroke)
                .translate(Point::new(1, scale(self.state.list_offset)))
                .draw(&mut scrollbar_display)?;

            content_area.resized_width(
                content_area.size().width - scrollbar_area.size().width,
                AnchorX::Left,
            )
        } else {
            content_area
        };

        let selected_menuitem_height =
            MenuItemCollection::bounds_of(&self.items, self.state.selected)
                .size()
                .height as i32;

        self.style.indicator.draw(
            selected_menuitem_height,
            self.top_offset(),
            self.state.last_input_state,
            display.cropped(&menu_display_area),
            &self.items,
            &self.style,
            &self.state,
        )?;

        Ok(())
    }
}