src/main.rs

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