src/main.rs

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