src/main.rs

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