//! # iamb //! //! The iamb client loops over user input and commands, and turns them into actions, [some of //! which][IambAction] are specific to iamb, and [some of which][Action] come from [modalkit]. When //! adding new functionality, you will usually want to extend [`IambAction`] or one of its variants //! (like [`RoomAction`]), and then add an appropriate [command][commands] or //! [keybinding][keybindings]. //! //! For more complicated changes, you may need to update [the async worker thread][worker], which //! handles background Matrix tasks with [matrix-rust-sdk][matrix_sdk]. //! //! Most rendering logic lives under the [windows] module, but [Matrix messages][message] have //! their own module. #![recursion_limit = "256"] #![allow(clippy::manual_range_contains)] #![allow(clippy::needless_return)] #![allow(clippy::result_large_err)] #![allow(clippy::bool_assert_comparison)] use std::collections::VecDeque; use std::fs::{File, create_dir_all}; use std::io::{BufWriter, Stdout, Write, stdout}; use std::process; use std::sync::atomic::AtomicUsize; use clap::{CommandFactory, Parser}; use matrix_sdk::OwnedServerName; use matrix_sdk::ruma::api::error::ErrorKind; use matrix_sdk::ruma::events::ignored_user_list::IgnoredUserListEventContent; use matrix_sdk::ruma::events::invite_permission_config::{ InvitePermissionAction, InvitePermissionConfigEventContent, }; use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer}; use modalkit::crossterm; use modalkit::crossterm::cursor::SetCursorStyle; use modalkit::crossterm::event::{Event, KeyEventKind, MouseEventKind, poll, read}; use modalkit::editing::key::KeyManager; use modalkit::editing::store::Store; use modalkit::keybindings::dialog::Pager; use modalkit::keybindings::{BindingMachine, InputBindings}; use modalkit::ui::FocusList; use modalkit_ratatui::cmdbar::CommandBarState; use modalkit_ratatui::screen::{Screen, ScreenState, TabbedLayoutDescription}; use modalkit_ratatui::windows::{WindowLayoutDescription, WindowLayoutState}; use modalkit_ratatui::{TerminalExtOps, Window}; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; use tokio::sync::Mutex as AsyncMutex; use tracing::Level; use tracing::level_filters::LevelFilter; use tracing_subscriber::{EnvFilter, FmtSubscriber}; use crate::base::{HomeserverAction, KeysAction}; use crate::completions::IambCompleter; use crate::config::{CursorShape, Iamb}; use crate::prelude::*; use crate::util::{restore_tty, setup_tty}; use crate::windows::IambWindow; use crate::worker::{ClientWorker, LoginStyle, create_room}; mod base; mod commands; mod completions; mod config; mod keybindings; mod message; mod notifications; mod oauth; mod prelude; mod preview; mod util; mod verifications; mod windows; mod worker; #[cfg(test)] mod tests; fn config_tab_to_desc( layout: config::WindowLayout, store: &mut ProgramStore, ) -> IambResult> { let desc = match layout { config::WindowLayout::Window { window } => { let window = match window { config::WindowPath::UserId(user_id) => { if let Some(dm) = store.application.worker.client.get_dm_room(&user_id) { IambId::Room(dm.room_id().to_owned().into(), RoomView::Main) } else { let room_id = store.application.worker.create_dm(user_id)?; IambId::Room(room_id.into(), RoomView::Main) } }, config::WindowPath::RoomId(room_id) => IambId::Room(room_id.into(), RoomView::Main), config::WindowPath::AliasId(alias_id) => { IambId::Room(alias_id.into(), RoomView::Main) }, config::WindowPath::Window(id) => id, }; WindowLayoutDescription::Window { window, length: None } }, config::WindowLayout::Split { split } => { let children = split .into_iter() .map(|child| config_tab_to_desc(child, store)) .collect::>>()?; WindowLayoutDescription::Split { children, length: None } }, }; Ok(desc) } fn restore_layout( area: Rect, settings: &ApplicationSettings, store: &mut ProgramStore, ) -> IambResult>> { let layout = std::fs::read(&settings.layout_json)?; let tabs: TabbedLayoutDescription = serde_json::from_slice(&layout).map_err(IambError::from)?; tabs.to_layout(area.into(), store) } fn resolve_mxid( store: &mut ProgramStore, id: MatrixId, via: Vec, ) -> IambResult { let mut view = RoomView::Main; let alias_id = match id { MatrixId::Room(room_id) => room_id.into(), MatrixId::RoomAlias(alias) => { if let Some(room_id) = store.application.aliases.get(&alias) { room_id.to_owned().into() } else { alias.into() } }, MatrixId::User(user_id) => { if let Some(dm) = store.application.worker.client.get_dm_room(&user_id) { dm.room_id().to_owned().into() } else { store.application.worker.create_dm(user_id.to_owned())?.into() } }, MatrixId::Event(alias_id, event_id) => { view = RoomView::Message(event_id.into()); alias_id }, _ => { tracing::error!("encountered unrecoginsed matrix id: {id:?}"); return Err(UIError::Failure("Matrix link cannot be opened.".to_string())); }, }; store .application .room_via .entry(alias_id.to_owned()) .or_default() .extend(via); Ok(IambId::Room(alias_id, view)) } fn setup_screen( settings: ApplicationSettings, store: &mut ProgramStore, initial_room: Option<(MatrixId, Vec)>, ) -> IambResult> { let cmd = CommandBarState::new(store); let dims = crossterm::terminal::size()?; let area = Rect::new(0, 0, dims.0, dims.1); if let Some((id, via)) = initial_room { match resolve_mxid(store, id, via) { Ok(id) => { return Ok(ScreenState::new(IambWindow::open(id, OpenFlags::NONE, store)?, cmd)); }, Err(err) => { store.application.draw_error = Some(format!("layout restore: {err}")); }, } } match settings.layout { config::Layout::Restore => { match restore_layout(area, &settings, store) { Ok(tabs) => { return Ok(ScreenState::from_list(tabs, cmd)); }, Err(e) => { // Log the issue with restoring and then continue. tracing::warn!(err = %e, "Failed to restore layout from disk"); }, } }, config::Layout::New => {}, config::Layout::Config { tabs } => { let mut list = FocusList::default(); for tab in tabs.into_iter() { let tab = config_tab_to_desc(tab, store)?; let tab = tab.to_layout(area.into(), store)?; list.push(tab); } return Ok(ScreenState::from_list(list, cmd)); }, } let win = settings .tunables .default_room .and_then(|room| IambWindow::find(room, OpenFlags::NONE, store).ok()) .or_else(|| IambWindow::open(IambId::Welcome, OpenFlags::NONE, store).ok()) .unwrap(); return Ok(ScreenState::new(win, cmd)); } /// The main application state and event loop. struct Application { /// Terminal backend. terminal: Terminal>, /// State for the Matrix client, editing, etc. store: AsyncProgramStore, /// Clone of the currently selected theme. theme: Arc, /// UI state (open tabs, command bar, etc.) to use when rendering. screen: ScreenState, /// Handle to communicate synchronously with the Matrix worker task. worker: Requester, /// Mapped keybindings. bindings: KeyManager, /// Pending actions to run. actstack: VecDeque<(ProgramAction, ProgramContext)>, /// Whether or not the terminal is currently focused. focused: bool, /// The tab layout before the last executed [TabAction]. last_layout: Option>, /// Whether we need to do a full redraw (e.g., after running a subprocess). dirty: bool, } impl Application { pub async fn new( settings: ApplicationSettings, store: AsyncProgramStore, initial_room: Option<(MatrixId, Vec)>, ) -> IambResult { let backend = CrosstermBackend::new(stdout()); let terminal = Terminal::new(backend)?; let theme = settings.theme.clone(); let mut bindings = crate::keybindings::setup_keybindings(&settings.tunables); settings.setup(&mut bindings); let bindings = KeyManager::new(bindings); let mut locked = store.lock().await; let screen = setup_screen(settings, locked.deref_mut(), initial_room)?; let worker = locked.application.worker.clone(); drop(locked); let actstack = VecDeque::new(); Ok(Application { store, worker, terminal, theme, bindings, actstack, screen, focused: true, last_layout: None, dirty: true, }) } fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> { let bindings = &mut self.bindings; let focused = self.focused; let sstate = &mut self.screen; let term = &mut self.terminal; if store.application.ring_bell { store.application.ring_bell = term.backend_mut().write_all(&[7]).is_err(); } if let Some(err) = store.application.draw_error.take() { sstate.push_error(err); } if full { term.clear()?; } let theme = store.application.settings.theme.clone(); term.draw(|f| { let area = f.area(); let modestr = bindings.show_mode(); let cursor = bindings.get_cursor_hint(); let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize); // Don't show terminal cursor when we show a dialog. let hide_cursor = !dialogstr.is_empty(); store.application.draw_curr = Some(Instant::now()); let screen = Screen::new(store) .show_dialog(dialogstr) .show_mode(modestr) .borders(true) .border_style(theme.windows.border) .border_style_focused(theme.windows.border_focused) .border_type(theme.windows.border_line) .border_type_focused(theme.windows.border_focused_line) .cmdbar_style(theme.cmdbar.default) .cmdbar_completions_style(theme.cmdbar.completions) .cmdbar_prompt_style(theme.cmdbar.prompt) .tab_style(theme.tabs.title) .tab_style_focused(theme.tabs.title_focused) .completion_style(theme.completion.default) .completion_style_selected(theme.completion.selected) .focus(focused); f.render_stateful_widget(screen, area, sstate); if hide_cursor { return; } if let Some((cx, cy)) = sstate.get_term_cursor() { if let Some(c) = cursor.get_indicator() { let style = Style::default().fg(Color::Green); let span = Span::styled(c.to_string(), style); let para = Paragraph::new(span); let inner = Rect::new(cx, cy, 1, 1); f.render_widget(para, inner) } if store.application.settings.tunables.terminal.cursor_shape == CursorShape::Auto { let shape = match cursor.get_insert_style() { Some(InsertStyle::Insert) => CursorShape::Line, Some(InsertStyle::Replace) => CursorShape::Underline, None => CursorShape::Block, }; let _ = crossterm::execute!(stdout(), SetCursorStyle::from(shape)); } f.set_cursor_position((cx, cy)); } })?; if sstate.hide_term_cursor() { term.hide_cursor()?; } Ok(()) } async fn step(&mut self) -> Result { loop { self.redraw(self.dirty, self.store.clone().lock().await.deref_mut())?; self.dirty = false; if !poll(Duration::from_secs(1))? { // Redraw in case there's new messages to show. continue; } match read()? { Event::Key(ke) => { if ke.kind == KeyEventKind::Release { continue; } return Ok(ke.into()); }, Event::Mouse(me) => { let dir = match me.kind { MouseEventKind::ScrollUp => MoveDir2D::Up, MouseEventKind::ScrollDown => MoveDir2D::Down, MouseEventKind::ScrollLeft => MoveDir2D::Left, MouseEventKind::ScrollRight => MoveDir2D::Right, _ => continue, }; let size = ScrollSize::Cell; let style = ScrollStyle::Direction2D(dir, size, 1.into()); let ctx = ProgramContext::default(); let mut store = self.store.lock().await; match self.screen.scroll(&style, &ctx, store.deref_mut()) { Ok(None) => {}, Ok(Some(info)) => { drop(store); self.handle_info(info); }, Err(e) => { drop(store); self.handle_error(e); }, } }, Event::FocusGained => { let mut store = self.store.lock().await; store.application.focused = true; self.focused = true; }, Event::FocusLost => { let mut store = self.store.lock().await; store.application.focused = false; self.focused = false; }, Event::Resize(_, _) => { // We'll redraw for the new size next time step() is called. }, Event::Paste(s) => { let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into()); let act = EditorAction::from(act); let ctx = ProgramContext::default(); let mut store = self.store.lock().await; match self.screen.editor_command(&act, &ctx, store.deref_mut()) { Ok(None) => {}, Ok(Some(info)) => { drop(store); self.handle_info(info); }, Err(e) => { drop(store); self.handle_error(e); }, } }, } } } fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) { let mut acts = VecDeque::from(acts); acts.append(&mut self.actstack); self.actstack = acts; } fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> { if let res @ Some(_) = self.actstack.pop_front() { return res; } if keyskip { return None; } else { return self.bindings.pop(); } } async fn action_run( &mut self, action: ProgramAction, ctx: ProgramContext, store: &mut ProgramStore, ) -> IambResult { let info = match action { // Do nothing. Action::NoOp => None, Action::Editor(act) => { match self.screen.editor_command(&act, &ctx, store) { Ok(info) => info, Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => { // Switch to the right window. if let Some(winid) = content.to_window() { let open = OpenTarget::Application(winid); let open = WindowAction::Switch(open, OpenFlags::NONE); let _ = self.screen.window_command(&open, &ctx, store)?; // Run command again. self.screen.editor_command(&act, &ctx, store)? } else { return Err(EditError::WrongBuffer(content).into()); } }, Err(err) => return Err(err.into()), } }, // Simple delegations. Action::Application(act) => self.iamb_run(act, ctx, store).await?, Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?, Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?, Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?, Action::ShowInfoMessage(info) => Some(info), Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?, Action::Jump(l, dir, count) => { let count = ctx.resolve(&count); let _ = self.screen.jump(l, dir, count, &ctx)?; None }, Action::Suspend => { self.terminal.program_suspend()?; None }, // UI actions. Action::Tab(cmd) => { if let TabAction::Close(_, _) = &cmd { self.last_layout = self.screen.as_description().into(); } self.screen.tab_command(&cmd, &ctx, store)? }, Action::RedrawScreen => { self.screen.clear_message(); self.redraw(true, store)?; None }, // Actions that create more Actions. Action::Prompt(act) => { let acts = self.screen.prompt(&act, &ctx, store)?; self.action_prepend(acts); None }, Action::Command(act) => { let acts = store.application.cmds.command(&act, &ctx, &mut store.registers)?; self.action_prepend(acts); None }, Action::Repeat(rt) => { self.bindings.repeat(rt, Some(ctx)); None }, // Unimplemented. Action::KeywordLookup(_) => { // XXX: implement None }, _ => { // XXX: log unhandled actions? print message? None }, }; return Ok(info); } async fn iamb_run( &mut self, action: IambAction, ctx: ProgramContext, store: &mut ProgramStore, ) -> IambResult { if action.scribbles() { self.dirty = true; } let info = match action { IambAction::ChangeTheme(theme) => { let Some(theme) = store.application.settings.themes.get(&theme) else { let err = format!("Unknown theme: {theme:?}"); return Err(UIError::Failure(err.to_string())); }; self.dirty = true; self.theme = Arc::new(theme.clone().values()); store.application.settings.theme = self.theme.clone(); self.screen.clear_message(); None }, IambAction::ClearUnreads => { // Clear any notifications we displayed: store.application.open_notifications.clear(); for room_id in store.application.sync_info.chats() { if let Some(room) = store.application.rooms.get_mut(room_id) { room.fully_read_all( room_id.to_owned(), &store.application.worker, &store.application.settings, &mut store.application.open_notifications, ); } } None }, IambAction::ToggleScrollbackFocus => { self.screen.current_window_mut()?.focus_toggle(); None }, IambAction::Homeserver(act) => { let acts = self.homeserver_command(act, ctx, store).await?; self.action_prepend(acts); None }, IambAction::Keys(act) => self.keys_command(act, ctx, store).await?, IambAction::Message(act) => { let acts = self.screen.current_window_mut()?.message_command(act, ctx, store).await?; self.action_prepend(acts); None }, IambAction::Space(act) => { self.screen.current_window_mut()?.space_command(act, ctx, store).await? }, IambAction::Timeline(act) => { self.screen.current_window_mut()?.timeline_command(act, ctx, store).await? }, IambAction::Room(act) => { let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?; self.action_prepend(acts); None }, IambAction::Join(act) => { let acts = self.screen.current_window_mut()?.join_command(act, ctx, store).await?; self.action_prepend(acts); None }, IambAction::Send(act) => { if store.application.settings.tunables.normal_after_send { self.bindings.reset_mode(); } self.screen.current_window_mut()?.send_command(act, ctx, store).await? }, IambAction::OpenLink(url) => { let matrix_uri = MatrixUri::parse(&url).ok(); let matrix_to_uri = MatrixToUri::parse(&url).ok(); let matrix_id = matrix_uri .as_ref() .map(|uri| (uri.id(), uri.via())) .or(matrix_to_uri.as_ref().map(|uri| (uri.id(), uri.via()))); if let Some((id, via)) = matrix_id { match resolve_mxid(store, id.to_owned(), via.to_vec()) { Ok(id) => { let target = OpenTarget::Application(id); let action = WindowAction::Switch(target, OpenFlags::NONE); self.action_prepend(vec![(action.into(), ctx)]); None }, Err(err) => return Err(UIError::Failure(err.to_string())), } } else { tokio::task::spawn_blocking(move || open::that(url)); None } }, IambAction::Verify(act, flow_id) => { return verifications::iamb_verify(act, flow_id, store).await; }, IambAction::VerifyUser(act, user_id) => { return verifications::iamb_verify_user(act, &user_id, store).await; }, IambAction::Recover(key) => { return verifications::iamb_recover(key, store).await; }, }; Ok(info) } async fn homeserver_command( &mut self, action: HomeserverAction, ctx: ProgramContext, store: &mut ProgramStore, ) -> IambResult, ProgramContext)>> { match action { HomeserverAction::CreateRoom(alias, vis, flags) => { let client = &store.application.worker.client; let room_id = create_room(client, alias, vis, flags).await?; let room = IambId::Room(room_id.into(), RoomView::Main); let target = OpenTarget::Application(room); let action = WindowAction::Switch(target, OpenFlags::NONE); Ok(vec![(action.into(), ctx)]) }, HomeserverAction::AccountSet(AccountField::Invites, perms) => { let perms = match perms.as_str() { "allow" => None, "block" => Some(InvitePermissionAction::Block), perm => { return Err(UIError::Failure(format!( "{perm:?} is not a valid invite permission" ))); }, }; let mut content = InvitePermissionConfigEventContent::new(); content.default_action = perms; let _ = self .worker .client .account() .set_account_data(content) .await .map_err(IambError::from)?; Ok(vec![]) }, HomeserverAction::AccountUnset(AccountField::Invites, val) => { if let Some(val) = val { let msg = format!("Cannot unset invites with a value (given {val:?})"); return Err(UIError::Failure(msg)); } let mut content = InvitePermissionConfigEventContent::new(); content.default_action = None; let _ = self .worker .client .account() .set_account_data(content) .await .map_err(IambError::from)?; Ok(vec![]) }, HomeserverAction::AccountShow(AccountField::Invites) => { let resp = self .worker .client .account() .fetch_account_data_static::() .await .map_err(IambError::from)?; let resp = resp .map(|r| r.deserialize()) .transpose() .map_err(IambError::from)? .and_then(|r| r.default_action); let action = match resp.as_ref() { None => "allow", Some(InvitePermissionAction::Block) => "block", Some(other) => other.as_str(), }; let msg = format!("Current default invite permission: {action}"); Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]) }, HomeserverAction::AccountSet(AccountField::Ignore, user) => { let Ok(user) = OwnedUserId::from_str(&user) else { return Err(IambError::InvalidUserId(user).into()); }; self.worker .client .account() .ignore_user(&user) .await .map_err(IambError::from)?; Ok(vec![]) }, HomeserverAction::AccountUnset(AccountField::Ignore, user) => { let Some(user) = user else { return Err(IambError::InvalidUserId("".into()).into()); }; let Ok(user) = OwnedUserId::from_str(&user) else { return Err(IambError::InvalidUserId(user).into()); }; self.worker .client .account() .unignore_user(&user) .await .map_err(IambError::from)?; store.application.clear_room_cache(&self.worker.client).await?; Ok(vec![]) }, HomeserverAction::AccountShow(AccountField::Ignore) => { let ignored = self .worker .client .account() .account_data::() .await .map_err(IambError::from)?; let ignored_users = ignored .map(|raw| raw.deserialize()) .transpose() .map_err(IambError::from)? .map(|c| c.ignored_users); let msg = match ignored_users { Some(users) if !users.is_empty() => { let mut s = String::from("You are currently ignoring:"); users.keys().for_each(|u| { s.push_str("\n - "); s.push_str(u.as_ref()); }); s }, _ => "You have no users in your ignore list.".into(), }; Ok(vec![(Action::ShowInfoMessage(InfoMessage::Pager(msg)), ctx)]) }, HomeserverAction::KnockSend(alias, reason) => { let _ = self .worker .client .knock(alias, reason, vec![]) .await .map_err(IambError::from)?; Ok(vec![]) }, HomeserverAction::Logout(user, true) => { self.worker.logout(user)?; let flags = CloseFlags::QUIT | CloseFlags::FORCE; let act = TabAction::Close(TabTarget::All, flags); Ok(vec![(act.into(), ctx)]) }, HomeserverAction::Logout(user, false) => { let msg = "Would you like to logout?"; let act = IambAction::from(HomeserverAction::Logout(user, true)); let prompt = PromptYesNo::new(msg, vec![Action::from(act)]); let prompt = Box::new(prompt); Err(UIError::NeedConfirm(prompt)) }, HomeserverAction::Forget => { let client = &store.application.worker.client; for room in client.left_rooms() { room.forget().await.map_err(IambError::from)?; } Ok(vec![]) }, HomeserverAction::ProfileFieldSet(value) => { let client = &store.application.worker.client; let account = client.account(); account.set_profile_field(value).await.map_err(IambError::from)?; Ok(vec![]) }, HomeserverAction::ProfileFieldUnset(field) => { let client = &store.application.worker.client; let account = client.account(); account.delete_profile_field(field).await.map_err(IambError::from)?; Ok(vec![]) }, HomeserverAction::ProfileFieldShow(field) => { let client = &store.application.worker.client; let user_id = store.application.settings.user_id.clone(); let account = client.account(); let value = account .fetch_profile_field_of(user_id, field.clone()) .await .map_err(IambError::from)?; let msg = match (field, value) { (_, Some(ProfileFieldValue::DisplayName(s))) => { format!("Your profile's display name is set to: {s}") }, (_, Some(ProfileFieldValue::TimeZone(s))) => { format!("Your profile's timezone is set to: {s}") }, (_, Some(ProfileFieldValue::AvatarUrl(s))) => { format!("Your profile's avatar URL is set to: {s}") }, (ProfileFieldName::DisplayName, None) => { "Your profile's display name is currently unset".into() }, (ProfileFieldName::TimeZone, None) => { "Your profile's timezone is currently unset".into() }, (ProfileFieldName::AvatarUrl, None) => { "Your profile's avatar URL is currently unset".into() }, (f, None) => { format!("Your profile's {f:?} is currently unset") }, (f, Some(s)) => { format!("Your profile's {f:?} is set to {s:?}") }, }; Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]) }, } } async fn keys_command( &mut self, action: KeysAction, _: ProgramContext, store: &mut ProgramStore, ) -> IambResult { let encryption = store.application.worker.client.encryption(); match action { KeysAction::Export(path, passphrase) => { encryption .export_room_keys(path.into(), &passphrase, |_| true) .await .map_err(IambError::from)?; Ok(Some("Successfully exported room keys".into())) }, KeysAction::Import(path, passphrase) => { let res = encryption .import_room_keys(path.into(), &passphrase) .await .map_err(IambError::from)?; let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count); Ok(Some(msg.into())) }, } } fn handle_info(&mut self, info: InfoMessage) { match info { InfoMessage::Message(info) => { self.screen.push_message(info, self.theme.cmdbar.info); }, InfoMessage::Pager(text) => { let pager = Box::new(Pager::new(text, vec![])); self.bindings.run_dialog(pager); }, } } fn handle_error(&mut self, err: impl ToString) { self.screen.push_message(err, self.theme.cmdbar.error); } pub async fn run(&mut self) -> Result<(), std::io::Error> { self.terminal.clear()?; let store = self.store.clone(); tracing::info!("starting main loop"); while self.screen.tabs() != 0 { let key = self.step().await?; self.bindings.input_key(key); let mut locked = store.lock().await; let mut keyskip = false; while let Some((action, ctx)) = self.action_pop(keyskip) { match self.action_run(action, ctx, locked.deref_mut()).await { Ok(None) => { // Continue processing. continue; }, Ok(Some(info)) => { self.handle_info(info); // Continue processing; we'll redraw later. continue; }, Err( UIError::NeedConfirm(dialog) | UIError::EditingFailure(EditError::NeedConfirm(dialog)), ) => { self.bindings.run_dialog(dialog); continue; }, Err(e) => { self.handle_error(e); // Skip processing any more keypress Actions until the next key. keyskip = true; continue; }, } } } if let Some(ref layout) = self.last_layout { let locked = self.store.lock().await; let path = locked.application.settings.layout_json.as_path(); path.parent().map(create_dir_all).transpose()?; let file = File::create(path)?; let writer = BufWriter::new(file); if let Err(e) = serde_json::to_writer(writer, layout) { tracing::error!("Failed to save window layout while exiting: {}", e); } } return Ok(()); } } fn read_response(question: &str) -> String { println!("{question}"); let mut input = String::new(); let _ = std::io::stdin().read_line(&mut input); input } async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> { if settings.session_json.is_file() { let session = settings.read_session(&settings.session_json)?; worker.login(LoginStyle::SessionRestore(session.into()))?; return Ok(()); } if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() { let session = settings.read_session(&settings.session_json_old)?; worker.login(LoginStyle::SessionRestore(session.into()))?; return Ok(()); } if let Some(ref password_file) = settings.profile.password_file { if let Err(e) = std::fs::read_to_string(password_file) .map(|password| worker.login(LoginStyle::Password(password))) { println!("Failed to log in using password file {password_file:?}: {e}"); println!("Continuing on to interactive login"); } else { return Ok(()); } } loop { let login_style = match read_response( "Please select login type: [p]assword / [s]ingle sign on / [o]auth", ) .chars() .next() .map(|c| c.to_ascii_lowercase()) { None | Some('p') => { let password = rpassword::prompt_password("Password: ")?; LoginStyle::Password(password) }, Some('s') => LoginStyle::SingleSignOn, Some('o') => LoginStyle::OAuth, Some(_) => { println!("Failed to login. Please enter 'p', 's' or 'o'"); continue; }, }; match worker.login(login_style) { Ok(info) => { if let Some(msg) = info { println!("{msg}"); } break; }, Err(err) => { println!("Failed to login: {err}"); continue; }, } } Ok(()) } fn print_exit(v: T) -> N { eprintln!("{v}"); process::exit(2); } async fn login_normal( worker: &Requester, settings: &ApplicationSettings, store: &AsyncProgramStore, ) -> IambResult<()> { println!("* Logging in for {}...", settings.user_id); login(worker, settings).await?; println!("* Syncing..."); // Only subscribe after the encryption session has been restored. worker .client .event_cache() .subscribe() .expect("Failed to start event cache"); worker.spawn_sync()?; worker.setup_persistent_tokens(); worker::do_first_sync(&worker.client, store) .await .map_err(IambError::from)?; Ok(()) } async fn run( mut settings: ApplicationSettings, initial_room: Option<(MatrixId, Vec)>, ) -> IambResult<()> { // Work out whether to use the Kitty keyboard protocol before anything // clones the settings, so that every copy agrees with the flags we push in // setup_tty() and pop in restore_tty(). settings.probe_enhanced_keys(); // Set up client state. tracing::info!("setting up client"); create_dir_all(settings.sqlite_dir.as_path())?; let client = worker::create_client(&settings).await; // Set up the async worker thread and global store. tracing::debug!("setting up worker"); let worker = ClientWorker::spawn(client.clone(), settings.clone()).await; let store = ChatStore::new(worker.clone(), settings.clone())?; let mut store = Store::new(store); store.completer = Box::new(IambCompleter); if let Some(r) = store.application.settings.tunables.default_register.as_ref() { // Set the RegisterStore to use the user's default register: store.registers.set_default_register(r.clone()); } tracing::debug!("initializing worker"); let store = Arc::new(AsyncMutex::new(store)); worker.init(store.clone()); tracing::info!("logging in"); let res = login_normal(&worker, &settings, &store).await; match res { Err(UIError::Application(IambError::Matrix(e))) => { if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() { print_exit(format!( "Server did not recognize our API token; did you log out from this session elsewhere?\nTry deleting `{}` to force a clean login.", settings.session_json.display() )) } else { print_exit(e) } }, Err(e) => print_exit(e), Ok(()) => (), } tracing::debug!("setting up tty"); // Set up the terminal for drawing, and cleanup properly on panics. setup_tty(&settings)?; let orig_hook = std::panic::take_hook(); let enable_enhanced_keys = settings.enable_enhanced_keys; let enable_mouse = settings.tunables.mouse.enabled; std::panic::set_hook(Box::new(move |panic_info| { restore_tty(enable_enhanced_keys, enable_mouse); orig_hook(panic_info); process::exit(1); })); // And finally, start running the terminal UI. tracing::debug!("creating application"); let mut application = Application::new(settings, store, initial_room) .await .inspect_err(|_| restore_tty(enable_enhanced_keys, enable_mouse))?; application .run() .await .inspect_err(|_| restore_tty(enable_enhanced_keys, enable_mouse))?; // Clean up the terminal on exit. restore_tty(enable_enhanced_keys, enable_mouse); Ok(()) } fn setup_logging(settings: &ApplicationSettings) -> tracing_appender::non_blocking::WorkerGuard { let log_prefix = format!("iamb-log-{}", settings.profile_name); let log_dir = settings.dirs.logs.as_path(); let max_log_files = settings.tunables.max_log_files; let log_level = &settings.tunables.log_level; let appender = tracing_appender::rolling::Builder::new() .rotation(tracing_appender::rolling::Rotation::DAILY) .filename_prefix(log_prefix) .max_log_files(max_log_files) .build(log_dir) .expect("can build appending tracing logger"); let (appender, guard) = tracing_appender::non_blocking(appender); let filter = if let Ok(dirs) = std::env::var(EnvFilter::DEFAULT_ENV) { EnvFilter::builder() .with_default_directive(Level::WARN.into()) .parse(dirs) .map_err(|err| format!("Unable to parse {}: {err}", EnvFilter::DEFAULT_ENV)) .unwrap_or_else(print_exit) } else { EnvFilter::builder() .with_default_directive(LevelFilter::OFF.into()) .parse(log_level) .map_err(|err| format!("Unable to parse `log_level`: {err}")) .unwrap_or_else(print_exit) }; let subscriber = FmtSubscriber::builder() .with_writer(appender) .with_env_filter(filter) .finish(); tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); guard } fn main() { // Parse command-line flags. let iamb = Iamb::parse(); if let Some(shell) = iamb.completions { clap_complete::generate(shell, &mut Iamb::command(), "iamb", &mut std::io::stdout()); return; } let initial_room = if let Some(uri) = &iamb.uri { MatrixUri::parse(uri) .map(|uri| (uri.id().clone(), uri.via().to_owned())) .or_else(|_| { MatrixToUri::parse(uri).map(|uri| (uri.id().clone(), uri.via().to_owned())) }) .ok() } else { None }; // Load configuration and set up the Matrix SDK. let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit); // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user. #[cfg(unix)] unsafe { libc::umask(0o077); }; let guard = setup_logging(&settings); let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .worker_threads(2) .thread_name_fn(|| { static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0); let id = ATOMIC_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst); format!("iamb-worker-{id}") }) .build() .unwrap(); if let Err(err) = rt.block_on(async move { run(settings, initial_room).await }) { eprintln!("\n{err}\n"); process::exit(2); } drop(guard); }