//! # Logic for loading and validating application configuration use std::collections::HashSet; use std::env; use std::fs::File; use std::io::{BufReader, BufWriter, Write as _}; use std::process; use std::sync::Arc; use anyhow::anyhow; use chrono::format::{Item, StrftimeItems}; use chrono::{DateTime, Local}; use clap::Parser; use indexmap::IndexMap; use lazy_static::lazy_static; use matrix_sdk::authentication::matrix::MatrixSession; use matrix_sdk::authentication::oauth::{ClientId, OAuthSession, UserSession}; use matrix_sdk::media::MediaRetentionPolicy; use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue}; use matrix_sdk::ruma::{DeviceId, OwnedDeviceId, owned_server_name}; use matrix_sdk::{AuthSession, EncryptionState, SessionMeta, SessionTokens}; use modalkit::crossterm; use modalkit::editing::completion::CompletionMap; use modalkit::env::vim::VimMode; use modalkit::keybindings::InputKey; use ratatui_image::FilterType; use ratatui_image::picker::ProtocolType; use serde::de::Error as SerdeError; use serde::de::Visitor; use serde::{Deserialize, Deserializer, Serialize}; use crate::base::{SortColumn, SortFieldRoom, SortFieldSpace, SortFieldUser, SortOrder}; use crate::prelude::*; pub mod theme; pub type Aliases = IndexMap; type Macros = HashMap>; macro_rules! usage { ( $($args: tt)* ) => { println!($($args)*); process::exit(2); } } lazy_static! { pub static ref DEFAULT_VIA_SERVER: OwnedServerName = owned_server_name!("matrix.org"); } const DEFAULT_MEMBERS_SORT: [SortColumn; 4] = [ SortColumn(SortFieldUser::PowerLevel, SortOrder::Ascending), SortColumn(SortFieldUser::Knock, SortOrder::Ascending), SortColumn(SortFieldUser::Invite, SortOrder::Descending), SortColumn(SortFieldUser::UserId, SortOrder::Ascending), ]; const DEFAULT_ROOM_SORT: [SortColumn; 10] = [ SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending), SortColumn(SortFieldRoom::Invite, SortOrder::Ascending), SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending), SortColumn(SortFieldRoom::Mentions, SortOrder::Ascending), SortColumn(SortFieldRoom::Notifications, SortOrder::Ascending), SortColumn(SortFieldRoom::Joined, SortOrder::Ascending), SortColumn(SortFieldRoom::Space, SortOrder::Ascending), SortColumn(SortFieldRoom::Direct, SortOrder::Ascending), SortColumn(SortFieldRoom::Recent, SortOrder::Ascending), SortColumn(SortFieldRoom::Name, SortOrder::Ascending), ]; const DEFAULT_SPACE_SORT: [SortColumn; 3] = [ SortColumn(SortFieldSpace::Room(SortFieldRoom::Space), SortOrder::Ascending), SortColumn(SortFieldSpace::Room(SortFieldRoom::Joined), SortOrder::Ascending), SortColumn(SortFieldSpace::SpaceOrder, SortOrder::Ascending), ]; const DEFAULT_ROOM_LABELS: [RoomLabel; 5] = [ RoomLabel::Unread, RoomLabel::Membership, RoomLabel::Tags, RoomLabel::Muted, RoomLabel::Type, ]; const DEFAULT_ENABLE_TITLE: bool = true; const DEFAULT_REQ_TIMEOUT: u64 = 120; const DEFAULT_SYNC_FREQUENCY: u64 = 250; const DEFAULT_ENC_INDICATOR_LOC: EncryptionIndicatorLocation = EncryptionIndicatorLocation::PROMPT; const DEFAULT_ICON_ENC: Cow<'static, str> = Cow::Borrowed("[E] "); const DEFAULT_ICON_UNENC: Cow<'static, str> = Cow::Borrowed("[U] "); const DEFAULT_ICON_UNKNOWN: Cow<'static, str> = Cow::Borrowed("[?] "); const DEFAULT_LOG_LEVEL: &str = "off"; /// Default date separator, matching the historical hard-coded `"%A, %B %d %Y"`. const DEFAULT_DATE_FORMAT: &str = "%A, %B %d %Y"; /// Default time gutter, preserving the historical ` [HH:MM:SS]` rendering. const DEFAULT_TIME_FORMAT: &str = " [%T]"; /// Unix seconds of the timestamp used to measure time-gutter width. /// /// 2024-01-17 13:25:30 UTC, so numeric fields have their usual widths. const TIME_GUTTER_SAMPLE_UNIX: i64 = 1_705_497_930; fn time_gutter_sample() -> DateTime { DateTime::from_timestamp(TIME_GUTTER_SAMPLE_UNIX, 0) .unwrap_or_default() .with_timezone(&Local) } /// Display columns reserved for the per-message time gutter. /// /// The width is the display width of `format` applied to one fixed sample /// timestamp, so a configuration keeps a constant column. An empty format /// reserves nothing and hides the time. pub fn time_gutter_width(format: &str) -> usize { if format.is_empty() { return 0; } let rendered = time_gutter_sample().format(format).to_string(); UnicodeWidthStr::width(rendered.as_str()) } fn is_profile_char(c: char) -> bool { c.is_ascii_alphanumeric() || c == '.' || c == '-' } fn default_true() -> bool { true } fn validate_profile_name(name: &str) -> bool { if name.is_empty() { return false; } let mut chars = name.chars(); if !chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) { return false; } name.chars().all(is_profile_char) } fn validate_profile_names(names: &BTreeMap) { for name in names.keys() { if validate_profile_name(name.as_str()) { continue; } usage!( "{:?} is not a valid profile name.\n\n\ Profile names can only contain the characters \ a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.", name ); } } fn deserialize_from_str_opt<'de, D, T>(deserializer: D) -> Result, D::Error> where D: serde::de::Deserializer<'de>, T: FromStr, ::Err: fmt::Display, { >::deserialize(deserializer)? .map(|s| { let t = T::from_str(s); t.map_err(|e| D::Error::custom(format!("failed to parse string: {e}"))) }) .transpose() } fn deserialize_register<'de, D>(deserializer: D) -> Result, D::Error> where D: serde::de::Deserializer<'de>, { let r = String::deserialize(deserializer)?; if r.len() > 1 { return Err(D::Error::custom("expected a single character to specify a register")); } let r = match r.chars().next() { Some(c @ 'a'..='z') => Register::Named(c), Some('_') => Register::Blackhole, Some('*') => Register::SelectionPrimary, Some('+') => Register::SelectionClipboard, Some('"') => Register::Unnamed, Some(c) => { return Err(D::Error::custom(format!( "expected one of a-z, \", _, *, or + for the register, not {c:?}" ))); }, None => { return Err(D::Error::custom("expected a single character to specify a register")); }, }; Ok(Some(r)) } fn deserialize_strftime<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { let value = String::deserialize(deserializer)?; // `DelayedFormat`'s `Display` impl returns `fmt::Error` for a bad specifier, // and `.to_string()` then panics. Reject those strings while loading config. if StrftimeItems::new(&value).any(|item| matches!(item, Item::Error)) { return Err(D::Error::custom(format!("invalid strftime format string: {value:?}"))); } Ok(Some(value)) } /// Load themes from disk, and merge in the configured overrides. fn load_themes( themes_dir: &Path, theme_overrides: theme::Theme, ) -> anyhow::Result> { let mut themes = CompletionMap::default(); let mut insert = |n, t| { let theme = theme_overrides.clone().merge(t).merge(theme::default_theme()); themes.insert(n, theme); }; let mut load_dir = |d: &Path| -> anyhow::Result<()> { theme::find_themes(d)?.into_iter().for_each(|(n, t)| insert(n, t)); Ok(()) }; // Load themes from the shared directory first for systems with XDG_DATA_DIRS: #[cfg(any(unix, target_os = "redox"))] xdg::BaseDirectories::new() .get_data_dirs() .into_iter() .map(|p| p.join("iamb/themes")) .try_for_each(|p| load_dir(&p))?; // Load from the `themes` directory in the user's configuration directory: load_dir(themes_dir)?; // Insert a default theme that defaults to using terminal colors: let default_theme = theme_overrides.clone().merge(theme::default_theme()); themes.insert("default".into(), default_theme); Ok(themes) } struct IambVersion; impl From for clap::builder::Str { fn from(_: IambVersion) -> Self { let version: Cow<'static, str> = match option_env!("VERGEN_GIT_SHA") { None => env!("CARGO_PKG_VERSION").into(), Some(sha) => format!("{} ({sha})", env!("CARGO_PKG_VERSION")).into(), }; version.into() } } #[derive(Parser)] #[clap(version = IambVersion, about, long_about = None)] #[clap(propagate_version = true)] pub struct Iamb { #[clap(long, value_parser)] pub completions: Option, #[clap(short = 'P', long, value_parser)] pub profile: Option, #[clap(short = 'C', long, value_parser)] pub config_directory: Option, /// `matrix:` uri or `https://matrix.to` link to open pub uri: Option, } #[derive(thiserror::Error, Debug)] pub enum ConfigError { #[error("Error reading configuration file: {0}")] IO(#[from] std::io::Error), #[error("Error loading configuration file: {0}")] Invalid(#[from] toml::de::Error), #[error("Error loading JSON configuration file: {0}")] InvalidJSON(#[from] serde_json::Error), } macro_rules! deserialize_str_with_visitor { ($t: ident, $v: ident) => { impl<'de> Deserialize<'de> for $t { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_str($v) } } }; } deserialize_str_with_visitor!(Keys, KeysVisitor); deserialize_str_with_visitor!(VimModes, VimModesVisitor); deserialize_str_with_visitor!(EncryptionIndicatorLocation, EncryptionIndicatorLocationVisitor); deserialize_str_with_visitor!(NotifyVia, NotifyViaVisitor); deserialize_str_with_visitor!(ProxyUrl, ProxyUrlVisitor); #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Keys(pub Vec, pub String); pub struct KeysVisitor; impl Visitor<'_> for KeysVisitor { type Value = Keys; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")") } fn visit_str(self, value: &str) -> Result where E: SerdeError, { match TerminalKey::from_macro_str(value) { Ok(keys) => Ok(Keys(keys, value.to_string())), Err(e) => Err(E::custom(format!("Could not parse key sequence: {e}"))), } } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct VimModes(pub Vec); pub struct VimModesVisitor; impl Visitor<'_> for VimModesVisitor { type Value = VimModes; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")") } fn visit_str(self, value: &str) -> Result where E: SerdeError, { let mut modes = vec![]; for mode in value.split('|') { let mode = match mode.to_ascii_lowercase().as_str() { "insert" | "i" => VimMode::Insert, "normal" | "n" => VimMode::Normal, "visual" | "v" => VimMode::Visual, "command" | "c" => VimMode::Command, "select" => VimMode::Select, "operator-pending" => VimMode::OperationPending, _ => return Err(E::custom("Could not parse into a Vim mode")), }; modes.push(mode); } Ok(VimModes(modes)) } } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct Session { access_token: String, refresh_token: Option, user_id: OwnedUserId, device_id: OwnedDeviceId, #[serde(skip_serializing_if = "Option::is_none")] client_id: Option, } impl From for AuthSession { fn from(session: Session) -> Self { if let Some(client_id) = session.client_id { AuthSession::OAuth(Box::new(OAuthSession { client_id, user: UserSession { meta: SessionMeta { user_id: session.user_id, device_id: session.device_id, }, tokens: SessionTokens { access_token: session.access_token, refresh_token: session.refresh_token, }, }, })) } else { AuthSession::Matrix(session.into()) } } } /// A device ID saved at logout so that the next login can reuse it. /// /// The SDK store is keyed by user and device ID, so logging back in with /// a freshly issued device ID would leave the existing store unusable /// (#775). Saving the ID lets the next login ask the homeserver for the /// same device and keep using that store. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum SavedDevice { OAuth { user_id: OwnedUserId, device_id: OwnedDeviceId, client_id: ClientId, }, MatrixAuth { user_id: OwnedUserId, device_id: OwnedDeviceId, }, } impl SavedDevice { pub fn device_id(&self) -> &DeviceId { match self { SavedDevice::OAuth { device_id, .. } => device_id, SavedDevice::MatrixAuth { device_id, .. } => device_id, } } pub fn client_id(&self) -> Option<&ClientId> { match self { SavedDevice::OAuth { client_id, .. } => Some(client_id), SavedDevice::MatrixAuth { .. } => None, } } pub fn is_user(&self, user: &UserId) -> bool { match self { SavedDevice::OAuth { user_id, .. } => user == user_id, SavedDevice::MatrixAuth { user_id, .. } => user == user_id, } } } impl From for MatrixSession { fn from(session: Session) -> Self { MatrixSession { tokens: matrix_sdk::authentication::SessionTokens { access_token: session.access_token, refresh_token: session.refresh_token, }, meta: matrix_sdk::SessionMeta { user_id: session.user_id, device_id: session.device_id, }, } } } impl From for Session { fn from(session: MatrixSession) -> Self { Session { access_token: session.tokens.access_token, refresh_token: session.tokens.refresh_token, user_id: session.meta.user_id, device_id: session.meta.device_id, client_id: None, } } } impl From for Session { fn from(session: OAuthSession) -> Self { Session { access_token: session.user.tokens.access_token, refresh_token: session.user.tokens.refresh_token, user_id: session.user.meta.user_id, device_id: session.user.meta.device_id, client_id: Some(session.client_id), } } } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] pub struct UserDisplayTunables { pub color: Option, pub name: Option, } pub type UserOverrides = HashMap; fn merge_maps(profile: Option, global: Option) -> Option where M: Extend<(K, V)> + IntoIterator, { match (global, profile) { (Some(m), None) | (None, Some(m)) => Some(m), (Some(mut global), Some(profile)) => { global.extend(profile); Some(global) }, (None, None) => None, } } #[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] #[repr(u8)] pub enum ReadReceiptTrigger { /// Update read receipts for a room when a window for it is focused, and it is scrolled to the /// last message. #[default] Focused, /// Update read receipts for a room when a window for it is visible, and it is scrolled to the /// last message. Visible, /// Update read receipts for a room whenever some portion of its scrollback is rendered. Scrollback, /// Update read receipts for a room once the user sends a message to it. Message, } impl ReadReceiptTrigger { /// Whether to update read receipts when a room is being rendered. pub fn on_render(&self, last_visible: bool, room_focused: bool) -> bool { match self { Self::Scrollback => true, Self::Focused => last_visible && room_focused, Self::Visible => last_visible, Self::Message => false, } } pub fn on_message(&self) -> bool { matches!(self, Self::Message) } } #[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] #[repr(u8)] pub enum EncryptionIndicator { /// Always indicate the room's encryption status. #[default] Enabled, /// Never indicate the room's encryption status. Disabled, /// Only indicate the room's encryption status when it is encrypted. OnlyEncrypted, /// Only indicate the room's encryption status when it is unencrypted. OnlyUnencrypted, } bitflags::bitflags! { /// Available options for where to show the encryption status indicator. #[derive(Clone, Debug, Eq, PartialEq)] pub struct EncryptionIndicatorLocation: u8 { const NONE = 0b00000000; const TITLE = 0b00000001; const PROMPT = 0b00000010; } } pub struct EncryptionIndicatorLocationVisitor; impl Visitor<'_> for EncryptionIndicatorLocationVisitor { type Value = EncryptionIndicatorLocation; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid encryption indicator location (e.g. \"title\" or \"prompt\")") } fn visit_str(self, value: &str) -> Result where E: SerdeError, { let mut location = EncryptionIndicatorLocation::NONE; for value in value.split('|') { match value.to_ascii_lowercase().as_str() { "title" => location |= EncryptionIndicatorLocation::TITLE, "prompt" => location |= EncryptionIndicatorLocation::PROMPT, _ => { return Err(E::custom("could not parse into an encryption indicator location")); }, }; } Ok(location) } } /// Types of room labels to display in room lists. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] #[repr(u8)] pub enum RoomLabel { Membership, Muted, Tags, Type, Unread, } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum UserDisplayStyle { // The Matrix username for the sender (e.g., "@user:example.com"). #[default] Username, // The localpart of the Matrix username (e.g., "@user"). LocalPart, // The display name for the Matrix user, calculated according to the rules from the spec. // // This is usually something like "Ada Lovelace" if the user has configured a display name, but // it can wind up being the Matrix username if there are display name collisions in the room, // in order to avoid any confusion. DisplayName, } #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum SplitDirection { #[default] Horizontal, Vertical, } impl From for Axis { fn from(dir: SplitDirection) -> Axis { match dir { SplitDirection::Horizontal => Axis::Horizontal, SplitDirection::Vertical => Axis::Vertical, } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct NotifyVia { /// Deliver notifications via terminal bell. pub bell: bool, /// Deliver notifications via desktop mechanism. #[cfg(feature = "desktop")] pub desktop: bool, } pub struct NotifyViaVisitor; impl Default for NotifyVia { fn default() -> Self { Self { bell: cfg!(not(feature = "desktop")), #[cfg(feature = "desktop")] desktop: true, } } } impl Visitor<'_> for NotifyViaVisitor { type Value = NotifyVia; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid notify destination (e.g. \"bell\" or \"desktop\")") } fn visit_str(self, value: &str) -> Result where E: SerdeError, { let mut via = NotifyVia { bell: false, #[cfg(feature = "desktop")] desktop: false, }; for value in value.split('|') { match value.to_ascii_lowercase().as_str() { "bell" => { via.bell = true; }, #[cfg(feature = "desktop")] "desktop" => { via.desktop = true; }, #[cfg(not(feature = "desktop"))] "desktop" => { return Err(E::custom("desktop notification support was compiled out")); }, _ => return Err(E::custom("could not parse into a notify destination")), }; } Ok(via) } } #[derive(Clone, Debug, Default, Deserialize)] pub struct Encryption { indicator: Option, indicator_location: Option, icon_encrypted: Option, icon_unencrypted: Option, icon_unknown: Option, } impl Encryption { fn merge(profile: Self, global: Self) -> Self { Encryption { indicator: profile.indicator.or(global.indicator), indicator_location: profile.indicator_location.or(global.indicator_location), icon_encrypted: profile.icon_encrypted.or(global.icon_encrypted), icon_unencrypted: profile.icon_unencrypted.or(global.icon_unencrypted), icon_unknown: profile.icon_unknown.or(global.icon_unknown), } } pub fn values(self) -> EncryptionValues { EncryptionValues { indicator: self.indicator.unwrap_or_default(), indicator_location: self.indicator_location.unwrap_or(DEFAULT_ENC_INDICATOR_LOC), icon_encrypted: self.icon_encrypted.map(Cow::Owned).unwrap_or(DEFAULT_ICON_ENC), icon_unencrypted: self.icon_unencrypted.map(Cow::Owned).unwrap_or(DEFAULT_ICON_UNENC), icon_unknown: self.icon_unknown.map(Cow::Owned).unwrap_or(DEFAULT_ICON_UNKNOWN), } } } #[derive(Clone, Debug)] pub struct EncryptionValues { pub indicator: EncryptionIndicator, pub indicator_location: EncryptionIndicatorLocation, pub icon_encrypted: Cow<'static, str>, pub icon_unencrypted: Cow<'static, str>, pub icon_unknown: Cow<'static, str>, } impl EncryptionValues { pub fn get_indicator( &self, location: EncryptionIndicatorLocation, state: EncryptionState, theme: &ThemeValues, ) -> Option> { if !self.indicator_location.contains(location) { return None; } let indicator = match (self.indicator, state) { (EncryptionIndicator::Disabled, _) | (EncryptionIndicator::OnlyUnencrypted, EncryptionState::Encrypted) | (EncryptionIndicator::OnlyEncrypted, EncryptionState::NotEncrypted) => { // User doesn't want to see anything: return None; }, ( EncryptionIndicator::Enabled | EncryptionIndicator::OnlyEncrypted, EncryptionState::Encrypted, ) => { // Green encrypted icon: Span::styled(self.icon_encrypted.clone(), theme.encryption.icon_encrypted) }, ( EncryptionIndicator::Enabled | EncryptionIndicator::OnlyUnencrypted, EncryptionState::NotEncrypted, ) => { // Red unencrypted icon: Span::styled(self.icon_unencrypted.clone(), theme.encryption.icon_unencrypted) }, (_, EncryptionState::Unknown) => { // Yellow unknown icon: Span::styled(self.icon_unknown.clone(), theme.encryption.icon_unknown) }, }; Some(indicator) } } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub enum ProxyUrl { Disabled, Endpoint(Url), #[default] System, } pub struct ProxyUrlVisitor; impl Visitor<'_> for ProxyUrlVisitor { type Value = ProxyUrl; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid proxy URL (e.g. \"socks5://localhost:9050\")") } fn visit_str(self, value: &str) -> Result where E: SerdeError, { if value.is_empty() { return Ok(ProxyUrl::Disabled); } match Url::from_str(value) { Ok(uri) => Ok(ProxyUrl::Endpoint(uri)), Err(e) => Err(E::custom(format!("could not parse {value:?}: {e}"))), } } } #[derive(Clone, Debug, Default, Deserialize)] pub struct Proxy { /// How and where to proxy the client's requests to the homeserver. url: Option, /// An optional value to include in the `Proxy-Authorization` header. #[serde(default, deserialize_with = "deserialize_from_str_opt")] auth: Option, /// Optional headers to include in requests sent to the proxy. #[serde(default, with = "http_serde::header_map")] headers: HeaderMap, } impl Proxy { pub fn values(self) -> ProxyValues { ProxyValues { url: self.url.unwrap_or_default(), auth: self.auth, headers: self.headers, } } } #[derive(Clone, Debug, Default)] pub struct ProxyValues { pub url: ProxyUrl, pub auth: Option, pub headers: HeaderMap, } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] pub struct Mouse { #[serde(default)] pub enabled: bool, } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] pub struct Notifications { #[serde(default)] pub enabled: bool, #[serde(default)] pub via: NotifyVia, #[serde(default = "default_true")] pub show_message: bool, #[serde(default)] pub sound_hint: Option, } #[derive(Clone)] pub struct ImagePreviewValues { pub enabled: bool, pub size: Size, pub protocol: ImagePreviewProtocolValues, } #[derive(Clone, Debug, Default, Deserialize)] pub struct ImagePreview { pub enabled: Option, pub size: Option, pub protocol: Option, } impl ImagePreview { pub fn values(self) -> ImagePreviewValues { ImagePreviewValues { enabled: self.enabled.unwrap_or(true), size: self.size.unwrap_or(Size { width: 66, height: 10 }), protocol: self.protocol.unwrap_or_default(), } } } #[derive(Clone, Debug, Deserialize, Default)] pub struct ImagePreviewProtocolValues { pub r#type: Option, pub filter: Option, pub font_size: Option<(u16, u16)>, } #[derive(Clone)] pub struct SortValues { pub chats: Vec>, pub dms: Vec>, pub rooms: Vec>, pub spaces: Vec>, pub members: Vec>, pub space: Vec>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct SortOverrides { pub chats: Option>>, pub dms: Option>>, pub rooms: Option>>, pub spaces: Option>>, pub members: Option>>, pub space: Option>>, } impl SortOverrides { fn merge(profile: Self, global: Self) -> Self { Self { chats: profile.chats.or(global.chats), dms: profile.dms.or(global.dms), rooms: profile.rooms.or(global.rooms), spaces: profile.spaces.or(global.spaces), members: profile.members.or(global.members), space: profile.space.or(global.space), } } pub fn values(self) -> SortValues { let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT)); let chats = self.chats.unwrap_or_else(|| rooms.clone()); let dms = self.dms.unwrap_or_else(|| rooms.clone()); let spaces = self.spaces.unwrap_or_else(|| rooms.clone()); let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT)); let space = self.space.unwrap_or_else(|| Vec::from(DEFAULT_SPACE_SORT)); SortValues { rooms, members, chats, dms, spaces, space } } } #[derive(Clone, Debug, Default, Deserialize)] pub struct Terminal { pub cursor_shape: Option, pub enable_extended_keys: Option, pub enable_title: Option, } impl Terminal { fn merge(profile: Self, global: Self) -> Self { Self { cursor_shape: profile.cursor_shape.or(global.cursor_shape), enable_extended_keys: profile.enable_extended_keys.or(global.enable_extended_keys), enable_title: profile.enable_title.or(global.enable_title), } } pub fn values(self) -> TerminalValues { TerminalValues { cursor_shape: self.cursor_shape.unwrap_or_default(), enable_extended_keys: self.enable_extended_keys, enable_title: self.enable_title.unwrap_or(DEFAULT_ENABLE_TITLE), } } } #[derive(Clone, Debug)] pub struct TerminalValues { pub cursor_shape: CursorShape, pub enable_extended_keys: Option, pub enable_title: bool, } /// The configuration settings to run with, after merging the /// per-profile overrides on top of the global settings. #[derive(Clone)] pub struct TunableValues { pub encryption: EncryptionValues, pub default_markup: MarkupFormat, pub ignorecase: bool, pub log_level: String, pub max_log_files: usize, pub message_formatted_display: bool, pub message_shortcode_display: bool, pub normal_after_send: bool, pub proxy: ProxyValues, pub reaction_display: bool, pub reaction_shortcode_display: bool, pub read_receipt_send: bool, pub read_receipt_trigger: ReadReceiptTrigger, pub read_receipt_display: bool, pub room_labels: Vec, pub request_timeout: u64, pub sort: SortValues, pub state_event_display: bool, pub sync_delay_ms: u64, pub theme: String, pub typing_notice_send: bool, pub typing_notice_display: bool, pub users: UserOverrides, pub username_display: UserDisplayStyle, pub message_user_color: bool, pub default_register: Option, pub default_room: Option, pub default_via: HashSet, pub open_command: Option>, pub mouse: Mouse, pub notifications: Notifications, pub terminal: TerminalValues, pub image_preview: ImagePreviewValues, pub user_gutter_width: usize, pub external_edit_file_suffix: String, pub tabstop: usize, pub input_prompt: Option, pub members_split: Option, pub default_split: SplitDirection, pub ssl_verify: bool, pub cache_policy: MediaRetentionPolicy, pub send_on_enter: bool, pub date_format: String, pub time_format: String, /// Display columns reserved for the time gutter, computed from /// `time_format` once when the settings are loaded. pub time_gutter_width: usize, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Tunables { /// Subsection for overriding encryption-related settings. #[serde(default)] pub encryption: Encryption, /// Subsection for configuring an HTTP(S) proxy. pub proxy: Option, /// Subsection for overriding sort orders in UI lists. #[serde(default)] pub sort: SortOverrides, /// Subsection for overriding terminal settings. #[serde(default)] pub terminal: Terminal, /// Subsection for overriding how specific Matrix users are rendered. pub users: Option, pub default_markup: Option, pub ignorecase: Option, pub log_level: Option, pub max_log_files: Option, pub message_formatted_display: Option, pub message_shortcode_display: Option, pub normal_after_send: Option, pub reaction_display: Option, pub reaction_shortcode_display: Option, pub read_receipt_send: Option, pub read_receipt_trigger: Option, pub read_receipt_display: Option, pub room_labels: Option>, pub request_timeout: Option, pub state_event_display: Option, pub sync_delay_ms: Option, pub theme: Option, pub typing_notice_send: Option, pub typing_notice_display: Option, pub username_display: Option, pub message_user_color: Option, #[serde(default, deserialize_with = "deserialize_register")] pub default_register: Option, pub default_room: Option, pub default_via: Option>, pub open_command: Option>, pub mouse: Option, pub notifications: Option, pub image_preview: Option, pub user_gutter_width: Option, pub external_edit_file_suffix: Option, pub tabstop: Option, pub input_prompt: Option, pub members_split: Option, pub default_split: Option, pub ssl_verify: Option, pub cache_policy: Option, pub send_on_enter: Option, #[serde(default, deserialize_with = "deserialize_strftime")] pub date_format: Option, /// strftime string for the per-message time gutter, including any brackets /// or spacing. The column is as wide as a sample rendering of this string. /// An empty string hides the time. #[serde(default, deserialize_with = "deserialize_strftime")] pub time_format: Option, } impl Tunables { fn merge(self, other: Self) -> Self { Tunables { encryption: Encryption::merge(self.encryption, other.encryption), sort: SortOverrides::merge(self.sort, other.sort), terminal: Terminal::merge(self.terminal, other.terminal), users: merge_maps(self.users, other.users), // Proxy configuration sub-field do *not* get merged, so that a // per-profile override won't inherit auth or headers from the // global settings. proxy: self.proxy.or(other.proxy), default_markup: self.default_markup.or(other.default_markup), ignorecase: self.ignorecase.or(other.ignorecase), log_level: self.log_level.or(other.log_level), max_log_files: self.max_log_files.or(other.max_log_files), message_formatted_display: self .message_formatted_display .or(other.message_formatted_display), message_shortcode_display: self .message_shortcode_display .or(other.message_shortcode_display), normal_after_send: self.normal_after_send.or(other.normal_after_send), reaction_display: self.reaction_display.or(other.reaction_display), reaction_shortcode_display: self .reaction_shortcode_display .or(other.reaction_shortcode_display), read_receipt_send: self.read_receipt_send.or(other.read_receipt_send), read_receipt_trigger: self.read_receipt_trigger.or(other.read_receipt_trigger), read_receipt_display: self.read_receipt_display.or(other.read_receipt_display), room_labels: self.room_labels.or(other.room_labels), request_timeout: self.request_timeout.or(other.request_timeout), state_event_display: self.state_event_display.or(other.state_event_display), sync_delay_ms: self.sync_delay_ms.or(other.sync_delay_ms), theme: self.theme.or(other.theme), typing_notice_send: self.typing_notice_send.or(other.typing_notice_send), typing_notice_display: self.typing_notice_display.or(other.typing_notice_display), username_display: self.username_display.or(other.username_display), message_user_color: self.message_user_color.or(other.message_user_color), default_register: self.default_register.or(other.default_register), default_room: self.default_room.or(other.default_room), default_via: self.default_via.or(other.default_via), open_command: self.open_command.or(other.open_command), mouse: self.mouse.or(other.mouse), notifications: self.notifications.or(other.notifications), image_preview: self.image_preview.or(other.image_preview), user_gutter_width: self.user_gutter_width.or(other.user_gutter_width), external_edit_file_suffix: self .external_edit_file_suffix .or(other.external_edit_file_suffix), tabstop: self.tabstop.or(other.tabstop), input_prompt: self.input_prompt.or(other.input_prompt), members_split: self.members_split.or(other.members_split), default_split: self.default_split.or(other.default_split), ssl_verify: self.ssl_verify.or(other.ssl_verify), cache_policy: self.cache_policy.or(other.cache_policy), send_on_enter: self.send_on_enter.or(other.send_on_enter), date_format: self.date_format.or(other.date_format), time_format: self.time_format.or(other.time_format), } } fn values(self) -> TunableValues { let time_format = self.time_format.unwrap_or_else(|| DEFAULT_TIME_FORMAT.to_owned()); let time_gutter_width = time_gutter_width(&time_format); TunableValues { encryption: self.encryption.values(), proxy: self.proxy.unwrap_or_default().values(), sort: self.sort.values(), terminal: self.terminal.values(), users: self.users.unwrap_or_default(), default_markup: self.default_markup.unwrap_or_default(), log_level: self.log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_owned()), ignorecase: self.ignorecase.unwrap_or(false), max_log_files: self.max_log_files.unwrap_or(7), message_formatted_display: self.message_formatted_display.unwrap_or(true), message_shortcode_display: self.message_shortcode_display.unwrap_or(false), normal_after_send: self.normal_after_send.unwrap_or(false), reaction_display: self.reaction_display.unwrap_or(true), reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false), read_receipt_send: self.read_receipt_send.unwrap_or(true), read_receipt_trigger: self.read_receipt_trigger.unwrap_or_default(), read_receipt_display: self.read_receipt_display.unwrap_or(true), room_labels: self.room_labels.unwrap_or_else(|| DEFAULT_ROOM_LABELS.to_vec()), request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT), state_event_display: self.state_event_display.unwrap_or(true), sync_delay_ms: self.sync_delay_ms.unwrap_or(DEFAULT_SYNC_FREQUENCY), theme: self.theme.unwrap_or_else(|| "default".to_string()), typing_notice_send: self.typing_notice_send.unwrap_or(true), typing_notice_display: self.typing_notice_display.unwrap_or(true), username_display: self.username_display.unwrap_or_default(), message_user_color: self.message_user_color.unwrap_or(false), default_register: self.default_register, default_room: self.default_room, default_via: self .default_via .unwrap_or_else(|| vec![DEFAULT_VIA_SERVER.clone()]) .into_iter() .collect(), open_command: self.open_command, mouse: self.mouse.unwrap_or_default(), notifications: self.notifications.unwrap_or_default(), image_preview: self.image_preview.unwrap_or_default().values(), user_gutter_width: self.user_gutter_width.unwrap_or(30), external_edit_file_suffix: self .external_edit_file_suffix .unwrap_or_else(|| ".md".to_string()), tabstop: self.tabstop.unwrap_or(4), input_prompt: self.input_prompt, members_split: self.members_split, default_split: self.default_split.unwrap_or_default(), ssl_verify: self.ssl_verify.unwrap_or(true), cache_policy: self.cache_policy.unwrap_or_default(), send_on_enter: self.send_on_enter.unwrap_or(true), date_format: self.date_format.unwrap_or_else(|| DEFAULT_DATE_FORMAT.to_owned()), time_format, time_gutter_width, } } } #[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] #[repr(u8)] pub enum CursorShape { Default, Block, Line, Underline, #[default] Auto, } impl From for modalkit::crossterm::cursor::SetCursorStyle { fn from(shape: CursorShape) -> Self { match shape { CursorShape::Default => Self::DefaultUserShape, CursorShape::Block => Self::SteadyBlock, CursorShape::Line => Self::SteadyBar, CursorShape::Underline => Self::SteadyUnderScore, // use steady block at startup and switch to the correct value on first render CursorShape::Auto => Self::SteadyBlock, } } } #[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] #[repr(u8)] pub enum MarkupFormat { Html, #[default] Markdown, Plaintext, } #[derive(Clone)] pub struct DirectoryValues { pub cache: PathBuf, pub data: PathBuf, pub logs: PathBuf, pub downloads: Option, } impl DirectoryValues { fn create_dir_all(&self) -> std::io::Result<()> { use std::fs::create_dir_all; let Self { cache, data, logs, downloads } = self; create_dir_all(cache)?; create_dir_all(data)?; create_dir_all(logs)?; if let Some(downloads) = downloads { create_dir_all(downloads)?; } Ok(()) } } #[derive(Clone, Default, Deserialize)] pub struct Directories { pub cache: Option, pub data: Option, pub logs: Option, pub downloads: Option, } impl Directories { fn merge(self, other: Self) -> Self { Directories { cache: self.cache.or(other.cache), data: self.data.or(other.data), logs: self.logs.or(other.logs), downloads: self.downloads.or(other.downloads), } } fn values(self) -> DirectoryValues { let cache = self .cache .map(|dir| { let dir = shellexpand::full(&dir) .expect("unable to expand shell variables in dirs.cache"); Path::new(dir.as_ref()).to_owned() }) .or_else(|| { let mut dir = dirs::cache_dir()?; dir.push("iamb"); dir.into() }) .expect("no dirs.cache value configured!"); let data = self .data .map(|dir| { let dir = shellexpand::full(&dir) .expect("unable to expand shell variables in dirs.cache"); Path::new(dir.as_ref()).to_owned() }) .or_else(|| { let mut dir = dirs::data_dir()?; dir.push("iamb"); dir.into() }) .expect("no dirs.data value configured!"); let logs = self .logs .map(|dir| { let dir = shellexpand::full(&dir) .expect("unable to expand shell variables in dirs.cache"); Path::new(dir.as_ref()).to_owned() }) .unwrap_or_else(|| { let mut dir = cache.clone(); dir.push("logs"); dir }); let downloads = self .downloads .map(|dir| { let dir = shellexpand::full(&dir) .expect("unable to expand shell variables in dirs.cache"); Path::new(dir.as_ref()).to_owned() }) .or_else(dirs::download_dir); DirectoryValues { cache, data, logs, downloads } } } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(untagged)] pub enum WindowPath { AliasId(OwnedRoomAliasId), RoomId(OwnedRoomId), UserId(OwnedUserId), Window(IambId), } #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(untagged, deny_unknown_fields)] pub enum WindowLayout { Window { window: WindowPath }, Split { split: Vec }, } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase", tag = "style")] pub enum Layout { /// Restore the layout from the previous session. #[default] Restore, /// Open a single window using the `default_room` value. New, /// Open the window layouts described under `tabs`. Config { tabs: Vec }, } #[derive(Clone, Deserialize)] pub struct ProfileConfig { pub user_id: OwnedUserId, pub password_file: Option, pub url: Option, pub settings: Option, pub theme: Option, pub dirs: Option, pub layout: Option, pub macros: Option, pub aliases: Option, } #[derive(Clone, Deserialize)] pub struct IambConfig { pub profiles: BTreeMap, pub default_profile: Option, pub settings: Option, pub dirs: Option, pub layout: Option, pub macros: Option, pub aliases: Option, pub theme: Option, } impl IambConfig { pub fn load_toml(path: &Path) -> Result { let s = std::fs::read_to_string(path)?; let config = toml::from_str(&s)?; Ok(config) } pub fn load_json(path: &Path) -> Result { let s = std::fs::read_to_string(path)?; let config = serde_json::from_str(&s)?; Ok(config) } } #[derive(Clone)] pub struct ApplicationSettings { pub layout_json: PathBuf, pub session_json: PathBuf, pub device_json: PathBuf, pub session_json_old: PathBuf, pub sled_dir: PathBuf, pub sqlite_dir: PathBuf, pub sqlite_cache_dir: PathBuf, pub profile_name: String, pub profile: ProfileConfig, pub theme: Arc, pub themes: Arc>, pub tunables: TunableValues, pub dirs: DirectoryValues, pub layout: Layout, pub macros: Macros, pub aliases: Aliases, /// Whether to use the Kitty keyboard protocol. Resolved by /// [`ApplicationSettings::probe_enhanced_keys`] once the TUI starts, since /// it may require querying the terminal. pub enable_enhanced_keys: bool, } impl ApplicationSettings { fn get_xdg_config_home() -> Option { env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from) } pub fn load(cli: Iamb) -> Result> { let mut config_dir = cli .config_directory .or_else(Self::get_xdg_config_home) .or_else(dirs::config_dir) .unwrap_or_else(|| { usage!( "No user configuration directory found;\ please specify one via -C.\n\n For more information try '--help'" ); }); config_dir.push("iamb"); let config_json = config_dir.join("config.json"); let config_toml = config_dir.join("config.toml"); let config = if config_toml.is_file() { IambConfig::load_toml(config_toml.as_path())? } else if config_json.is_file() { IambConfig::load_json(config_json.as_path())? } else { usage!( "Please create a configuration file at {}\n\n\ For more information try '--help'", config_toml.display(), ); }; let IambConfig { mut profiles, default_profile, dirs, settings: global, layout, macros, aliases, theme, } = config; validate_profile_names(&profiles); let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) { profiles.remove_entry(&profile).unwrap_or_else(|| { usage!( "No configured profile with the name {:?} in {}", profile, config_json.display() ); }) } else if profiles.len() == 1 { profiles.into_iter().next().unwrap() } else { loop { println!("\nNo profile specified. Available profiles:"); profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}")); print!("Select a number or 'q' to quit: "); let _ = std::io::stdout().flush(); let mut input = String::new(); let _ = std::io::stdin().read_line(&mut input); if input.trim() == "q" { usage!( "No profile specified. \ Please use -P or add \"default_profile\" to your configuration.\n\n\ For more information try '--help'", ); } if let Ok(i) = input.trim().parse::() && i < profiles.len() { break profiles.into_iter().nth(i).unwrap(); } println!("\nInvalid index."); } }; let aliases = merge_maps(profile.aliases.take(), aliases).unwrap_or_default(); let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default(); let layout = profile.layout.take().or(layout).unwrap_or_default(); let tunables = global.unwrap_or_default(); let tunables = profile.settings.take().unwrap_or_default().merge(tunables); let tunables = tunables.values(); let dirs = dirs.unwrap_or_default(); let dirs = profile.dirs.take().unwrap_or_default().merge(dirs); let dirs = dirs.values(); let themes_dir = config_dir.join("themes"); let overrides = profile.theme.clone().unwrap_or_default().merge(theme.unwrap_or_default()); let themes = Arc::new(load_themes(&themes_dir, overrides)?); let theme = if let Some(theme) = themes.get(&tunables.theme) { Arc::new(theme.clone().values()) } else { let err = anyhow!( "Could not find the {:?} theme; check {}?", tunables.theme, themes_dir.display() ); return Err(err.into_boxed_dyn_error()); }; // Create directories dirs.create_dir_all()?; // Set up paths that live inside the profile's data directory. let mut profile_dir = config_dir.clone(); profile_dir.push("profiles"); profile_dir.push(profile_name.as_str()); let mut profile_data_dir = dirs.data.clone(); profile_data_dir.push("profiles"); profile_data_dir.push(profile_name.as_str()); let mut sled_dir = profile_dir.clone(); sled_dir.push("matrix"); let mut sqlite_dir = profile_data_dir.clone(); sqlite_dir.push("sqlite"); let mut session_json = profile_data_dir.clone(); session_json.push("session.json"); let mut device_json = profile_data_dir; device_json.push("device.json"); let mut session_json_old = profile_dir; session_json_old.push("session.json"); // Set up paths that live inside the profile's cache directory. let mut cache_dir = dirs.cache.clone(); cache_dir.push("profiles"); cache_dir.push(profile_name.as_str()); let mut layout_json = cache_dir.clone(); layout_json.push("layout.json"); let mut sqlite_cache_dir = cache_dir; sqlite_cache_dir.push("sqlite"); let settings = ApplicationSettings { sled_dir, layout_json, session_json, device_json, session_json_old, sqlite_dir, sqlite_cache_dir, profile_name, profile, themes, theme, tunables, dirs, layout, macros, aliases, enable_enhanced_keys: false, }; Ok(settings) } /// Work out whether to use the Kitty keyboard protocol, asking the terminal /// when the user has not configured it explicitly. /// /// This queries the terminal, so it must only be called once, before the /// TUI starts reading input. pub fn probe_enhanced_keys(&mut self) { self.enable_enhanced_keys = self.tunables.terminal.enable_extended_keys.unwrap_or_else(|| { crossterm::terminal::supports_keyboard_enhancement() .inspect_err(|e| { tracing::warn!( err = %e, "Failed to determine whether the terminal supports keyboard enhancements" ) }) .unwrap_or_default() }); } pub fn read_session(&self, path: impl AsRef) -> Result { let file = File::open(path)?; let reader = BufReader::new(file); let session = serde_json::from_reader(reader).map_err(IambError::from)?; Ok(session) } pub fn write_session(&self, session: impl Into) -> Result<(), IambError> { let file = File::create(self.session_json.as_path())?; let writer = BufWriter::new(file); let session: Session = session.into(); serde_json::to_writer(writer, &session).map_err(IambError::from)?; Ok(()) } /// The device ID saved at logout, if it was saved for this profile's /// user. A missing or stale file is not an error: the next login then /// simply gets a fresh device ID from the homeserver. pub fn read_saved_device(&self) -> Option { let file = File::open(self.device_json.as_path()).ok()?; let reader = BufReader::new(file); let saved: SavedDevice = serde_json::from_reader(reader).ok()?; if saved.is_user(&self.profile.user_id) { Some(saved) } else { None } } pub fn write_saved_device( &self, device_id: &DeviceId, client_id: Option, ) -> Result<(), IambError> { let file = File::create(self.device_json.as_path())?; let writer = BufWriter::new(file); let saved = match client_id { Some(client) => { SavedDevice::OAuth { user_id: self.profile.user_id.clone(), device_id: device_id.to_owned(), client_id: client, } }, None => { SavedDevice::MatrixAuth { user_id: self.profile.user_id.clone(), device_id: device_id.to_owned(), } }, }; serde_json::to_writer(writer, &saved).map_err(IambError::from)?; Ok(()) } pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> { let (color, c) = self .tunables .users .get(user_id) .map(|user| (user.color, user.name.as_ref().and_then(|s| s.chars().next()))) .unwrap_or_default(); let style = self.theme.users.style(user_id.as_str(), color); let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' ')); Span::styled(String::from(c), style) } pub fn get_user_overrides( &self, user_id: &UserId, ) -> (Option, Option>) { self.tunables .users .get(user_id) .map(|user| (user.color, user.name.clone().map(Cow::Owned))) .unwrap_or_default() } pub fn get_user_color(&self, user_id: &UserId) -> Color { self.tunables .users .get(user_id) .and_then(|user| user.color) .unwrap_or_else(|| self.theme.users.color(user_id.as_str())) } pub fn get_user_style(&self, user_id: &UserId) -> Style { let (color, _) = self.get_user_overrides(user_id); self.theme.users.style(user_id.as_str(), color) } pub fn get_user_span_maybe<'a>( &self, user_id: &'a UserId, info: Option<&'a RoomInfo>, ) -> Span<'a> { let (color, name) = self.get_user_overrides(user_id); let style = self.theme.users.style(user_id.as_str(), color); let name = match (name, &self.tunables.username_display) { (Some(name), _) => name, (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()), (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()), (None, UserDisplayStyle::DisplayName) => { if let Some(name) = info.and_then(|info| info.display_names.get(user_id)) { name } else { Cow::Borrowed(user_id.as_str()) } }, }; Span::styled(name, style) } pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> { self.get_user_span_maybe(user_id, Some(info)) } } #[cfg(test)] mod tests { use super::*; use std::convert::TryFrom; use matrix_sdk::ruma::user_id; use crate::tests::{TEST_USER1, mock_room, mock_settings}; #[test] fn test_get_user_span_borrowed() { // fix `StyleTreeNode::print` for `StyleTreeNode::UserId` if this breaks let info = mock_room(); let settings = mock_settings(); let span = settings.get_user_span(&TEST_USER1, &info); assert!(matches!(span.content, Cow::Borrowed(_))); } #[test] fn test_profile_name_invalid() { assert_eq!(validate_profile_name(""), false); assert_eq!(validate_profile_name(" "), false); assert_eq!(validate_profile_name("a b"), false); assert_eq!(validate_profile_name("foo^bar"), false); assert_eq!(validate_profile_name("FOO/BAR"), false); assert_eq!(validate_profile_name("-b-c"), false); assert_eq!(validate_profile_name("-B-c"), false); assert_eq!(validate_profile_name(".b-c"), false); assert_eq!(validate_profile_name(".B-c"), false); } #[test] fn test_profile_name_valid() { assert_eq!(validate_profile_name("foo"), true); assert_eq!(validate_profile_name("FOO"), true); assert_eq!(validate_profile_name("a-b-c"), true); assert_eq!(validate_profile_name("a-B-c"), true); assert_eq!(validate_profile_name("a.b-c"), true); assert_eq!(validate_profile_name("a.B-c"), true); } #[test] fn test_merge_users() { let a = None; let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables { color: Some(Color::Red), name: Some("Hello".into()), })] .into_iter() .collect::>(); let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables { color: Some(Color::Green), name: Some("World".into()), })] .into_iter() .collect::>(); let res = merge_maps(a.clone(), a.clone()); assert_eq!(res, None); let res = merge_maps(a.clone(), Some(b.clone())); assert_eq!(res, Some(b.clone())); let res = merge_maps(Some(b.clone()), a.clone()); assert_eq!(res, Some(b.clone())); let res = merge_maps(Some(b.clone()), Some(b.clone())); assert_eq!(res, Some(b.clone())); let res = merge_maps(Some(b.clone()), Some(c.clone())); assert_eq!(res, Some(b.clone())); let res = merge_maps(Some(c.clone()), Some(b.clone())); assert_eq!(res, Some(c.clone())); } #[test] fn test_parse_tunables() { let res: Tunables = serde_json::from_str("{}").unwrap(); assert_eq!(res.typing_notice_send, None); assert_eq!(res.typing_notice_display, None); assert_eq!(res.users, None); let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap(); assert_eq!(res.typing_notice_send, Some(true)); assert_eq!(res.typing_notice_display, None); assert_eq!(res.users, None); let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap(); assert_eq!(res.typing_notice_send, Some(false)); assert_eq!(res.typing_notice_display, None); assert_eq!(res.users, None); let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap(); assert_eq!(res.typing_notice_send, None); assert_eq!(res.typing_notice_display, None); assert_eq!(res.users, Some(HashMap::new())); } #[test] fn test_parse_user_colors() { let expect = |color| UserDisplayTunables { color: Some(color), name: Some("Tim".into()) }; // Unprefixed color: let res: Tunables = serde_json::from_str( "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}", ) .unwrap(); assert_eq!(res.typing_notice_send, None); assert_eq!(res.typing_notice_display, None); let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::Black))]; assert_eq!(res.users, Some(users.into_iter().collect())); // Color with `light-` prefix: let res: Tunables = serde_json::from_str( "{\"users\": {\"@a:b.c\": {\"color\": \"light-red\", \"name\": \"Tim\"}}}", ) .unwrap(); let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightRed))]; assert_eq!(res.users, Some(users.into_iter().collect())); // Color name with `light-` prefix: let res: Tunables = serde_json::from_str( "{\"users\": {\"@a:b.c\": {\"color\": \"light-red\", \"name\": \"Tim\"}}}", ) .unwrap(); let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightRed))]; assert_eq!(res.users, Some(users.into_iter().collect())); // Color name with `light` prefix, no hyphen: let res: Tunables = serde_json::from_str( "{\"users\": {\"@a:b.c\": {\"color\": \"lightblue\", \"name\": \"Tim\"}}}", ) .unwrap(); let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightBlue))]; assert_eq!(res.users, Some(users.into_iter().collect())); // Hex color name: let res: Tunables = serde_json::from_str( "{\"users\": {\"@a:b.c\": {\"color\": \"#ff55bb\", \"name\": \"Tim\"}}}", ) .unwrap(); let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::Rgb(0xff, 0x55, 0xbb)))]; assert_eq!(res.users, Some(users.into_iter().collect())); } fn parse_settings_toml(input: &str) -> Result { #[derive(Deserialize)] struct SettingsToml { settings: Tunables, } toml::from_str::(input).map(|doc| doc.settings) } #[test] fn test_parse_tunables_date_time_format() { let settings = parse_settings_toml( r#" [settings] date_format = "%Y-%m-%d" time_format = "%H:%M" "#, ) .unwrap(); assert_eq!(settings.date_format.as_deref(), Some("%Y-%m-%d")); assert_eq!(settings.time_format.as_deref(), Some("%H:%M")); let values = settings.values(); assert_eq!(values.date_format, "%Y-%m-%d"); assert_eq!(values.time_format, "%H:%M"); assert_eq!(values.time_gutter_width, 5); // Absent keys keep today's formats. let settings = parse_settings_toml("[settings]\n").unwrap(); assert_eq!(settings.date_format, None); assert_eq!(settings.time_format, None); let values = settings.values(); assert_eq!(values.date_format, "%A, %B %d %Y"); assert_eq!(values.time_format, " [%T]"); assert_eq!(values.time_gutter_width, 12); // An empty format is valid and disables the time column. let settings = parse_settings_toml( r#" [settings] time_format = "" "#, ) .unwrap(); assert_eq!(settings.time_format.as_deref(), Some("")); let values = settings.values(); assert_eq!(values.time_format, ""); assert_eq!(values.time_gutter_width, 0); // Brackets and spacing are literal gutter text, not added later. let settings = parse_settings_toml( r#" [settings] time_format = " [%H:%M]" "#, ) .unwrap(); let values = settings.values(); assert_eq!(values.time_format, " [%H:%M]"); assert_eq!(values.time_gutter_width, 9); } #[test] fn test_parse_tunables_date_time_format_invalid() { let err = parse_settings_toml( r#" [settings] date_format = "%Q" "#, ) .unwrap_err(); let msg = err.to_string(); assert!(msg.contains("invalid strftime"), "{msg}"); let err = parse_settings_toml( r#" [settings] time_format = "%" "#, ) .unwrap_err(); let msg = err.to_string(); assert!(msg.contains("invalid strftime"), "{msg}"); } #[test] fn test_parse_tunables_username_display() { let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap(); assert_eq!(res.username_display, Some(UserDisplayStyle::Username)); let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap(); assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart)); let res: Tunables = serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap(); assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName)); } #[test] fn test_parse_tunables_sort() { let res: Tunables = serde_json::from_str( r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#, ) .unwrap(); assert_eq!( res.sort.members, Some(vec![ SortColumn(SortFieldUser::Server, SortOrder::Ascending), SortColumn(SortFieldUser::LocalPart, SortOrder::Descending), ]) ); assert_eq!( res.sort.spaces, Some(vec![ SortColumn(SortFieldRoom::Favorite, SortOrder::Descending), SortColumn(SortFieldRoom::Alias, SortOrder::Ascending), ]) ); assert_eq!(res.sort.rooms, None); assert_eq!(res.sort.dms, None); // Check that we get the right default "rooms" and "dms" values. let res = res.values(); assert_eq!(res.sort.members, vec![ SortColumn(SortFieldUser::Server, SortOrder::Ascending), SortColumn(SortFieldUser::LocalPart, SortOrder::Descending), ]); assert_eq!(res.sort.spaces, vec![ SortColumn(SortFieldRoom::Favorite, SortOrder::Descending), SortColumn(SortFieldRoom::Alias, SortOrder::Ascending), ]); assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT)); assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT)); } #[test] fn test_parse_default_members_sort() { let sort: Vec> = serde_json::from_str(r#"["power","knock","~invite","id"]"#).unwrap(); assert_eq!(sort.as_slice(), &DEFAULT_MEMBERS_SORT[..]); } #[test] fn test_parse_default_rooms_sort() { let sort: Vec> = serde_json::from_str(r#"["favorite","invite","lowpriority","mentions","notifications","joined","space","dm","recent","name"]"#) .unwrap(); assert_eq!(sort.as_slice(), &DEFAULT_ROOM_SORT[..]); } #[test] fn test_parse_default_space_sort() { let sort: Vec> = serde_json::from_str(r#"["space","joined","spaceorder"]"#).unwrap(); assert_eq!(sort.as_slice(), &DEFAULT_SPACE_SORT[..]); } #[test] fn test_parse_tunables_proxy_invalid() { let res = serde_json::from_str::(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err(); // Should result in a validation error: assert_eq!(res.classify(), serde_json::error::Category::Data); } #[test] fn test_parse_tunables_proxy_empty() { let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap(); let proxy = res.proxy.unwrap(); assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled); } #[test] fn test_parse_tunables_proxy_socks5() { let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap(); let proxy = res.proxy.unwrap(); let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else { panic!("should parse ProxyUrl::Endpoint") }; assert_eq!(url.scheme(), "socks5"); assert_eq!(url.host_str().unwrap(), "localhost"); assert_eq!(url.port().unwrap(), 1080); assert_eq!(url.authority(), "localhost:1080"); } #[test] fn test_parse_tunables_proxy_https() { let res: Tunables = serde_json::from_str( r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"# ).unwrap(); let proxy = res.proxy.unwrap(); let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else { panic!("should parse ProxyUrl::Endpoint") }; // Verify URL fields: assert_eq!(url.scheme(), "https"); assert_eq!(url.host_str().unwrap(), "localhost"); assert_eq!(url.port().unwrap(), 8080); assert_eq!(url.authority(), "localhost:8080"); // Verify our `Proxy-Authorization` value: assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234"); // Verify our custom header is present: assert_eq!(proxy.headers.len(), 1); assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb"); } #[test] fn test_parse_tunables_proxy_merge() { let global: Tunables = serde_json::from_str( r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"# ).unwrap(); let profile: Tunables = serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap(); // The configuration merge should select the entirety of the profile proxy config, // and not merge subfields, to ensure that things like `auth` and `headers` are // not ever sent to a `url` they were meant for. let merged = profile.merge(global).values(); let ProxyUrl::Endpoint(url) = merged.proxy.url else { panic!("should parse ProxyUrl::Endpoint") }; assert_eq!(url.scheme(), "socks5"); assert_eq!(url.authority(), "localhost:1080"); assert_eq!(merged.proxy.auth, None); assert_eq!(merged.proxy.headers.is_empty(), true); } #[test] fn test_parse_tunables_default_register() { let reg_a: Tunables = serde_json::from_str(r#"{"default_register": "a"}"#).unwrap(); assert_eq!(reg_a.default_register, Some(Register::Named('a'))); let reg_z: Tunables = serde_json::from_str(r#"{"default_register": "z"}"#).unwrap(); assert_eq!(reg_z.default_register, Some(Register::Named('z'))); let reg_blackhole: Tunables = serde_json::from_str(r#"{"default_register": "_"}"#).unwrap(); assert_eq!(reg_blackhole.default_register, Some(Register::Blackhole)); let res: Result = serde_json::from_str(r#"{"default_register": "A"}"#); assert!(res.is_err()); let res: Result = serde_json::from_str(r#"{"default_register": "0"}"#); assert!(res.is_err()); } #[test] fn test_parse_layout() { let user = WindowPath::UserId(user_id!("@user:example.com").to_owned()); let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap()); let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap()); let dms = WindowPath::Window(IambId::DirectList); let welcome = WindowPath::Window(IambId::Welcome); let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap(); assert_eq!(res, Layout::Restore); let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap(); assert_eq!(res, Layout::New); let res: Layout = serde_json::from_str( "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}", ) .unwrap(); assert_eq!(res, Layout::Config { tabs: vec![WindowLayout::Window { window: user.clone() }] }); let res: Layout = serde_json::from_str( "{\ \"style\": \"config\",\ \"tabs\": [\ {\"split\":[\ {\"window\":\"@user:example.com\"},\ {\"window\":\"#room:example.com\"}\ ]},\ {\"split\":[\ {\"window\":\"!room:example.com\"},\ {\"split\":[\ {\"window\":\"iamb://dms\"},\ {\"window\":\"iamb://welcome\"}\ ]}\ ]}\ ]}", ) .unwrap(); let split1 = WindowLayout::Split { split: vec![ WindowLayout::Window { window: user.clone() }, WindowLayout::Window { window: alias }, ], }; let split2 = WindowLayout::Split { split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window { window: welcome, }], }; let split3 = WindowLayout::Split { split: vec![WindowLayout::Window { window: room }, split2], }; let tabs = vec![split1, split3]; assert_eq!(res, Layout::Config { tabs }); } #[test] fn test_parse_aliases() { let res: Aliases = serde_json::from_str("{\"c\":\"chats\"}").unwrap(); assert_eq!(res.len(), 1); let aliased = res.get("c").unwrap(); assert_eq!(aliased, "chats"); } #[test] fn test_parse_aliases_preserves_order() { // Aliases are registered in order, which allows alias to refer to earlier ones, so // ensure we register in user-specified order: let res: Aliases = toml::from_str("c = \"chats\"\ncc = \"c\"\nd = \"download\"").unwrap(); let order = res.keys().map(String::as_str).collect::>(); assert_eq!(order, vec!["c", "cc", "d"]); } #[test] fn test_merge_aliases_preserves_order() { let profile: Aliases = toml::from_str("c = \"chats\"\nz = \"redact\"").unwrap(); let global: Aliases = toml::from_str("c = \"cancel\"\nd = \"download\"").unwrap(); let res = merge_maps(Some(profile), Some(global)).unwrap(); let order = res.keys().map(String::as_str).collect::>(); // The profile wins for keys in both, but doesn't get to move them. assert_eq!(order, vec!["c", "d", "z"]); assert_eq!(res.get("c").unwrap(), "chats"); } #[test] fn test_parse_macros() { let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"\"}}").unwrap(); assert_eq!(res.len(), 1); let modes = VimModes(vec![VimMode::Insert, VimMode::Command]); let mapped = res.get(&modes).unwrap(); assert_eq!(mapped.len(), 1); let j = "j".parse::().unwrap(); let esc = "".parse::().unwrap(); let jj = Keys(vec![j, j], "jj".into()); let run = mapped.get(&jj).unwrap(); let exp = Keys(vec![esc], "".into()); assert_eq!(run, &exp); } #[test] fn test_parse_notify_via() { assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default()); assert_eq!( NotifyVia { bell: false, desktop: true }, serde_json::from_str(r#""desktop""#).unwrap() ); assert_eq!( NotifyVia { bell: true, desktop: false }, serde_json::from_str(r#""bell""#).unwrap() ); assert_eq!( NotifyVia { bell: true, desktop: true }, serde_json::from_str(r#""bell|desktop""#).unwrap() ); assert_eq!( NotifyVia { bell: true, desktop: true }, serde_json::from_str(r#""desktop|bell""#).unwrap() ); assert!(serde_json::from_str::(r#""other""#).is_err()); assert!(serde_json::from_str::(r#""""#).is_err()); } #[test] fn test_parse_room_labels() { assert_eq!(RoomLabel::Membership, serde_json::from_str(r#""membership""#).unwrap()); assert_eq!(RoomLabel::Tags, serde_json::from_str(r#""tags""#).unwrap()); assert_eq!(RoomLabel::Type, serde_json::from_str(r#""type""#).unwrap()); } #[test] fn test_parse_cursor_shape() { assert_eq!(CursorShape::Auto, CursorShape::default()); assert_eq!(CursorShape::Auto, serde_json::from_str(r#""auto""#).unwrap()); assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap()); assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap()); assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap()); assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap()); assert!(serde_json::from_str::(r#""beam""#).is_err()); } #[test] fn test_load_example_config_toml() { let path = PathBuf::from("config.full.toml"); let config = IambConfig::load_toml(&path).expect("can load config.full.toml"); let IambConfig { profiles, default_profile, settings, dirs, layout, macros, aliases, theme, } = &config; // There should be an example object for each top-level field. assert!(!profiles.is_empty()); assert!(default_profile.is_some()); assert!(settings.is_some()); assert!(dirs.is_some()); assert!(layout.is_some()); assert!(macros.is_some()); assert!(aliases.is_some()); assert!(theme.is_some()); } #[test] fn test_encryption_indicator_enabled() { use EncryptionState::*; let enc = Encryption { indicator: Some(EncryptionIndicator::Enabled), indicator_location: Some(EncryptionIndicatorLocation::TITLE), ..Default::default() }; let enc = enc.values(); let theme = theme::ThemeValues::default(); // Always shows in the title: assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme) .is_some() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme) .is_some() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme) .is_some() ); // Doesn't show in the prompt: assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme) .is_none() ); } #[test] fn test_encryption_indicator_disabled() { use EncryptionState::*; let enc = Encryption { indicator: Some(EncryptionIndicator::Disabled), indicator_location: Some(EncryptionIndicatorLocation::TITLE), ..Default::default() }; let enc = enc.values(); let theme = theme::ThemeValues::default(); // Never shows in the title or the prompt: assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme) .is_none() ); } #[test] fn test_encryption_indicator_only_encrypted() { use EncryptionState::*; let enc = Encryption { indicator: Some(EncryptionIndicator::OnlyEncrypted), indicator_location: Some(EncryptionIndicatorLocation::PROMPT), ..Default::default() }; let enc = enc.values(); let theme = theme::ThemeValues::default(); // Shows in the prompt when encrypted or unknown: assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme) .is_some() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme) .is_some() ); // But is hidden when unencrypted: assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme) .is_none() ); // Doesn't show in the title: assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme) .is_none() ); } #[test] fn test_encryption_indicator_only_unencrypted() { use EncryptionState::*; let enc = Encryption { indicator: Some(EncryptionIndicator::OnlyUnencrypted), indicator_location: Some(EncryptionIndicatorLocation::all()), ..Default::default() }; let enc = enc.values(); let theme = theme::ThemeValues::default(); // Shows in both the prompt and title when unencrypted or unknown: assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme) .is_some() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme) .is_some() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme) .is_some() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme) .is_some() ); // But is hidden when encrypted: assert!( enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme) .is_none() ); assert!( enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme) .is_none() ); } }