src/main.rs

1072 lines · 34119 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.area();
 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_position((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::Space(act) => {
 561                self.screen.current_window_mut()?.space_command(act, ctx, store).await?
 562            },
 563            IambAction::Room(act) => {
 564                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
 565                self.action_prepend(acts);
 566
 567                None
 568            },
 569            IambAction::Send(act) => {
 570                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
 571            },
 572
 573            IambAction::OpenLink(url) => {
 574                tokio::task::spawn_blocking(move || {
 575                    return open::that(url);
 576                });
 577
 578                None
 579            },
 580
 581            IambAction::Verify(act, user_dev) => {
 582                if let Some(sas) = store.application.verifications.get(&user_dev) {
 583                    self.worker.verify(act, sas.clone())?
 584                } else {
 585                    return Err(IambError::InvalidVerificationId(user_dev).into());
 586                }
 587            },
 588            IambAction::VerifyRequest(user_id) => {
 589                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
 590                    self.worker.verify_request(user_id)?
 591                } else {
 592                    return Err(IambError::InvalidUserId(user_id).into());
 593                }
 594            },
 595        };
 596
 597        Ok(info)
 598    }
 599
 600    async fn homeserver_command(
 601        &mut self,
 602        action: HomeserverAction,
 603        ctx: ProgramContext,
 604        store: &mut ProgramStore,
 605    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
 606        match action {
 607            HomeserverAction::CreateRoom(alias, vis, flags) => {
 608                let client = &store.application.worker.client;
 609                let room_id = create_room(client, alias, vis, flags).await?;
 610                let room = IambId::Room(room_id, None);
 611                let target = OpenTarget::Application(room);
 612                let action = WindowAction::Switch(target);
 613
 614                Ok(vec![(action.into(), ctx)])
 615            },
 616            HomeserverAction::Logout(user, true) => {
 617                self.worker.logout(user)?;
 618                let flags = CloseFlags::QUIT | CloseFlags::FORCE;
 619                let act = TabAction::Close(TabTarget::All, flags);
 620
 621                Ok(vec![(act.into(), ctx)])
 622            },
 623            HomeserverAction::Logout(user, false) => {
 624                let msg = "Would you like to logout?";
 625                let act = IambAction::from(HomeserverAction::Logout(user, true));
 626                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 627                let prompt = Box::new(prompt);
 628
 629                Err(UIError::NeedConfirm(prompt))
 630            },
 631        }
 632    }
 633
 634    async fn keys_command(
 635        &mut self,
 636        action: KeysAction,
 637        _: ProgramContext,
 638        store: &mut ProgramStore,
 639    ) -> IambResult<EditInfo> {
 640        let encryption = store.application.worker.client.encryption();
 641
 642        match action {
 643            KeysAction::Export(path, passphrase) => {
 644                encryption
 645                    .export_room_keys(path.into(), &passphrase, |_| true)
 646                    .await
 647                    .map_err(IambError::from)?;
 648
 649                Ok(Some("Successfully exported room keys".into()))
 650            },
 651            KeysAction::Import(path, passphrase) => {
 652                let res = encryption
 653                    .import_room_keys(path.into(), &passphrase)
 654                    .await
 655                    .map_err(IambError::from)?;
 656
 657                let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count);
 658
 659                Ok(Some(msg.into()))
 660            },
 661        }
 662    }
 663
 664    fn handle_info(&mut self, info: InfoMessage) {
 665        match info {
 666            InfoMessage::Message(info) => {
 667                self.screen.push_info(info);
 668            },
 669            InfoMessage::Pager(text) => {
 670                let pager = Box::new(Pager::new(text, vec![]));
 671                self.bindings.run_dialog(pager);
 672            },
 673        }
 674    }
 675
 676    pub async fn run(&mut self) -> Result<(), std::io::Error> {
 677        self.terminal.clear()?;
 678
 679        let store = self.store.clone();
 680
 681        while self.screen.tabs() != 0 {
 682            let key = self.step().await?;
 683
 684            self.bindings.input_key(key);
 685
 686            let mut locked = store.lock().await;
 687            let mut keyskip = false;
 688
 689            while let Some((action, ctx)) = self.action_pop(keyskip) {
 690                match self.action_run(action, ctx, locked.deref_mut()).await {
 691                    Ok(None) => {
 692                        // Continue processing.
 693                        continue;
 694                    },
 695                    Ok(Some(info)) => {
 696                        self.handle_info(info);
 697
 698                        // Continue processing; we'll redraw later.
 699                        continue;
 700                    },
 701                    Err(
 702                        UIError::NeedConfirm(dialog) |
 703                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
 704                    ) => {
 705                        self.bindings.run_dialog(dialog);
 706                        continue;
 707                    },
 708                    Err(e) => {
 709                        self.screen.push_error(e);
 710
 711                        // Skip processing any more keypress Actions until the next key.
 712                        keyskip = true;
 713                        continue;
 714                    },
 715                }
 716            }
 717        }
 718
 719        if let Some(ref layout) = self.last_layout {
 720            let locked = self.store.lock().await;
 721            let path = locked.application.settings.layout_json.as_path();
 722            path.parent().map(create_dir_all).transpose()?;
 723
 724            let file = File::create(path)?;
 725            let writer = BufWriter::new(file);
 726
 727            if let Err(e) = serde_json::to_writer(writer, layout) {
 728                tracing::error!("Failed to save window layout while exiting: {}", e);
 729            }
 730        }
 731
 732        crossterm::terminal::disable_raw_mode()?;
 733        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
 734        self.terminal.show_cursor()?;
 735
 736        return Ok(());
 737    }
 738}
 739
 740fn gen_passphrase() -> String {
 741    rand::thread_rng()
 742        .sample_iter(&Alphanumeric)
 743        .take(20)
 744        .map(char::from)
 745        .collect()
 746}
 747
 748fn read_response(question: &str) -> String {
 749    println!("{question}");
 750    let mut input = String::new();
 751    let _ = std::io::stdin().read_line(&mut input);
 752    input
 753}
 754
 755fn read_yesno(question: &str) -> Option<char> {
 756    read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
 757}
 758
 759async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
 760    if settings.session_json.is_file() {
 761        let session = settings.read_session(&settings.session_json)?;
 762        worker.login(LoginStyle::SessionRestore(session.into()))?;
 763
 764        return Ok(());
 765    }
 766
 767    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
 768        let session = settings.read_session(&settings.session_json_old)?;
 769        worker.login(LoginStyle::SessionRestore(session.into()))?;
 770
 771        return Ok(());
 772    }
 773
 774    loop {
 775        let login_style =
 776            match read_response("Please select login type: [p]assword / [s]ingle sign on")
 777                .chars()
 778                .next()
 779                .map(|c| c.to_ascii_lowercase())
 780            {
 781                None | Some('p') => {
 782                    let password = rpassword::prompt_password("Password: ")?;
 783                    LoginStyle::Password(password)
 784                },
 785                Some('s') => LoginStyle::SingleSignOn,
 786                Some(_) => {
 787                    println!("Failed to login. Please enter 'p' or 's'");
 788                    continue;
 789                },
 790            };
 791
 792        match worker.login(login_style) {
 793            Ok(info) => {
 794                if let Some(msg) = info {
 795                    println!("{msg}");
 796                }
 797
 798                break;
 799            },
 800            Err(err) => {
 801                println!("Failed to login: {err}");
 802                continue;
 803            },
 804        }
 805    }
 806
 807    Ok(())
 808}
 809
 810fn print_exit<T: Display, N>(v: T) -> N {
 811    eprintln!("{v}");
 812    process::exit(2);
 813}
 814
 815// We can't access the OlmMachine directly, so write the keys to a temporary
 816// file first, and then import them later.
 817async fn check_import_keys(
 818    settings: &ApplicationSettings,
 819) -> IambResult<Option<(temp_dir::TempDir, String)>> {
 820    let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();
 821
 822    if !do_import {
 823        return Ok(None);
 824    }
 825
 826    let question = format!(
 827        "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
 828        settings.sled_dir.display()
 829    );
 830
 831    loop {
 832        match read_yesno(&question) {
 833            Some('y') => {
 834                break;
 835            },
 836            Some('n') => {
 837                return Ok(None);
 838            },
 839            Some(_) | None => {
 840                continue;
 841            },
 842        }
 843    }
 844
 845    let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
 846    let passphrase = gen_passphrase();
 847
 848    println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());
 849
 850    let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
 851        Ok(encrypted) => encrypted,
 852        Err(e) => {
 853            println!("* Failed to encrypt room keys during export: {e}");
 854            process::exit(2);
 855        },
 856    };
 857
 858    let tmpdir = TempDir::new()?;
 859    let exported = tmpdir.child("keys");
 860
 861    println!("* Writing encrypted room keys to {}...", exported.display());
 862    tokio::fs::write(&exported, &encrypted).await?;
 863
 864    Ok(Some((tmpdir, passphrase)))
 865}
 866
 867async fn login_upgrade(
 868    keydir: TempDir,
 869    passphrase: String,
 870    worker: &Requester,
 871    settings: &ApplicationSettings,
 872    store: &AsyncProgramStore,
 873) -> IambResult<()> {
 874    println!(
 875        "Please log in for {} to import the room keys into a new session",
 876        settings.profile.user_id
 877    );
 878
 879    login(worker, settings).await?;
 880
 881    println!("* Importing room keys...");
 882
 883    let exported = keydir.child("keys");
 884    let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;
 885
 886    match imported {
 887        Ok(res) => {
 888            println!(
 889                "* Successfully imported {} out of {} keys",
 890                res.imported_count, res.total_count
 891            );
 892            let _ = keydir.cleanup();
 893        },
 894        Err(e) => {
 895            println!(
 896                "Failed to import room keys from {}/keys: {e}\n\n\
 897                They have been encrypted with the passphrase {passphrase:?}.\
 898                Please save them and try importing them manually instead\n",
 899                keydir.path().display()
 900            );
 901
 902            loop {
 903                match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
 904                    Some('y') => break,
 905                    Some('n') => print_exit("* Exiting..."),
 906                    Some(_) | None => continue,
 907                }
 908            }
 909        },
 910    }
 911
 912    println!("* Syncing...");
 913    worker::do_first_sync(&worker.client, store)
 914        .await
 915        .map_err(IambError::from)?;
 916
 917    Ok(())
 918}
 919
 920async fn login_normal(
 921    worker: &Requester,
 922    settings: &ApplicationSettings,
 923    store: &AsyncProgramStore,
 924) -> IambResult<()> {
 925    println!("* Logging in for {}...", settings.profile.user_id);
 926    login(worker, settings).await?;
 927    println!("* Syncing...");
 928    worker::do_first_sync(&worker.client, store)
 929        .await
 930        .map_err(IambError::from)?;
 931    Ok(())
 932}
 933
 934/// Set up the terminal for drawing the TUI, and getting additional info.
 935fn setup_tty(title: &str, enable_enhanced_keys: bool) -> std::io::Result<()> {
 936    let title = format!("iamb ({})", title);
 937
 938    // Enable raw mode and enter the alternate screen.
 939    crossterm::terminal::enable_raw_mode()?;
 940    crossterm::execute!(stdout(), EnterAlternateScreen)?;
 941
 942    if enable_enhanced_keys {
 943        // Enable the Kitty keyboard enhancement protocol for improved keypresses.
 944        crossterm::queue!(
 945            stdout(),
 946            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
 947        )?;
 948    }
 949
 950    crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, SetTitle(title))
 951}
 952
 953// Do our best to reverse what we did in setup_tty() when we exit or crash.
 954fn restore_tty(enable_enhanced_keys: bool) {
 955    if enable_enhanced_keys {
 956        let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
 957    }
 958
 959    let _ = crossterm::execute!(
 960        stdout(),
 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}