src/main.rs

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