src/main.rs

1072 lines · 33784 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                    let mut store = self.store.lock().await;
 359                    store.application.focused = true;
 360                    self.focused = true;
 361                },
 362                Event::FocusLost => {
 363                    let mut store = self.store.lock().await;
 364                    store.application.focused = false;
 365                    self.focused = false;
 366                },
 367                Event::Resize(_, _) => {
 368                    // We'll redraw for the new size next time step() is called.
 369                },
 370                Event::Paste(s) => {
 371                    let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
 372                    let act = EditorAction::from(act);
 373                    let ctx = ProgramContext::default();
 374                    let mut store = self.store.lock().await;
 375
 376                    match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
 377                        Ok(None) => {},
 378                        Ok(Some(info)) => {
 379                            drop(store);
 380                            self.handle_info(info);
 381                        },
 382                        Err(e) => {
 383                            self.screen.push_error(e);
 384                        },
 385                    }
 386                },
 387            }
 388        }
 389    }
 390
 391    fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
 392        let mut acts = VecDeque::from(acts);
 393        acts.append(&mut self.actstack);
 394        self.actstack = acts;
 395    }
 396
 397    fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
 398        if let res @ Some(_) = self.actstack.pop_front() {
 399            return res;
 400        }
 401
 402        if keyskip {
 403            return None;
 404        } else {
 405            return self.bindings.pop();
 406        }
 407    }
 408
 409    async fn action_run(
 410        &mut self,
 411        action: ProgramAction,
 412        ctx: ProgramContext,
 413        store: &mut ProgramStore,
 414    ) -> IambResult<EditInfo> {
 415        let info = match action {
 416            // Do nothing.
 417            Action::NoOp => None,
 418
 419            Action::Editor(act) => {
 420                match self.screen.editor_command(&act, &ctx, store) {
 421                    Ok(info) => info,
 422                    Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
 423                        // Switch to the right window.
 424                        if let Some(winid) = content.to_window() {
 425                            let open = OpenTarget::Application(winid);
 426                            let open = WindowAction::Switch(open);
 427                            let _ = self.screen.window_command(&open, &ctx, store)?;
 428
 429                            // Run command again.
 430                            self.screen.editor_command(&act, &ctx, store)?
 431                        } else {
 432                            return Err(EditError::WrongBuffer(content).into());
 433                        }
 434                    },
 435                    Err(err) => return Err(err.into()),
 436                }
 437            },
 438
 439            // Simple delegations.
 440            Action::Application(act) => self.iamb_run(act, ctx, store).await?,
 441            Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
 442            Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
 443            Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
 444            Action::ShowInfoMessage(info) => Some(info),
 445            Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
 446
 447            Action::Jump(l, dir, count) => {
 448                let count = ctx.resolve(&count);
 449                let _ = self.screen.jump(l, dir, count, &ctx)?;
 450
 451                None
 452            },
 453            Action::Suspend => {
 454                self.terminal.program_suspend()?;
 455
 456                None
 457            },
 458
 459            // UI actions.
 460            Action::Tab(cmd) => {
 461                if let TabAction::Close(_, _) = &cmd {
 462                    self.last_layout = self.screen.as_description().into();
 463                }
 464
 465                self.screen.tab_command(&cmd, &ctx, store)?
 466            },
 467            Action::RedrawScreen => {
 468                self.screen.clear_message();
 469                self.redraw(true, store)?;
 470
 471                None
 472            },
 473
 474            // Actions that create more Actions.
 475            Action::Prompt(act) => {
 476                let acts = self.screen.prompt(&act, &ctx, store)?;
 477                self.action_prepend(acts);
 478
 479                None
 480            },
 481            Action::Command(act) => {
 482                let acts = store.application.cmds.command(&act, &ctx)?;
 483                self.action_prepend(acts);
 484
 485                None
 486            },
 487            Action::Repeat(rt) => {
 488                self.bindings.repeat(rt, Some(ctx));
 489
 490                None
 491            },
 492
 493            // Unimplemented.
 494            Action::KeywordLookup => {
 495                // XXX: implement
 496                None
 497            },
 498
 499            _ => {
 500                // XXX: log unhandled actions? print message?
 501                None
 502            },
 503        };
 504
 505        return Ok(info);
 506    }
 507
 508    async fn iamb_run(
 509        &mut self,
 510        action: IambAction,
 511        ctx: ProgramContext,
 512        store: &mut ProgramStore,
 513    ) -> IambResult<EditInfo> {
 514        if action.scribbles() {
 515            self.dirty = true;
 516        }
 517
 518        let info = match action {
 519            IambAction::ToggleScrollbackFocus => {
 520                self.screen.current_window_mut()?.focus_toggle();
 521
 522                None
 523            },
 524
 525            IambAction::Homeserver(act) => {
 526                let acts = self.homeserver_command(act, ctx, store).await?;
 527                self.action_prepend(acts);
 528
 529                None
 530            },
 531            IambAction::Keys(act) => self.keys_command(act, ctx, store).await?,
 532            IambAction::Message(act) => {
 533                self.screen.current_window_mut()?.message_command(act, ctx, store).await?
 534            },
 535            IambAction::Room(act) => {
 536                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
 537                self.action_prepend(acts);
 538
 539                None
 540            },
 541            IambAction::Send(act) => {
 542                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
 543            },
 544
 545            IambAction::OpenLink(url) => {
 546                tokio::task::spawn_blocking(move || {
 547                    return open::that(url);
 548                });
 549
 550                None
 551            },
 552
 553            IambAction::Verify(act, user_dev) => {
 554                if let Some(sas) = store.application.verifications.get(&user_dev) {
 555                    self.worker.verify(act, sas.clone())?
 556                } else {
 557                    return Err(IambError::InvalidVerificationId(user_dev).into());
 558                }
 559            },
 560            IambAction::VerifyRequest(user_id) => {
 561                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
 562                    self.worker.verify_request(user_id)?
 563                } else {
 564                    return Err(IambError::InvalidUserId(user_id).into());
 565                }
 566            },
 567        };
 568
 569        Ok(info)
 570    }
 571
 572    async fn homeserver_command(
 573        &mut self,
 574        action: HomeserverAction,
 575        ctx: ProgramContext,
 576        store: &mut ProgramStore,
 577    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
 578        match action {
 579            HomeserverAction::CreateRoom(alias, vis, flags) => {
 580                let client = &store.application.worker.client;
 581                let room_id = create_room(client, alias, vis, flags).await?;
 582                let room = IambId::Room(room_id, None);
 583                let target = OpenTarget::Application(room);
 584                let action = WindowAction::Switch(target);
 585
 586                Ok(vec![(action.into(), ctx)])
 587            },
 588            HomeserverAction::Logout(user, true) => {
 589                self.worker.logout(user)?;
 590                let flags = CloseFlags::QUIT | CloseFlags::FORCE;
 591                let act = TabAction::Close(TabTarget::All, flags);
 592
 593                Ok(vec![(act.into(), ctx)])
 594            },
 595            HomeserverAction::Logout(user, false) => {
 596                let msg = "Would you like to logout?";
 597                let act = IambAction::from(HomeserverAction::Logout(user, true));
 598                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 599                let prompt = Box::new(prompt);
 600
 601                Err(UIError::NeedConfirm(prompt))
 602            },
 603        }
 604    }
 605
 606    async fn keys_command(
 607        &mut self,
 608        action: KeysAction,
 609        _: ProgramContext,
 610        store: &mut ProgramStore,
 611    ) -> IambResult<EditInfo> {
 612        let encryption = store.application.worker.client.encryption();
 613
 614        match action {
 615            KeysAction::Export(path, passphrase) => {
 616                encryption
 617                    .export_room_keys(path.into(), &passphrase, |_| true)
 618                    .await
 619                    .map_err(IambError::from)?;
 620
 621                Ok(Some("Successfully exported room keys".into()))
 622            },
 623            KeysAction::Import(path, passphrase) => {
 624                let res = encryption
 625                    .import_room_keys(path.into(), &passphrase)
 626                    .await
 627                    .map_err(IambError::from)?;
 628
 629                let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count);
 630
 631                Ok(Some(msg.into()))
 632            },
 633        }
 634    }
 635
 636    fn handle_info(&mut self, info: InfoMessage) {
 637        match info {
 638            InfoMessage::Message(info) => {
 639                self.screen.push_info(info);
 640            },
 641            InfoMessage::Pager(text) => {
 642                let pager = Box::new(Pager::new(text, vec![]));
 643                self.bindings.run_dialog(pager);
 644            },
 645        }
 646    }
 647
 648    pub async fn run(&mut self) -> Result<(), std::io::Error> {
 649        self.terminal.clear()?;
 650
 651        let store = self.store.clone();
 652
 653        while self.screen.tabs() != 0 {
 654            let key = self.step().await?;
 655
 656            self.bindings.input_key(key);
 657
 658            let mut locked = store.lock().await;
 659            let mut keyskip = false;
 660
 661            while let Some((action, ctx)) = self.action_pop(keyskip) {
 662                match self.action_run(action, ctx, locked.deref_mut()).await {
 663                    Ok(None) => {
 664                        // Continue processing.
 665                        continue;
 666                    },
 667                    Ok(Some(info)) => {
 668                        self.handle_info(info);
 669
 670                        // Continue processing; we'll redraw later.
 671                        continue;
 672                    },
 673                    Err(
 674                        UIError::NeedConfirm(dialog) |
 675                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
 676                    ) => {
 677                        self.bindings.run_dialog(dialog);
 678                        continue;
 679                    },
 680                    Err(e) => {
 681                        self.screen.push_error(e);
 682
 683                        // Skip processing any more keypress Actions until the next key.
 684                        keyskip = true;
 685                        continue;
 686                    },
 687                }
 688            }
 689        }
 690
 691        if let Some(ref layout) = self.last_layout {
 692            let locked = self.store.lock().await;
 693            let path = locked.application.settings.layout_json.as_path();
 694            path.parent().map(create_dir_all).transpose()?;
 695
 696            let file = File::create(path)?;
 697            let writer = BufWriter::new(file);
 698
 699            if let Err(e) = serde_json::to_writer(writer, layout) {
 700                tracing::error!("Failed to save window layout while exiting: {}", e);
 701            }
 702        }
 703
 704        crossterm::terminal::disable_raw_mode()?;
 705        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
 706        self.terminal.show_cursor()?;
 707
 708        return Ok(());
 709    }
 710}
 711
 712fn gen_passphrase() -> String {
 713    rand::thread_rng()
 714        .sample_iter(&Alphanumeric)
 715        .take(20)
 716        .map(char::from)
 717        .collect()
 718}
 719
 720fn read_response(question: &str) -> String {
 721    println!("{question}");
 722    let mut input = String::new();
 723    let _ = std::io::stdin().read_line(&mut input);
 724    input
 725}
 726
 727fn read_yesno(question: &str) -> Option<char> {
 728    read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
 729}
 730
 731async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
 732    if settings.session_json.is_file() {
 733        let session = settings.read_session(&settings.session_json)?;
 734        worker.login(LoginStyle::SessionRestore(session.into()))?;
 735
 736        return Ok(());
 737    }
 738
 739    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
 740        let session = settings.read_session(&settings.session_json_old)?;
 741        worker.login(LoginStyle::SessionRestore(session.into()))?;
 742
 743        return Ok(());
 744    }
 745
 746    loop {
 747        let login_style =
 748            match read_response("Please select login type: [p]assword / [s]ingle sign on")
 749                .chars()
 750                .next()
 751                .map(|c| c.to_ascii_lowercase())
 752            {
 753                None | Some('p') => {
 754                    let password = rpassword::prompt_password("Password: ")?;
 755                    LoginStyle::Password(password)
 756                },
 757                Some('s') => LoginStyle::SingleSignOn,
 758                Some(_) => {
 759                    println!("Failed to login. Please enter 'p' or 's'");
 760                    continue;
 761                },
 762            };
 763
 764        match worker.login(login_style) {
 765            Ok(info) => {
 766                if let Some(msg) = info {
 767                    println!("{msg}");
 768                }
 769
 770                break;
 771            },
 772            Err(err) => {
 773                println!("Failed to login: {err}");
 774                continue;
 775            },
 776        }
 777    }
 778
 779    Ok(())
 780}
 781
 782fn print_exit<T: Display, N>(v: T) -> N {
 783    eprintln!("{v}");
 784    process::exit(2);
 785}
 786
 787// We can't access the OlmMachine directly, so write the keys to a temporary
 788// file first, and then import them later.
 789async fn check_import_keys(
 790    settings: &ApplicationSettings,
 791) -> IambResult<Option<(temp_dir::TempDir, String)>> {
 792    let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();
 793
 794    if !do_import {
 795        return Ok(None);
 796    }
 797
 798    let question = format!(
 799        "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
 800        settings.sled_dir.display()
 801    );
 802
 803    loop {
 804        match read_yesno(&question) {
 805            Some('y') => {
 806                break;
 807            },
 808            Some('n') => {
 809                return Ok(None);
 810            },
 811            Some(_) | None => {
 812                continue;
 813            },
 814        }
 815    }
 816
 817    let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
 818    let passphrase = gen_passphrase();
 819
 820    println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());
 821
 822    let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
 823        Ok(encrypted) => encrypted,
 824        Err(e) => {
 825            format!("* Failed to encrypt room keys during export: {e}");
 826            process::exit(2);
 827        },
 828    };
 829
 830    let tmpdir = TempDir::new()?;
 831    let exported = tmpdir.child("keys");
 832
 833    println!("* Writing encrypted room keys to {}...", exported.display());
 834    tokio::fs::write(&exported, &encrypted).await?;
 835
 836    Ok(Some((tmpdir, passphrase)))
 837}
 838
 839async fn login_upgrade(
 840    keydir: TempDir,
 841    passphrase: String,
 842    worker: &Requester,
 843    settings: &ApplicationSettings,
 844    store: &AsyncProgramStore,
 845) -> IambResult<()> {
 846    println!(
 847        "Please log in for {} to import the room keys into a new session",
 848        settings.profile.user_id
 849    );
 850
 851    login(worker, settings).await?;
 852
 853    println!("* Importing room keys...");
 854
 855    let exported = keydir.child("keys");
 856    let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;
 857
 858    match imported {
 859        Ok(res) => {
 860            println!(
 861                "* Successfully imported {} out of {} keys",
 862                res.imported_count, res.total_count
 863            );
 864            let _ = keydir.cleanup();
 865        },
 866        Err(e) => {
 867            println!(
 868                "Failed to import room keys from {}/keys: {e}\n\n\
 869                They have been encrypted with the passphrase {passphrase:?}.\
 870                Please save them and try importing them manually instead\n",
 871                keydir.path().display()
 872            );
 873
 874            loop {
 875                match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
 876                    Some('y') => break,
 877                    Some('n') => print_exit("* Exiting..."),
 878                    Some(_) | None => continue,
 879                }
 880            }
 881        },
 882    }
 883
 884    println!("* Syncing...");
 885    worker::do_first_sync(&worker.client, store)
 886        .await
 887        .map_err(IambError::from)?;
 888
 889    Ok(())
 890}
 891
 892async fn login_normal(
 893    worker: &Requester,
 894    settings: &ApplicationSettings,
 895    store: &AsyncProgramStore,
 896) -> IambResult<()> {
 897    println!("* Logging in for {}...", settings.profile.user_id);
 898    login(worker, settings).await?;
 899    println!("* Syncing...");
 900    worker::do_first_sync(&worker.client, store)
 901        .await
 902        .map_err(IambError::from)?;
 903    Ok(())
 904}
 905
 906struct EnableModifyOtherKeys;
 907struct DisableModifyOtherKeys;
 908
 909impl crossterm::Command for EnableModifyOtherKeys {
 910    fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result {
 911        write!(f, "\x1B[>4;2m")
 912    }
 913
 914    #[cfg(windows)]
 915    fn execute_winapi(&self) -> std::io::Result<()> {
 916        Ok(())
 917    }
 918}
 919
 920impl crossterm::Command for DisableModifyOtherKeys {
 921    fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result {
 922        write!(f, "\x1B[>4;0m")
 923    }
 924
 925    #[cfg(windows)]
 926    fn execute_winapi(&self) -> std::io::Result<()> {
 927        Ok(())
 928    }
 929}
 930
 931/// Set up the terminal for drawing the TUI, and getting additional info.
 932fn setup_tty(title: &str, enable_enhanced_keys: bool) -> std::io::Result<()> {
 933    let title = format!("iamb ({})", title);
 934
 935    // Enable raw mode and enter the alternate screen.
 936    crossterm::terminal::enable_raw_mode()?;
 937    crossterm::execute!(stdout(), EnterAlternateScreen)?;
 938
 939    if enable_enhanced_keys {
 940        // Enable the Kitty keyboard enhancement protocol for improved keypresses.
 941        crossterm::queue!(
 942            stdout(),
 943            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
 944        )?;
 945    } else {
 946        crossterm::queue!(stdout(), EnableModifyOtherKeys)?;
 947    }
 948
 949    crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, SetTitle(title))
 950}
 951
 952// Do our best to reverse what we did in setup_tty() when we exit or crash.
 953fn restore_tty(enable_enhanced_keys: bool) {
 954    if enable_enhanced_keys {
 955        let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
 956    }
 957
 958    let _ = crossterm::execute!(
 959        stdout(),
 960        DisableModifyOtherKeys,
 961        DisableBracketedPaste,
 962        DisableFocusChange,
 963        LeaveAlternateScreen,
 964        CursorShow,
 965    );
 966
 967    let _ = crossterm::terminal::disable_raw_mode();
 968}
 969
 970async fn run(settings: ApplicationSettings) -> IambResult<()> {
 971    // Get old keys the first time we run w/ the upgraded SDK.
 972    let import_keys = check_import_keys(&settings).await?;
 973
 974    // Set up client state.
 975    create_dir_all(settings.sqlite_dir.as_path())?;
 976    let client = worker::create_client(&settings).await;
 977
 978    // Set up the async worker thread and global store.
 979    let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
 980    let store = ChatStore::new(worker.clone(), settings.clone());
 981    let store = Store::new(store);
 982    let store = Arc::new(AsyncMutex::new(store));
 983    worker.init(store.clone());
 984
 985    let res = if let Some((keydir, pass)) = import_keys {
 986        login_upgrade(keydir, pass, &worker, &settings, &store).await
 987    } else {
 988        login_normal(&worker, &settings, &store).await
 989    };
 990
 991    match res {
 992        Err(UIError::Application(IambError::Matrix(e))) => {
 993            if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
 994                print_exit("Server did not recognize our API token; did you log out from this session elsewhere?")
 995            } else {
 996                print_exit(e)
 997            }
 998        },
 999        Err(e) => print_exit(e),
1000        Ok(()) => (),
1001    }
1002
1003    // Set up the terminal for drawing, and cleanup properly on panics.
1004    let enable_enhanced_keys = match crossterm::terminal::supports_keyboard_enhancement() {
1005        Ok(supported) => supported,
1006        Err(e) => {
1007            tracing::warn!(err = %e,
1008               "Failed to determine whether the terminal supports keyboard enhancements");
1009            false
1010        },
1011    };
1012    setup_tty(settings.profile.user_id.as_str(), enable_enhanced_keys)?;
1013
1014    let orig_hook = std::panic::take_hook();
1015    std::panic::set_hook(Box::new(move |panic_info| {
1016        restore_tty(enable_enhanced_keys);
1017        orig_hook(panic_info);
1018        process::exit(1);
1019    }));
1020
1021    // And finally, start running the terminal UI.
1022    let mut application = Application::new(settings, store).await?;
1023    application.run().await?;
1024
1025    // Clean up the terminal on exit.
1026    restore_tty(enable_enhanced_keys);
1027
1028    Ok(())
1029}
1030
1031fn main() -> IambResult<()> {
1032    // Parse command-line flags.
1033    let iamb = Iamb::parse();
1034
1035    // Load configuration and set up the Matrix SDK.
1036    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
1037
1038    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
1039    #[cfg(unix)]
1040    unsafe {
1041        libc::umask(0o077);
1042    };
1043
1044    // Set up the tracing subscriber so we can log client messages.
1045    let log_prefix = format!("iamb-log-{}", settings.profile_name);
1046    let log_dir = settings.dirs.logs.as_path();
1047
1048    let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
1049    let (appender, guard) = tracing_appender::non_blocking(appender);
1050
1051    let subscriber = FmtSubscriber::builder()
1052        .with_writer(appender)
1053        .with_max_level(settings.tunables.log_level)
1054        .finish();
1055    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
1056
1057    let rt = tokio::runtime::Builder::new_multi_thread()
1058        .enable_all()
1059        .worker_threads(2)
1060        .thread_name_fn(|| {
1061            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
1062            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
1063            format!("iamb-worker-{id}")
1064        })
1065        .build()
1066        .unwrap();
1067
1068    rt.block_on(async move { run(settings).await })?;
1069
1070    drop(guard);
1071    process::exit(0);
1072}