src/main.rs

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