src/main.rs

1288 lines · 46409 bytes

40 symbols in this file
   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::VerifyRequest(user_id) => {
 691                let Ok(user_id) = <&UserId>::try_from(user_id.as_str()) else {
 692                    return Err(IambError::InvalidUserId(user_id).into());
 693                };
 694
 695                return verifications::iamb_verify_request(user_id, store).await;
 696            },
 697            IambAction::Recover(key) => {
 698                return verifications::iamb_recover(key, store).await;
 699            },
 700        };
 701
 702        Ok(info)
 703    }
 704
 705    async fn homeserver_command(
 706        &mut self,
 707        action: HomeserverAction,
 708        ctx: ProgramContext,
 709        store: &mut ProgramStore,
 710    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
 711        match action {
 712            HomeserverAction::CreateRoom(alias, vis, flags) => {
 713                let client = &store.application.worker.client;
 714                let room_id = create_room(client, alias, vis, flags).await?;
 715                let room = IambId::Room(room_id.into(), RoomView::Main);
 716                let target = OpenTarget::Application(room);
 717                let action = WindowAction::Switch(target, OpenFlags::NONE);
 718
 719                Ok(vec![(action.into(), ctx)])
 720            },
 721            HomeserverAction::AccountSet(AccountField::Invites, perms) => {
 722                let perms = match perms.as_str() {
 723                    "allow" => None,
 724                    "block" => Some(InvitePermissionAction::Block),
 725                    perm => {
 726                        return Err(UIError::Failure(format!(
 727                            "{perm:?} is not a valid invite permission"
 728                        )));
 729                    },
 730                };
 731                let mut content = InvitePermissionConfigEventContent::new();
 732                content.default_action = perms;
 733                let _ = self
 734                    .worker
 735                    .client
 736                    .account()
 737                    .set_account_data(content)
 738                    .await
 739                    .map_err(IambError::from)?;
 740                Ok(vec![])
 741            },
 742            HomeserverAction::AccountUnset(AccountField::Invites, val) => {
 743                if let Some(val) = val {
 744                    let msg = format!("Cannot unset invites with a value (given {val:?})");
 745                    return Err(UIError::Failure(msg));
 746                }
 747
 748                let mut content = InvitePermissionConfigEventContent::new();
 749                content.default_action = None;
 750                let _ = self
 751                    .worker
 752                    .client
 753                    .account()
 754                    .set_account_data(content)
 755                    .await
 756                    .map_err(IambError::from)?;
 757                Ok(vec![])
 758            },
 759            HomeserverAction::AccountShow(AccountField::Invites) => {
 760                let resp = self
 761                    .worker
 762                    .client
 763                    .account()
 764                    .fetch_account_data_static::<InvitePermissionConfigEventContent>()
 765                    .await
 766                    .map_err(IambError::from)?;
 767                let resp = resp
 768                    .map(|r| r.deserialize())
 769                    .transpose()
 770                    .map_err(IambError::from)?
 771                    .and_then(|r| r.default_action);
 772                let action = match resp.as_ref() {
 773                    None => "allow",
 774                    Some(InvitePermissionAction::Block) => "block",
 775                    Some(other) => other.as_str(),
 776                };
 777                let msg = format!("Current default invite permission: {action}");
 778                Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)])
 779            },
 780            HomeserverAction::AccountSet(AccountField::Ignore, user) => {
 781                let Ok(user) = OwnedUserId::from_str(&user) else {
 782                    return Err(IambError::InvalidUserId(user).into());
 783                };
 784                self.worker
 785                    .client
 786                    .account()
 787                    .ignore_user(&user)
 788                    .await
 789                    .map_err(IambError::from)?;
 790                Ok(vec![])
 791            },
 792            HomeserverAction::AccountUnset(AccountField::Ignore, user) => {
 793                let Some(user) = user else {
 794                    return Err(IambError::InvalidUserId("".into()).into());
 795                };
 796                let Ok(user) = OwnedUserId::from_str(&user) else {
 797                    return Err(IambError::InvalidUserId(user).into());
 798                };
 799                self.worker
 800                    .client
 801                    .account()
 802                    .unignore_user(&user)
 803                    .await
 804                    .map_err(IambError::from)?;
 805                store.application.clear_room_cache(&self.worker.client).await?;
 806                Ok(vec![])
 807            },
 808            HomeserverAction::AccountShow(AccountField::Ignore) => {
 809                let ignored = self
 810                    .worker
 811                    .client
 812                    .account()
 813                    .account_data::<IgnoredUserListEventContent>()
 814                    .await
 815                    .map_err(IambError::from)?;
 816                let ignored_users = ignored
 817                    .map(|raw| raw.deserialize())
 818                    .transpose()
 819                    .map_err(IambError::from)?
 820                    .map(|c| c.ignored_users);
 821
 822                let msg = match ignored_users {
 823                    Some(users) if !users.is_empty() => {
 824                        let mut s = String::from("You are currently ignoring:");
 825                        users.keys().for_each(|u| {
 826                            s.push_str("\n - ");
 827                            s.push_str(u.as_ref());
 828                        });
 829                        s
 830                    },
 831                    _ => "You have no users in your ignore list.".into(),
 832                };
 833
 834                Ok(vec![(Action::ShowInfoMessage(InfoMessage::Pager(msg)), ctx)])
 835            },
 836            HomeserverAction::KnockSend(alias, reason) => {
 837                let _ = self
 838                    .worker
 839                    .client
 840                    .knock(alias, reason, vec![])
 841                    .await
 842                    .map_err(IambError::from)?;
 843                Ok(vec![])
 844            },
 845            HomeserverAction::Logout(user, true) => {
 846                self.worker.logout(user)?;
 847                let flags = CloseFlags::QUIT | CloseFlags::FORCE;
 848                let act = TabAction::Close(TabTarget::All, flags);
 849
 850                Ok(vec![(act.into(), ctx)])
 851            },
 852            HomeserverAction::Logout(user, false) => {
 853                let msg = "Would you like to logout?";
 854                let act = IambAction::from(HomeserverAction::Logout(user, true));
 855                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 856                let prompt = Box::new(prompt);
 857
 858                Err(UIError::NeedConfirm(prompt))
 859            },
 860            HomeserverAction::Forget => {
 861                let client = &store.application.worker.client;
 862                for room in client.left_rooms() {
 863                    room.forget().await.map_err(IambError::from)?;
 864                }
 865                Ok(vec![])
 866            },
 867            HomeserverAction::ProfileFieldSet(value) => {
 868                let client = &store.application.worker.client;
 869                let account = client.account();
 870                account.set_profile_field(value).await.map_err(IambError::from)?;
 871                Ok(vec![])
 872            },
 873            HomeserverAction::ProfileFieldUnset(field) => {
 874                let client = &store.application.worker.client;
 875                let account = client.account();
 876                account.delete_profile_field(field).await.map_err(IambError::from)?;
 877                Ok(vec![])
 878            },
 879            HomeserverAction::ProfileFieldShow(field) => {
 880                let client = &store.application.worker.client;
 881                let user_id = store.application.settings.user_id.clone();
 882                let account = client.account();
 883                let value = account
 884                    .fetch_profile_field_of(user_id, field.clone())
 885                    .await
 886                    .map_err(IambError::from)?;
 887
 888                let msg = match (field, value) {
 889                    (_, Some(ProfileFieldValue::DisplayName(s))) => {
 890                        format!("Your profile's display name is set to: {s}")
 891                    },
 892                    (_, Some(ProfileFieldValue::TimeZone(s))) => {
 893                        format!("Your profile's timezone is set to: {s}")
 894                    },
 895                    (_, Some(ProfileFieldValue::AvatarUrl(s))) => {
 896                        format!("Your profile's avatar URL is set to: {s}")
 897                    },
 898                    (ProfileFieldName::DisplayName, None) => {
 899                        "Your profile's display name is currently unset".into()
 900                    },
 901                    (ProfileFieldName::TimeZone, None) => {
 902                        "Your profile's timezone is currently unset".into()
 903                    },
 904                    (ProfileFieldName::AvatarUrl, None) => {
 905                        "Your profile's avatar URL is currently unset".into()
 906                    },
 907                    (f, None) => {
 908                        format!("Your profile's {f:?} is currently unset")
 909                    },
 910                    (f, Some(s)) => {
 911                        format!("Your profile's {f:?} is set to {s:?}")
 912                    },
 913                };
 914
 915                Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)])
 916            },
 917        }
 918    }
 919
 920    async fn keys_command(
 921        &mut self,
 922        action: KeysAction,
 923        _: ProgramContext,
 924        store: &mut ProgramStore,
 925    ) -> IambResult<EditInfo> {
 926        let encryption = store.application.worker.client.encryption();
 927
 928        match action {
 929            KeysAction::Export(path, passphrase) => {
 930                encryption
 931                    .export_room_keys(path.into(), &passphrase, |_| true)
 932                    .await
 933                    .map_err(IambError::from)?;
 934
 935                Ok(Some("Successfully exported room keys".into()))
 936            },
 937            KeysAction::Import(path, passphrase) => {
 938                let res = encryption
 939                    .import_room_keys(path.into(), &passphrase)
 940                    .await
 941                    .map_err(IambError::from)?;
 942
 943                let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count);
 944
 945                Ok(Some(msg.into()))
 946            },
 947        }
 948    }
 949
 950    fn handle_info(&mut self, info: InfoMessage) {
 951        match info {
 952            InfoMessage::Message(info) => {
 953                self.screen.push_message(info, self.theme.cmdbar.info);
 954            },
 955            InfoMessage::Pager(text) => {
 956                let pager = Box::new(Pager::new(text, vec![]));
 957                self.bindings.run_dialog(pager);
 958            },
 959        }
 960    }
 961
 962    fn handle_error(&mut self, err: impl ToString) {
 963        self.screen.push_message(err, self.theme.cmdbar.error);
 964    }
 965
 966    pub async fn run(&mut self) -> Result<(), std::io::Error> {
 967        self.terminal.clear()?;
 968
 969        let store = self.store.clone();
 970
 971        tracing::info!("starting main loop");
 972        while self.screen.tabs() != 0 {
 973            let key = self.step().await?;
 974
 975            self.bindings.input_key(key);
 976
 977            let mut locked = store.lock().await;
 978            let mut keyskip = false;
 979
 980            while let Some((action, ctx)) = self.action_pop(keyskip) {
 981                match self.action_run(action, ctx, locked.deref_mut()).await {
 982                    Ok(None) => {
 983                        // Continue processing.
 984                        continue;
 985                    },
 986                    Ok(Some(info)) => {
 987                        self.handle_info(info);
 988
 989                        // Continue processing; we'll redraw later.
 990                        continue;
 991                    },
 992                    Err(
 993                        UIError::NeedConfirm(dialog) |
 994                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
 995                    ) => {
 996                        self.bindings.run_dialog(dialog);
 997                        continue;
 998                    },
 999                    Err(e) => {
1000                        self.handle_error(e);
1001
1002                        // Skip processing any more keypress Actions until the next key.
1003                        keyskip = true;
1004                        continue;
1005                    },
1006                }
1007            }
1008        }
1009
1010        if let Some(ref layout) = self.last_layout {
1011            let locked = self.store.lock().await;
1012            let path = locked.application.settings.layout_json.as_path();
1013            path.parent().map(create_dir_all).transpose()?;
1014
1015            let file = File::create(path)?;
1016            let writer = BufWriter::new(file);
1017
1018            if let Err(e) = serde_json::to_writer(writer, layout) {
1019                tracing::error!("Failed to save window layout while exiting: {}", e);
1020            }
1021        }
1022
1023        return Ok(());
1024    }
1025}
1026
1027fn read_response(question: &str) -> String {
1028    println!("{question}");
1029    let mut input = String::new();
1030    let _ = std::io::stdin().read_line(&mut input);
1031    input
1032}
1033
1034async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
1035    if settings.session_json.is_file() {
1036        let session = settings.read_session(&settings.session_json)?;
1037        worker.login(LoginStyle::SessionRestore(session.into()))?;
1038        return Ok(());
1039    }
1040
1041    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
1042        let session = settings.read_session(&settings.session_json_old)?;
1043        worker.login(LoginStyle::SessionRestore(session.into()))?;
1044        return Ok(());
1045    }
1046
1047    if let Some(ref password_file) = settings.profile.password_file {
1048        if let Err(e) = std::fs::read_to_string(password_file)
1049            .map(|password| worker.login(LoginStyle::Password(password)))
1050        {
1051            println!("Failed to log in using password file {password_file:?}: {e}");
1052            println!("Continuing on to interactive login");
1053        } else {
1054            return Ok(());
1055        }
1056    }
1057
1058    loop {
1059        let login_style = match read_response(
1060            "Please select login type: [p]assword / [s]ingle sign on / [o]auth",
1061        )
1062        .chars()
1063        .next()
1064        .map(|c| c.to_ascii_lowercase())
1065        {
1066            None | Some('p') => {
1067                let password = rpassword::prompt_password("Password: ")?;
1068                LoginStyle::Password(password)
1069            },
1070            Some('s') => LoginStyle::SingleSignOn,
1071            Some('o') => LoginStyle::OAuth,
1072            Some(_) => {
1073                println!("Failed to login. Please enter 'p', 's' or 'o'");
1074                continue;
1075            },
1076        };
1077
1078        match worker.login(login_style) {
1079            Ok(info) => {
1080                if let Some(msg) = info {
1081                    println!("{msg}");
1082                }
1083
1084                break;
1085            },
1086            Err(err) => {
1087                println!("Failed to login: {err}");
1088                continue;
1089            },
1090        }
1091    }
1092
1093    Ok(())
1094}
1095
1096fn print_exit<T: Display, N>(v: T) -> N {
1097    eprintln!("{v}");
1098    process::exit(2);
1099}
1100
1101async fn login_normal(
1102    worker: &Requester,
1103    settings: &ApplicationSettings,
1104    store: &AsyncProgramStore,
1105) -> IambResult<()> {
1106    println!("* Logging in for {}...", settings.user_id);
1107    login(worker, settings).await?;
1108    println!("* Syncing...");
1109
1110    // Only subscribe after the encryption session has been restored.
1111    worker
1112        .client
1113        .event_cache()
1114        .subscribe()
1115        .expect("Failed to start event cache");
1116
1117    worker.spawn_sync()?;
1118    worker.setup_persistent_tokens();
1119    worker::do_first_sync(&worker.client, store)
1120        .await
1121        .map_err(IambError::from)?;
1122    Ok(())
1123}
1124
1125async fn run(
1126    mut settings: ApplicationSettings,
1127    initial_room: Option<(MatrixId, Vec<OwnedServerName>)>,
1128) -> IambResult<()> {
1129    // Work out whether to use the Kitty keyboard protocol before anything
1130    // clones the settings, so that every copy agrees with the flags we push in
1131    // setup_tty() and pop in restore_tty().
1132    settings.probe_enhanced_keys();
1133
1134    // Set up client state.
1135    tracing::info!("setting up client");
1136    create_dir_all(settings.sqlite_dir.as_path())?;
1137    let client = worker::create_client(&settings).await;
1138
1139    // Set up the async worker thread and global store.
1140    tracing::debug!("setting up worker");
1141    let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
1142    let store = ChatStore::new(worker.clone(), settings.clone())?;
1143    let mut store = Store::new(store);
1144    store.completer = Box::new(IambCompleter);
1145
1146    if let Some(r) = store.application.settings.tunables.default_register.as_ref() {
1147        // Set the RegisterStore to use the user's default register:
1148        store.registers.set_default_register(r.clone());
1149    }
1150
1151    tracing::debug!("initializing worker");
1152    let store = Arc::new(AsyncMutex::new(store));
1153    worker.init(store.clone());
1154
1155    tracing::info!("logging in");
1156    let res = login_normal(&worker, &settings, &store).await;
1157
1158    match res {
1159        Err(UIError::Application(IambError::Matrix(e))) => {
1160            if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
1161                print_exit(format!(
1162                    "Server did not recognize our API token; did you log out from this session elsewhere?\nTry deleting `{}` to force a clean login.",
1163                    settings.session_json.display()
1164                ))
1165            } else {
1166                print_exit(e)
1167            }
1168        },
1169        Err(e) => print_exit(e),
1170        Ok(()) => (),
1171    }
1172
1173    tracing::debug!("setting up tty");
1174    // Set up the terminal for drawing, and cleanup properly on panics.
1175    setup_tty(&settings)?;
1176
1177    let orig_hook = std::panic::take_hook();
1178    let enable_enhanced_keys = settings.enable_enhanced_keys;
1179    let enable_mouse = settings.tunables.mouse.enabled;
1180    std::panic::set_hook(Box::new(move |panic_info| {
1181        restore_tty(enable_enhanced_keys, enable_mouse);
1182        orig_hook(panic_info);
1183        process::exit(1);
1184    }));
1185
1186    // And finally, start running the terminal UI.
1187    tracing::debug!("creating application");
1188    let mut application = Application::new(settings, store, initial_room)
1189        .await
1190        .inspect_err(|_| restore_tty(enable_enhanced_keys, enable_mouse))?;
1191    application
1192        .run()
1193        .await
1194        .inspect_err(|_| restore_tty(enable_enhanced_keys, enable_mouse))?;
1195
1196    // Clean up the terminal on exit.
1197    restore_tty(enable_enhanced_keys, enable_mouse);
1198
1199    Ok(())
1200}
1201
1202fn setup_logging(settings: &ApplicationSettings) -> tracing_appender::non_blocking::WorkerGuard {
1203    let log_prefix = format!("iamb-log-{}", settings.profile_name);
1204    let log_dir = settings.dirs.logs.as_path();
1205    let max_log_files = settings.tunables.max_log_files;
1206    let log_level = &settings.tunables.log_level;
1207
1208    let appender = tracing_appender::rolling::Builder::new()
1209        .rotation(tracing_appender::rolling::Rotation::DAILY)
1210        .filename_prefix(log_prefix)
1211        .max_log_files(max_log_files)
1212        .build(log_dir)
1213        .expect("can build appending tracing logger");
1214    let (appender, guard) = tracing_appender::non_blocking(appender);
1215
1216    let filter = if let Ok(dirs) = std::env::var(EnvFilter::DEFAULT_ENV) {
1217        EnvFilter::builder()
1218            .with_default_directive(Level::WARN.into())
1219            .parse(dirs)
1220            .map_err(|err| format!("Unable to parse {}: {err}", EnvFilter::DEFAULT_ENV))
1221            .unwrap_or_else(print_exit)
1222    } else {
1223        EnvFilter::builder()
1224            .with_default_directive(LevelFilter::OFF.into())
1225            .parse(log_level)
1226            .map_err(|err| format!("Unable to parse `log_level`: {err}"))
1227            .unwrap_or_else(print_exit)
1228    };
1229
1230    let subscriber = FmtSubscriber::builder()
1231        .with_writer(appender)
1232        .with_env_filter(filter)
1233        .finish();
1234
1235    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
1236
1237    guard
1238}
1239
1240fn main() {
1241    // Parse command-line flags.
1242    let iamb = Iamb::parse();
1243
1244    if let Some(shell) = iamb.completions {
1245        clap_complete::generate(shell, &mut Iamb::command(), "iamb", &mut std::io::stdout());
1246        return;
1247    }
1248
1249    let initial_room = if let Some(uri) = &iamb.uri {
1250        MatrixUri::parse(uri)
1251            .map(|uri| (uri.id().clone(), uri.via().to_owned()))
1252            .or_else(|_| {
1253                MatrixToUri::parse(uri).map(|uri| (uri.id().clone(), uri.via().to_owned()))
1254            })
1255            .ok()
1256    } else {
1257        None
1258    };
1259
1260    // Load configuration and set up the Matrix SDK.
1261    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
1262
1263    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
1264    #[cfg(unix)]
1265    unsafe {
1266        libc::umask(0o077);
1267    };
1268
1269    let guard = setup_logging(&settings);
1270
1271    let rt = tokio::runtime::Builder::new_multi_thread()
1272        .enable_all()
1273        .worker_threads(2)
1274        .thread_name_fn(|| {
1275            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
1276            let id = ATOMIC_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1277            format!("iamb-worker-{id}")
1278        })
1279        .build()
1280        .unwrap();
1281
1282    if let Err(err) = rt.block_on(async move { run(settings, initial_room).await }) {
1283        eprintln!("\n{err}\n");
1284        process::exit(2);
1285    }
1286
1287    drop(guard);
1288}