src/main.rs

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