src/main.rs

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