src/main.rs

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