src/main.rs

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