summaryrefslogtreecommitdiff
path: root/src/state.rs
blob: b9e7aefb5578dca6ed2fd73ce944393fc6fd84a8 (plain)
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
/*
 * meli
 *
 * Copyright 2017-2018 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

/*! The application's state.

The UI crate has an Box<dyn Component>-Component-System design. The System part, is also the application's state, so they're both merged in the `State` struct.

`State` owns all the Components of the UI. In the application's main event loop, input is handed to the state in the form of `UIEvent` objects which traverse the component graph. Components decide to handle each input or not.

Input is received in the main loop from threads which listen on the stdin for user input, observe folders for file changes etc. The relevant struct is `ThreadEvent`.
*/

use super::*;
//use crate::plugins::PluginManager;
use melib::backends::{AccountHash, BackendEventConsumer};

use crate::jobs::JobExecutor;
use crate::terminal::screen::Screen;
use crossbeam::channel::{unbounded, Receiver, Sender};
use indexmap::IndexMap;
use smallvec::SmallVec;
use std::env;
use std::os::unix::io::RawFd;
use std::sync::Arc;
use std::thread;

struct InputHandler {
    pipe: (RawFd, RawFd),
    rx: Receiver<InputCommand>,
    tx: Sender<InputCommand>,
    state_tx: Sender<ThreadEvent>,
    control: std::sync::Weak<()>,
}

impl InputHandler {
    fn restore(&mut self) {
        let working = Arc::new(());
        let control = Arc::downgrade(&working);

        /* Clear channel without blocking. switch_to_main_screen() issues a kill when
         * returning from a fork and there's no input thread, so the newly created thread will
         * receive it and die. */
        //let _ = self.rx.try_iter().count();
        let rx = self.rx.clone();
        let pipe = self.pipe.0;
        let tx = self.state_tx.clone();
        thread::Builder::new()
            .name("input-thread".to_string())
            .spawn(move || {
                get_events(
                    |i| {
                        tx.send(ThreadEvent::Input(i)).unwrap();
                    },
                    &rx,
                    pipe,
                    working,
                )
            })
            .unwrap();
        self.control = control;
    }

    fn kill(&self) {
        let _ = nix::unistd::write(self.pipe.1, &[1]);
        self.tx.send(InputCommand::Kill).unwrap();
    }

    fn check(&mut self) {
        match self.control.upgrade() {
            Some(_) => {}
            None => {
                debug!("restarting input_thread");
                self.restore();
            }
        }
    }
}

/// A context container for loaded settings, accounts, UI changes, etc.
pub struct Context {
    pub accounts: IndexMap<AccountHash, Account>,
    pub settings: Box<Settings>,

    /// Areas of the screen that must be redrawn in the next render
    pub dirty_areas: VecDeque<Area>,

    /// Events queue that components send back to the state
    pub replies: VecDeque<UIEvent>,
    pub sender: Sender<ThreadEvent>,
    receiver: Receiver<ThreadEvent>,
    input_thread: InputHandler,
    pub job_executor: Arc<JobExecutor>,
    pub children: Vec<std::process::Child>,

    pub temp_files: Vec<File>,
}

impl Context {
    pub fn replies(&mut self) -> smallvec::SmallVec<[UIEvent; 8]> {
        self.replies.drain(0..).collect()
    }

    pub fn input_kill(&self) {
        self.input_thread.kill();
    }

    pub fn restore_input(&mut self) {
        self.input_thread.restore();
    }

    pub fn is_online_idx(&mut self, account_pos: usize) -> Result<()> {
        let Context {
            ref mut accounts,
            ref mut replies,
            ..
        } = self;
        let was_online = accounts[account_pos].is_online.is_ok();
        let ret = accounts[account_pos].is_online();
        if ret.is_ok() && !was_online {
            debug!("inserting mailbox hashes:");
            for mailbox_node in accounts[account_pos].list_mailboxes() {
                debug!(
                    "hash & mailbox: {:?} {}",
                    mailbox_node.hash,
                    accounts[account_pos][&mailbox_node.hash].name()
                );
            }
            accounts[account_pos].watch();

            replies.push_back(UIEvent::AccountStatusChange(
                accounts[account_pos].hash(),
                None,
            ));
        }
        if ret.is_ok() != was_online {
            replies.push_back(UIEvent::AccountStatusChange(
                accounts[account_pos].hash(),
                None,
            ));
        }
        ret
    }

    pub fn is_online(&mut self, account_hash: AccountHash) -> Result<()> {
        let idx = self.accounts.get_index_of(&account_hash).unwrap();
        self.is_online_idx(idx)
    }

    #[cfg(test)]
    pub fn new_mock() -> Self {
        let (sender, receiver) =
            crossbeam::channel::bounded(32 * ::std::mem::size_of::<ThreadEvent>());
        let job_executor = Arc::new(JobExecutor::new(sender.clone()));
        let input_thread = unbounded();
        let input_thread_pipe = nix::unistd::pipe()
            .map_err(|err| Box::new(err) as Box<dyn std::error::Error + Send + Sync + 'static>)
            .unwrap();
        let backends = Backends::new();
        let settings = Box::new(Settings::new().unwrap());
        let accounts = vec![{
            let name = "test".to_string();
            let mut account_conf = AccountConf::default();
            account_conf.conf.format = "maildir".to_string();
            account_conf.account.format = "maildir".to_string();
            account_conf.account.root_mailbox = "/tmp/".to_string();
            let sender = sender.clone();
            let account_hash = AccountHash::from_bytes(name.as_bytes());
            Account::new(
                account_hash,
                name,
                account_conf,
                &backends,
                job_executor.clone(),
                sender.clone(),
                BackendEventConsumer::new(Arc::new(
                    move |account_hash: AccountHash, ev: BackendEvent| {
                        sender
                            .send(ThreadEvent::UIEvent(UIEvent::BackendEvent(
                                account_hash,
                                ev,
                            )))
                            .unwrap();
                    },
                )),
            )
            .unwrap()
        }];
        let accounts = accounts.into_iter().map(|acc| (acc.hash(), acc)).collect();
        let working = Arc::new(());
        let control = Arc::downgrade(&working);
        Context {
            accounts,
            settings,
            dirty_areas: VecDeque::with_capacity(0),
            replies: VecDeque::with_capacity(0),
            temp_files: Vec::new(),
            job_executor,
            children: vec![],

            input_thread: InputHandler {
                pipe: input_thread_pipe,
                rx: input_thread.1,
                tx: input_thread.0,
                control,
                state_tx: sender.clone(),
            },
            sender,
            receiver,
        }
    }
}

/// A State object to manage and own components and components of the UI. `State` is responsible for
/// managing the terminal and interfacing with `melib`
pub struct State {
    screen: Box<Screen>,
    draw_rate_limit: RateLimit,
    child: Option<ForkType>,
    pub mode: UIMode,
    overlay: Vec<Box<dyn Component>>,
    components: Vec<Box<dyn Component>>,
    pub context: Box<Context>,
    timer: thread::JoinHandle<()>,

    display_messages: SmallVec<[DisplayMessage; 8]>,
    display_messages_expiration_start: Option<UnixTimestamp>,
    display_messages_active: bool,
    display_messages_dirty: bool,
    display_messages_initialised: bool,
    display_messages_pos: usize,
    display_messages_area: Area,
}

#[derive(Debug)]
struct DisplayMessage {
    timestamp: UnixTimestamp,
    msg: String,
}

impl Drop for State {
    fn drop(&mut self) {
        // When done, restore the defaults to avoid messing with the terminal.
        self.screen.switch_to_main_screen();
        use nix::sys::wait::{waitpid, WaitPidFlag};
        for child in self.context.children.iter_mut() {
            if let Err(err) = waitpid(
                nix::unistd::Pid::from_raw(child.id() as i32),
                Some(WaitPidFlag::WNOHANG),
            ) {
                debug!("Failed to wait on subprocess {}: {}", child.id(), err);
            }
        }
        if let Some(ForkType::Embed(child_pid)) = self.child.take() {
            /* Try wait, we don't want to block */
            if let Err(e) = waitpid(child_pid, Some(WaitPidFlag::WNOHANG)) {
                debug!("Failed to wait on subprocess {}: {}", child_pid, e);
            }
        }
    }
}

impl State {
    pub fn new(
        settings: Option<Settings>,
        sender: Sender<ThreadEvent>,
        receiver: Receiver<ThreadEvent>,
    ) -> Result<Self> {
        /*
         * Create async channel to block the input-thread if we need to fork and stop it from reading
         * stdin, see get_events() for details
         * */
        let input_thread = unbounded();
        let input_thread_pipe = nix::unistd::pipe()
            .map_err(|err| Box::new(err) as Box<dyn std::error::Error + Send + Sync + 'static>)?;
        let backends = Backends::new();
        let settings = Box::new(if let Some(settings) = settings {
            settings
        } else {
            Settings::new()?
        });
        /*
        let mut plugin_manager = PluginManager::new();
        for (_, p) in settings.plugins.clone() {
            if crate::plugins::PluginKind::Backend == p.kind() {
                debug!("registering {:?}", &p);
                crate::plugins::backend::PluginBackend::register(
                    plugin_manager.listener(),
                    p.clone(),
                    &mut backends,
                );
            }
            plugin_manager.register(p)?;
        }
        */

        let termsize = termion::terminal_size()?;
        let cols = termsize.0 as usize;
        let rows = termsize.1 as usize;

        let job_executor = Arc::new(JobExecutor::new(sender.clone()));
        let accounts = {
            settings
                .accounts
                .iter()
                .map(|(n, a_s)| {
                    let sender = sender.clone();
                    let account_hash = AccountHash::from_bytes(n.as_bytes());
                    Account::new(
                        account_hash,
                        n.to_string(),
                        a_s.clone(),
                        &backends,
                        job_executor.clone(),
                        sender.clone(),
                        BackendEventConsumer::new(Arc::new(
                            move |account_hash: AccountHash, ev: BackendEvent| {
                                sender
                                    .send(ThreadEvent::UIEvent(UIEvent::BackendEvent(
                                        account_hash,
                                        ev,
                                    )))
                                    .unwrap();
                            },
                        )),
                    )
                })
                .collect::<Result<Vec<Account>>>()?
        };
        let accounts = accounts.into_iter().map(|acc| (acc.hash(), acc)).collect();

        let timer = {
            let sender = sender.clone();
            thread::Builder::new().spawn(move || {
                let sender = sender;
                loop {
                    thread::park();

                    sender.send(ThreadEvent::Pulse).unwrap();
                    thread::sleep(std::time::Duration::from_millis(100));
                }
            })
        }?;

        timer.thread().unpark();

        let working = Arc::new(());
        let control = Arc::downgrade(&working);
        let mut s = State {
            screen: Box::new(Screen {
                cols,
                rows,
                grid: CellBuffer::new(cols, rows, Cell::with_char(' ')),
                overlay_grid: CellBuffer::new(cols, rows, Cell::with_char(' ')),
                mouse: settings.terminal.use_mouse.is_true(),
                stdout: None,
                draw_horizontal_segment_fn: if settings.terminal.use_color() {
                    Screen::draw_horizontal_segment
                } else {
                    Screen::draw_horizontal_segment_no_color
                },
            }),
            child: None,
            mode: UIMode::Normal,
            components: Vec::with_capacity(8),
            overlay: Vec::new(),
            timer,
            draw_rate_limit: RateLimit::new(1, 3, job_executor.clone()),
            display_messages: SmallVec::new(),
            display_messages_expiration_start: None,
            display_messages_pos: 0,
            display_messages_active: false,
            display_messages_dirty: false,
            display_messages_initialised: false,
            display_messages_area: ((0, 0), (0, 0)),
            context: Box::new(Context {
                accounts,
                settings,
                dirty_areas: VecDeque::with_capacity(5),
                replies: VecDeque::with_capacity(5),
                temp_files: Vec::new(),
                job_executor,
                children: vec![],

                input_thread: InputHandler {
                    pipe: input_thread_pipe,
                    rx: input_thread.1,
                    tx: input_thread.0,
                    control,
                    state_tx: sender.clone(),
                },
                sender,
                receiver,
            }),
        };
        if s.context.settings.terminal.ascii_drawing {
            s.screen.grid.set_ascii_drawing(true);
            s.screen.overlay_grid.set_ascii_drawing(true);
        }

        s.screen.switch_to_alternate_screen(&s.context);
        for i in 0..s.context.accounts.len() {
            if !s.context.accounts[i].backend_capabilities.is_remote {
                s.context.accounts[i].watch();
            }
            if s.context.is_online_idx(i).is_ok() && s.context.accounts[i].is_empty() {
                //return Err(Error::new(format!(
                //    "Account {} has no mailboxes configured.",
                //    s.context.accounts[i].name()
                //)));
            }
        }
        s.context.restore_input();
        Ok(s)
    }

    /*
     * When we receive a mailbox hash from a watcher thread,
     * we match the hash to the index of the mailbox, request a reload
     * and startup a thread to remind us to poll it every now and then till it's finished.
     */
    pub fn refresh_event(&mut self, event: RefreshEvent) {
        let account_hash = event.account_hash;
        let mailbox_hash = event.mailbox_hash;
        if self.context.accounts[&account_hash]
            .mailbox_entries
            .contains_key(&mailbox_hash)
        {
            if self.context.accounts[&account_hash]
                .load(mailbox_hash)
                .is_err()
            {
                self.context.replies.push_back(UIEvent::from(event));
                return;
            }
            let Context {
                ref mut accounts, ..
            } = &mut *self.context;

            if let Some(notification) = accounts[&account_hash].reload(event, mailbox_hash) {
                if let UIEvent::Notification(_, _, _) = notification {
                    self.rcv_event(UIEvent::MailboxUpdate((account_hash, mailbox_hash)));
                }
                self.rcv_event(notification);
            }
        } else if let melib::backends::RefreshEventKind::Failure(err) = event.kind {
            debug!(err);
        }
    }

    pub fn receiver(&self) -> Receiver<ThreadEvent> {
        self.context.receiver.clone()
    }

    pub fn sender(&self) -> Sender<ThreadEvent> {
        self.context.sender.clone()
    }

    pub fn restore_input(&mut self) {
        self.context.restore_input();
    }

    /// On `SIGWNICH` the `State` redraws itself according to the new terminal size.
    pub fn update_size(&mut self) {
        self.screen.update_size();
        self.rcv_event(UIEvent::Resize);
        self.display_messages_dirty = true;
        self.display_messages_initialised = false;
        self.display_messages_area = ((0, 0), (0, 0));

        // Invalidate dirty areas.
        self.context.dirty_areas.clear();
    }

    /// Force a redraw for all dirty components.
    pub fn redraw(&mut self) {
        if !self.draw_rate_limit.tick() {
            return;
        }

        for i in 0..self.components.len() {
            self.draw_component(i);
        }
        let mut areas: smallvec::SmallVec<[Area; 8]> =
            self.context.dirty_areas.drain(0..).collect();
        if self.display_messages_active {
            let now = melib::datetime::now();
            if self
                .display_messages_expiration_start
                .map(|t| t + 5 < now)
                .unwrap_or(false)
            {
                self.display_messages_active = false;
                self.display_messages_dirty = true;
                self.display_messages_initialised = false;
                self.display_messages_expiration_start = None;
                areas.push((
                    (0, 0),
                    (
                        self.screen.cols.saturating_sub(1),
                        self.screen.rows.saturating_sub(1),
                    ),
                ));
            }
        }

        /* Sort by x_start, ie upper_left corner's x coordinate */
        areas.sort_by(|a, b| (a.0).0.partial_cmp(&(b.0).0).unwrap());

        if self.display_messages_active {
            /* Check if any dirty area intersects with the area occupied by floating notification
             * box */
            let (displ_top, displ_bot) = self.display_messages_area;
            for &((top_x, top_y), (bottom_x, bottom_y)) in &areas {
                self.display_messages_dirty |= !(bottom_y < displ_top.1
                    || displ_bot.1 < top_y
                    || bottom_x < displ_top.0
                    || displ_bot.0 < top_x);
            }
        }
        /* draw each dirty area */
        let rows = self.screen.rows;
        for y in 0..rows {
            let mut segment = None;
            for ((x_start, y_start), (x_end, y_end)) in &areas {
                if y < *y_start || y > *y_end {
                    continue;
                }
                if let Some((x_start, x_end)) = segment.take() {
                    (self.screen.draw_horizontal_segment_fn)(
                        &mut self.screen.grid,
                        self.screen.stdout.as_mut().unwrap(),
                        x_start,
                        x_end,
                        y,
                    );
                }
                match segment {
                    ref mut s @ None => {
                        *s = Some((*x_start, *x_end));
                    }
                    ref mut s @ Some(_) if s.unwrap().1 < *x_start => {
                        (self.screen.draw_horizontal_segment_fn)(
                            &mut self.screen.grid,
                            self.screen.stdout.as_mut().unwrap(),
                            s.unwrap().0,
                            s.unwrap().1,
                            y,
                        );
                        *s = Some((*x_start, *x_end));
                    }
                    ref mut s @ Some(_) if s.unwrap().1 < *x_end => {
                        (self.screen.draw_horizontal_segment_fn)(
                            &mut self.screen.grid,
                            self.screen.stdout.as_mut().unwrap(),
                            s.unwrap().0,
                            s.unwrap().1,
                            y,
                        );
                        *s = Some((s.unwrap().1, *x_end));
                    }
                    Some((_, ref mut x)) => {
                        *x = *x_end;
                    }
                }
            }
            if let Some((x_start, x_end)) = segment {
                (self.screen.draw_horizontal_segment_fn)(
                    &mut self.screen.grid,
                    self.screen.stdout.as_mut().unwrap(),
                    x_start,
                    x_end,
                    y,
                );
            }
        }

        if self.display_messages_dirty && self.display_messages_active {
            if let Some(DisplayMessage {
                ref timestamp,
                ref msg,
                ..
            }) = self.display_messages.get(self.display_messages_pos)
            {
                if !self.display_messages_initialised {
                    {
                        /* Clear area previously occupied by floating notification box */
                        let displ_area = self.display_messages_area;
                        for y in get_y(upper_left!(displ_area))..=get_y(bottom_right!(displ_area)) {
                            (self.screen.draw_horizontal_segment_fn)(
                                &mut self.screen.grid,
                                self.screen.stdout.as_mut().unwrap(),
                                get_x(upper_left!(displ_area)),
                                get_x(bottom_right!(displ_area)),
                                y,
                            );
                        }
                    }
                    let noto_colors = crate::conf::value(&self.context, "status.notification");
                    use crate::melib::text_processing::{Reflow, TextProcessing};

                    let msg_lines = msg.split_lines_reflow(Reflow::All, Some(self.screen.cols / 3));
                    let width = msg_lines
                        .iter()
                        .map(|line| line.grapheme_len() + 4)
                        .max()
                        .unwrap_or(0);

                    let displ_area = place_in_area(
                        (
                            (0, 0),
                            (
                                self.screen.cols.saturating_sub(1),
                                self.screen.rows.saturating_sub(1),
                            ),
                        ),
                        (width, std::cmp::min(self.screen.rows, msg_lines.len() + 4)),
                        false,
                        false,
                    );
                    let box_displ_area = create_box(&mut self.screen.overlay_grid, displ_area);
                    for row in self.screen.overlay_grid.bounds_iter(box_displ_area) {
                        for c in row {
                            self.screen.overlay_grid[c]
                                .set_ch(' ')
                                .set_fg(noto_colors.fg)
                                .set_bg(noto_colors.bg)
                                .set_attrs(noto_colors.attrs);
                        }
                    }
                    let ((x, mut y), box_displ_area_bottom_right) = box_displ_area;
                    for line in msg_lines.into_iter().chain(Some(String::new())).chain(Some(
                        melib::datetime::timestamp_to_string(*timestamp, None, false),
                    )) {
                        write_string_to_grid(
                            &line,
                            &mut self.screen.overlay_grid,
                            noto_colors.fg,
                            noto_colors.bg,
                            noto_colors.attrs,
                            ((x, y), box_displ_area_bottom_right),
                            Some(x),
                        );
                        y += 1;
                    }

                    if self.display_messages.len() > 1 {
                        write_string_to_grid(
                            &if self.display_messages_pos == 0 {
                                format!(
                                    "Next: {}",
                                    self.context.settings.shortcuts.general.info_message_next
                                )
                            } else if self.display_messages_pos + 1 == self.display_messages.len() {
                                format!(
                                    "Prev: {}",
                                    self.context
                                        .settings
                                        .shortcuts
                                        .general
                                        .info_message_previous
                                )
                            } else {
                                format!(
                                    "Prev: {} Next: {}",
                                    self.context
                                        .settings
                                        .shortcuts
                                        .general
                                        .info_message_previous,
                                    self.context.settings.shortcuts.general.info_message_next
                                )
                            },
                            &mut self.screen.overlay_grid,
                            noto_colors.fg,
                            noto_colors.bg,
                            noto_colors.attrs,
                            ((x, y), box_displ_area_bottom_right),
                            Some(x),
                        );
                    }
                    self.display_messages_area = displ_area;
                }
                for y in get_y(upper_left!(self.display_messages_area))
                    ..=get_y(bottom_right!(self.display_messages_area))
                {
                    (self.screen.draw_horizontal_segment_fn)(
                        &mut self.screen.overlay_grid,
                        self.screen.stdout.as_mut().unwrap(),
                        get_x(upper_left!(self.display_messages_area)),
                        get_x(bottom_right!(self.display_messages_area)),
                        y,
                    );
                }
            }
            self.display_messages_dirty = false;
        } else if self.display_messages_dirty {
            /* Clear area previously occupied by floating notification box */
            let displ_area = self.display_messages_area;
            for y in get_y(upper_left!(displ_area))..=get_y(bottom_right!(displ_area)) {
                (self.screen.draw_horizontal_segment_fn)(
                    &mut self.screen.grid,
                    self.screen.stdout.as_mut().unwrap(),
                    get_x(upper_left!(displ_area)),
                    get_x(bottom_right!(displ_area)),
                    y,
                );
            }
            self.display_messages_dirty = false;
        }
        if !self.overlay.is_empty() {
            let area = center_area(
                (
                    (0, 0),
                    (
                        self.screen.cols.saturating_sub(1),
                        self.screen.rows.saturating_sub(1),
                    ),
                ),
                (
                    if self.screen.cols / 3 > 30 {
                        self.screen.cols / 3
                    } else {
                        self.screen.cols
                    },
                    if self.screen.rows / 5 > 10 {
                        self.screen.rows / 5
                    } else {
                        self.screen.rows
                    },
                ),
            );
            copy_area(&mut self.screen.overlay_grid, &self.screen.grid, area, area);
            self.overlay.get_mut(0).unwrap().draw(
                &mut self.screen.overlay_grid,
                area,
                &mut self.context,
            );
            for y in get_y(upper_left!(area))..=get_y(bottom_right!(area)) {
                (self.screen.draw_horizontal_segment_fn)(
                    &mut self.screen.overlay_grid,
                    self.screen.stdout.as_mut().unwrap(),
                    get_x(upper_left!(area)),
                    get_x(bottom_right!(area)),
                    y,
                );
            }
        }
        self.flush();
    }

    /// Draw the entire screen from scratch.
    pub fn render(&mut self) {
        self.screen.update_size();
        let cols = self.screen.cols;
        let rows = self.screen.rows;
        self.context
            .dirty_areas
            .push_back(((0, 0), (cols - 1, rows - 1)));

        self.redraw();
    }

    pub fn draw_component(&mut self, idx: usize) {
        let component = &mut self.components[idx];
        let upper_left = (0, 0);
        let bottom_right = (self.screen.cols - 1, self.screen.rows - 1);

        if component.is_dirty() {
            component.draw(
                &mut self.screen.grid,
                (upper_left, bottom_right),
                &mut self.context,
            );
        }
    }

    pub fn can_quit_cleanly(&mut self) -> bool {
        let State {
            ref mut components,
            ref context,
            ..
        } = self;
        components.iter_mut().all(|c| c.can_quit_cleanly(context))
    }

    pub fn register_component(&mut self, component: Box<dyn Component>) {
        self.components.push(component);
    }

    /// Convert user commands to actions/method calls.
    fn exec_command(&mut self, cmd: Action) {
        match cmd {
            SetEnv(key, val) => {
                env::set_var(key.as_str(), val.as_str());
            }
            PrintEnv(key) => {
                self.context
                    .replies
                    .push_back(UIEvent::StatusEvent(StatusEvent::DisplayMessage(
                        env::var(key.as_str()).unwrap_or_else(|e| e.to_string()),
                    )));
            }
            Mailbox(account_name, op) => {
                if let Some(account) = self
                    .context
                    .accounts
                    .values_mut()
                    .find(|a| a.name() == account_name)
                {
                    if let Err(err) = account.mailbox_operation(op) {
                        self.context.replies.push_back(UIEvent::StatusEvent(
                            StatusEvent::DisplayMessage(err.to_string()),
                        ));
                    }
                } else {
                    self.context.replies.push_back(UIEvent::StatusEvent(
                        StatusEvent::DisplayMessage(format!(
                            "Account with name `{}` not found.",
                            account_name
                        )),
                    ));
                }
            }
            #[cfg(feature = "sqlite3")]
            AccountAction(ref account_name, ReIndex) => {
                let account_index = if let Some(a) = self
                    .context
                    .accounts
                    .iter()
                    .position(|(_, acc)| acc.name() == account_name)
                {
                    a
                } else {
                    self.context.replies.push_back(UIEvent::Notification(
                        None,
                        format!("Account {} was not found.", account_name),
                        Some(NotificationType::Error(ErrorKind::None)),
                    ));
                    return;
                };
                if *self.context.accounts[account_index]
                    .settings
                    .conf
                    .search_backend()
                    != crate::conf::SearchBackend::Sqlite3
                {
                    self.context.replies.push_back(UIEvent::Notification(
                        None,
                        format!(
                            "Account {} doesn't have an sqlite3 search backend.",
                            account_name
                        ),
                        Some(NotificationType::Error(ErrorKind::None)),
                    ));
                    return;
                }
                match crate::sqlite3::index(&mut self.context, account_index) {
                    Ok(job) => {
                        let handle = self.context.job_executor.spawn_blocking(job);
                        self.context.accounts[account_index].active_jobs.insert(
                            handle.job_id,
                            crate::conf::accounts::JobRequest::Generic {
                                name: "Message index rebuild".into(),
                                handle,
                                on_finish: None,
                                logging_level: melib::LoggingLevel::INFO,
                            },
                        );
                        self.context.replies.push_back(UIEvent::Notification(
                            None,
                            "Message index rebuild started.".to_string(),
                            Some(NotificationType::Info),
                        ));
                    }
                    Err(err) => {
                        self.context.replies.push_back(UIEvent::Notification(
                            Some("Message index rebuild failed".to_string()),
                            err.to_string(),
                            Some(NotificationType::Error(err.kind)),
                        ));
                    }
                }
            }
            #[cfg(not(feature = "sqlite3"))]
            AccountAction(ref account_name, ReIndex) => {
                self.context.replies.push_back(UIEvent::Notification(
                    None,
                    "Message index rebuild failed: meli is not built with sqlite3 support."
                        .to_string(),
                    Some(NotificationType::Error(ErrorKind::None)),
                ));
            }
            AccountAction(ref account_name, PrintAccountSetting(ref setting)) => {
                let path = setting.split('.').collect::<SmallVec<[&str; 16]>>();
                if let Some(pos) = self
                    .context
                    .accounts
                    .iter()
                    .position(|(_h, a)| a.name() == account_name)
                {
                    self.context.replies.push_back(UIEvent::StatusEvent(
                        StatusEvent::UpdateStatus(
                            self.context.accounts[pos]
                                .settings
                                .lookup("settings", &path)
                                .unwrap_or_else(|err| err.to_string()),
                        ),
                    ));
                } else {
                    self.context.replies.push_back(UIEvent::Notification(
                        None,
                        format!("Account {} was not found.", account_name),
                        Some(NotificationType::Error(ErrorKind::None)),
                    ));
                }
            }
            PrintSetting(ref setting) => {
                let path = setting.split('.').collect::<SmallVec<[&str; 16]>>();
                self.context
                    .replies
                    .push_back(UIEvent::StatusEvent(StatusEvent::UpdateStatus(
                        self.context
                            .settings
                            .lookup("settings", &path)
                            .unwrap_or_else(|err| err.to_string()),
                    )));
            }
            ToggleMouse => {
                self.screen.mouse = !self.screen.mouse;
                self.screen.set_mouse(self.screen.mouse);
                self.rcv_event(UIEvent::StatusEvent(StatusEvent::SetMouse(
                    self.screen.mouse,
                )));
            }
            Quit => {
                self.context
                    .sender
                    .send(ThreadEvent::Input((
                        self.context.settings.shortcuts.general.quit.clone(),
                        vec![],
                    )))
                    .unwrap();
            }
            v => {
                self.rcv_event(UIEvent::Action(v));
            }
        }
    }

    /// The application's main loop sends `UIEvents` to state via this method.
    pub fn rcv_event(&mut self, mut event: UIEvent) {
        if let UIEvent::Input(_) = event {
            if self.display_messages_expiration_start.is_none() {
                self.display_messages_expiration_start = Some(melib::datetime::now());
            }
        }

        match event {
            // Command type is handled only by State.
            UIEvent::Command(cmd) => {
                if let Ok(action) = parse_command(cmd.as_bytes()) {
                    if action.needs_confirmation() {
                        self.overlay.push(Box::new(UIConfirmationDialog::new(
                            "You sure?",
                            vec![(true, "yes".to_string()), (false, "no".to_string())],
                            true,
                            Some(Box::new(move |id: ComponentId, result: bool| {
                                Some(UIEvent::FinishedUIDialog(
                                    id,
                                    Box::new(if result { Some(action) } else { None }),
                                ))
                            })),
                            &self.context,
                        )));
                    } else if let Action::ReloadConfiguration = action {
                        match Settings::new().and_then(|new_settings| {
                            let old_accounts = self.context.settings.accounts.keys().collect::<std::collections::HashSet<&String>>();
                            let new_accounts = new_settings.accounts.keys().collect::<std::collections::HashSet<&String>>();
                            if old_accounts != new_accounts {
                                return Err("cannot reload account configuration changes; restart meli instead.".into());
                            }
                            for (key, acc) in new_settings.accounts.iter() {
                                if toml::Value::try_from(&acc) != toml::Value::try_from(&self.context.settings.accounts[key]) {
                                    return Err("cannot reload account configuration changes; restart meli instead.".into());
                                }
                            }
                            if toml::Value::try_from(&new_settings) == toml::Value::try_from(&self.context.settings) {
                                return Err("No changes detected.".into());
                            }
                            Ok(Box::new(new_settings))
                        }) {
                            Ok(new_settings) => {
                                let old_settings = std::mem::replace(&mut self.context.settings, new_settings);
                                self.context.replies.push_back(UIEvent::ConfigReload {
                                    old_settings
                                });
                                self.context.replies.push_back(UIEvent::Resize);
                            }
                            Err(err) => {
                                self.context.replies.push_back(UIEvent::StatusEvent(
                                        StatusEvent::DisplayMessage(format!(
                                                "Could not load configuration: {}",
                                                err
                                        )),
                                ));
                            }
                        }
                    } else {
                        self.exec_command(action);
                    }
                } else {
                    self.context.replies.push_back(UIEvent::StatusEvent(
                        StatusEvent::DisplayMessage("invalid command".to_string()),
                    ));
                }
                return;
            }
            UIEvent::Fork(ForkType::Finished) => {
                /*
                 * Fork has finished in the past.
                 * We're back in the AlternateScreen, but the cursor is reset to Shown, so fix
                 * it.
                write!(self.screen.stdout(), "{}", cursor::Hide,).unwrap();
                self.flush();
                 */
                self.screen.switch_to_main_screen();
                self.screen.switch_to_alternate_screen(&self.context);
                self.context.restore_input();
                return;
            }
            UIEvent::Fork(ForkType::Generic(child)) => {
                self.context.children.push(child);
                return;
            }
            UIEvent::Fork(child) => {
                self.mode = UIMode::Fork;
                self.child = Some(child);
                return;
            }
            UIEvent::BackendEvent(
                account_hash,
                BackendEvent::Notice {
                    ref description,
                    ref content,
                    level,
                },
            ) => {
                log(
                    format!(
                        "{}: {}{}{}",
                        self.context.accounts[&account_hash].name(),
                        description.as_str(),
                        if content.is_some() { ": " } else { "" },
                        content.as_ref().map(|s| s.as_str()).unwrap_or("")
                    ),
                    level,
                );
                self.rcv_event(UIEvent::StatusEvent(StatusEvent::DisplayMessage(
                    description.to_string(),
                )));
                return;
            }
            UIEvent::BackendEvent(account_hash, BackendEvent::AccountStateChange { message }) => {
                self.rcv_event(UIEvent::AccountStatusChange(account_hash, Some(message)));
                return;
            }
            UIEvent::BackendEvent(_, BackendEvent::Refresh(refresh_event)) => {
                self.refresh_event(refresh_event);
                return;
            }
            UIEvent::ChangeMode(m) => {
                self.context
                    .sender
                    .send(ThreadEvent::UIEvent(UIEvent::ChangeMode(m)))
                    .unwrap();
            }
            UIEvent::Timer(id) if id == self.draw_rate_limit.id() => {
                self.draw_rate_limit.reset();
                self.redraw();
                return;
            }
            UIEvent::Input(ref key)
                if *key
                    == self
                        .context
                        .settings
                        .shortcuts
                        .general
                        .info_message_previous =>
            {
                self.display_messages_expiration_start = Some(melib::datetime::now());
                self.display_messages_active = true;
                self.display_messages_initialised = false;
                self.display_messages_dirty = true;
                self.display_messages_pos = self.display_messages_pos.saturating_sub(1);
                return;
            }
            UIEvent::Input(ref key)
                if *key == self.context.settings.shortcuts.general.info_message_next =>
            {
                self.display_messages_expiration_start = Some(melib::datetime::now());
                self.display_messages_active = true;
                self.display_messages_initialised = false;
                self.display_messages_dirty = true;
                self.display_messages_pos = std::cmp::min(
                    self.display_messages.len().saturating_sub(1),
                    self.display_messages_pos + 1,
                );
                return;
            }
            UIEvent::StatusEvent(StatusEvent::DisplayMessage(ref msg)) => {
                self.display_messages.push(DisplayMessage {
                    timestamp: melib::datetime::now(),
                    msg: msg.clone(),
                });
                self.display_messages_active = true;
                self.display_messages_initialised = false;
                self.display_messages_dirty = true;
                self.display_messages_expiration_start = None;
                self.display_messages_pos = self.display_messages.len() - 1;
                self.redraw();
            }
            UIEvent::ComponentKill(ref id) if self.overlay.iter().any(|c| c.id() == *id) => {
                let pos = self.overlay.iter().position(|c| c.id() == *id).unwrap();
                self.overlay.remove(pos);
            }
            UIEvent::FinishedUIDialog(ref id, ref mut results)
                if self.overlay.iter().any(|c| c.id() == *id) =>
            {
                if let Some(ref mut action @ Some(_)) = results.downcast_mut::<Option<Action>>() {
                    self.exec_command(action.take().unwrap());

                    return;
                }
            }
            UIEvent::Callback(callback_fn) => {
                (callback_fn.0)(&mut self.context);
                return;
            }
            UIEvent::GlobalUIDialog(dialog) => {
                self.overlay.push(dialog);
                return;
            }
            _ => {}
        }
        let Self {
            ref mut components,
            ref mut context,
            ref mut overlay,
            ..
        } = self;

        /* inform each component */
        for c in overlay.iter_mut().chain(components.iter_mut()) {
            if c.process_event(&mut event, context) {
                break;
            }
        }

        if !self.context.replies.is_empty() {
            let replies: smallvec::SmallVec<[UIEvent; 8]> =
                self.context.replies.drain(0..).collect();
            // Pass replies to self and call count on the map iterator to force evaluation
            replies.into_iter().map(|r| self.rcv_event(r)).count();
        }
    }

    pub fn try_wait_on_child(&mut self) -> Option<bool> {
        let should_return_flag = match self.child {
            Some(ForkType::NewDraft(_, ref mut c)) => {
                let w = c.try_wait();
                match w {
                    Ok(Some(_)) => true,
                    Ok(None) => false,
                    Err(err) => {
                        log(format!("Failed to wait on editor process: {}", err), ERROR);
                        return None;
                    }
                }
            }
            Some(ForkType::Generic(ref mut c)) => {
                let w = c.try_wait();
                match w {
                    Ok(Some(_)) => true,
                    Ok(None) => false,
                    Err(err) => {
                        log(format!("Failed to wait on child process: {}", err), ERROR);
                        return None;
                    }
                }
            }
            Some(ForkType::Finished) => {
                /* Fork has already finished */
                self.child = None;
                return None;
            }
            _ => {
                return None;
            }
        };
        if should_return_flag {
            return Some(true);
        }
        Some(false)
    }
    /// Switch back to the terminal's main screen (The command line the user sees before opening
    /// the application)
    pub fn switch_to_main_screen(&mut self) {
        self.screen.switch_to_main_screen();
    }

    pub fn switch_to_alternate_screen(&mut self) {
        self.screen.switch_to_alternate_screen(&self.context);
    }

    fn flush(&mut self) {
        self.screen.flush();
    }

    pub fn check_accounts(&mut self) {
        let mut ctr = 0;
        for i in 0..self.context.accounts.len() {
            if self.context.is_online_idx(i).is_ok() {
                ctr += 1;
            }
        }
        if ctr != self.context.accounts.len() {
            self.timer.thread().unpark();
        }
        self.context.input_thread.check();
    }
}