src/main.rs

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