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
use geom::{Distance, Polygon};

use crate::{
    svg, Color, Drawable, EdgeInsets, EventCtx, GeomBatch, GfxCtx, Key, Line, MultiKey, Outcome,
    RewriteColor, ScreenDims, ScreenPt, ScreenRectangle, Text, Widget, WidgetImpl, WidgetOutput,
};

pub struct Button {
    pub action: String,

    // Both of these must have the same dimensions and are oriented with their top-left corner at
    // 0, 0. Transformation happens later.
    draw_normal: Drawable,
    draw_hovered: Drawable,

    pub(crate) hotkey: Option<MultiKey>,
    tooltip: Text,
    // Screenspace, top-left always at the origin. Also, probably not a box. :P
    hitbox: Polygon,

    pub(crate) hovering: bool,

    pub(crate) top_left: ScreenPt,
    pub(crate) dims: ScreenDims,
}

impl Button {
    fn new(
        ctx: &EventCtx,
        normal: GeomBatch,
        hovered: GeomBatch,
        hotkey: Option<MultiKey>,
        tooltip: &str,
        maybe_tooltip: Option<Text>,
        hitbox: Polygon,
    ) -> Widget {
        // dims are based on the hitbox, not the two drawables!
        let bounds = hitbox.get_bounds();
        let dims = ScreenDims::new(bounds.width(), bounds.height());
        assert!(!tooltip.is_empty());
        Widget::new(Box::new(Button {
            action: tooltip.to_string(),

            draw_normal: ctx.upload(normal),
            draw_hovered: ctx.upload(hovered),
            tooltip: if let Some(t) = maybe_tooltip {
                t
            } else {
                Text::tooltip(ctx, hotkey.clone(), tooltip)
            },
            hotkey,
            hitbox,

            hovering: false,

            top_left: ScreenPt::new(0.0, 0.0),
            dims,
        }))
        .named(tooltip)
    }
}

impl WidgetImpl for Button {
    fn get_dims(&self) -> ScreenDims {
        self.dims
    }

    fn set_pos(&mut self, top_left: ScreenPt) {
        self.top_left = top_left;
    }

    fn event(&mut self, ctx: &mut EventCtx, output: &mut WidgetOutput) {
        if ctx.redo_mouseover() {
            if let Some(pt) = ctx.canvas.get_cursor_in_screen_space() {
                self.hovering = self
                    .hitbox
                    .translate(self.top_left.x, self.top_left.y)
                    .contains_pt(pt.to_pt());
            } else {
                self.hovering = false;
            }
        }
        if self.hovering && ctx.normal_left_click() {
            self.hovering = false;
            output.outcome = Outcome::Clicked(self.action.clone());
            return;
        }

        if ctx.input.pressed(self.hotkey.clone()) {
            self.hovering = false;
            output.outcome = Outcome::Clicked(self.action.clone());
            return;
        }

        if self.hovering {
            ctx.cursor_clickable();
        }
    }

    fn draw(&self, g: &mut GfxCtx) {
        if self.hovering {
            g.redraw_at(self.top_left, &self.draw_hovered);
            if !self.tooltip.is_empty() {
                g.draw_mouse_tooltip(self.tooltip.clone());
            }
        } else {
            g.redraw_at(self.top_left, &self.draw_normal);
        }
    }
}

pub struct Btn {}

impl Btn {
    pub fn svg<I: Into<String>>(path: I, rewrite_hover: RewriteColor) -> BtnBuilder {
        BtnBuilder::SVG {
            path: path.into(),
            rewrite_hover,
            maybe_tooltip: None,
        }
    }
    pub fn svg_def<I: Into<String>>(path: I) -> BtnBuilder {
        BtnBuilder::SVG {
            path: path.into(),
            rewrite_hover: RewriteColor::ChangeAll(Color::ORANGE),
            maybe_tooltip: None,
        }
    }

    pub fn plaintext<I: Into<String>>(label: I) -> BtnBuilder {
        let label = label.into();
        BtnBuilder::PlainText {
            label: label.clone(),
            txt: Text::from(Line(label)),
            maybe_tooltip: None,
        }
    }
    pub fn plaintext_custom<I: Into<String>>(label: I, txt: Text) -> BtnBuilder {
        BtnBuilder::PlainText {
            label: label.into(),
            txt,
            maybe_tooltip: None,
        }
    }

    pub fn text_fg<I: Into<String>>(label: I) -> BtnBuilder {
        let label = label.into();
        BtnBuilder::TextFG(label.clone(), Text::from(Line(label)), None)
    }

    pub fn txt<I: Into<String>>(label: I, txt: Text) -> BtnBuilder {
        BtnBuilder::TextFG(label.into(), txt, None)
    }

    pub fn text_bg<I: Into<String>>(
        label: I,
        text: Text,
        unselected_bg_color: Color,
        selected_bg_color: Color,
    ) -> BtnBuilder {
        BtnBuilder::TextBG {
            label: label.into(),
            maybe_tooltip: None,

            text,
            unselected_bg_color,
            selected_bg_color,
        }
    }

    // The info panel style with the lighter background color
    pub fn text_bg1<I: Into<String>>(label: I) -> BtnBuilder {
        let label = label.into();
        BtnBuilder::TextBG {
            label: label.clone(),
            maybe_tooltip: None,

            text: Text::from(Line(label)),
            unselected_bg_color: Color::grey(0.5),
            selected_bg_color: Color::ORANGE,
        }
    }

    // The white background.
    pub fn text_bg2<I: Into<String>>(label: I) -> BtnBuilder {
        let label = label.into();
        BtnBuilder::TextBG {
            label: label.clone(),
            maybe_tooltip: None,

            text: Text::from(Line(label).fg(Color::hex("#5B5B5B"))),
            // This is sometimes against a white background and could just be None, but some
            // callers need the background.
            unselected_bg_color: Color::WHITE,
            selected_bg_color: Color::grey(0.8),
        }
    }

    pub fn pop_up<I: Into<String>>(ctx: &EventCtx, label: Option<I>) -> BtnBuilder {
        let mut icon_batch = GeomBatch::new();
        let icon_container = Polygon::rectangle(20.0, 30.0);
        icon_batch.push(Color::INVISIBLE, icon_container);

        let icon = GeomBatch::from_svg_contents(
            include_bytes!("../../../data/system/assets/widgetry/arrow_drop_down.svg").to_vec(),
        )
        .color(RewriteColor::ChangeAll(ctx.style().outline_color))
        .autocrop()
        .centered_on(icon_batch.get_bounds().center());

        icon_batch.append(icon);

        let button_geom = if let Some(label) = label {
            let text = Text::from(Line(label));
            let mut text_geom: GeomBatch = text.render(ctx);
            text_geom.append(icon_batch.translate(text_geom.get_bounds().width() + 8.0, 0.0));
            text_geom
        } else {
            icon_batch
        };

        let (button_geom, hitbox) = button_geom
            .batch()
            .container()
            .padding(EdgeInsets {
                top: 4.0,
                bottom: 4.0,
                left: 8.0,
                right: 8.0,
            })
            .to_geom(ctx, None);

        let hovered = button_geom.clone().color(RewriteColor::Change(
            ctx.style().outline_color,
            ctx.style().hovering_color,
        ));

        let outline = (ctx.style().outline_thickness, ctx.style().outline_color);
        BtnBuilder::Custom {
            normal: button_geom,
            hovered,
            hitbox,
            maybe_tooltip: None,
            maybe_outline: Some(outline),
        }
    }

    pub fn custom(
        normal: GeomBatch,
        hovered: GeomBatch,
        hitbox: Polygon,
        outline: Option<(f64, Color)>,
    ) -> BtnBuilder {
        BtnBuilder::Custom {
            normal,
            hovered,
            hitbox,
            maybe_tooltip: None,
            maybe_outline: outline,
        }
    }

    /// An "X" button to close the current state. Bound to the escape key and aligned to the right,
    /// usually after a title.
    pub fn close(ctx: &EventCtx) -> Widget {
        Btn::plaintext("X")
            .build(ctx, "close", Key::Escape)
            .align_right()
    }
}

pub enum BtnBuilder {
    SVG {
        path: String,
        rewrite_hover: RewriteColor,
        maybe_tooltip: Option<Text>,
    },
    TextFG(String, Text, Option<Text>),
    PlainText {
        label: String,
        txt: Text,
        maybe_tooltip: Option<Text>,
    },
    TextBG {
        label: String,
        maybe_tooltip: Option<Text>,

        text: Text,
        unselected_bg_color: Color,
        selected_bg_color: Color,
    },
    Custom {
        normal: GeomBatch,
        hovered: GeomBatch,
        hitbox: Polygon,
        maybe_tooltip: Option<Text>,
        // thickness, color
        maybe_outline: Option<(f64, Color)>,
    },
}

impl BtnBuilder {
    pub fn tooltip(mut self, tooltip: Text) -> BtnBuilder {
        match self {
            BtnBuilder::TextFG(_, _, ref mut maybe_tooltip)
            | BtnBuilder::PlainText {
                ref mut maybe_tooltip,
                ..
            }
            | BtnBuilder::Custom {
                ref mut maybe_tooltip,
                ..
            } => {
                assert!(maybe_tooltip.is_none());
                *maybe_tooltip = Some(tooltip);
            }
            BtnBuilder::SVG {
                ref mut maybe_tooltip,
                ..
            }
            | BtnBuilder::TextBG {
                ref mut maybe_tooltip,
                ..
            } => {
                assert!(maybe_tooltip.is_none());
                *maybe_tooltip = Some(tooltip);
            }
        }
        self
    }

    pub fn build<I: Into<String>, MK: Into<Option<MultiKey>>>(
        self,
        ctx: &EventCtx,
        action_tooltip: I,
        key: MK,
    ) -> Widget {
        match self {
            BtnBuilder::SVG {
                path,
                rewrite_hover,
                maybe_tooltip,
            } => {
                let (normal, bounds) = svg::load_svg(ctx.prerender, &path);
                let geom = Polygon::rectangle(bounds.width(), bounds.height());

                let hovered = normal.clone().color(rewrite_hover);

                Button::new(
                    ctx,
                    normal,
                    hovered,
                    key.into(),
                    &action_tooltip.into(),
                    maybe_tooltip,
                    geom,
                )
            }
            BtnBuilder::TextFG(_, normal_txt, maybe_t) => {
                let (normal, hitbox) = normal_txt
                    .clone()
                    .batch(ctx)
                    .container()
                    .padding(8)
                    .to_geom(ctx, None);
                let (hovered, _) = normal_txt
                    .change_fg(Color::ORANGE)
                    .batch(ctx)
                    .container()
                    .padding(8)
                    .to_geom(ctx, None);

                Button::new(
                    ctx,
                    normal,
                    hovered,
                    key.into(),
                    &action_tooltip.into(),
                    maybe_t,
                    hitbox,
                )
                .outline(2.0, Color::WHITE)
            }
            // Same as TextFG without the outline
            BtnBuilder::PlainText {
                txt, maybe_tooltip, ..
            } => {
                let (normal, hitbox) = txt
                    .clone()
                    .batch(ctx)
                    .container()
                    .padding(8)
                    .to_geom(ctx, None);
                let (hovered, _) = txt
                    .change_fg(Color::ORANGE)
                    .batch(ctx)
                    .container()
                    .padding(8)
                    .to_geom(ctx, None);

                Button::new(
                    ctx,
                    normal,
                    hovered,
                    key.into(),
                    &action_tooltip.into(),
                    maybe_tooltip,
                    hitbox,
                )
            }
            BtnBuilder::TextBG {
                text,
                maybe_tooltip,
                unselected_bg_color,
                selected_bg_color,
                ..
            } => {
                let (normal, hitbox) = text
                    .clone()
                    .batch(ctx)
                    .container()
                    .padding(15)
                    .bg(unselected_bg_color)
                    .to_geom(ctx, None);
                let (hovered, _) = text
                    .batch(ctx)
                    .container()
                    .padding(15)
                    .bg(selected_bg_color)
                    .to_geom(ctx, None);

                Button::new(
                    ctx,
                    normal,
                    hovered,
                    key.into(),
                    &action_tooltip.into(),
                    maybe_tooltip,
                    hitbox,
                )
            }
            BtnBuilder::Custom {
                normal,
                hovered,
                hitbox,
                maybe_tooltip,
                maybe_outline,
            } => {
                let button = Button::new(
                    ctx,
                    normal,
                    hovered,
                    key.into(),
                    &action_tooltip.into(),
                    maybe_tooltip,
                    hitbox,
                );

                if let Some(outline) = maybe_outline {
                    button.outline(outline.0, outline.1)
                } else {
                    button
                }
            }
        }
    }

    // Use the text as the action
    pub fn build_def<MK: Into<Option<MultiKey>>>(self, ctx: &EventCtx, key: MK) -> Widget {
        match self {
            BtnBuilder::SVG { .. } => panic!("Can't use build_def on an SVG button"),
            BtnBuilder::Custom { .. } => panic!("Can't use build_def on a custom button"),
            BtnBuilder::TextFG(ref label, _, _)
            | BtnBuilder::PlainText { ref label, .. }
            | BtnBuilder::TextBG { ref label, .. } => {
                assert!(!label.is_empty());
                let copy = label.clone();
                self.build(ctx, copy, key)
            }
        }
    }

    pub fn inactive(self, ctx: &EventCtx) -> Widget {
        match self {
            BtnBuilder::TextFG(label, txt, _) => Widget::draw_batch(
                ctx,
                txt.change_fg(Color::grey(0.5))
                    .render(ctx)
                    .batch()
                    .container()
                    .padding(8)
                    .outline(2.0, Color::WHITE)
                    .to_geom(ctx, None)
                    .0,
            )
            .named(label),
            // TODO This'll only work reasonably for text_bg2
            BtnBuilder::TextBG {
                text,
                unselected_bg_color,
                label,
                ..
            } => {
                assert_eq!(unselected_bg_color, Color::WHITE);
                Widget::draw_batch(
                    ctx,
                    text.render(ctx)
                        .batch()
                        .container()
                        .padding(15)
                        .bg(Color::grey(0.7))
                        .to_geom(ctx, None)
                        .0,
                )
                .named(label)
            }
            BtnBuilder::PlainText { txt, label, .. } => Widget::draw_batch(
                ctx,
                txt.change_fg(Color::grey(0.5))
                    .render(ctx)
                    .batch()
                    .container()
                    .padding(8)
                    .to_geom(ctx, None)
                    .0,
            )
            .named(label),
            _ => panic!("Can't use inactive on this kind of button"),
        }
    }
}

// Like an image map from the old HTML days
pub struct MultiButton {
    draw: Drawable,
    hitboxes: Vec<(Polygon, String)>,
    hovering: Option<usize>,

    top_left: ScreenPt,
    dims: ScreenDims,
}

impl MultiButton {
    pub fn new(ctx: &EventCtx, batch: GeomBatch, hitboxes: Vec<(Polygon, String)>) -> Widget {
        Widget::new(Box::new(MultiButton {
            dims: batch.get_dims(),
            top_left: ScreenPt::new(0.0, 0.0),
            draw: ctx.upload(batch),
            hitboxes,
            hovering: None,
        }))
    }
}

impl WidgetImpl for MultiButton {
    fn get_dims(&self) -> ScreenDims {
        self.dims
    }

    fn set_pos(&mut self, top_left: ScreenPt) {
        self.top_left = top_left;
    }

    fn event(&mut self, ctx: &mut EventCtx, output: &mut WidgetOutput) {
        if ctx.redo_mouseover() {
            self.hovering = None;
            if let Some(cursor) = ctx.canvas.get_cursor_in_screen_space() {
                if !ScreenRectangle::top_left(self.top_left, self.dims).contains(cursor) {
                    return;
                }
                let translated =
                    ScreenPt::new(cursor.x - self.top_left.x, cursor.y - self.top_left.y).to_pt();
                // TODO Assume regions are non-overlapping
                for (idx, (region, _)) in self.hitboxes.iter().enumerate() {
                    if region.contains_pt(translated) {
                        self.hovering = Some(idx);
                        break;
                    }
                }
            }
        }
        if let Some(idx) = self.hovering {
            if ctx.normal_left_click() {
                self.hovering = None;
                output.outcome = Outcome::Clicked(self.hitboxes[idx].1.clone());
            }
        }
    }

    fn draw(&self, g: &mut GfxCtx) {
        g.redraw_at(self.top_left, &self.draw);
        if let Some(idx) = self.hovering {
            if let Ok(p) = self.hitboxes[idx].0.to_outline(Distance::meters(1.0)) {
                let draw = g.upload(GeomBatch::from(vec![(Color::YELLOW, p)]));
                g.redraw_at(self.top_left, &draw);
            }
        }
    }
}