src/main.rs

1125 lines · 36491 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            HomeserverAction::Forget => {
 667                let client = &store.application.worker.client;
 668                for room in client.left_rooms() {
 669                    room.forget().await.map_err(IambError::from)?;
 670                }
 671                Ok(vec![])
 672            },
 673        }
 674    }
 675
 676    async fn keys_command(
 677        &mut self,
 678        action: KeysAction,
 679        _: ProgramContext,
 680        store: &mut ProgramStore,
 681    ) -> IambResult<EditInfo> {
 682        let encryption = store.application.worker.client.encryption();
 683
 684        match action {
 685            KeysAction::Export(path, passphrase) => {
 686                encryption
 687                    .export_room_keys(path.into(), &passphrase, |_| true)
 688                    .await
 689                    .map_err(IambError::from)?;
 690
 691                Ok(Some("Successfully exported room keys".into()))
 692            },
 693            KeysAction::Import(path, passphrase) => {
 694                let res = encryption
 695                    .import_room_keys(path.into(), &passphrase)
 696                    .await
 697                    .map_err(IambError::from)?;
 698
 699                let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count);
 700
 701                Ok(Some(msg.into()))
 702            },
 703        }
 704    }
 705
 706    fn handle_info(&mut self, info: InfoMessage) {
 707        match info {
 708            InfoMessage::Message(info) => {
 709                self.screen.push_info(info);
 710            },
 711            InfoMessage::Pager(text) => {
 712                let pager = Box::new(Pager::new(text, vec![]));
 713                self.bindings.run_dialog(pager);
 714            },
 715        }
 716    }
 717
 718    pub async fn run(&mut self) -> Result<(), std::io::Error> {
 719        self.terminal.clear()?;
 720
 721        let store = self.store.clone();
 722
 723        while self.screen.tabs() != 0 {
 724            let key = self.step().await?;
 725
 726            self.bindings.input_key(key);
 727
 728            let mut locked = store.lock().await;
 729            let mut keyskip = false;
 730
 731            while let Some((action, ctx)) = self.action_pop(keyskip) {
 732                match self.action_run(action, ctx, locked.deref_mut()).await {
 733                    Ok(None) => {
 734                        // Continue processing.
 735                        continue;
 736                    },
 737                    Ok(Some(info)) => {
 738                        self.handle_info(info);
 739
 740                        // Continue processing; we'll redraw later.
 741                        continue;
 742                    },
 743                    Err(
 744                        UIError::NeedConfirm(dialog) |
 745                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
 746                    ) => {
 747                        self.bindings.run_dialog(dialog);
 748                        continue;
 749                    },
 750                    Err(e) => {
 751                        self.screen.push_error(e);
 752
 753                        // Skip processing any more keypress Actions until the next key.
 754                        keyskip = true;
 755                        continue;
 756                    },
 757                }
 758            }
 759        }
 760
 761        if let Some(ref layout) = self.last_layout {
 762            let locked = self.store.lock().await;
 763            let path = locked.application.settings.layout_json.as_path();
 764            path.parent().map(create_dir_all).transpose()?;
 765
 766            let file = File::create(path)?;
 767            let writer = BufWriter::new(file);
 768
 769            if let Err(e) = serde_json::to_writer(writer, layout) {
 770                tracing::error!("Failed to save window layout while exiting: {}", e);
 771            }
 772        }
 773
 774        crossterm::terminal::disable_raw_mode()?;
 775        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
 776        self.terminal.show_cursor()?;
 777
 778        return Ok(());
 779    }
 780}
 781
 782fn gen_passphrase() -> String {
 783    rand::thread_rng()
 784        .sample_iter(&Alphanumeric)
 785        .take(20)
 786        .map(char::from)
 787        .collect()
 788}
 789
 790fn read_response(question: &str) -> String {
 791    println!("{question}");
 792    let mut input = String::new();
 793    let _ = std::io::stdin().read_line(&mut input);
 794    input
 795}
 796
 797fn read_yesno(question: &str) -> Option<char> {
 798    read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
 799}
 800
 801async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
 802    if settings.session_json.is_file() {
 803        let session = settings.read_session(&settings.session_json)?;
 804        worker.login(LoginStyle::SessionRestore(session.into()))?;
 805
 806        return Ok(());
 807    }
 808
 809    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
 810        let session = settings.read_session(&settings.session_json_old)?;
 811        worker.login(LoginStyle::SessionRestore(session.into()))?;
 812
 813        return Ok(());
 814    }
 815
 816    loop {
 817        let login_style =
 818            match read_response("Please select login type: [p]assword / [s]ingle sign on")
 819                .chars()
 820                .next()
 821                .map(|c| c.to_ascii_lowercase())
 822            {
 823                None | Some('p') => {
 824                    let password = rpassword::prompt_password("Password: ")?;
 825                    LoginStyle::Password(password)
 826                },
 827                Some('s') => LoginStyle::SingleSignOn,
 828                Some(_) => {
 829                    println!("Failed to login. Please enter 'p' or 's'");
 830                    continue;
 831                },
 832            };
 833
 834        match worker.login(login_style) {
 835            Ok(info) => {
 836                if let Some(msg) = info {
 837                    println!("{msg}");
 838                }
 839
 840                break;
 841            },
 842            Err(err) => {
 843                println!("Failed to login: {err}");
 844                continue;
 845            },
 846        }
 847    }
 848
 849    Ok(())
 850}
 851
 852fn print_exit<T: Display, N>(v: T) -> N {
 853    eprintln!("{v}");
 854    process::exit(2);
 855}
 856
 857// We can't access the OlmMachine directly, so write the keys to a temporary
 858// file first, and then import them later.
 859async fn check_import_keys(
 860    settings: &ApplicationSettings,
 861) -> IambResult<Option<(temp_dir::TempDir, String)>> {
 862    let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();
 863
 864    if !do_import {
 865        return Ok(None);
 866    }
 867
 868    let question = format!(
 869        "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
 870        settings.sled_dir.display()
 871    );
 872
 873    loop {
 874        match read_yesno(&question) {
 875            Some('y') => {
 876                break;
 877            },
 878            Some('n') => {
 879                return Ok(None);
 880            },
 881            Some(_) | None => {
 882                continue;
 883            },
 884        }
 885    }
 886
 887    let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
 888    let passphrase = gen_passphrase();
 889
 890    println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());
 891
 892    let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
 893        Ok(encrypted) => encrypted,
 894        Err(e) => {
 895            println!("* Failed to encrypt room keys during export: {e}");
 896            process::exit(2);
 897        },
 898    };
 899
 900    let tmpdir = TempDir::new()?;
 901    let exported = tmpdir.child("keys");
 902
 903    println!("* Writing encrypted room keys to {}...", exported.display());
 904    tokio::fs::write(&exported, &encrypted).await?;
 905
 906    Ok(Some((tmpdir, passphrase)))
 907}
 908
 909async fn login_upgrade(
 910    keydir: TempDir,
 911    passphrase: String,
 912    worker: &Requester,
 913    settings: &ApplicationSettings,
 914    store: &AsyncProgramStore,
 915) -> IambResult<()> {
 916    println!(
 917        "Please log in for {} to import the room keys into a new session",
 918        settings.profile.user_id
 919    );
 920
 921    login(worker, settings).await?;
 922
 923    println!("* Importing room keys...");
 924
 925    let exported = keydir.child("keys");
 926    let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;
 927
 928    match imported {
 929        Ok(res) => {
 930            println!(
 931                "* Successfully imported {} out of {} keys",
 932                res.imported_count, res.total_count
 933            );
 934            let _ = keydir.cleanup();
 935        },
 936        Err(e) => {
 937            println!(
 938                "Failed to import room keys from {}/keys: {e}\n\n\
 939                They have been encrypted with the passphrase {passphrase:?}.\
 940                Please save them and try importing them manually instead\n",
 941                keydir.path().display()
 942            );
 943
 944            loop {
 945                match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
 946                    Some('y') => break,
 947                    Some('n') => print_exit("* Exiting..."),
 948                    Some(_) | None => continue,
 949                }
 950            }
 951        },
 952    }
 953
 954    println!("* Syncing...");
 955    worker::do_first_sync(&worker.client, store)
 956        .await
 957        .map_err(IambError::from)?;
 958
 959    Ok(())
 960}
 961
 962async fn login_normal(
 963    worker: &Requester,
 964    settings: &ApplicationSettings,
 965    store: &AsyncProgramStore,
 966) -> IambResult<()> {
 967    println!("* Logging in for {}...", settings.profile.user_id);
 968    login(worker, settings).await?;
 969    println!("* Syncing...");
 970    worker::do_first_sync(&worker.client, store)
 971        .await
 972        .map_err(IambError::from)?;
 973    Ok(())
 974}
 975
 976/// Set up the terminal for drawing the TUI, and getting additional info.
 977fn setup_tty(settings: &ApplicationSettings, enable_enhanced_keys: bool) -> std::io::Result<()> {
 978    let title = format!("iamb ({})", settings.profile.user_id.as_str());
 979
 980    // Enable raw mode and enter the alternate screen.
 981    crossterm::terminal::enable_raw_mode()?;
 982    crossterm::execute!(stdout(), EnterAlternateScreen)?;
 983
 984    if enable_enhanced_keys {
 985        // Enable the Kitty keyboard enhancement protocol for improved keypresses.
 986        crossterm::queue!(
 987            stdout(),
 988            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
 989        )?;
 990    }
 991
 992    if settings.tunables.mouse.enabled {
 993        crossterm::execute!(stdout(), EnableMouseCapture)?;
 994    }
 995
 996    crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, SetTitle(title))
 997}
 998
 999// Do our best to reverse what we did in setup_tty() when we exit or crash.
1000fn restore_tty(enable_enhanced_keys: bool, enable_mouse: bool) {
1001    if enable_enhanced_keys {
1002        let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
1003    }
1004
1005    if enable_mouse {
1006        let _ = crossterm::queue!(stdout(), DisableMouseCapture);
1007    }
1008
1009    let _ = crossterm::execute!(
1010        stdout(),
1011        DisableBracketedPaste,
1012        DisableFocusChange,
1013        LeaveAlternateScreen,
1014        CursorShow,
1015    );
1016
1017    let _ = crossterm::terminal::disable_raw_mode();
1018}
1019
1020async fn run(settings: ApplicationSettings) -> IambResult<()> {
1021    // Get old keys the first time we run w/ the upgraded SDK.
1022    let import_keys = check_import_keys(&settings).await?;
1023
1024    // Set up client state.
1025    create_dir_all(settings.sqlite_dir.as_path())?;
1026    let client = worker::create_client(&settings).await;
1027
1028    // Set up the async worker thread and global store.
1029    let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
1030    let store = ChatStore::new(worker.clone(), settings.clone());
1031    let mut store = Store::new(store);
1032    store.completer = Box::new(IambCompleter);
1033
1034    let store = Arc::new(AsyncMutex::new(store));
1035    worker.init(store.clone());
1036
1037    let res = if let Some((keydir, pass)) = import_keys {
1038        login_upgrade(keydir, pass, &worker, &settings, &store).await
1039    } else {
1040        login_normal(&worker, &settings, &store).await
1041    };
1042
1043    match res {
1044        Err(UIError::Application(IambError::Matrix(e))) => {
1045            if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
1046                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()))
1047            } else {
1048                print_exit(e)
1049            }
1050        },
1051        Err(e) => print_exit(e),
1052        Ok(()) => (),
1053    }
1054
1055    // Set up the terminal for drawing, and cleanup properly on panics.
1056    let enable_enhanced_keys = match crossterm::terminal::supports_keyboard_enhancement() {
1057        Ok(supported) => supported,
1058        Err(e) => {
1059            tracing::warn!(err = %e,
1060               "Failed to determine whether the terminal supports keyboard enhancements");
1061            false
1062        },
1063    };
1064    setup_tty(&settings, enable_enhanced_keys)?;
1065
1066    let orig_hook = std::panic::take_hook();
1067    let enable_mouse = settings.tunables.mouse.enabled;
1068    std::panic::set_hook(Box::new(move |panic_info| {
1069        restore_tty(enable_enhanced_keys, enable_mouse);
1070        orig_hook(panic_info);
1071        process::exit(1);
1072    }));
1073
1074    // And finally, start running the terminal UI.
1075    let mut application = Application::new(settings, store).await?;
1076    application.run().await?;
1077
1078    // Clean up the terminal on exit.
1079    restore_tty(enable_enhanced_keys, enable_mouse);
1080
1081    Ok(())
1082}
1083
1084fn main() -> IambResult<()> {
1085    // Parse command-line flags.
1086    let iamb = Iamb::parse();
1087
1088    // Load configuration and set up the Matrix SDK.
1089    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
1090
1091    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
1092    #[cfg(unix)]
1093    unsafe {
1094        libc::umask(0o077);
1095    };
1096
1097    // Set up the tracing subscriber so we can log client messages.
1098    let log_prefix = format!("iamb-log-{}", settings.profile_name);
1099    let log_dir = settings.dirs.logs.as_path();
1100
1101    let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
1102    let (appender, guard) = tracing_appender::non_blocking(appender);
1103
1104    let subscriber = FmtSubscriber::builder()
1105        .with_writer(appender)
1106        .with_max_level(settings.tunables.log_level)
1107        .finish();
1108    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
1109
1110    let rt = tokio::runtime::Builder::new_multi_thread()
1111        .enable_all()
1112        .worker_threads(2)
1113        .thread_name_fn(|| {
1114            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
1115            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
1116            format!("iamb-worker-{id}")
1117        })
1118        .build()
1119        .unwrap();
1120
1121    rt.block_on(async move { run(settings).await })?;
1122
1123    drop(guard);
1124    process::exit(0);
1125}