iced_rizzen 0.14.0

Extra widgets for official releases of iced GUI library.
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
// This file is part of `iced_rizzen` project. For the terms of use, please see the file
// called `LICENSE-BSD-3-Clause` at the top level of the `iced_rizzen` project's Git repository.

//! A simple cell containing text.
//!
//! Supports the following features:
//!
//!  * Border color and thickness,
//!
//!  * Background color,
//!
//!  * Alignment (horizontal and vertical),
//!
//!  * Padding (in addition to border thickness).

use crate::core::{
    Border, Clipboard, Color, Element, Event, Length, Padding, Rectangle, Shadow, Shell, Size,
    Theme, Vector, alignment,
    layout::{self, Layout},
    mouse, overlay, renderer, touch,
    widget::{Operation, Tree, Widget, tree},
};
use iced_widget::core::{Alignment, Pixels, border::Radius};

pub const BORDER_WIDTH: f32 = 0.25;
pub const PADDING: Padding = Padding::new(2.0);

pub struct Cell<'a, Message, Theme, Renderer>
where
    Renderer: renderer::Renderer + 'a,
    Theme: Catalog + 'a,
{
    // Content
    content: Element<'a, Message, Theme, Renderer>,

    // Layout
    height: Length,
    width: Length,
    padding: Padding,
    align_x: Alignment,
    align_y: Alignment,

    // Events
    on_press: Option<Message>,

    // Styling
    class: Theme::Class<'a>, // Used for defaults
    style_options: StyleOptions,
}

impl<'a, Message, Theme, Renderer> Cell<'a, Message, Theme, Renderer>
where
    Message: Clone + 'a,
    Renderer: renderer::Renderer + 'a,
    Theme: Catalog + 'a,
{
    pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self {
        Cell {
            // Content
            content: content.into(),

            // Layout
            height: Length::Fill,
            width: Length::Fill,
            padding: PADDING,
            align_x: Alignment::Start,
            align_y: Alignment::Start,

            // Events
            on_press: None,

            // Styling
            class: Theme::default(),
            style_options: StyleOptions::default(),
        }
    }

    //
    // ----- Layout
    //

    /// Sets the height of the widget.
    pub fn height(mut self, length: Length) -> Self {
        self.height = length;
        self
    }

    /// Sets the width of the widget.
    pub fn width(mut self, length: Length) -> Self {
        self.width = length;
        self
    }

    /// Sets the [`Padding`] within the [`Cell`]. Must also include border width.
    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
        self.padding = padding.into();
        self
    }

    /// Sets the horizontal alignment of the contents of the [`Cell`].
    pub fn align_x(mut self, alignment: impl Into<alignment::Alignment>) -> Self {
        self.align_x = alignment.into();
        self
    }

    /// Sets the vertical alignment of the contents of the [`Cell`].
    pub fn align_y(mut self, alignment: impl Into<alignment::Alignment>) -> Self {
        self.align_y = alignment.into();
        self
    }

    //
    // ----- Events related
    //

    /// Sets the message that will be produced when the [`Cell`] is pressed.
    ///
    /// Unless `on_press` is called, the [`Cell`] will be disabled.
    pub fn on_press(mut self, message: Message) -> Self {
        self.on_press = Some(message);
        self
    }

    //
    // ----- Styling

    /// Sets the border [`Color`] of the [`Cell`].
    pub fn border_width(mut self, width: impl Into<Pixels>) -> Self
    where
        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
    {
        self.style_options.border_width = Some(width.into().0);
        self
    }

    /// This function can override the theme colouring for components: background,
    /// and border.
    ///
    /// Note: Invalid component simply results in no change.
    pub fn color(mut self, component: Component, color: Color) -> Self {
        match component {
            Component::Background => self.style_options.background = Some(color),
            Component::Border => self.style_options.border = Some(color),
            #[allow(unreachable_patterns)]
            _ => {}
        }
        self
    }

    /// Sets the default style of the [`Cell`].
    #[must_use]
    pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self
    where
        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
    {
        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
        self
    }
}

impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
    for Cell<'_, Message, Theme, Renderer>
where
    Renderer: renderer::Renderer,
    Theme: Catalog,
    Message: std::clone::Clone,
{
    fn tag(&self) -> tree::Tag {
        tree::Tag::of::<State>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(State::default())
    }

    fn children(&self) -> Vec<Tree> {
        vec![Tree::new(&self.content)]
    }

    fn diff(&self, tree: &mut Tree) {
        tree.diff_children(std::slice::from_ref(&self.content));
    }

    fn size(&self) -> Size<Length> {
        Size {
            width: Length::Fill,
            height: Length::Fill,
        }
    }

    fn layout(
        &mut self,
        tree: &mut Tree,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        layout::positioned(
            &limits,
            self.width,
            self.height,
            self.padding,
            |limits| {
                self.content
                    .as_widget_mut()
                    .layout(&mut tree.children[0], renderer, limits)
            },
            |node, size| node.align(self.align_x.into(), self.align_y.into(), size),
        )
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation,
    ) {
        operation.container(None, layout.bounds());
        operation.traverse(&mut |operation| {
            self.content.as_widget_mut().operate(
                &mut tree.children[0],
                layout.children().next().unwrap(),
                renderer,
                operation,
            );
        });
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _renderer: &Renderer,
        _clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        _viewport: &Rectangle,
    ) {
        let state = tree.state.downcast_mut::<State>();
        match event {
            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerPressed { .. }) => {
                if self.on_press.is_some() && cursor.is_over(layout.bounds()) {
                    let state = tree.state.downcast_mut::<State>();
                    state.is_pressed = true;
                    shell.capture_event();
                }
            }
            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerLifted { .. }) => {
                if state.is_pressed {
                    state.is_pressed = false;
                    if let Some(on_press) = &self.on_press
                        && cursor.is_over(layout.bounds())
                    {
                        shell.publish(on_press.clone());
                    }
                    shell.capture_event();
                }
            }
            Event::Touch(touch::Event::FingerLost { .. }) => {
                let state = tree.state.downcast_mut::<State>();
                state.is_pressed = false;
            }
            _ => {}
        }
        if !shell.is_event_captured() {}
    }

    fn mouse_interaction(
        &self,
        _tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _viewport: &Rectangle,
        _renderer: &Renderer,
    ) -> mouse::Interaction {
        if cursor.is_over(layout.bounds()) {
            mouse::Interaction::Pointer
        } else {
            mouse::Interaction::default()
        }
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        renderer_style: &renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        // Handle any styling overrides.
        let widget_style = theme.style(&self.class);
        let background = self
            .style_options
            .background
            .unwrap_or(widget_style.background);
        let border = self.style_options.border.unwrap_or(widget_style.border);
        let border_width = self
            .style_options
            .border_width
            .unwrap_or(widget_style.border_width);

        let bounds = layout.bounds();
        if let Some(clipped_viewport) = bounds.intersection(viewport) {
            renderer.fill_quad(
                renderer::Quad {
                    bounds: clipped_viewport,
                    border: Border {
                        color: border,
                        width: border_width,
                        radius: Radius::new(0.0),
                    },
                    shadow: Shadow::default(),
                    snap: false,
                },
                background,
            );
            renderer.with_layer(bounds, |renderer| {
                self.content.as_widget().draw(
                    &tree.children[0],
                    renderer,
                    theme,
                    renderer_style,
                    layout.children().next().unwrap(),
                    cursor,
                    &clipped_viewport,
                )
            });
        }
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'b>,
        renderer: &Renderer,
        viewport: &Rectangle,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
        self.content.as_widget_mut().overlay(
            &mut tree.children[0],
            layout.children().next().unwrap(),
            renderer,
            viewport,
            translation,
        )
    }
}

impl<'a, Message, Theme, Renderer> From<Cell<'a, Message, Theme, Renderer>>
    for Element<'a, Message, Theme, Renderer>
where
    Message: Clone + 'a,
    Renderer: renderer::Renderer + 'a,
    Theme: Catalog + 'a,
{
    fn from(cell: Cell<'a, Message, Theme, Renderer>) -> Element<'a, Message, Theme, Renderer> {
        Element::new(cell)
    }
}

/// Just a smaller persistent state for the `Tree`.
#[derive(Debug, Clone, Copy, Default)]
pub struct State {
    is_pressed: bool,
}

/// The appearance of a cell.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Style {
    /// The background [`Color`] of the cell.
    pub background: Color,
    /// The [`Color`] of the cell's border.
    pub border: Color,
    /// The cell's border width.
    pub border_width: f32,
}

// Background has no Default implementation.
impl Default for Style {
    fn default() -> Self {
        Self {
            background: Color::default(),
            border: Color::default(),
            border_width: f32::default(),
        }
    }
}

// Mirrors the Style struct, but all fields are Option.
#[derive(Default, Clone, Copy, PartialEq)]
pub(crate) struct StyleOptions {
    pub background: Option<Color>,
    pub border: Option<Color>,
    pub border_width: Option<f32>,
}

/// The components of [`Cell`].
pub enum Component {
    /// The background of the cell.
    Background,
    /// The border of the cell..
    Border,
}

/// The theme catalog of a [`Cell`].
pub trait Catalog {
    /// The item class of this [`Catalog`].
    type Class<'a>;

    /// The default class produced by this [`Catalog`].
    fn default<'a>() -> <Self as Catalog>::Class<'a>;

    /// The [`Style`] of a class.
    fn style(&self, class: &<Self as Catalog>::Class<'_>) -> Style;
}

/// A styling function for a [`Cell`].
///
/// This is just a boxed closure: `Fn(&Theme) -> Style`.
pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>;

impl Catalog for Theme {
    type Class<'a> = StyleFn<'a, Self>;

    fn default<'a>() -> StyleFn<'a, Self> {
        Box::new(default)
    }

    fn style(&self, class: &StyleFn<'_, Self>) -> Style {
        class(self)
    }
}

/// The default style of a [`Cell`].
pub fn default(theme: &Theme) -> Style {
    let palette = theme.extended_palette();
    Style {
        background: palette.background.base.color,
        border: palette.primary.base.text,
        border_width: BORDER_WIDTH,
    }
}