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

use Scalar;
use clock_ticks::precise_time_ns;
use color::Color;
use elmesque::element::Element;
use graphics::character::CharacterCache;
use label::FontSize;
use mouse::Mouse;
use position::{self, Dimensions, Horizontal, Margin, Padding, Place, Point, Position};
use super::drag;
use theme::Theme;
use widget::{self, Widget};
use ui::GlyphCache;


/// A widget designed to be a parent for other widgets.
pub struct Canvas<'a> {
    common: widget::CommonBuilder,
    /// The builder data related to the style of the Canvas.
    pub style: Style,
    maybe_title_bar_label: Option<&'a str>,
    show_title_bar: bool,
}

/// Canvas state to be cached.
#[derive(Clone, Debug, PartialEq)]
pub struct State {
    interaction: Interaction,
    maybe_title_bar: Option<TitleBar>,
    time_last_clicked: u64,
}

/// The padding between the edge of the title bar and the title bar's label.
const TITLE_BAR_LABEL_PADDING: f64 = 4.0;

/// State of the title bar.
#[derive(Clone, Debug, PartialEq)]
pub struct TitleBar {
    maybe_label: Option<(String, FontSize)>,
    y: Scalar,
    h: Scalar,
}

/// A builder for the padding of the area where child widgets will be placed.
#[derive(Copy, Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
pub struct PaddingBuilder {
    /// The padding for the left of the area where child widgets will be placed.
    pub maybe_left: Option<Scalar>,
    /// The padding for the right of the area where child widgets will be placed.
    pub maybe_right: Option<Scalar>,
    /// The padding for the top of the area where child widgets will be placed.
    pub maybe_top: Option<Scalar>,
    /// The padding for the bottom of the area where child widgets will be placed.
    pub maybe_bottom: Option<Scalar>,
}

/// A builder for the margin of the area where child widgets will be placed.
#[derive(Copy, Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
pub struct MarginBuilder {
    /// The margin for the left of the area where child widgets will be placed.
    pub maybe_left: Option<Scalar>,
    /// The margin for the right of the area where child widgets will be placed.
    pub maybe_right: Option<Scalar>,
    /// The margin for the top of the area where child widgets will be placed.
    pub maybe_top: Option<Scalar>,
    /// The margin for the bottom of the area where child widgets will be placed.
    pub maybe_bottom: Option<Scalar>,
}

/// Describes the style of a Canvas Floating.
#[allow(missing_copy_implementations)]
#[derive(Clone, Debug, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Style {
    /// Color of the canvas
    pub maybe_color: Option<Color>,
    /// The width of the frame surrounding the canvas.
    pub maybe_frame: Option<f64>,
    /// The color of the canvas' frame.
    pub maybe_frame_color: Option<Color>,
    /// The font size of the canvas' title bar label.
    pub maybe_title_bar_font_size: Option<FontSize>,
    /// The alignment of the canvas' title bar label.
    pub maybe_title_bar_label_align: Option<Horizontal>,
    /// The color of the title bar's label.
    pub maybe_title_bar_label_color: Option<Color>,
    /// Padding of the kid area.
    pub padding: PaddingBuilder,
    /// Margin for the kid area.
    pub margin: MarginBuilder,
}

/// Describes an interaction with the Floating Canvas.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Interaction {
    Normal,
    Highlighted(Elem),
    Clicked(Elem, Point),
}

/// Describes the different Elements that make up the Canvas.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Elem {
    TitleBar,
    WidgetArea,
}


impl<'a> Canvas<'a> {

    /// Construct a new Canvas builder.
    pub fn new() -> Canvas<'a> {
        Canvas {
            common: widget::CommonBuilder::new(),
            style: Style::new(),
            maybe_title_bar_label: None,
            show_title_bar: false,
        }
    }

    /// Show or hide the title bar.
    pub fn show_title_bar(mut self, show: bool) -> Self {
        self.show_title_bar = show;
        self
    }

    /// Set the padding of the left of the area where child widgets will be placed.
    #[inline]
    pub fn pad_left(mut self, pad: Scalar) -> Self {
        self.style.padding.maybe_left = Some(pad);
        self
    }

    /// Set the padding of the right of the area where child widgets will be placed.
    #[inline]
    pub fn pad_right(mut self, pad: Scalar) -> Self {
        self.style.padding.maybe_right = Some(pad);
        self
    }

    /// Set the padding of the top of the area where child widgets will be placed.
    #[inline]
    pub fn pad_top(mut self, pad: Scalar) -> Self {
        self.style.padding.maybe_top = Some(pad);
        self
    }

    /// Set the padding of the bottom of the area where child widgets will be placed.
    #[inline]
    pub fn pad_bottom(mut self, pad: Scalar) -> Self {
        self.style.padding.maybe_bottom = Some(pad);
        self
    }

    /// Set the padding of the area where child widgets will be placed.
    #[inline]
    pub fn padding(self, pad: Padding) -> Self {
        self.pad_left(pad.left)
            .pad_right(pad.right)
            .pad_right(pad.top)
            .pad_right(pad.bottom)
    }

    /// Set the margin of the left of the area where child widgets will be placed.
    #[inline]
    pub fn margin_left(mut self, mgn: Scalar) -> Self {
        self.style.margin.maybe_left = Some(mgn);
        self
    }

    /// Set the margin of the right of the area where child widgets will be placed.
    #[inline]
    pub fn margin_right(mut self, mgn: Scalar) -> Self {
        self.style.margin.maybe_right = Some(mgn);
        self
    }

    /// Set the margin of the top of the area where child widgets will be placed.
    #[inline]
    pub fn margin_top(mut self, mgn: Scalar) -> Self {
        self.style.margin.maybe_top = Some(mgn);
        self
    }

    /// Set the margin of the bottom of the area where child widgets will be placed.
    #[inline]
    pub fn margin_bottom(mut self, mgn: Scalar) -> Self {
        self.style.margin.maybe_bottom = Some(mgn);
        self
    }

    /// Set the padding of the area where child widgets will be placed.
    #[inline]
    pub fn margin(self, mgn: Margin) -> Self {
        self.pad_left(mgn.left)
            .pad_right(mgn.right)
            .pad_right(mgn.top)
            .pad_right(mgn.bottom)
    }

}


impl<'a> Widget for Canvas<'a> {
    type State = State;
    type Style = Style;

    fn common(&self) -> &widget::CommonBuilder { &self.common }
    fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common }
    fn unique_kind(&self) -> &'static str { "Canvas" }
    fn init_state(&self) -> State {
        State {
            interaction: Interaction::Normal,
            time_last_clicked: precise_time_ns(),
            maybe_title_bar: None,
        }
    }
    fn style(&self) -> Style {
        self.style.clone()
    }

    fn default_position(&self, _theme: &Theme) -> Position {
        Position::Place(Place::Middle, None)
    }

    fn default_width<C: CharacterCache>(&self, theme: &Theme, _: &GlyphCache<C>) -> Scalar {
        const DEFAULT_WIDTH: Scalar = 160.0;
        self.common.maybe_width.or(theme.maybe_button.as_ref().map(|default| {
            default.common.maybe_width.unwrap_or(DEFAULT_WIDTH)
        })).unwrap_or(DEFAULT_WIDTH)
    }

    fn default_height(&self, theme: &Theme) -> Scalar {
        const DEFAULT_HEIGHT: Scalar = 80.0;
        self.common.maybe_height.or(theme.maybe_button.as_ref().map(|default| {
            default.common.maybe_height.unwrap_or(DEFAULT_HEIGHT)
        })).unwrap_or(DEFAULT_HEIGHT)
    }

    /// The title bar area at which the Canvas can be clicked and dragged.
    /// The position of the area should be relative to the center of the widget..
    fn drag_area(&self, dim: Dimensions, style: &Style, theme: &Theme) -> Option<drag::Area> {
        if self.show_title_bar {
            let font_size = style.title_bar_font_size(theme);
            let (h, y) = title_bar_h_y(dim, font_size as f64);
            Some(drag::Area {
                xy: [0.0, y],
                dim: [dim[0], h],
            })
        } else {
            None
        }
    }

    /// The area of the widget below the title bar, upon which child widgets will be placed.
    fn kid_area(state: &widget::State<State>, style: &Style, theme: &Theme) -> widget::KidArea {
        let widget::State { ref state, xy, dim, .. } = *state;
        match state.maybe_title_bar {
            None => widget::KidArea {
                xy: xy,
                dim: dim,
                pad: style.padding(theme),
            },
            Some(ref title_bar) => widget::KidArea {
                xy: [xy[0], xy[1] - (title_bar.h / 2.0)],
                dim: [dim[0], dim[1] - title_bar.h],
                pad: style.padding(theme),
            },
        }
    }

    /// Update the state of the Canvas.
    fn update<'b, C>(self, args: widget::UpdateArgs<'b, Self, C>) -> Option<State>
        where C: CharacterCache,
    {
        let widget::UpdateArgs { prev_state, xy, dim, ui, .. } = args;
        let widget::State { ref state, .. } = *prev_state;
        let State { interaction, time_last_clicked, ref maybe_title_bar } = *state;
        let maybe_mouse = ui.input().maybe_mouse.map(|mouse| mouse.relative_to(xy));
        let title_bar_font_size = self.style.title_bar_font_size(ui.theme());

        // Calculate the height and y coord of the title bar.
        let (title_bar_h, title_bar_y) = if self.show_title_bar {
            title_bar_h_y(dim, title_bar_font_size as f64)
        } else {
            (0.0, 0.0)
        };

        // If there is new mouse state, check for a new interaction.
        let new_interaction = if let Some(mouse) = maybe_mouse {
            let is_over_elem = is_over(mouse.xy, dim, title_bar_y, title_bar_h);
            get_new_interaction(is_over_elem, interaction, mouse)
        } else {
            Interaction::Normal
        };

        // If the canvas was clicked, dragged or released, update the time_last_clicked.
        let new_time_last_clicked = match (interaction, new_interaction) {
            (Interaction::Highlighted(_), Interaction::Clicked(_, _)) |
            (Interaction::Clicked(_, _), Interaction::Highlighted(_)) |
            (Interaction::Clicked(_, _), Interaction::Clicked(_, _))  => precise_time_ns(),
            _ => time_last_clicked,
        };

        // A function for constructing a new state.
        let new_state = || State {
            interaction: new_interaction,
            time_last_clicked: new_time_last_clicked,
            maybe_title_bar: if self.show_title_bar {
                Some(TitleBar {
                    maybe_label: self.maybe_title_bar_label.as_ref()
                        .map(|label| (label.to_string(), title_bar_font_size)),
                    h: title_bar_h,
                    y: title_bar_y,
                })
            } else {
                None
            },
        };

        // Check whether or not the state has changed since the previous update.
        let state_has_changed = interaction != new_interaction
            || time_last_clicked != new_time_last_clicked
            || match *maybe_title_bar {
                None => self.show_title_bar,
                Some(ref title_bar) => {
                    title_bar.y != title_bar_y
                    || title_bar.h != title_bar_h
                    || match title_bar.maybe_label {
                        None => false,
                        Some((ref label, font_size)) => {
                            Some(&label[..]) != self.maybe_title_bar_label
                            || font_size != title_bar_font_size
                        },
                    }
                },
            };

        // Construct the new state if there was a change.
        if state_has_changed { Some(new_state()) } else { None }
    }

    /// Draw the canvas.
    fn draw<'b, C>(args: widget::DrawArgs<'b, Self, C>) -> Element
        where C: CharacterCache
    {
        use elmesque::form::{collage, rect, text};

        let widget::DrawArgs { state, style, theme, glyph_cache } = args;
        let widget::State { ref state, dim, xy, .. } = *state;

        let frame = style.frame(theme);
        let inner_dim = ::vecmath::vec2_sub(dim, [frame * 2.0; 2]);
        let color = style.color(theme);
        let frame_color = style.frame_color(theme);
        let frame_form = rect(dim[0], dim[1]).filled(frame_color);
        let rect_form = rect(inner_dim[0], inner_dim[1]).filled(color);

        // Check whether or not to draw the title bar.
        let maybe_title_bar_form = if let Some(ref title_bar) = state.maybe_title_bar {
            let inner_dim = ::vecmath::vec2_sub([dim[0], title_bar.h], [frame * 2.0; 2]);
            let title_bar_frame_form = rect(dim[0], title_bar.h).filled(frame_color);
            let title_bar_rect_form = rect(inner_dim[0], inner_dim[1]).filled(color);
            // Check whether or not to draw the title bar's label.
            let maybe_label_form = title_bar.maybe_label.as_ref().map(|&(ref label, font_size)| {
                use elmesque::text::Text;
                let label_color = style.title_bar_label_color(theme);
                let align = style.title_bar_label_align(theme);
                let label_width = glyph_cache.width(font_size, label);
                let label_x = align.to(inner_dim[0], label_width) + TITLE_BAR_LABEL_PADDING;
                text(Text::from_string(label.clone())
                        .color(label_color)
                        .height(font_size as f64)).shift_x(label_x)
            });
            Some(Some(title_bar_frame_form).into_iter()
                .chain(Some(title_bar_rect_form).into_iter())
                .chain(maybe_label_form)
                .map(move |form| form.shift_y(title_bar.y)))
        } else {
            None
        };

        // Chain the Canvas' Forms together.
        let form_chain = Some(frame_form).into_iter()
            .chain(Some(rect_form).into_iter())
            .chain(maybe_title_bar_form.into_iter().flat_map(|it| it))
            .map(|form| form.shift(xy[0], xy[1]));

        // Construct the renderable element.
        collage(dim[0] as i32, dim[1] as i32, form_chain.collect())
    }

}


/// Calculate the height and y position of the Title Bar.
fn title_bar_h_y(dim: Dimensions, font_size: f64) -> (Scalar, Scalar) {
    let h = font_size as f64 + TITLE_BAR_LABEL_PADDING * 2.0;
    let y = position::align_top_of(dim[1], h);
    (h, y)
}


/// Is the mouse over the canvas, if so which Elem.
fn is_over(mouse_xy: Point,
           dim: Dimensions,
           title_bar_y: f64,
           title_bar_h: f64) -> Option<Elem>
{
    use utils::is_over_rect;
    if is_over_rect([0.0, 0.0], mouse_xy, dim) {
        if is_over_rect([0.0, title_bar_y], mouse_xy, [dim[0], title_bar_h]) {
            Some(Elem::TitleBar)
        } else {
            Some(Elem::WidgetArea)
        }
    } else {
        None
    }
}


/// Determine the new interaction given the mouse state and previous interaction.
fn get_new_interaction(is_over_elem: Option<Elem>, prev: Interaction, mouse: Mouse) -> Interaction {
    use mouse::ButtonState::{Down, Up};
    use self::Interaction::{Normal, Highlighted, Clicked};
    match (is_over_elem, prev, mouse.left) {
        (Some(_),    Normal,          Down)  => Normal,
        (Some(elem), _,               Up)    => Highlighted(elem),
        (Some(elem), Highlighted(_),  Down)  => Clicked(elem, mouse.xy),
        (Some(_),    Clicked(elem, _), Down) => Clicked(elem, mouse.xy),
        (None,       Clicked(elem, _), Down) => Clicked(elem, mouse.xy),
        _                                    => Normal,
    }
}


impl Style {

    /// Construct a default Canvas Style.
    pub fn new() -> Style {
        Style {
            maybe_color: None,
            maybe_frame: None,
            maybe_frame_color: None,
            maybe_title_bar_font_size: None,
            maybe_title_bar_label_align: None,
            maybe_title_bar_label_color: None,
            padding: PaddingBuilder {
                maybe_left: None,
                maybe_right: None,
                maybe_top: None,
                maybe_bottom: None,
            },
            margin: MarginBuilder {
                maybe_left: None,
                maybe_right: None,
                maybe_top: None,
                maybe_bottom: None,
            },
        }
    }

    /// Get the color for the Floating's Element.
    pub fn color(&self, theme: &Theme) -> Color {
        self.maybe_color.or(theme.maybe_canvas.as_ref().map(|default| {
            default.style.maybe_color.unwrap_or(theme.background_color)
        })).unwrap_or(theme.background_color)
    }

    /// Get the frame for an Element.
    pub fn frame(&self, theme: &Theme) -> f64 {
        self.maybe_frame.or(theme.maybe_canvas.as_ref().map(|default| {
            default.style.maybe_frame.unwrap_or(theme.frame_width)
        })).unwrap_or(theme.frame_width)
    }

    /// Get the frame Color for an Element.
    pub fn frame_color(&self, theme: &Theme) -> Color {
        self.maybe_frame_color.or(theme.maybe_canvas.as_ref().map(|default| {
            default.style.maybe_frame_color.unwrap_or(theme.frame_color)
        })).unwrap_or(theme.frame_color)
    }

    /// Get the font size of the title bar.
    pub fn title_bar_font_size(&self, theme: &Theme) -> FontSize {
        self.maybe_title_bar_font_size.or(theme.maybe_canvas.as_ref().map(|default| {
            default.style.maybe_title_bar_font_size.unwrap_or(theme.font_size_medium)
        })).unwrap_or(theme.font_size_medium)
    }

    /// Get the alignment of the title bar label.
    pub fn title_bar_label_align(&self, theme: &Theme) -> Horizontal {
        const DEFAULT_ALIGN: Horizontal = Horizontal::Middle;
        self.maybe_title_bar_label_align.or(theme.maybe_canvas.as_ref().map(|default| {
            default.style.maybe_title_bar_label_align.unwrap_or(DEFAULT_ALIGN)
        })).unwrap_or(DEFAULT_ALIGN)
    }

    /// Get the color of the title bar label.
    pub fn title_bar_label_color(&self, theme: &Theme) -> Color {
        self.maybe_title_bar_label_color.or(theme.maybe_canvas.as_ref().map(|default| {
            default.style.maybe_title_bar_label_color.unwrap_or(theme.label_color)
        })).unwrap_or(theme.label_color)
    }

    /// Get the Padding for the Canvas' kid area.
    pub fn padding(&self, theme: &Theme) -> position::Padding {
        position::Padding {
            top: self.padding.maybe_top.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.padding.maybe_top.unwrap_or(theme.padding.top)
            })).unwrap_or(theme.padding.top),
            bottom: self.padding.maybe_bottom.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.padding.maybe_bottom.unwrap_or(theme.padding.bottom)
            })).unwrap_or(theme.padding.bottom),
            left: self.padding.maybe_left.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.padding.maybe_left.unwrap_or(theme.padding.left)
            })).unwrap_or(theme.padding.left),
            right: self.padding.maybe_right.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.padding.maybe_right.unwrap_or(theme.padding.right)
            })).unwrap_or(theme.padding.right),
        }
    }

    /// Get the Margin for the Canvas' kid area.
    pub fn margin(&self, theme: &Theme) -> position::Margin {
        position::Margin {
            top: self.margin.maybe_top.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.margin.maybe_top.unwrap_or(theme.margin.top)
            })).unwrap_or(theme.margin.top),
            bottom: self.margin.maybe_bottom.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.margin.maybe_bottom.unwrap_or(theme.margin.bottom)
            })).unwrap_or(theme.margin.bottom),
            left: self.margin.maybe_left.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.margin.maybe_left.unwrap_or(theme.margin.left)
            })).unwrap_or(theme.margin.left),
            right: self.margin.maybe_right.or(theme.maybe_canvas.as_ref().map(|default| {
                default.style.margin.maybe_right.unwrap_or(theme.margin.right)
            })).unwrap_or(theme.margin.right),
        }
    }

}


impl<'a> ::color::Colorable for Canvas<'a> {
    fn color(mut self, color: Color) -> Self {
        self.style.maybe_color = Some(color);
        self
    }
}

impl<'a> ::frame::Frameable for Canvas<'a> {
    fn frame(mut self, width: f64) -> Self {
        self.style.maybe_frame = Some(width);
        self
    }
    fn frame_color(mut self, color: Color) -> Self {
        self.style.maybe_frame_color = Some(color);
        self
    }
}

impl<'a> ::label::Labelable<'a> for Canvas<'a> {
    fn label(mut self, text: &'a str) -> Self {
        self.maybe_title_bar_label = Some(text);
        self.show_title_bar = true;
        self
    }
    fn label_color(mut self, color: Color) -> Self {
        self.style.maybe_title_bar_label_color = Some(color);
        self
    }
    fn label_font_size(mut self, size: FontSize) -> Self {
        self.style.maybe_title_bar_font_size = Some(size);
        self
    }
}