src/main.rs

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