src/main.rs

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