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
use core::time;
use std::sync::mpsc::{channel, TryRecvError};
use std::thread;

use adw::prelude::AdwApplicationWindowExt;
use gtk::prelude::{
    BoxExt, ButtonExt, CheckButtonExt, DialogExt, EntryBufferExtManual, EntryExt, GtkWindowExt,
    OrientableExt, PopoverExt, ToggleButtonExt, WidgetExt,
};
use rand::prelude::SliceRandom;
use rand::Rng;
use relm4::{
    adw, gtk, send, AppUpdate, ComponentUpdate, MessageHandler, Model, RelmApp, RelmComponent,
    RelmMsgHandler, Sender, WidgetPlus, Widgets,
};

struct DialogModel {
    hidden: bool,
    correct: u32,
    incorrect: u32,
}

enum DialogMsg {
    Show(u32, u32),
    Accept,
}

impl Model for DialogModel {
    type Msg = DialogMsg;
    type Widgets = DialogWidgets;
    type Components = ();
}

impl ComponentUpdate<AppModel> for DialogModel {
    fn init_model(_parent_model: &AppModel) -> Self {
        DialogModel {
            hidden: true,
            correct: 0,
            incorrect: 0,
        }
    }

    fn update(
        &mut self,
        msg: DialogMsg,
        _components: &(),
        _sender: Sender<DialogMsg>,
        _parent_sender: Sender<AppMsg>,
    ) {
        match msg {
            DialogMsg::Show(correct, incorrect) => {
                self.hidden = false;
                self.correct = correct;
                self.incorrect = incorrect;
            }
            DialogMsg::Accept => {
                self.hidden = true;
            }
        }
    }
}

#[relm4::widget]
impl Widgets<DialogModel, AppModel> for DialogWidgets {
    view! {
        dialog = gtk::MessageDialog {
            set_transient_for: parent!(Some(&parent_widgets.main_window)),
            set_modal: true,
            set_visible: watch!(!model.hidden),
            set_text: Some("Congratulations!"),
            set_secondary_text: watch!(Some(&format!("You got {} correct and {} incorrect results.\nThat are {} points",
                model.correct, model.incorrect, model.correct as i32 - model.incorrect as i32 * 2))),
            add_button: args!("Ok", gtk::ResponseType::Accept),
            connect_response(sender) => move |_, _| {
                send!(sender,DialogMsg::Accept);
            }
        }
    }
}

#[derive(Clone)]
enum PracticeMode {
    Plus,
    Minus,
    Multiply,
}

enum TaskType {
    ValueValueEntry,
    ValueEntryValue,
    EntryValueValue,
}

struct AppModel {
    plus: bool,
    minus: bool,
    multiply: bool,
    mode: PracticeMode,
    task_type: TaskType,
    range: u32,
    display_task_1: String,
    display_task_2: String,
    correct_value: u32,
    feedback: String,
    timer: Option<u32>,
    timer_init_value: u32,
    correct_calculations: u32,
    incorrect_calculations: u32,
}

impl AppModel {
    fn calculate_task(&mut self) {
        match self.mode {
            PracticeMode::Plus => match self.task_type {
                TaskType::ValueValueEntry => {
                    self.correct_value = rand::thread_rng().gen_range(1..=self.range);
                    let v1 = rand::thread_rng().gen_range(1..=self.correct_value);
                    let v2 = self.correct_value - v1;
                    self.display_task_1 = format!("<big>{} + {} = </big>", v1, v2);
                }
                TaskType::ValueEntryValue => {
                    let result = rand::thread_rng().gen_range(1..=self.range);
                    let v1 = rand::thread_rng().gen_range(1..=result);
                    self.correct_value = result - v1;
                    self.display_task_1 = format!("<big>{} + </big>", v1);
                    self.display_task_2 = format!("<big> = {}</big>", result);
                }
                TaskType::EntryValueValue => {
                    let result = rand::thread_rng().gen_range(1..=self.range);
                    self.correct_value = rand::thread_rng().gen_range(1..=result);
                    let v2 = result - self.correct_value;
                    self.display_task_2 = format!("<big> + {} = {}</big>", v2, result);
                }
            },
            PracticeMode::Minus => match self.task_type {
                TaskType::ValueValueEntry => {
                    let v1 = rand::thread_rng().gen_range(1..=self.range);
                    let v2 = rand::thread_rng().gen_range(0..=v1);
                    self.correct_value = v1 - v2;
                    self.display_task_1 = format!("<big>{} - {} = </big>", v1, v2);
                }
                TaskType::ValueEntryValue => {
                    let v1 = rand::thread_rng().gen_range(1..=self.range);
                    self.correct_value = rand::thread_rng().gen_range(0..=v1);
                    let result = v1 - self.correct_value;
                    self.display_task_1 = format!("<big>{} - </big>", v1);
                    self.display_task_2 = format!("<big> = {}</big>", result);
                }
                TaskType::EntryValueValue => {
                    self.correct_value = rand::thread_rng().gen_range(1..=self.range);
                    let v2 = rand::thread_rng().gen_range(0..=self.correct_value);
                    let result = self.correct_value - v2;
                    self.display_task_2 = format!("<big> - {} = {}</big>", v2, result);
                }
            },
            PracticeMode::Multiply => match self.task_type {
                TaskType::ValueValueEntry => {
                    let v1 = rand::thread_rng().gen_range(1..=self.range);
                    let v2 = rand::thread_rng().gen_range(0..=self.range);
                    self.correct_value = v1 * v2;
                    self.display_task_1 = format!("<big>{} ∙ {} = </big>", v1, v2);
                }
                TaskType::ValueEntryValue => {
                    let v1 = rand::thread_rng().gen_range(1..=self.range);
                    self.correct_value = rand::thread_rng().gen_range(0..=self.range);
                    let result = v1 * self.correct_value;
                    self.display_task_1 = format!("<big>{} ∙ </big>", v1);
                    self.display_task_2 = format!("<big> = {}</big>", result);
                }
                TaskType::EntryValueValue => {
                    self.correct_value = rand::thread_rng().gen_range(0..=self.range);
                    let v2 = rand::thread_rng().gen_range(1..=self.range);
                    let result = self.correct_value * v2;
                    self.display_task_2 = format!("<big> ∙ {} = {}</big>", v2, result);
                }
            },
        }
    }

    fn pick_random_task_type(&mut self) {
        let mut v = Vec::new();
        if self.minus {
            v.push(PracticeMode::Minus);
        }
        if self.plus {
            v.push(PracticeMode::Plus);
        }
        if self.multiply {
            v.push(PracticeMode::Multiply);
        }

        if !v.is_empty() {
            self.mode = v.choose(&mut rand::thread_rng()).unwrap().clone();
        } else {
            return;
        }

        let task_type = rand::thread_rng().gen_range(0..3);
        match task_type {
            0 => self.task_type = TaskType::ValueValueEntry,
            1 => self.task_type = TaskType::ValueEntryValue,
            _ => self.task_type = TaskType::EntryValueValue,
        }
    }
}

enum AppMsg {
    Plus(bool),
    Minus(bool),
    Multiply(bool),
    MaxValue(u32),
    Entry(i32),
    EntryError,
    SetTimer(u32),
    StartTimer,
    CountDown,
}

impl Model for AppModel {
    type Msg = AppMsg;
    type Widgets = AppWidgets;
    type Components = AppComponents;
}

impl AppUpdate for AppModel {
    fn update(&mut self, msg: AppMsg, components: &AppComponents, _sender: Sender<AppMsg>) -> bool {
        match msg {
            AppMsg::Plus(v) => {
                if self.minus || self.multiply {
                    self.plus = v;
                }
            }
            AppMsg::Multiply(v) => {
                if self.minus || self.plus {
                    self.multiply = v;
                }
            }
            AppMsg::Minus(v) => {
                if self.plus || self.multiply {
                    self.minus = v;
                }
            }
            AppMsg::MaxValue(v) => {
                self.range = v;
                self.calculate_task();
            }
            AppMsg::Entry(v) => {
                if self.correct_value == v as u32 {
                    self.feedback = "<big>😀 That was right!! 💓</big>".to_string();
                    self.pick_random_task_type();
                    self.calculate_task();
                    self.correct_calculations += 1;
                } else {
                    self.feedback = "<big>😕 Unfortunately wrong. 😓</big>".to_string();
                    self.incorrect_calculations += 1;
                }
            }
            AppMsg::EntryError => {
                self.feedback = "<big>Please enter a valid number.</big>".to_string();
            }
            AppMsg::SetTimer(v) => {
                self.timer_init_value = v;
            }
            AppMsg::StartTimer => {
                // if timer is running a press on the button will reset button
                // otherwise initialize the timer with the selected init value
                components.timer_handler.send(TimerMsg::StartStopTimer);
                if self.timer.is_some() {
                    self.timer = None;
                } else {
                    self.pick_random_task_type();
                    self.calculate_task();
                    self.timer = Some(self.timer_init_value);
                    self.correct_calculations = 0;
                    self.incorrect_calculations = 0;
                }
            }
            AppMsg::CountDown => {
                if let Some(t) = &mut self.timer {
                    *t -= 1;

                    // check if time is up
                    if *t == 0 {
                        self.timer = None;
                        // stop timer
                        components.timer_handler.send(TimerMsg::StartStopTimer);
                        // display results
                        components
                            .dialog
                            .send(DialogMsg::Show(
                                self.correct_calculations,
                                self.incorrect_calculations,
                            ))
                            .unwrap();
                    }
                }
            }
        }
        true
    }
}

#[relm4::widget]
impl Widgets<AppModel, ()> for AppWidgets {
    view! {
        main_window = adw::ApplicationWindow {
            set_default_width: 350,
            set_default_height: 200,
            set_resizable: false,

            set_content: main_box = Some(&gtk::Box) {
                set_orientation: gtk::Orientation::Vertical,

                append = &adw::HeaderBar {
                    set_title_widget = Some(&adw::WindowTitle::new("Practice mental arithmetic!",
                        "Challenge yourself with math")) {
                    },
                    pack_start = &adw::SplitButton {
                        set_label: watch!({
                            &*if let Some(t) = model.timer {
                                format!("{}s", t)
                            } else {
                                "Start".to_string()
                            }
                        }),
                        connect_clicked(sender) => move |_| {
                            send!(sender, AppMsg::StartTimer)
                        },
                        set_popover: popover = Some(&gtk::Popover) {
                            set_child = Some(&gtk::Box) {
                                set_orientation: gtk::Orientation::Vertical,
                                append: timer = &gtk::CheckButton::with_label("30s") {
                                    connect_toggled(sender) => move |b| {
                                        if b.is_active() {
                                            send!(sender, AppMsg::SetTimer(30))
                                        }
                                    }
                                },
                                append = &gtk::CheckButton::with_label("60s") {
                                    set_group: Some(&timer),
                                    connect_toggled(sender) => move |b| {
                                        if b.is_active() {
                                            send!(sender, AppMsg::SetTimer(60))
                                        }
                                    }
                                },
                                append = &gtk::CheckButton::with_label("180s") {
                                    set_group: Some(&timer),
                                    connect_toggled(sender) => move |b| {
                                        if b.is_active() {
                                            send!(sender, AppMsg::SetTimer(180))
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                append = &gtk::Label {
                    set_text: "Calculation Type:",
                    set_margin_top: 10,
                },
                append = &gtk::Box {
                    set_orientation: gtk::Orientation::Horizontal,
                    set_halign: gtk::Align::Center,
                    set_margin_all: 5,
                    set_spacing: 5,
                    append = &gtk::ToggleButton {
                        set_label: "+",
                        set_active: watch!(model.plus),
                        connect_toggled(sender) => move |b| {
                            send!(sender, AppMsg::Plus(b.is_active()));
                        },
                    },
                    append = &gtk::ToggleButton {
                        set_label: "-",
                        set_active: watch!(model.minus),
                        connect_toggled(sender) => move |b| {
                            send!(sender, AppMsg::Minus(b.is_active()));
                        },
                    },
                    append = &gtk::ToggleButton {
                        set_label: "∙",
                        set_active: watch!(model.multiply),
                        connect_toggled(sender) => move |b| {
                            send!(sender, AppMsg::Multiply(b.is_active()));
                        },
                    },
                    append = &gtk::DropDown::from_strings(&["0-10", "0-20", "0-100", "0-1000"]) {
                        connect_selected_notify(sender) => move |dd| {
                            match dd.selected() {
                                0 => send!(sender, AppMsg::MaxValue(10)),
                                1 => send!(sender, AppMsg::MaxValue(20)),
                                2 => send!(sender, AppMsg::MaxValue(100)),
                                3 => send!(sender, AppMsg::MaxValue(1000)),
                                _ => {},
                            }
                        }
                    }
                },
                append : stack = &gtk::Stack {
                    add_child: value_value_entry = &gtk::Box {
                        set_orientation: gtk::Orientation::Horizontal,
                        set_margin_all: 5,
                        set_spacing: 5,
                        set_halign: gtk::Align::Center,
                        append = &gtk::Label {
                            set_markup: watch! { model.display_task_1.as_str() },
                        },
                        append = &gtk::Entry {
                            connect_activate(sender) => move |entry| {
                                let value = entry.buffer().text().parse::<i32>();
                                if let Ok(v) = value {
                                    send!(sender, AppMsg::Entry(v));
                                } else {
                                    send!(sender, AppMsg::EntryError);
                                }
                                entry.set_buffer(&gtk::EntryBuffer::new(None));
                            }
                        }
                    },
                    add_child: value_entry_value = &gtk::Box {
                        set_orientation: gtk::Orientation::Horizontal,
                        set_margin_all: 5,
                        set_spacing: 5,
                        set_halign: gtk::Align::Center,
                        append = &gtk::Label {
                            set_markup: watch! { model.display_task_1.as_str() },
                        },
                        append = &gtk::Entry {
                            connect_activate(sender) => move |entry| {
                                let value = entry.buffer().text().parse::<i32>();
                                if let Ok(v) = value {
                                    send!(sender, AppMsg::Entry(v));
                                } else {
                                    send!(sender, AppMsg::EntryError);
                                }
                                entry.set_buffer(&gtk::EntryBuffer::new(None));
                            }
                        },
                        append = &gtk::Label {
                            set_markup: watch! { model.display_task_2.as_str() },
                        },
                    },
                    add_child: entry_value_value = &gtk::Box {
                        set_orientation: gtk::Orientation::Horizontal,
                        set_margin_all: 5,
                        set_spacing: 5,
                        set_halign: gtk::Align::Center,
                        append = &gtk::Entry {
                            connect_activate(sender) => move |entry| {
                                let value = entry.buffer().text().parse::<i32>();
                                if let Ok(v) = value {
                                    send!(sender, AppMsg::Entry(v));
                                } else {
                                    send!(sender, AppMsg::EntryError);
                                }
                                entry.set_buffer(&gtk::EntryBuffer::new(None));
                            }
                        },
                        append = &gtk::Label {
                            set_markup: watch! { model.display_task_2.as_str() },
                        },
                    },
                },
                append: feedback = &gtk::Label {
                    set_markup: watch!( &model.feedback ),
                }
            }
        }
    }

    fn pre_view() {
        match model.task_type {
            TaskType::EntryValueValue => self.stack.set_visible_child(&self.entry_value_value),
            TaskType::ValueEntryValue => self.stack.set_visible_child(&self.value_entry_value),
            TaskType::ValueValueEntry => self.stack.set_visible_child(&self.value_value_entry),
        }
    }

    fn post_init() {
        // Set radio button initial to 30s
        timer.set_active(true);
    }
}

struct TimerHandler {
    sender: std::sync::mpsc::Sender<TimerMsg>,
}

#[derive(Debug)]
enum TimerMsg {
    StartStopTimer,
}

impl MessageHandler<AppModel> for TimerHandler {
    type Msg = TimerMsg;
    type Sender = std::sync::mpsc::Sender<TimerMsg>;

    fn init(_parent_model: &AppModel, parent_sender: Sender<AppMsg>) -> Self {
        let (sender, receiver) = channel();

        thread::spawn(move || {
            loop {
                // Wait for start message
                let _ = receiver.recv();
                // loop as long channel is empty
                while receiver.try_recv().err() == Some(TryRecvError::Empty) {
                    thread::sleep(time::Duration::from_secs(1));
                    send!(parent_sender, AppMsg::CountDown);
                }
            }
        });

        TimerHandler { sender }
    }

    fn send(&self, msg: Self::Msg) {
        self.sender.send(msg).unwrap();
    }

    fn sender(&self) -> Self::Sender {
        self.sender.clone()
    }
}

#[derive(relm4::Components)]
struct AppComponents {
    timer_handler: RelmMsgHandler<TimerHandler, AppModel>,
    dialog: RelmComponent<DialogModel, AppModel>,
}

fn main() {
    let mut model = AppModel {
        mode: PracticeMode::Plus,
        range: 10,
        display_task_1: "".to_string(),
        display_task_2: "".to_string(),
        correct_value: 0,
        feedback: "<big>Welcome to the mental math trainer!</big>".to_string(),
        task_type: TaskType::ValueValueEntry,
        plus: true,
        minus: false,
        multiply: false,
        timer_init_value: 30,
        timer: None,
        correct_calculations: 0,
        incorrect_calculations: 0,
    };

    model.calculate_task();

    let app = RelmApp::new(model);
    app.run();
}