src/main.rs

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