iamb 0.0.12-alpha.1

A Matrix chat client that uses Vim keybindings
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
//! # iamb
//!
//! The iamb client loops over user input and commands, and turns them into actions, [some of
//! which][IambAction] are specific to iamb, and [some of which][Action] come from [modalkit]. When
//! adding new functionality, you will usually want to extend [IambAction] or one of its variants
//! (like [RoomAction][base::RoomAction]), and then add an appropriate [command][commands] or
//! [keybinding][keybindings].
//!
//! For more complicated changes, you may need to update [the async worker thread][worker], which
//! handles background Matrix tasks with [matrix-rust-sdk][matrix_sdk].
//!
//! Most rendering logic lives under the [windows] module, but [Matrix messages][message] have
//! their own module.
#![recursion_limit = "256"]
#![allow(clippy::manual_range_contains)]
#![allow(clippy::needless_return)]
#![allow(clippy::result_large_err)]
#![allow(clippy::bool_assert_comparison)]
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::fmt::Display;
use std::fs::{File, create_dir_all};
use std::io::{BufWriter, Stdout, Write, stdout};
use std::ops::DerefMut;
use std::process;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use clap::{CommandFactory, Parser};
use matrix_sdk::ruma::OwnedUserId;
use matrix_sdk::ruma::api::error::ErrorKind;
use matrix_sdk_crypto::encrypt_room_key_export;
use modalkit::keybindings::InputBindings;
use rand::RngExt as _;
use rand::distr::Alphanumeric;
use temp_dir::TempDir;
use tokio::sync::Mutex as AsyncMutex;
use tracing::Level;
use tracing_subscriber::{EnvFilter, FmtSubscriber};

use modalkit::crossterm::{
    self,
    cursor::{SetCursorStyle, Show as CursorShow},
    event::{
        DisableBracketedPaste,
        DisableFocusChange,
        DisableMouseCapture,
        EnableBracketedPaste,
        EnableFocusChange,
        EnableMouseCapture,
        Event,
        KeyEventKind,
        KeyboardEnhancementFlags,
        MouseEventKind,
        PopKeyboardEnhancementFlags,
        PushKeyboardEnhancementFlags,
        poll,
        read,
    },
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
};

use ratatui::{
    Terminal,
    backend::CrosstermBackend,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::Span,
    widgets::Paragraph,
};

mod base;
mod commands;
mod config;
mod keybindings;
mod message;
mod notifications;
mod preview;
mod sled_export;
mod util;
mod windows;
mod worker;

#[cfg(test)]
mod tests;

use crate::{
    base::{
        AsyncProgramStore,
        ChatStore,
        HomeserverAction,
        IambAction,
        IambCompleter,
        IambError,
        IambId,
        IambInfo,
        IambResult,
        KeysAction,
        ProgramAction,
        ProgramContext,
        ProgramStore,
    },
    config::{ApplicationSettings, Iamb},
    windows::IambWindow,
    worker::{ClientWorker, LoginStyle, Requester, create_room},
};

use modalkit::{
    actions::{
        Action,
        Commandable,
        Editable,
        EditorAction,
        InsertTextAction,
        Jumpable,
        Promptable,
        Scrollable,
        TabAction,
        TabContainer,
        TabCount,
        WindowAction,
        WindowContainer,
    },
    editing::{context::Resolve, key::KeyManager, store::Store},
    errors::{EditError, UIError},
    key::TerminalKey,
    keybindings::{
        BindingMachine,
        dialog::{Pager, PromptYesNo},
    },
    prelude::*,
    ui::FocusList,
};

use modalkit_ratatui::{
    TerminalCursor,
    TerminalExtOps,
    Window,
    cmdbar::CommandBarState,
    screen::{Screen, ScreenState, TabbedLayoutDescription},
    windows::{WindowLayoutDescription, WindowLayoutState},
};

fn config_tab_to_desc(
    layout: config::WindowLayout,
    store: &mut ProgramStore,
) -> IambResult<WindowLayoutDescription<IambInfo>> {
    let desc = match layout {
        config::WindowLayout::Window { window } => {
            let ChatStore { names, worker, .. } = &mut store.application;

            let window = match window {
                config::WindowPath::UserId(user_id) => {
                    let name = user_id.to_string();
                    let room_id = worker.join_room(name.clone())?;
                    names.insert(name, room_id.clone());
                    IambId::Room(room_id, None)
                },
                config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None),
                config::WindowPath::AliasId(alias) => {
                    let name = alias.to_string();
                    let room_id = worker.join_room(name.clone())?;
                    names.insert(name, room_id.clone());
                    IambId::Room(room_id, None)
                },
                config::WindowPath::Window(id) => id,
            };

            WindowLayoutDescription::Window { window, length: None }
        },
        config::WindowLayout::Split { split } => {
            let children = split
                .into_iter()
                .map(|child| config_tab_to_desc(child, store))
                .collect::<IambResult<Vec<_>>>()?;

            WindowLayoutDescription::Split { children, length: None }
        },
    };

    Ok(desc)
}

fn restore_layout(
    area: Rect,
    settings: &ApplicationSettings,
    store: &mut ProgramStore,
) -> IambResult<FocusList<WindowLayoutState<IambWindow, IambInfo>>> {
    let layout = std::fs::read(&settings.layout_json)?;
    let tabs: TabbedLayoutDescription<IambInfo> =
        serde_json::from_slice(&layout).map_err(IambError::from)?;
    tabs.to_layout(area.into(), store)
}

fn setup_screen(
    settings: ApplicationSettings,
    store: &mut ProgramStore,
) -> IambResult<ScreenState<IambWindow, IambInfo>> {
    let cmd = CommandBarState::new(store);
    let dims = crossterm::terminal::size()?;
    let area = Rect::new(0, 0, dims.0, dims.1);

    match settings.layout {
        config::Layout::Restore => {
            match restore_layout(area, &settings, store) {
                Ok(tabs) => {
                    return Ok(ScreenState::from_list(tabs, cmd));
                },
                Err(e) => {
                    // Log the issue with restoring and then continue.
                    tracing::warn!(err = %e, "Failed to restore layout from disk");
                },
            }
        },
        config::Layout::New => {},
        config::Layout::Config { tabs } => {
            let mut list = FocusList::default();

            for tab in tabs.into_iter() {
                let tab = config_tab_to_desc(tab, store)?;
                let tab = tab.to_layout(area.into(), store)?;
                list.push(tab);
            }

            return Ok(ScreenState::from_list(list, cmd));
        },
    }

    let win = settings
        .tunables
        .default_room
        .and_then(|room| IambWindow::find(room, store).ok())
        .or_else(|| IambWindow::open(IambId::Welcome, store).ok())
        .unwrap();

    return Ok(ScreenState::new(win, cmd));
}

/// The main application state and event loop.
struct Application {
    /// Terminal backend.
    terminal: Terminal<CrosstermBackend<Stdout>>,

    /// State for the Matrix client, editing, etc.
    store: AsyncProgramStore,

    /// UI state (open tabs, command bar, etc.) to use when rendering.
    screen: ScreenState<IambWindow, IambInfo>,

    /// Handle to communicate synchronously with the Matrix worker task.
    worker: Requester,

    /// Mapped keybindings.
    bindings: KeyManager<TerminalKey, ProgramAction, RepeatType>,

    /// Pending actions to run.
    actstack: VecDeque<(ProgramAction, ProgramContext)>,

    /// Whether or not the terminal is currently focused.
    focused: bool,

    /// The tab layout before the last executed [TabAction].
    last_layout: Option<TabbedLayoutDescription<IambInfo>>,

    /// Whether we need to do a full redraw (e.g., after running a subprocess).
    dirty: bool,
}

impl Application {
    pub async fn new(
        settings: ApplicationSettings,
        store: AsyncProgramStore,
    ) -> IambResult<Application> {
        let backend = CrosstermBackend::new(stdout());
        let terminal = Terminal::new(backend)?;

        let mut bindings = crate::keybindings::setup_keybindings();
        settings.setup(&mut bindings);
        let bindings = KeyManager::new(bindings);

        let mut locked = store.lock().await;
        let screen = setup_screen(settings, locked.deref_mut())?;

        let worker = locked.application.worker.clone();

        drop(locked);

        let actstack = VecDeque::new();

        Ok(Application {
            store,
            worker,
            terminal,
            bindings,
            actstack,
            screen,
            focused: true,
            last_layout: None,
            dirty: true,
        })
    }

    fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
        let bindings = &mut self.bindings;
        let focused = self.focused;
        let sstate = &mut self.screen;
        let term = &mut self.terminal;

        if store.application.ring_bell {
            store.application.ring_bell = term.backend_mut().write_all(&[7]).is_err();
        }

        if full {
            term.clear()?;
        }

        term.draw(|f| {
            let area = f.area();

            let modestr = bindings.show_mode();
            let cursor = bindings.get_cursor_indicator();
            let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);

            // Don't show terminal cursor when we show a dialog.
            let hide_cursor = !dialogstr.is_empty();

            store.application.draw_curr = Some(Instant::now());
            let screen = Screen::new(store)
                .show_dialog(dialogstr)
                .show_mode(modestr)
                .borders(true)
                .border_style(Style::default().add_modifier(Modifier::DIM))
                .tab_style(Style::default().add_modifier(Modifier::DIM))
                .tab_style_focused(Style::default().remove_modifier(Modifier::DIM))
                .focus(focused);
            f.render_stateful_widget(screen, area, sstate);

            if hide_cursor {
                return;
            }

            if let Some((cx, cy)) = sstate.get_term_cursor() {
                if let Some(c) = cursor {
                    let style = Style::default().fg(Color::Green);
                    let span = Span::styled(c.to_string(), style);
                    let para = Paragraph::new(span);
                    let inner = Rect::new(cx, cy, 1, 1);
                    f.render_widget(para, inner)
                }
                f.set_cursor_position((cx, cy));
            }
        })?;

        Ok(())
    }

    async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
        loop {
            self.redraw(self.dirty, self.store.clone().lock().await.deref_mut())?;
            self.dirty = false;

            if !poll(Duration::from_secs(1))? {
                // Redraw in case there's new messages to show.
                continue;
            }

            match read()? {
                Event::Key(ke) => {
                    if ke.kind == KeyEventKind::Release {
                        continue;
                    }

                    return Ok(ke.into());
                },
                Event::Mouse(me) => {
                    let dir = match me.kind {
                        MouseEventKind::ScrollUp => MoveDir2D::Up,
                        MouseEventKind::ScrollDown => MoveDir2D::Down,
                        MouseEventKind::ScrollLeft => MoveDir2D::Left,
                        MouseEventKind::ScrollRight => MoveDir2D::Right,
                        _ => continue,
                    };

                    let size = ScrollSize::Cell;
                    let style = ScrollStyle::Direction2D(dir, size, 1.into());
                    let ctx = ProgramContext::default();
                    let mut store = self.store.lock().await;

                    match self.screen.scroll(&style, &ctx, store.deref_mut()) {
                        Ok(None) => {},
                        Ok(Some(info)) => {
                            drop(store);
                            self.handle_info(info);
                        },
                        Err(e) => {
                            self.screen.push_error(e);
                        },
                    }
                },
                Event::FocusGained => {
                    let mut store = self.store.lock().await;
                    store.application.focused = true;
                    self.focused = true;
                },
                Event::FocusLost => {
                    let mut store = self.store.lock().await;
                    store.application.focused = false;
                    self.focused = false;
                },
                Event::Resize(_, _) => {
                    // We'll redraw for the new size next time step() is called.
                },
                Event::Paste(s) => {
                    let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
                    let act = EditorAction::from(act);
                    let ctx = ProgramContext::default();
                    let mut store = self.store.lock().await;

                    match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
                        Ok(None) => {},
                        Ok(Some(info)) => {
                            drop(store);
                            self.handle_info(info);
                        },
                        Err(e) => {
                            self.screen.push_error(e);
                        },
                    }
                },
            }
        }
    }

    fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
        let mut acts = VecDeque::from(acts);
        acts.append(&mut self.actstack);
        self.actstack = acts;
    }

    fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
        if let res @ Some(_) = self.actstack.pop_front() {
            return res;
        }

        if keyskip {
            return None;
        } else {
            return self.bindings.pop();
        }
    }

    async fn action_run(
        &mut self,
        action: ProgramAction,
        ctx: ProgramContext,
        store: &mut ProgramStore,
    ) -> IambResult<EditInfo> {
        let info = match action {
            // Do nothing.
            Action::NoOp => None,

            Action::Editor(act) => {
                match self.screen.editor_command(&act, &ctx, store) {
                    Ok(info) => info,
                    Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
                        // Switch to the right window.
                        if let Some(winid) = content.to_window() {
                            let open = OpenTarget::Application(winid);
                            let open = WindowAction::Switch(open);
                            let _ = self.screen.window_command(&open, &ctx, store)?;

                            // Run command again.
                            self.screen.editor_command(&act, &ctx, store)?
                        } else {
                            return Err(EditError::WrongBuffer(content).into());
                        }
                    },
                    Err(err) => return Err(err.into()),
                }
            },

            // Simple delegations.
            Action::Application(act) => self.iamb_run(act, ctx, store).await?,
            Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
            Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
            Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
            Action::ShowInfoMessage(info) => Some(info),
            Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,

            Action::Jump(l, dir, count) => {
                let count = ctx.resolve(&count);
                let _ = self.screen.jump(l, dir, count, &ctx)?;

                None
            },
            Action::Suspend => {
                self.terminal.program_suspend()?;

                None
            },

            // UI actions.
            Action::Tab(cmd) => {
                if let TabAction::Close(_, _) = &cmd {
                    self.last_layout = self.screen.as_description().into();
                }

                self.screen.tab_command(&cmd, &ctx, store)?
            },
            Action::RedrawScreen => {
                self.screen.clear_message();
                self.redraw(true, store)?;

                None
            },

            // Actions that create more Actions.
            Action::Prompt(act) => {
                let acts = self.screen.prompt(&act, &ctx, store)?;
                self.action_prepend(acts);

                None
            },
            Action::Command(act) => {
                let acts = store.application.cmds.command(&act, &ctx, &mut store.registers)?;
                self.action_prepend(acts);

                None
            },
            Action::Repeat(rt) => {
                self.bindings.repeat(rt, Some(ctx));

                None
            },

            // Unimplemented.
            Action::KeywordLookup(_) => {
                // XXX: implement
                None
            },

            _ => {
                // XXX: log unhandled actions? print message?
                None
            },
        };

        return Ok(info);
    }

    async fn iamb_run(
        &mut self,
        action: IambAction,
        ctx: ProgramContext,
        store: &mut ProgramStore,
    ) -> IambResult<EditInfo> {
        if action.scribbles() {
            self.dirty = true;
        }

        let info = match action {
            IambAction::ClearUnreads => {
                let user_id = &store.application.settings.profile.user_id;

                // Clear any notifications we displayed:
                store.application.open_notifications.clear();

                for room_id in store.application.sync_info.chats() {
                    if let Some(room) = store.application.rooms.get_mut(room_id) {
                        room.fully_read_all(user_id);
                    }
                }

                None
            },

            IambAction::ToggleScrollbackFocus => {
                self.screen.current_window_mut()?.focus_toggle();

                None
            },

            IambAction::Homeserver(act) => {
                let acts = self.homeserver_command(act, ctx, store).await?;
                self.action_prepend(acts);

                None
            },
            IambAction::Keys(act) => self.keys_command(act, ctx, store).await?,
            IambAction::Message(act) => {
                self.screen.current_window_mut()?.message_command(act, ctx, store).await?
            },
            IambAction::Space(act) => {
                self.screen.current_window_mut()?.space_command(act, ctx, store).await?
            },
            IambAction::Room(act) => {
                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
                self.action_prepend(acts);

                None
            },
            IambAction::Send(act) => {
                if store.application.settings.tunables.normal_after_send {
                    self.bindings.reset_mode();
                }
                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
            },

            IambAction::OpenLink(url) => {
                tokio::task::spawn_blocking(move || {
                    return open::that(url);
                });

                None
            },

            IambAction::Verify(act, user_dev) => {
                if let Some(sas) = store.application.verifications.get(&user_dev) {
                    self.worker.verify(act, sas.clone())?
                } else {
                    return Err(IambError::InvalidVerificationId(user_dev).into());
                }
            },
            IambAction::VerifyRequest(user_id) => {
                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
                    self.worker.verify_request(user_id)?
                } else {
                    return Err(IambError::InvalidUserId(user_id).into());
                }
            },
        };

        Ok(info)
    }

    async fn homeserver_command(
        &mut self,
        action: HomeserverAction,
        ctx: ProgramContext,
        store: &mut ProgramStore,
    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
        match action {
            HomeserverAction::CreateRoom(alias, vis, flags) => {
                let client = &store.application.worker.client;
                let room_id = create_room(client, alias, vis, flags).await?;
                let room = IambId::Room(room_id, None);
                let target = OpenTarget::Application(room);
                let action = WindowAction::Switch(target);

                Ok(vec![(action.into(), ctx)])
            },
            HomeserverAction::Logout(user, true) => {
                self.worker.logout(user)?;
                let flags = CloseFlags::QUIT | CloseFlags::FORCE;
                let act = TabAction::Close(TabTarget::All, flags);

                Ok(vec![(act.into(), ctx)])
            },
            HomeserverAction::Logout(user, false) => {
                let msg = "Would you like to logout?";
                let act = IambAction::from(HomeserverAction::Logout(user, true));
                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
                let prompt = Box::new(prompt);

                Err(UIError::NeedConfirm(prompt))
            },
            HomeserverAction::Forget => {
                let client = &store.application.worker.client;
                for room in client.left_rooms() {
                    room.forget().await.map_err(IambError::from)?;
                }
                Ok(vec![])
            },
        }
    }

    async fn keys_command(
        &mut self,
        action: KeysAction,
        _: ProgramContext,
        store: &mut ProgramStore,
    ) -> IambResult<EditInfo> {
        let encryption = store.application.worker.client.encryption();

        match action {
            KeysAction::Export(path, passphrase) => {
                encryption
                    .export_room_keys(path.into(), &passphrase, |_| true)
                    .await
                    .map_err(IambError::from)?;

                Ok(Some("Successfully exported room keys".into()))
            },
            KeysAction::Import(path, passphrase) => {
                let res = encryption
                    .import_room_keys(path.into(), &passphrase)
                    .await
                    .map_err(IambError::from)?;

                let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count);

                Ok(Some(msg.into()))
            },
        }
    }

    fn handle_info(&mut self, info: InfoMessage) {
        match info {
            InfoMessage::Message(info) => {
                self.screen.push_info(info);
            },
            InfoMessage::Pager(text) => {
                let pager = Box::new(Pager::new(text, vec![]));
                self.bindings.run_dialog(pager);
            },
        }
    }

    pub async fn run(&mut self) -> Result<(), std::io::Error> {
        self.terminal.clear()?;

        let store = self.store.clone();

        while self.screen.tabs() != 0 {
            let key = self.step().await?;

            self.bindings.input_key(key);

            let mut locked = store.lock().await;
            let mut keyskip = false;

            while let Some((action, ctx)) = self.action_pop(keyskip) {
                match self.action_run(action, ctx, locked.deref_mut()).await {
                    Ok(None) => {
                        // Continue processing.
                        continue;
                    },
                    Ok(Some(info)) => {
                        self.handle_info(info);

                        // Continue processing; we'll redraw later.
                        continue;
                    },
                    Err(
                        UIError::NeedConfirm(dialog) |
                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
                    ) => {
                        self.bindings.run_dialog(dialog);
                        continue;
                    },
                    Err(e) => {
                        self.screen.push_error(e);

                        // Skip processing any more keypress Actions until the next key.
                        keyskip = true;
                        continue;
                    },
                }
            }
        }

        if let Some(ref layout) = self.last_layout {
            let locked = self.store.lock().await;
            let path = locked.application.settings.layout_json.as_path();
            path.parent().map(create_dir_all).transpose()?;

            let file = File::create(path)?;
            let writer = BufWriter::new(file);

            if let Err(e) = serde_json::to_writer(writer, layout) {
                tracing::error!("Failed to save window layout while exiting: {}", e);
            }
        }

        crossterm::terminal::disable_raw_mode()?;
        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
        self.terminal.show_cursor()?;

        return Ok(());
    }
}

fn gen_passphrase() -> String {
    rand::rng().sample_iter(&Alphanumeric).take(20).map(char::from).collect()
}

fn read_response(question: &str) -> String {
    println!("{question}");
    let mut input = String::new();
    let _ = std::io::stdin().read_line(&mut input);
    input
}

fn read_yesno(question: &str) -> Option<char> {
    read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
}

async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
    if settings.session_json.is_file() {
        let session = settings.read_session(&settings.session_json)?;
        worker.login(LoginStyle::SessionRestore(session.into()))?;

        return Ok(());
    }

    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
        let session = settings.read_session(&settings.session_json_old)?;
        worker.login(LoginStyle::SessionRestore(session.into()))?;

        return Ok(());
    }

    if let Some(ref password_file) = settings.profile.password_file {
        if let Err(e) = std::fs::read_to_string(password_file)
            .map(|password| worker.login(LoginStyle::Password(password)))
        {
            println!("Failed to log in using password file {password_file:?}: {e}");
            println!("Continuing on to interactive login");
        } else {
            return Ok(());
        }
    }

    loop {
        let login_style =
            match read_response("Please select login type: [p]assword / [s]ingle sign on")
                .chars()
                .next()
                .map(|c| c.to_ascii_lowercase())
            {
                None | Some('p') => {
                    let password = rpassword::prompt_password("Password: ")?;
                    LoginStyle::Password(password)
                },
                Some('s') => LoginStyle::SingleSignOn,
                Some(_) => {
                    println!("Failed to login. Please enter 'p' or 's'");
                    continue;
                },
            };

        match worker.login(login_style) {
            Ok(info) => {
                if let Some(msg) = info {
                    println!("{msg}");
                }

                break;
            },
            Err(err) => {
                println!("Failed to login: {err}");
                continue;
            },
        }
    }

    Ok(())
}

fn print_exit<T: Display, N>(v: T) -> N {
    eprintln!("{v}");
    process::exit(2);
}

// We can't access the OlmMachine directly, so write the keys to a temporary
// file first, and then import them later.
async fn check_import_keys(
    settings: &ApplicationSettings,
) -> IambResult<Option<(temp_dir::TempDir, String)>> {
    let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();

    if !do_import {
        return Ok(None);
    }

    let question = format!(
        "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
        settings.sled_dir.display()
    );

    loop {
        match read_yesno(&question) {
            Some('y') => {
                break;
            },
            Some('n') => {
                return Ok(None);
            },
            Some(_) | None => {
                continue;
            },
        }
    }

    let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
    let passphrase = gen_passphrase();

    println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());

    let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
        Ok(encrypted) => encrypted,
        Err(e) => {
            eprintln!("* Failed to encrypt room keys during export: {e}");
            process::exit(2);
        },
    };

    let tmpdir = TempDir::new()?;
    let exported = tmpdir.child("keys");

    println!("* Writing encrypted room keys to {}...", exported.display());
    tokio::fs::write(&exported, &encrypted).await?;

    Ok(Some((tmpdir, passphrase)))
}

async fn login_upgrade(
    keydir: TempDir,
    passphrase: String,
    worker: &Requester,
    settings: &ApplicationSettings,
    store: &AsyncProgramStore,
) -> IambResult<()> {
    println!(
        "Please log in for {} to import the room keys into a new session",
        settings.profile.user_id
    );

    login(worker, settings).await?;

    println!("* Importing room keys...");

    let exported = keydir.child("keys");
    let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;

    match imported {
        Ok(res) => {
            println!(
                "* Successfully imported {} out of {} keys",
                res.imported_count, res.total_count
            );
            let _ = keydir.cleanup();
        },
        Err(e) => {
            println!(
                "Failed to import room keys from {}/keys: {e}\n\n\
                They have been encrypted with the passphrase {passphrase:?}.\
                Please save them and try importing them manually instead\n",
                keydir.path().display()
            );

            loop {
                match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
                    Some('y') => break,
                    Some('n') => print_exit("* Exiting..."),
                    Some(_) | None => continue,
                }
            }
        },
    }

    println!("* Syncing...");
    worker::do_first_sync(&worker.client, store)
        .await
        .map_err(IambError::from)?;

    Ok(())
}

async fn login_normal(
    worker: &Requester,
    settings: &ApplicationSettings,
    store: &AsyncProgramStore,
) -> IambResult<()> {
    println!("* Logging in for {}...", settings.profile.user_id);
    login(worker, settings).await?;
    println!("* Syncing...");
    worker::do_first_sync(&worker.client, store)
        .await
        .map_err(IambError::from)?;
    Ok(())
}

/// Set up the terminal for drawing the TUI, and getting additional info.
fn setup_tty(settings: &ApplicationSettings, enable_enhanced_keys: bool) -> std::io::Result<()> {
    // Enable raw mode and enter the alternate screen.
    crossterm::terminal::enable_raw_mode()?;
    crossterm::execute!(stdout(), EnterAlternateScreen)?;

    if enable_enhanced_keys {
        // Enable the Kitty keyboard enhancement protocol for improved keypresses.
        crossterm::queue!(
            stdout(),
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        )?;
    }

    if settings.tunables.mouse.enabled {
        crossterm::execute!(stdout(), EnableMouseCapture)?;
    }

    if settings.tunables.terminal.enable_title {
        let title = format!("iamb ({})", settings.profile.user_id.as_str());
        crossterm::execute!(stdout(), SetTitle(title))?;
    }

    let cursor_shape = SetCursorStyle::from(settings.tunables.terminal.cursor_shape);

    crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, cursor_shape)
}

// Do our best to reverse what we did in setup_tty() when we exit or crash.
fn restore_tty(enable_enhanced_keys: bool, enable_mouse: bool) {
    if enable_enhanced_keys {
        let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
    }

    if enable_mouse {
        let _ = crossterm::queue!(stdout(), DisableMouseCapture);
    }

    let _ = crossterm::execute!(
        stdout(),
        DisableBracketedPaste,
        DisableFocusChange,
        SetCursorStyle::DefaultUserShape,
        LeaveAlternateScreen,
        CursorShow,
    );

    let _ = crossterm::terminal::disable_raw_mode();
}

async fn run(settings: ApplicationSettings) -> IambResult<()> {
    // Get old keys the first time we run w/ the upgraded SDK.
    let import_keys = check_import_keys(&settings).await?;

    // Set up client state.
    create_dir_all(settings.sqlite_dir.as_path())?;
    let client = worker::create_client(&settings).await;

    // Set up the async worker thread and global store.
    let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
    let store = ChatStore::new(worker.clone(), settings.clone());
    let mut store = Store::new(store);
    store.completer = Box::new(IambCompleter);

    let store = Arc::new(AsyncMutex::new(store));
    worker.init(store.clone());

    let res = if let Some((keydir, pass)) = import_keys {
        login_upgrade(keydir, pass, &worker, &settings, &store).await
    } else {
        login_normal(&worker, &settings, &store).await
    };

    match res {
        Err(UIError::Application(IambError::Matrix(e))) => {
            if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
                print_exit(format!(
                    "Server did not recognize our API token; did you log out from this session elsewhere?\nTry deleting `{}` to force a clean login.",
                    settings.session_json.display()
                ))
            } else {
                print_exit(e)
            }
        },
        Err(e) => print_exit(e),
        Ok(()) => (),
    }

    // Set up the terminal for drawing, and cleanup properly on panics.
    let enable_enhanced_keys =
        settings.tunables.terminal.enable_extended_keys.unwrap_or_else(|| {
            crossterm::terminal::supports_keyboard_enhancement()
                .inspect_err(|e| tracing::warn!(
                        err = %e,
                       "Failed to determine whether the terminal supports keyboard enhancements"
               ))
                .unwrap_or_default()
        });
    setup_tty(&settings, enable_enhanced_keys)?;

    let orig_hook = std::panic::take_hook();
    let enable_mouse = settings.tunables.mouse.enabled;
    std::panic::set_hook(Box::new(move |panic_info| {
        restore_tty(enable_enhanced_keys, enable_mouse);
        orig_hook(panic_info);
        process::exit(1);
    }));

    // And finally, start running the terminal UI.
    let mut application = Application::new(settings, store).await?;
    application.run().await?;

    // Clean up the terminal on exit.
    restore_tty(enable_enhanced_keys, enable_mouse);

    Ok(())
}

fn setup_logging(settings: &ApplicationSettings) -> tracing_appender::non_blocking::WorkerGuard {
    let log_prefix = format!("iamb-log-{}", settings.profile_name);
    let log_dir = settings.dirs.logs.as_path();
    let max_log_files = settings.tunables.max_log_files;
    let log_level = &settings.tunables.log_level;

    let appender = tracing_appender::rolling::Builder::new()
        .rotation(tracing_appender::rolling::Rotation::DAILY)
        .filename_prefix(log_prefix)
        .max_log_files(max_log_files)
        .build(log_dir)
        .expect("can build appending tracing logger");
    let (appender, guard) = tracing_appender::non_blocking(appender);

    let filter = if let Ok(dirs) = std::env::var(EnvFilter::DEFAULT_ENV) {
        EnvFilter::builder()
            .with_default_directive(Level::WARN.into())
            .parse(dirs)
            .map_err(|err| format!("Unable to parse {}: {err}", EnvFilter::DEFAULT_ENV))
            .unwrap_or_else(print_exit)
    } else {
        EnvFilter::builder()
            .with_default_directive(Level::WARN.into())
            .parse(log_level)
            .map_err(|err| format!("Unable to parse `log_level`: {err}"))
            .unwrap_or_else(print_exit)
    };

    let subscriber = FmtSubscriber::builder()
        .with_writer(appender)
        .with_env_filter(filter)
        .finish();

    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");

    guard
}

fn main() {
    // Parse command-line flags.
    let iamb = Iamb::parse();

    if let Some(shell) = iamb.completions {
        clap_complete::generate(shell, &mut Iamb::command(), "iamb", &mut std::io::stdout());
        return;
    }

    // Load configuration and set up the Matrix SDK.
    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);

    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
    #[cfg(unix)]
    unsafe {
        libc::umask(0o077);
    };

    let guard = setup_logging(&settings);

    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .worker_threads(2)
        .thread_name_fn(|| {
            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
            format!("iamb-worker-{id}")
        })
        .build()
        .unwrap();

    if let Err(err) = rt.block_on(async move { run(settings).await }) {
        eprintln!("\n{err}\n");
        process::exit(2);
    }

    drop(guard);
}