src/main.rs

1069 lines · 33964 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::ClearUnreads => {
 533                let user_id = &store.application.settings.profile.user_id;
 534
 535                for room_id in store.application.sync_info.chats() {
 536                    if let Some(room) = store.application.rooms.get_mut(room_id) {
 537                        room.fully_read(user_id.clone());
 538                    }
 539                }
 540
 541                None
 542            },
 543
 544            IambAction::ToggleScrollbackFocus => {
 545                self.screen.current_window_mut()?.focus_toggle();
 546
 547                None
 548            },
 549
 550            IambAction::Homeserver(act) => {
 551                let acts = self.homeserver_command(act, ctx, store).await?;
 552                self.action_prepend(acts);
 553
 554                None
 555            },
 556            IambAction::Keys(act) => self.keys_command(act, ctx, store).await?,
 557            IambAction::Message(act) => {
 558                self.screen.current_window_mut()?.message_command(act, ctx, store).await?
 559            },
 560            IambAction::Room(act) => {
 561                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
 562                self.action_prepend(acts);
 563
 564                None
 565            },
 566            IambAction::Send(act) => {
 567                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
 568            },
 569
 570            IambAction::OpenLink(url) => {
 571                tokio::task::spawn_blocking(move || {
 572                    return open::that(url);
 573                });
 574
 575                None
 576            },
 577
 578            IambAction::Verify(act, user_dev) => {
 579                if let Some(sas) = store.application.verifications.get(&user_dev) {
 580                    self.worker.verify(act, sas.clone())?
 581                } else {
 582                    return Err(IambError::InvalidVerificationId(user_dev).into());
 583                }
 584            },
 585            IambAction::VerifyRequest(user_id) => {
 586                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
 587                    self.worker.verify_request(user_id)?
 588                } else {
 589                    return Err(IambError::InvalidUserId(user_id).into());
 590                }
 591            },
 592        };
 593
 594        Ok(info)
 595    }
 596
 597    async fn homeserver_command(
 598        &mut self,
 599        action: HomeserverAction,
 600        ctx: ProgramContext,
 601        store: &mut ProgramStore,
 602    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
 603        match action {
 604            HomeserverAction::CreateRoom(alias, vis, flags) => {
 605                let client = &store.application.worker.client;
 606                let room_id = create_room(client, alias, vis, flags).await?;
 607                let room = IambId::Room(room_id, None);
 608                let target = OpenTarget::Application(room);
 609                let action = WindowAction::Switch(target);
 610
 611                Ok(vec![(action.into(), ctx)])
 612            },
 613            HomeserverAction::Logout(user, true) => {
 614                self.worker.logout(user)?;
 615                let flags = CloseFlags::QUIT | CloseFlags::FORCE;
 616                let act = TabAction::Close(TabTarget::All, flags);
 617
 618                Ok(vec![(act.into(), ctx)])
 619            },
 620            HomeserverAction::Logout(user, false) => {
 621                let msg = "Would you like to logout?";
 622                let act = IambAction::from(HomeserverAction::Logout(user, true));
 623                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 624                let prompt = Box::new(prompt);
 625
 626                Err(UIError::NeedConfirm(prompt))
 627            },
 628        }
 629    }
 630
 631    async fn keys_command(
 632        &mut self,
 633        action: KeysAction,
 634        _: ProgramContext,
 635        store: &mut ProgramStore,
 636    ) -> IambResult<EditInfo> {
 637        let encryption = store.application.worker.client.encryption();
 638
 639        match action {
 640            KeysAction::Export(path, passphrase) => {
 641                encryption
 642                    .export_room_keys(path.into(), &passphrase, |_| true)
 643                    .await
 644                    .map_err(IambError::from)?;
 645
 646                Ok(Some("Successfully exported room keys".into()))
 647            },
 648            KeysAction::Import(path, passphrase) => {
 649                let res = encryption
 650                    .import_room_keys(path.into(), &passphrase)
 651                    .await
 652                    .map_err(IambError::from)?;
 653
 654                let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count);
 655
 656                Ok(Some(msg.into()))
 657            },
 658        }
 659    }
 660
 661    fn handle_info(&mut self, info: InfoMessage) {
 662        match info {
 663            InfoMessage::Message(info) => {
 664                self.screen.push_info(info);
 665            },
 666            InfoMessage::Pager(text) => {
 667                let pager = Box::new(Pager::new(text, vec![]));
 668                self.bindings.run_dialog(pager);
 669            },
 670        }
 671    }
 672
 673    pub async fn run(&mut self) -> Result<(), std::io::Error> {
 674        self.terminal.clear()?;
 675
 676        let store = self.store.clone();
 677
 678        while self.screen.tabs() != 0 {
 679            let key = self.step().await?;
 680
 681            self.bindings.input_key(key);
 682
 683            let mut locked = store.lock().await;
 684            let mut keyskip = false;
 685
 686            while let Some((action, ctx)) = self.action_pop(keyskip) {
 687                match self.action_run(action, ctx, locked.deref_mut()).await {
 688                    Ok(None) => {
 689                        // Continue processing.
 690                        continue;
 691                    },
 692                    Ok(Some(info)) => {
 693                        self.handle_info(info);
 694
 695                        // Continue processing; we'll redraw later.
 696                        continue;
 697                    },
 698                    Err(
 699                        UIError::NeedConfirm(dialog) |
 700                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
 701                    ) => {
 702                        self.bindings.run_dialog(dialog);
 703                        continue;
 704                    },
 705                    Err(e) => {
 706                        self.screen.push_error(e);
 707
 708                        // Skip processing any more keypress Actions until the next key.
 709                        keyskip = true;
 710                        continue;
 711                    },
 712                }
 713            }
 714        }
 715
 716        if let Some(ref layout) = self.last_layout {
 717            let locked = self.store.lock().await;
 718            let path = locked.application.settings.layout_json.as_path();
 719            path.parent().map(create_dir_all).transpose()?;
 720
 721            let file = File::create(path)?;
 722            let writer = BufWriter::new(file);
 723
 724            if let Err(e) = serde_json::to_writer(writer, layout) {
 725                tracing::error!("Failed to save window layout while exiting: {}", e);
 726            }
 727        }
 728
 729        crossterm::terminal::disable_raw_mode()?;
 730        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
 731        self.terminal.show_cursor()?;
 732
 733        return Ok(());
 734    }
 735}
 736
 737fn gen_passphrase() -> String {
 738    rand::thread_rng()
 739        .sample_iter(&Alphanumeric)
 740        .take(20)
 741        .map(char::from)
 742        .collect()
 743}
 744
 745fn read_response(question: &str) -> String {
 746    println!("{question}");
 747    let mut input = String::new();
 748    let _ = std::io::stdin().read_line(&mut input);
 749    input
 750}
 751
 752fn read_yesno(question: &str) -> Option<char> {
 753    read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
 754}
 755
 756async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
 757    if settings.session_json.is_file() {
 758        let session = settings.read_session(&settings.session_json)?;
 759        worker.login(LoginStyle::SessionRestore(session.into()))?;
 760
 761        return Ok(());
 762    }
 763
 764    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
 765        let session = settings.read_session(&settings.session_json_old)?;
 766        worker.login(LoginStyle::SessionRestore(session.into()))?;
 767
 768        return Ok(());
 769    }
 770
 771    loop {
 772        let login_style =
 773            match read_response("Please select login type: [p]assword / [s]ingle sign on")
 774                .chars()
 775                .next()
 776                .map(|c| c.to_ascii_lowercase())
 777            {
 778                None | Some('p') => {
 779                    let password = rpassword::prompt_password("Password: ")?;
 780                    LoginStyle::Password(password)
 781                },
 782                Some('s') => LoginStyle::SingleSignOn,
 783                Some(_) => {
 784                    println!("Failed to login. Please enter 'p' or 's'");
 785                    continue;
 786                },
 787            };
 788
 789        match worker.login(login_style) {
 790            Ok(info) => {
 791                if let Some(msg) = info {
 792                    println!("{msg}");
 793                }
 794
 795                break;
 796            },
 797            Err(err) => {
 798                println!("Failed to login: {err}");
 799                continue;
 800            },
 801        }
 802    }
 803
 804    Ok(())
 805}
 806
 807fn print_exit<T: Display, N>(v: T) -> N {
 808    eprintln!("{v}");
 809    process::exit(2);
 810}
 811
 812// We can't access the OlmMachine directly, so write the keys to a temporary
 813// file first, and then import them later.
 814async fn check_import_keys(
 815    settings: &ApplicationSettings,
 816) -> IambResult<Option<(temp_dir::TempDir, String)>> {
 817    let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();
 818
 819    if !do_import {
 820        return Ok(None);
 821    }
 822
 823    let question = format!(
 824        "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
 825        settings.sled_dir.display()
 826    );
 827
 828    loop {
 829        match read_yesno(&question) {
 830            Some('y') => {
 831                break;
 832            },
 833            Some('n') => {
 834                return Ok(None);
 835            },
 836            Some(_) | None => {
 837                continue;
 838            },
 839        }
 840    }
 841
 842    let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
 843    let passphrase = gen_passphrase();
 844
 845    println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());
 846
 847    let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
 848        Ok(encrypted) => encrypted,
 849        Err(e) => {
 850            format!("* Failed to encrypt room keys during export: {e}");
 851            process::exit(2);
 852        },
 853    };
 854
 855    let tmpdir = TempDir::new()?;
 856    let exported = tmpdir.child("keys");
 857
 858    println!("* Writing encrypted room keys to {}...", exported.display());
 859    tokio::fs::write(&exported, &encrypted).await?;
 860
 861    Ok(Some((tmpdir, passphrase)))
 862}
 863
 864async fn login_upgrade(
 865    keydir: TempDir,
 866    passphrase: String,
 867    worker: &Requester,
 868    settings: &ApplicationSettings,
 869    store: &AsyncProgramStore,
 870) -> IambResult<()> {
 871    println!(
 872        "Please log in for {} to import the room keys into a new session",
 873        settings.profile.user_id
 874    );
 875
 876    login(worker, settings).await?;
 877
 878    println!("* Importing room keys...");
 879
 880    let exported = keydir.child("keys");
 881    let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;
 882
 883    match imported {
 884        Ok(res) => {
 885            println!(
 886                "* Successfully imported {} out of {} keys",
 887                res.imported_count, res.total_count
 888            );
 889            let _ = keydir.cleanup();
 890        },
 891        Err(e) => {
 892            println!(
 893                "Failed to import room keys from {}/keys: {e}\n\n\
 894                They have been encrypted with the passphrase {passphrase:?}.\
 895                Please save them and try importing them manually instead\n",
 896                keydir.path().display()
 897            );
 898
 899            loop {
 900                match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
 901                    Some('y') => break,
 902                    Some('n') => print_exit("* Exiting..."),
 903                    Some(_) | None => continue,
 904                }
 905            }
 906        },
 907    }
 908
 909    println!("* Syncing...");
 910    worker::do_first_sync(&worker.client, store)
 911        .await
 912        .map_err(IambError::from)?;
 913
 914    Ok(())
 915}
 916
 917async fn login_normal(
 918    worker: &Requester,
 919    settings: &ApplicationSettings,
 920    store: &AsyncProgramStore,
 921) -> IambResult<()> {
 922    println!("* Logging in for {}...", settings.profile.user_id);
 923    login(worker, settings).await?;
 924    println!("* Syncing...");
 925    worker::do_first_sync(&worker.client, store)
 926        .await
 927        .map_err(IambError::from)?;
 928    Ok(())
 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    }
 946
 947    crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, SetTitle(title))
 948}
 949
 950// Do our best to reverse what we did in setup_tty() when we exit or crash.
 951fn restore_tty(enable_enhanced_keys: bool) {
 952    if enable_enhanced_keys {
 953        let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
 954    }
 955
 956    let _ = crossterm::execute!(
 957        stdout(),
 958        DisableBracketedPaste,
 959        DisableFocusChange,
 960        LeaveAlternateScreen,
 961        CursorShow,
 962    );
 963
 964    let _ = crossterm::terminal::disable_raw_mode();
 965}
 966
 967async fn run(settings: ApplicationSettings) -> IambResult<()> {
 968    // Get old keys the first time we run w/ the upgraded SDK.
 969    let import_keys = check_import_keys(&settings).await?;
 970
 971    // Set up client state.
 972    create_dir_all(settings.sqlite_dir.as_path())?;
 973    let client = worker::create_client(&settings).await;
 974
 975    // Set up the async worker thread and global store.
 976    let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
 977    let store = ChatStore::new(worker.clone(), settings.clone());
 978    let store = Store::new(store);
 979    let store = Arc::new(AsyncMutex::new(store));
 980    worker.init(store.clone());
 981
 982    let res = if let Some((keydir, pass)) = import_keys {
 983        login_upgrade(keydir, pass, &worker, &settings, &store).await
 984    } else {
 985        login_normal(&worker, &settings, &store).await
 986    };
 987
 988    match res {
 989        Err(UIError::Application(IambError::Matrix(e))) => {
 990            if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
 991                print_exit("Server did not recognize our API token; did you log out from this session elsewhere?")
 992            } else {
 993                print_exit(e)
 994            }
 995        },
 996        Err(e) => print_exit(e),
 997        Ok(()) => (),
 998    }
 999
1000    // Set up the terminal for drawing, and cleanup properly on panics.
1001    let enable_enhanced_keys = match crossterm::terminal::supports_keyboard_enhancement() {
1002        Ok(supported) => supported,
1003        Err(e) => {
1004            tracing::warn!(err = %e,
1005               "Failed to determine whether the terminal supports keyboard enhancements");
1006            false
1007        },
1008    };
1009    setup_tty(settings.profile.user_id.as_str(), enable_enhanced_keys)?;
1010
1011    let orig_hook = std::panic::take_hook();
1012    std::panic::set_hook(Box::new(move |panic_info| {
1013        restore_tty(enable_enhanced_keys);
1014        orig_hook(panic_info);
1015        process::exit(1);
1016    }));
1017
1018    // And finally, start running the terminal UI.
1019    let mut application = Application::new(settings, store).await?;
1020    application.run().await?;
1021
1022    // Clean up the terminal on exit.
1023    restore_tty(enable_enhanced_keys);
1024
1025    Ok(())
1026}
1027
1028fn main() -> IambResult<()> {
1029    // Parse command-line flags.
1030    let iamb = Iamb::parse();
1031
1032    // Load configuration and set up the Matrix SDK.
1033    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
1034
1035    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
1036    #[cfg(unix)]
1037    unsafe {
1038        libc::umask(0o077);
1039    };
1040
1041    // Set up the tracing subscriber so we can log client messages.
1042    let log_prefix = format!("iamb-log-{}", settings.profile_name);
1043    let log_dir = settings.dirs.logs.as_path();
1044
1045    let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
1046    let (appender, guard) = tracing_appender::non_blocking(appender);
1047
1048    let subscriber = FmtSubscriber::builder()
1049        .with_writer(appender)
1050        .with_max_level(settings.tunables.log_level)
1051        .finish();
1052    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
1053
1054    let rt = tokio::runtime::Builder::new_multi_thread()
1055        .enable_all()
1056        .worker_threads(2)
1057        .thread_name_fn(|| {
1058            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
1059            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
1060            format!("iamb-worker-{id}")
1061        })
1062        .build()
1063        .unwrap();
1064
1065    rt.block_on(async move { run(settings).await })?;
1066
1067    drop(guard);
1068    process::exit(0);
1069}