src/main.rs

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