src/main.rs

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