src/main.rs

944 lines · 29709 bytes

  1//! # iamb
  2//!
  3//! The iamb client loops over user input and commands, and turns them into actions, [some of
  4//! which][IambAction] are specific to iamb, and [some of which][Action] come from [modalkit]. When
  5//! adding new functionality, you will usually want to extend [IambAction] or one of its variants
  6//! (like [RoomAction][base::RoomAction]), and then add an appropriate [command][commands] or
  7//! [keybinding][keybindings].
  8//!
  9//! For more complicated changes, you may need to update [the async worker thread][worker], which
 10//! handles background Matrix tasks with [matrix-rust-sdk][matrix_sdk].
 11//!
 12//! Most rendering logic lives under the [windows] module, but [Matrix messages][message] have
 13//! their own module.
 14#![allow(clippy::manual_range_contains)]
 15#![allow(clippy::needless_return)]
 16#![allow(clippy::result_large_err)]
 17#![allow(clippy::bool_assert_comparison)]
 18use std::collections::VecDeque;
 19use std::convert::TryFrom;
 20use std::fmt::Display;
 21use std::fs::{create_dir_all, File};
 22use std::io::{stdout, BufWriter, Stdout};
 23use std::ops::DerefMut;
 24use std::process;
 25use std::sync::atomic::{AtomicUsize, Ordering};
 26use std::sync::Arc;
 27use std::time::Duration;
 28
 29use clap::Parser;
 30use matrix_sdk::crypto::encrypt_room_key_export;
 31use matrix_sdk::ruma::OwnedUserId;
 32use rand::{distributions::Alphanumeric, Rng};
 33use temp_dir::TempDir;
 34use tokio::sync::Mutex as AsyncMutex;
 35use tracing_subscriber::FmtSubscriber;
 36
 37use modalkit::crossterm::{
 38    self,
 39    cursor::Show as CursorShow,
 40    event::{
 41        poll,
 42        read,
 43        DisableBracketedPaste,
 44        DisableFocusChange,
 45        EnableBracketedPaste,
 46        EnableFocusChange,
 47        Event,
 48    },
 49    execute,
 50    terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
 51};
 52
 53use ratatui::{
 54    backend::CrosstermBackend,
 55    layout::Rect,
 56    style::{Color, Style},
 57    text::Span,
 58    widgets::Paragraph,
 59    Terminal,
 60};
 61
 62mod base;
 63mod commands;
 64mod config;
 65mod keybindings;
 66mod message;
 67mod preview;
 68mod sled_export;
 69mod util;
 70mod windows;
 71mod worker;
 72
 73#[cfg(test)]
 74mod tests;
 75
 76use crate::{
 77    base::{
 78        AsyncProgramStore,
 79        ChatStore,
 80        HomeserverAction,
 81        IambAction,
 82        IambError,
 83        IambId,
 84        IambInfo,
 85        IambResult,
 86        ProgramAction,
 87        ProgramContext,
 88        ProgramStore,
 89    },
 90    config::{ApplicationSettings, Iamb},
 91    windows::IambWindow,
 92    worker::{create_room, ClientWorker, LoginStyle, Requester},
 93};
 94
 95use modalkit::{
 96    actions::{
 97        Action,
 98        Commandable,
 99        Editable,
100        EditorAction,
101        InsertTextAction,
102        Jumpable,
103        Promptable,
104        Scrollable,
105        TabAction,
106        TabContainer,
107        TabCount,
108        WindowAction,
109        WindowContainer,
110    },
111    editing::{context::Resolve, key::KeyManager, store::Store},
112    errors::{EditError, UIError},
113    key::TerminalKey,
114    keybindings::{
115        dialog::{Pager, PromptYesNo},
116        BindingMachine,
117    },
118    prelude::*,
119    ui::FocusList,
120};
121
122use modalkit_ratatui::{
123    cmdbar::CommandBarState,
124    screen::{Screen, ScreenState, TabLayoutDescription},
125    windows::WindowLayoutDescription,
126    TerminalCursor,
127    TerminalExtOps,
128    Window,
129};
130
131fn config_tab_to_desc(
132    layout: config::WindowLayout,
133    store: &mut ProgramStore,
134) -> IambResult<WindowLayoutDescription<IambInfo>> {
135    let desc = match layout {
136        config::WindowLayout::Window { window } => {
137            let ChatStore { names, worker, .. } = &mut store.application;
138
139            let window = match window {
140                config::WindowPath::UserId(user_id) => {
141                    let name = user_id.to_string();
142                    let room_id = worker.join_room(name.clone())?;
143                    names.insert(name, room_id.clone());
144                    IambId::Room(room_id, None)
145                },
146                config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None),
147                config::WindowPath::AliasId(alias) => {
148                    let name = alias.to_string();
149                    let room_id = worker.join_room(name.clone())?;
150                    names.insert(name, room_id.clone());
151                    IambId::Room(room_id, None)
152                },
153                config::WindowPath::Window(id) => id,
154            };
155
156            WindowLayoutDescription::Window { window, length: None }
157        },
158        config::WindowLayout::Split { split } => {
159            let children = split
160                .into_iter()
161                .map(|child| config_tab_to_desc(child, store))
162                .collect::<IambResult<Vec<_>>>()?;
163
164            WindowLayoutDescription::Split { children, length: None }
165        },
166    };
167
168    Ok(desc)
169}
170
171fn setup_screen(
172    settings: ApplicationSettings,
173    store: &mut ProgramStore,
174) -> IambResult<ScreenState<IambWindow, IambInfo>> {
175    let cmd = CommandBarState::new(store);
176    let dims = crossterm::terminal::size()?;
177    let area = Rect::new(0, 0, dims.0, dims.1);
178
179    match settings.layout {
180        config::Layout::Restore => {
181            if let Ok(layout) = std::fs::read(&settings.layout_json) {
182                let tabs: TabLayoutDescription<IambInfo> =
183                    serde_json::from_slice(&layout).map_err(IambError::from)?;
184                let tabs = tabs.to_layout(area.into(), store)?;
185
186                return Ok(ScreenState::from_list(tabs, cmd));
187            }
188        },
189        config::Layout::New => {},
190        config::Layout::Config { tabs } => {
191            let mut list = FocusList::default();
192
193            for tab in tabs.into_iter() {
194                let tab = config_tab_to_desc(tab, store)?;
195                let tab = tab.to_layout(area.into(), store)?;
196                list.push(tab);
197            }
198
199            return Ok(ScreenState::from_list(list, cmd));
200        },
201    }
202
203    let win = settings
204        .tunables
205        .default_room
206        .and_then(|room| IambWindow::find(room, store).ok())
207        .or_else(|| IambWindow::open(IambId::Welcome, store).ok())
208        .unwrap();
209
210    return Ok(ScreenState::new(win, cmd));
211}
212
213/// The main application state and event loop.
214struct Application {
215    /// Terminal backend.
216    terminal: Terminal<CrosstermBackend<Stdout>>,
217
218    /// State for the Matrix client, editing, etc.
219    store: AsyncProgramStore,
220
221    /// UI state (open tabs, command bar, etc.) to use when rendering.
222    screen: ScreenState<IambWindow, IambInfo>,
223
224    /// Handle to communicate synchronously with the Matrix worker task.
225    worker: Requester,
226
227    /// Mapped keybindings.
228    bindings: KeyManager<TerminalKey, ProgramAction, RepeatType>,
229
230    /// Pending actions to run.
231    actstack: VecDeque<(ProgramAction, ProgramContext)>,
232
233    /// Whether or not the terminal is currently focused.
234    focused: bool,
235
236    /// The tab layout before the last executed [TabAction].
237    last_layout: Option<TabLayoutDescription<IambInfo>>,
238
239    /// Whether we need to do a full redraw (e.g., after running a subprocess).
240    dirty: bool,
241}
242
243impl Application {
244    pub async fn new(
245        settings: ApplicationSettings,
246        store: AsyncProgramStore,
247    ) -> IambResult<Application> {
248        let mut stdout = stdout();
249        crossterm::terminal::enable_raw_mode()?;
250        crossterm::execute!(stdout, EnterAlternateScreen)?;
251        crossterm::execute!(stdout, EnableBracketedPaste)?;
252        crossterm::execute!(stdout, EnableFocusChange)?;
253
254        let title = format!("iamb ({})", settings.profile.user_id);
255        crossterm::execute!(stdout, SetTitle(title))?;
256
257        let backend = CrosstermBackend::new(stdout);
258        let terminal = Terminal::new(backend)?;
259
260        let bindings = crate::keybindings::setup_keybindings();
261        let bindings = KeyManager::new(bindings);
262
263        let mut locked = store.lock().await;
264        let screen = setup_screen(settings, locked.deref_mut())?;
265
266        let worker = locked.application.worker.clone();
267
268        drop(locked);
269
270        let actstack = VecDeque::new();
271
272        Ok(Application {
273            store,
274            worker,
275            terminal,
276            bindings,
277            actstack,
278            screen,
279            focused: true,
280            last_layout: None,
281            dirty: true,
282        })
283    }
284
285    fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
286        let bindings = &mut self.bindings;
287        let focused = self.focused;
288        let sstate = &mut self.screen;
289        let term = &mut self.terminal;
290
291        if full {
292            term.clear()?;
293        }
294
295        term.draw(|f| {
296            let area = f.size();
297
298            let modestr = bindings.show_mode();
299            let cursor = bindings.get_cursor_indicator();
300            let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);
301
302            // Don't show terminal cursor when we show a dialog.
303            let hide_cursor = !dialogstr.is_empty();
304
305            let screen = Screen::new(store)
306                .show_dialog(dialogstr)
307                .show_mode(modestr)
308                .borders(true)
309                .focus(focused);
310            f.render_stateful_widget(screen, area, sstate);
311
312            if hide_cursor {
313                return;
314            }
315
316            if let Some((cx, cy)) = sstate.get_term_cursor() {
317                if let Some(c) = cursor {
318                    let style = Style::default().fg(Color::Green);
319                    let span = Span::styled(c.to_string(), style);
320                    let para = Paragraph::new(span);
321                    let inner = Rect::new(cx, cy, 1, 1);
322                    f.render_widget(para, inner)
323                }
324                f.set_cursor(cx, cy);
325            }
326        })?;
327
328        Ok(())
329    }
330
331    async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
332        loop {
333            self.redraw(self.dirty, self.store.clone().lock().await.deref_mut())?;
334            self.dirty = false;
335
336            if !poll(Duration::from_secs(1))? {
337                // Redraw in case there's new messages to show.
338                continue;
339            }
340
341            match read()? {
342                Event::Key(ke) => return Ok(ke.into()),
343                Event::Mouse(_) => {
344                    // Do nothing for now.
345                },
346                Event::FocusGained => {
347                    self.focused = true;
348                },
349                Event::FocusLost => {
350                    self.focused = false;
351                },
352                Event::Resize(_, _) => {
353                    // We'll redraw for the new size next time step() is called.
354                },
355                Event::Paste(s) => {
356                    let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
357                    let act = EditorAction::from(act);
358                    let ctx = ProgramContext::default();
359                    let mut store = self.store.lock().await;
360
361                    match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
362                        Ok(None) => {},
363                        Ok(Some(info)) => {
364                            drop(store);
365                            self.handle_info(info);
366                        },
367                        Err(e) => {
368                            self.screen.push_error(e);
369                        },
370                    }
371                },
372            }
373        }
374    }
375
376    fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
377        let mut acts = VecDeque::from(acts);
378        acts.append(&mut self.actstack);
379        self.actstack = acts;
380    }
381
382    fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
383        if let res @ Some(_) = self.actstack.pop_front() {
384            return res;
385        }
386
387        if keyskip {
388            return None;
389        } else {
390            return self.bindings.pop();
391        }
392    }
393
394    async fn action_run(
395        &mut self,
396        action: ProgramAction,
397        ctx: ProgramContext,
398        store: &mut ProgramStore,
399    ) -> IambResult<EditInfo> {
400        let info = match action {
401            // Do nothing.
402            Action::NoOp => None,
403
404            Action::Editor(act) => {
405                match self.screen.editor_command(&act, &ctx, store) {
406                    Ok(info) => info,
407                    Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
408                        // Switch to the right window.
409                        if let Some(winid) = content.to_window() {
410                            let open = OpenTarget::Application(winid);
411                            let open = WindowAction::Switch(open);
412                            let _ = self.screen.window_command(&open, &ctx, store)?;
413
414                            // Run command again.
415                            self.screen.editor_command(&act, &ctx, store)?
416                        } else {
417                            return Err(EditError::WrongBuffer(content).into());
418                        }
419                    },
420                    Err(err) => return Err(err.into()),
421                }
422            },
423
424            // Simple delegations.
425            Action::Application(act) => self.iamb_run(act, ctx, store).await?,
426            Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
427            Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
428            Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
429            Action::ShowInfoMessage(info) => Some(info),
430            Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
431
432            Action::Jump(l, dir, count) => {
433                let count = ctx.resolve(&count);
434                let _ = self.screen.jump(l, dir, count, &ctx)?;
435
436                None
437            },
438            Action::Suspend => {
439                self.terminal.program_suspend()?;
440
441                None
442            },
443
444            // UI actions.
445            Action::Tab(cmd) => {
446                if let TabAction::Close(_, _) = &cmd {
447                    self.last_layout = self.screen.as_description().into();
448                }
449
450                self.screen.tab_command(&cmd, &ctx, store)?
451            },
452            Action::RedrawScreen => {
453                self.screen.clear_message();
454                self.redraw(true, store)?;
455
456                None
457            },
458
459            // Actions that create more Actions.
460            Action::Prompt(act) => {
461                let acts = self.screen.prompt(&act, &ctx, store)?;
462                self.action_prepend(acts);
463
464                None
465            },
466            Action::Command(act) => {
467                let acts = store.application.cmds.command(&act, &ctx)?;
468                self.action_prepend(acts);
469
470                None
471            },
472            Action::Repeat(rt) => {
473                self.bindings.repeat(rt, Some(ctx));
474
475                None
476            },
477
478            // Unimplemented.
479            Action::KeywordLookup => {
480                // XXX: implement
481                None
482            },
483
484            _ => {
485                // XXX: log unhandled actions? print message?
486                None
487            },
488        };
489
490        return Ok(info);
491    }
492
493    async fn iamb_run(
494        &mut self,
495        action: IambAction,
496        ctx: ProgramContext,
497        store: &mut ProgramStore,
498    ) -> IambResult<EditInfo> {
499        if action.scribbles() {
500            self.dirty = true;
501        }
502
503        let info = match action {
504            IambAction::ToggleScrollbackFocus => {
505                self.screen.current_window_mut()?.focus_toggle();
506
507                None
508            },
509
510            IambAction::Homeserver(act) => {
511                let acts = self.homeserver_command(act, ctx, store).await?;
512                self.action_prepend(acts);
513
514                None
515            },
516            IambAction::Message(act) => {
517                self.screen.current_window_mut()?.message_command(act, ctx, store).await?
518            },
519            IambAction::Room(act) => {
520                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
521                self.action_prepend(acts);
522
523                None
524            },
525            IambAction::Send(act) => {
526                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
527            },
528
529            IambAction::OpenLink(url) => {
530                tokio::task::spawn_blocking(move || {
531                    return open::that(url);
532                });
533
534                None
535            },
536
537            IambAction::Verify(act, user_dev) => {
538                if let Some(sas) = store.application.verifications.get(&user_dev) {
539                    self.worker.verify(act, sas.clone())?
540                } else {
541                    return Err(IambError::InvalidVerificationId(user_dev).into());
542                }
543            },
544            IambAction::VerifyRequest(user_id) => {
545                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
546                    self.worker.verify_request(user_id)?
547                } else {
548                    return Err(IambError::InvalidUserId(user_id).into());
549                }
550            },
551        };
552
553        Ok(info)
554    }
555
556    async fn homeserver_command(
557        &mut self,
558        action: HomeserverAction,
559        ctx: ProgramContext,
560        store: &mut ProgramStore,
561    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
562        match action {
563            HomeserverAction::CreateRoom(alias, vis, flags) => {
564                let client = &store.application.worker.client;
565                let room_id = create_room(client, alias, vis, flags).await?;
566                let room = IambId::Room(room_id, None);
567                let target = OpenTarget::Application(room);
568                let action = WindowAction::Switch(target);
569
570                Ok(vec![(action.into(), ctx)])
571            },
572            HomeserverAction::Logout(user, true) => {
573                self.worker.logout(user)?;
574                let flags = CloseFlags::QUIT | CloseFlags::FORCE;
575                let act = TabAction::Close(TabTarget::All, flags);
576
577                Ok(vec![(act.into(), ctx)])
578            },
579            HomeserverAction::Logout(user, false) => {
580                let msg = "Would you like to logout?";
581                let act = IambAction::from(HomeserverAction::Logout(user, true));
582                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
583                let prompt = Box::new(prompt);
584
585                Err(UIError::NeedConfirm(prompt))
586            },
587        }
588    }
589
590    fn handle_info(&mut self, info: InfoMessage) {
591        match info {
592            InfoMessage::Message(info) => {
593                self.screen.push_info(info);
594            },
595            InfoMessage::Pager(text) => {
596                let pager = Box::new(Pager::new(text, vec![]));
597                self.bindings.run_dialog(pager);
598            },
599        }
600    }
601
602    pub async fn run(&mut self) -> Result<(), std::io::Error> {
603        self.terminal.clear()?;
604
605        let store = self.store.clone();
606
607        while self.screen.tabs() != 0 {
608            let key = self.step().await?;
609
610            self.bindings.input_key(key);
611
612            let mut locked = store.lock().await;
613            let mut keyskip = false;
614
615            while let Some((action, ctx)) = self.action_pop(keyskip) {
616                match self.action_run(action, ctx, locked.deref_mut()).await {
617                    Ok(None) => {
618                        // Continue processing.
619                        continue;
620                    },
621                    Ok(Some(info)) => {
622                        self.handle_info(info);
623
624                        // Continue processing; we'll redraw later.
625                        continue;
626                    },
627                    Err(
628                        UIError::NeedConfirm(dialog) |
629                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
630                    ) => {
631                        self.bindings.run_dialog(dialog);
632                        continue;
633                    },
634                    Err(e) => {
635                        self.screen.push_error(e);
636
637                        // Skip processing any more keypress Actions until the next key.
638                        keyskip = true;
639                        continue;
640                    },
641                }
642            }
643        }
644
645        if let Some(ref layout) = self.last_layout {
646            let locked = self.store.lock().await;
647            let path = locked.application.settings.layout_json.as_path();
648            path.parent().map(create_dir_all).transpose()?;
649
650            let file = File::create(path)?;
651            let writer = BufWriter::new(file);
652
653            if let Err(e) = serde_json::to_writer(writer, layout) {
654                tracing::error!("Failed to save window layout while exiting: {}", e);
655            }
656        }
657
658        crossterm::terminal::disable_raw_mode()?;
659        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
660        self.terminal.show_cursor()?;
661
662        return Ok(());
663    }
664}
665
666fn gen_passphrase() -> String {
667    rand::thread_rng()
668        .sample_iter(&Alphanumeric)
669        .take(20)
670        .map(char::from)
671        .collect()
672}
673
674fn read_response(question: &str) -> String {
675    println!("{question}");
676    let mut input = String::new();
677    let _ = std::io::stdin().read_line(&mut input);
678    input
679}
680
681fn read_yesno(question: &str) -> Option<char> {
682    read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
683}
684
685async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
686    if settings.session_json.is_file() {
687        let session = settings.read_session(&settings.session_json)?;
688        worker.login(LoginStyle::SessionRestore(session.into()))?;
689
690        return Ok(());
691    }
692
693    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
694        let session = settings.read_session(&settings.session_json_old)?;
695        worker.login(LoginStyle::SessionRestore(session.into()))?;
696
697        return Ok(());
698    }
699
700    loop {
701        let login_style =
702            match read_response("Please select login type: [p]assword / [s]ingle sign on")
703                .chars()
704                .next()
705                .map(|c| c.to_ascii_lowercase())
706            {
707                None | Some('p') => {
708                    let password = rpassword::prompt_password("Password: ")?;
709                    LoginStyle::Password(password)
710                },
711                Some('s') => LoginStyle::SingleSignOn,
712                Some(_) => {
713                    println!("Failed to login. Please enter 'p' or 's'");
714                    continue;
715                },
716            };
717
718        match worker.login(login_style) {
719            Ok(info) => {
720                if let Some(msg) = info {
721                    println!("{msg}");
722                }
723
724                break;
725            },
726            Err(err) => {
727                println!("Failed to login: {err}");
728                continue;
729            },
730        }
731    }
732
733    Ok(())
734}
735
736fn print_exit<T: Display, N>(v: T) -> N {
737    println!("{v}");
738    process::exit(2);
739}
740
741// We can't access the OlmMachine directly, so write the keys to a temporary
742// file first, and then import them later.
743async fn check_import_keys(
744    settings: &ApplicationSettings,
745) -> IambResult<Option<(temp_dir::TempDir, String)>> {
746    let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();
747
748    if !do_import {
749        return Ok(None);
750    }
751
752    let question = format!(
753        "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
754        settings.sled_dir.display()
755    );
756
757    loop {
758        match read_yesno(&question) {
759            Some('y') => {
760                break;
761            },
762            Some('n') => {
763                return Ok(None);
764            },
765            Some(_) | None => {
766                continue;
767            },
768        }
769    }
770
771    let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
772    let passphrase = gen_passphrase();
773
774    println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());
775
776    let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
777        Ok(encrypted) => encrypted,
778        Err(e) => {
779            format!("* Failed to encrypt room keys during export: {e}");
780            process::exit(2);
781        },
782    };
783
784    let tmpdir = TempDir::new()?;
785    let exported = tmpdir.child("keys");
786
787    println!("* Writing encrypted room keys to {}...", exported.display());
788    tokio::fs::write(&exported, &encrypted).await?;
789
790    Ok(Some((tmpdir, passphrase)))
791}
792
793async fn login_upgrade(
794    keydir: TempDir,
795    passphrase: String,
796    worker: &Requester,
797    settings: &ApplicationSettings,
798    store: &AsyncProgramStore,
799) -> IambResult<()> {
800    println!(
801        "Please log in for {} to import the room keys into a new session",
802        settings.profile.user_id
803    );
804
805    login(worker, settings).await?;
806
807    println!("* Importing room keys...");
808
809    let exported = keydir.child("keys");
810    let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;
811
812    match imported {
813        Ok(res) => {
814            println!(
815                "* Successfully imported {} out of {} keys",
816                res.imported_count, res.total_count
817            );
818            let _ = keydir.cleanup();
819        },
820        Err(e) => {
821            println!(
822                "Failed to import room keys from {}/keys: {e}\n\n\
823                They have been encrypted with the passphrase {passphrase:?}.\
824                Please save them and try importing them manually instead\n",
825                keydir.path().display()
826            );
827
828            loop {
829                match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
830                    Some('y') => break,
831                    Some('n') => print_exit("* Exiting..."),
832                    Some(_) | None => continue,
833                }
834            }
835        },
836    }
837
838    println!("* Syncing...");
839    worker::do_first_sync(&worker.client, store).await;
840
841    Ok(())
842}
843
844async fn login_normal(
845    worker: &Requester,
846    settings: &ApplicationSettings,
847    store: &AsyncProgramStore,
848) -> IambResult<()> {
849    println!("* Logging in for {}...", settings.profile.user_id);
850    login(worker, settings).await?;
851    worker::do_first_sync(&worker.client, store).await;
852    Ok(())
853}
854
855async fn run(settings: ApplicationSettings) -> IambResult<()> {
856    // Get old keys the first time we run w/ the upgraded SDK.
857    let import_keys = check_import_keys(&settings).await?;
858
859    // Set up client state.
860    create_dir_all(settings.sqlite_dir.as_path())?;
861    let client = worker::create_client(&settings).await;
862
863    // Set up the async worker thread and global store.
864    let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
865    let store = ChatStore::new(worker.clone(), settings.clone());
866    let store = Store::new(store);
867    let store = Arc::new(AsyncMutex::new(store));
868    worker.init(store.clone());
869
870    if let Some((keydir, pass)) = import_keys {
871        login_upgrade(keydir, pass, &worker, &settings, &store)
872            .await
873            .unwrap_or_else(print_exit);
874    } else {
875        login_normal(&worker, &settings, &store).await.unwrap_or_else(print_exit);
876    }
877
878    fn restore_tty() {
879        let _ = crossterm::terminal::disable_raw_mode();
880        let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
881        let _ = crossterm::execute!(stdout(), DisableFocusChange);
882        let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
883        let _ = crossterm::execute!(stdout(), CursorShow);
884    }
885
886    // Make sure panics clean up the terminal properly.
887    let orig_hook = std::panic::take_hook();
888    std::panic::set_hook(Box::new(move |panic_info| {
889        restore_tty();
890        orig_hook(panic_info);
891        process::exit(1);
892    }));
893
894    let mut application = Application::new(settings, store).await?;
895
896    // We can now run the application.
897    application.run().await?;
898    restore_tty();
899
900    Ok(())
901}
902
903fn main() -> IambResult<()> {
904    // Parse command-line flags.
905    let iamb = Iamb::parse();
906
907    // Load configuration and set up the Matrix SDK.
908    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
909
910    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
911    #[cfg(unix)]
912    unsafe {
913        libc::umask(0o077);
914    };
915
916    // Set up the tracing subscriber so we can log client messages.
917    let log_prefix = format!("iamb-log-{}", settings.profile_name);
918    let log_dir = settings.dirs.logs.as_path();
919
920    let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
921    let (appender, guard) = tracing_appender::non_blocking(appender);
922
923    let subscriber = FmtSubscriber::builder()
924        .with_writer(appender)
925        .with_max_level(settings.tunables.log_level)
926        .finish();
927    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
928
929    let rt = tokio::runtime::Builder::new_multi_thread()
930        .enable_all()
931        .worker_threads(2)
932        .thread_name_fn(|| {
933            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
934            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
935            format!("iamb-worker-{id}")
936        })
937        .build()
938        .unwrap();
939
940    rt.block_on(async move { run(settings).await })?;
941
942    drop(guard);
943    process::exit(0);
944}