src/config/mod.rs

2722 lines · 93995 bytes

180 symbols in this file
   1//! # Logic for loading and validating application configuration
   2use std::collections::btree_map;
   3use std::collections::{HashSet, hash_map};
   4use std::env;
   5use std::fs::File;
   6use std::io::{BufReader, BufWriter, Write as _};
   7use std::process;
   8use std::sync::Arc;
   9
  10use anyhow::anyhow;
  11use chrono::format::{Item, StrftimeItems};
  12use chrono::{DateTime, Local};
  13use clap::Parser;
  14use indexmap::IndexMap;
  15use lazy_static::lazy_static;
  16use matrix_sdk::authentication::matrix::MatrixSession;
  17use matrix_sdk::authentication::oauth::{ClientId, OAuthSession, UserSession};
  18use matrix_sdk::media::MediaRetentionPolicy;
  19use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
  20use matrix_sdk::ruma::{DeviceId, OwnedDeviceId, owned_server_name};
  21use matrix_sdk::{AuthSession, EncryptionState, SessionMeta, SessionTokens};
  22use modalkit::crossterm;
  23use modalkit::editing::completion::CompletionMap;
  24use modalkit::env::vim::VimMode;
  25use modalkit::keybindings::InputKey;
  26use ratatui_image::FilterType;
  27use ratatui_image::picker::ProtocolType;
  28use serde::de::Error as SerdeError;
  29use serde::de::Visitor;
  30use serde::{Deserialize, Deserializer, Serialize};
  31
  32use crate::base::{SortColumn, SortFieldRoom, SortFieldSpace, SortFieldUser, SortOrder};
  33use crate::prelude::*;
  34
  35pub mod theme;
  36
  37pub type Aliases = IndexMap<String, String>;
  38type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
  39
  40macro_rules! usage {
  41    ( $($args: tt)* ) => {
  42        println!($($args)*);
  43        process::exit(2);
  44    }
  45}
  46
  47macro_rules! merge_options {
  48    ($a: expr, $b: expr) => {
  49        match ($a, $b) {
  50            (None, None) => None,
  51            (Some(v), None) | (None, Some(v)) => Some(v),
  52            (Some(a), Some(b)) => Some(a.merge(b)),
  53        }
  54    };
  55}
  56
  57lazy_static! {
  58    pub static ref DEFAULT_VIA_SERVER: OwnedServerName = owned_server_name!("matrix.org");
  59}
  60
  61const DEFAULT_MEMBERS_SORT: [SortColumn<SortFieldUser>; 4] = [
  62    SortColumn(SortFieldUser::PowerLevel, SortOrder::Ascending),
  63    SortColumn(SortFieldUser::Knock, SortOrder::Ascending),
  64    SortColumn(SortFieldUser::Invite, SortOrder::Descending),
  65    SortColumn(SortFieldUser::UserId, SortOrder::Ascending),
  66];
  67
  68const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 11] = [
  69    SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
  70    SortColumn(SortFieldRoom::Invite, SortOrder::Ascending),
  71    SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending),
  72    SortColumn(SortFieldRoom::Mentions, SortOrder::Ascending),
  73    SortColumn(SortFieldRoom::Notifications, SortOrder::Ascending),
  74    SortColumn(SortFieldRoom::MarkedUnread, SortOrder::Ascending),
  75    SortColumn(SortFieldRoom::Joined, SortOrder::Ascending),
  76    SortColumn(SortFieldRoom::Space, SortOrder::Ascending),
  77    SortColumn(SortFieldRoom::Direct, SortOrder::Ascending),
  78    SortColumn(SortFieldRoom::Recent, SortOrder::Ascending),
  79    SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
  80];
  81
  82const DEFAULT_SPACE_SORT: [SortColumn<SortFieldSpace>; 3] = [
  83    SortColumn(SortFieldSpace::Room(SortFieldRoom::Space), SortOrder::Ascending),
  84    SortColumn(SortFieldSpace::Room(SortFieldRoom::Joined), SortOrder::Ascending),
  85    SortColumn(SortFieldSpace::SpaceOrder, SortOrder::Ascending),
  86];
  87
  88const DEFAULT_ROOM_LABELS: [RoomLabel; 5] = [
  89    RoomLabel::Unread,
  90    RoomLabel::Membership,
  91    RoomLabel::Tags,
  92    RoomLabel::Muted,
  93    RoomLabel::Type,
  94];
  95
  96const DEFAULT_ENABLE_TITLE: bool = true;
  97const DEFAULT_REQ_TIMEOUT: u64 = 120;
  98const DEFAULT_SYNC_FREQUENCY: u64 = 250;
  99
 100const DEFAULT_ENC_INDICATOR_LOC: EncryptionIndicatorLocation = EncryptionIndicatorLocation::PROMPT;
 101const DEFAULT_ICON_ENC: Cow<'static, str> = Cow::Borrowed("[E] ");
 102const DEFAULT_ICON_UNENC: Cow<'static, str> = Cow::Borrowed("[U] ");
 103const DEFAULT_ICON_UNKNOWN: Cow<'static, str> = Cow::Borrowed("[?] ");
 104
 105const DEFAULT_LOG_LEVEL: &str = "off";
 106
 107/// Default date separator, matching the historical hard-coded `"%A, %B %d %Y"`.
 108const DEFAULT_DATE_FORMAT: &str = "%A, %B %d %Y";
 109
 110/// Default time gutter, preserving the historical `  [HH:MM:SS]` rendering.
 111const DEFAULT_TIME_FORMAT: &str = "  [%T]";
 112
 113/// Unix seconds of the timestamp used to measure time-gutter width.
 114///
 115/// 2024-01-17 13:25:30 UTC, so numeric fields have their usual widths.
 116const TIME_GUTTER_SAMPLE_UNIX: i64 = 1_705_497_930;
 117
 118fn time_gutter_sample() -> DateTime<Local> {
 119    DateTime::from_timestamp(TIME_GUTTER_SAMPLE_UNIX, 0)
 120        .unwrap_or_default()
 121        .with_timezone(&Local)
 122}
 123
 124/// Display columns reserved for the per-message time gutter.
 125///
 126/// The width is the display width of `format` applied to one fixed sample
 127/// timestamp, so a configuration keeps a constant column. An empty format
 128/// reserves nothing and hides the time.
 129pub fn time_gutter_width(format: &str) -> usize {
 130    if format.is_empty() {
 131        return 0;
 132    }
 133
 134    let rendered = time_gutter_sample().format(format).to_string();
 135    UnicodeWidthStr::width(rendered.as_str())
 136}
 137
 138fn is_profile_char(c: char) -> bool {
 139    c.is_ascii_alphanumeric() || c == '.' || c == '-'
 140}
 141
 142fn default_true() -> bool {
 143    true
 144}
 145
 146fn validate_profile_name(name: &str) -> bool {
 147    if name.is_empty() {
 148        return false;
 149    }
 150
 151    let mut chars = name.chars();
 152
 153    if !chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) {
 154        return false;
 155    }
 156
 157    name.chars().all(is_profile_char)
 158}
 159
 160fn validate_profile_names(names: &BTreeMap<String, ProfileConfig>) {
 161    for name in names.keys() {
 162        if validate_profile_name(name.as_str()) {
 163            continue;
 164        }
 165
 166        usage!(
 167            "{:?} is not a valid profile name.\n\n\
 168            Profile names can only contain the characters \
 169            a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
 170            name
 171        );
 172    }
 173}
 174
 175fn deserialize_from_str_opt<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
 176where
 177    D: serde::de::Deserializer<'de>,
 178    T: FromStr,
 179    <T as FromStr>::Err: fmt::Display,
 180{
 181    <Option<&'de str>>::deserialize(deserializer)?
 182        .map(|s| {
 183            let t = T::from_str(s);
 184            t.map_err(|e| D::Error::custom(format!("failed to parse string: {e}")))
 185        })
 186        .transpose()
 187}
 188
 189fn deserialize_register<'de, D>(deserializer: D) -> Result<Option<Register>, D::Error>
 190where
 191    D: serde::de::Deserializer<'de>,
 192{
 193    let r = String::deserialize(deserializer)?;
 194
 195    if r.len() > 1 {
 196        return Err(D::Error::custom("expected a single character to specify a register"));
 197    }
 198
 199    let r = match r.chars().next() {
 200        Some(c @ 'a'..='z') => Register::Named(c),
 201        Some('_') => Register::Blackhole,
 202        Some('*') => Register::SelectionPrimary,
 203        Some('+') => Register::SelectionClipboard,
 204        Some('"') => Register::Unnamed,
 205        Some(c) => {
 206            return Err(D::Error::custom(format!(
 207                "expected one of a-z, \", _, *, or + for the register, not {c:?}"
 208            )));
 209        },
 210        None => {
 211            return Err(D::Error::custom("expected a single character to specify a register"));
 212        },
 213    };
 214
 215    Ok(Some(r))
 216}
 217
 218fn deserialize_strftime<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
 219where
 220    D: Deserializer<'de>,
 221{
 222    let value = String::deserialize(deserializer)?;
 223
 224    // `DelayedFormat`'s `Display` impl returns `fmt::Error` for a bad specifier,
 225    // and `.to_string()` then panics. Reject those strings while loading config.
 226    if StrftimeItems::new(&value).any(|item| matches!(item, Item::Error)) {
 227        return Err(D::Error::custom(format!("invalid strftime format string: {value:?}")));
 228    }
 229
 230    Ok(Some(value))
 231}
 232
 233/// Load themes from disk, and merge in the configured overrides.
 234fn load_themes(
 235    themes_dir: &Path,
 236    theme_overrides: theme::Theme,
 237) -> anyhow::Result<CompletionMap<String, theme::Theme>> {
 238    let mut themes = CompletionMap::default();
 239
 240    let mut insert = |n, t| {
 241        let theme = theme_overrides.clone().merge(t).merge(theme::default_theme());
 242        themes.insert(n, theme);
 243    };
 244
 245    let mut load_dir = |d: &Path| -> anyhow::Result<()> {
 246        theme::find_themes(d)?.into_iter().for_each(|(n, t)| insert(n, t));
 247        Ok(())
 248    };
 249
 250    // Load themes from the shared directory first for systems with XDG_DATA_DIRS:
 251    #[cfg(any(unix, target_os = "redox"))]
 252    xdg::BaseDirectories::new()
 253        .get_data_dirs()
 254        .into_iter()
 255        .map(|p| p.join("iamb/themes"))
 256        .try_for_each(|p| load_dir(&p))?;
 257
 258    // Load from the `themes` directory in the user's configuration directory:
 259    load_dir(themes_dir)?;
 260
 261    // Insert a default theme that defaults to using terminal colors:
 262    let default_theme = theme_overrides.clone().merge(theme::default_theme());
 263    themes.insert("default".into(), default_theme);
 264    Ok(themes)
 265}
 266
 267/// This must be called before the alternate screen is entered
 268fn load_config_includes(mut config: IambConfig, config_dir: &Path) -> IambConfig {
 269    for include in std::mem::take(&mut config.include) {
 270        let expanded = shellexpand::full(&include)
 271            .unwrap_or_else(|err| panic!("unable to expand shell variables in include: {err}"));
 272
 273        let path = config_dir.join(&*expanded);
 274
 275        if path.is_dir() {
 276            let dir = match path.read_dir() {
 277                Ok(dir) => dir,
 278                Err(e) => {
 279                    eprintln!("Unable to read config files in {path:?}: {e}");
 280                    continue;
 281                },
 282            };
 283
 284            // get paths in lexicographic order
 285            let mut paths: Vec<_> = dir
 286                .flat_map(|entry| {
 287                    match entry {
 288                        Ok(file) => Some(file),
 289                        Err(e) => {
 290                            eprintln!("Unable to read config file in {path:?}: {e}");
 291                            None
 292                        },
 293                    }
 294                })
 295                .collect();
 296            paths.sort_unstable_by_key(|file| file.file_name());
 297
 298            for file in paths {
 299                let path = file.path();
 300                if path.extension().and_then(|e| e.to_str()) != Some("toml") {
 301                    continue;
 302                }
 303
 304                match IambConfig::load_toml(&path) {
 305                    Ok(include) => {
 306                        if !include.include.is_empty() {
 307                            eprintln!("Ignoring nested includes in {path:?}");
 308                        }
 309                        config = include.merge(config);
 310                    },
 311                    Err(e) => {
 312                        eprintln!("Unable to load config file in {path:?}: {e}");
 313                    },
 314                };
 315            }
 316        } else {
 317            match IambConfig::load_toml(&path) {
 318                Ok(include) => {
 319                    if !include.include.is_empty() {
 320                        eprintln!("Ignoring nested includes in {path:?}");
 321                    }
 322                    config = include.merge(config);
 323                },
 324                Err(e) => {
 325                    eprintln!("Unable to load config file in {path:?}: {e}");
 326                },
 327            };
 328        }
 329    }
 330
 331    config
 332}
 333
 334struct IambVersion;
 335
 336impl From<IambVersion> for clap::builder::Str {
 337    fn from(_: IambVersion) -> Self {
 338        let version: Cow<'static, str> = match option_env!("VERGEN_GIT_SHA") {
 339            None => env!("CARGO_PKG_VERSION").into(),
 340            Some(sha) => format!("{} ({sha})", env!("CARGO_PKG_VERSION")).into(),
 341        };
 342
 343        version.into()
 344    }
 345}
 346
 347#[derive(Parser)]
 348#[clap(version = IambVersion, about, long_about = None)]
 349#[clap(propagate_version = true)]
 350pub struct Iamb {
 351    #[clap(long, value_parser)]
 352    pub completions: Option<clap_complete::Shell>,
 353
 354    #[clap(short = 'P', long, value_parser)]
 355    pub profile: Option<String>,
 356
 357    #[clap(short = 'C', long, value_parser)]
 358    pub config_directory: Option<PathBuf>,
 359
 360    /// `matrix:` uri or `https://matrix.to` link to open
 361    pub uri: Option<String>,
 362}
 363
 364#[derive(thiserror::Error, Debug)]
 365pub enum ConfigError {
 366    #[error("Error reading configuration file: {0}")]
 367    IO(#[from] std::io::Error),
 368
 369    #[error("Error loading configuration file: {0}")]
 370    Invalid(#[from] toml::de::Error),
 371
 372    #[error("Error loading JSON configuration file: {0}")]
 373    InvalidJSON(#[from] serde_json::Error),
 374}
 375
 376macro_rules! deserialize_str_with_visitor {
 377    ($t: ident, $v: ident) => {
 378        impl<'de> Deserialize<'de> for $t {
 379            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 380            where
 381                D: Deserializer<'de>,
 382            {
 383                deserializer.deserialize_str($v)
 384            }
 385        }
 386    };
 387}
 388
 389deserialize_str_with_visitor!(Keys, KeysVisitor);
 390deserialize_str_with_visitor!(VimModes, VimModesVisitor);
 391deserialize_str_with_visitor!(EncryptionIndicatorLocation, EncryptionIndicatorLocationVisitor);
 392deserialize_str_with_visitor!(NotifyVia, NotifyViaVisitor);
 393deserialize_str_with_visitor!(ProxyUrl, ProxyUrlVisitor);
 394
 395#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 396pub struct Keys(pub Vec<TerminalKey>, pub String);
 397pub struct KeysVisitor;
 398
 399impl Visitor<'_> for KeysVisitor {
 400    type Value = Keys;
 401
 402    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 403        formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
 404    }
 405
 406    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 407    where
 408        E: SerdeError,
 409    {
 410        match TerminalKey::from_macro_str(value) {
 411            Ok(keys) => Ok(Keys(keys, value.to_string())),
 412            Err(e) => Err(E::custom(format!("Could not parse key sequence: {e}"))),
 413        }
 414    }
 415}
 416
 417#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 418pub struct VimModes(pub Vec<VimMode>);
 419pub struct VimModesVisitor;
 420
 421impl Visitor<'_> for VimModesVisitor {
 422    type Value = VimModes;
 423
 424    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 425        formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
 426    }
 427
 428    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 429    where
 430        E: SerdeError,
 431    {
 432        let mut modes = vec![];
 433
 434        for mode in value.split('|') {
 435            let mode = match mode.to_ascii_lowercase().as_str() {
 436                "insert" | "i" => VimMode::Insert,
 437                "normal" | "n" => VimMode::Normal,
 438                "visual" | "v" => VimMode::Visual,
 439                "command" | "c" => VimMode::Command,
 440                "select" => VimMode::Select,
 441                "operator-pending" => VimMode::OperationPending,
 442                _ => return Err(E::custom("Could not parse into a Vim mode")),
 443            };
 444
 445            modes.push(mode);
 446        }
 447
 448        Ok(VimModes(modes))
 449    }
 450}
 451
 452#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
 453pub struct Session {
 454    access_token: String,
 455    refresh_token: Option<String>,
 456    user_id: OwnedUserId,
 457    device_id: OwnedDeviceId,
 458    #[serde(skip_serializing_if = "Option::is_none")]
 459    client_id: Option<ClientId>,
 460}
 461
 462impl From<Session> for AuthSession {
 463    fn from(session: Session) -> Self {
 464        if let Some(client_id) = session.client_id {
 465            AuthSession::OAuth(Box::new(OAuthSession {
 466                client_id,
 467                user: UserSession {
 468                    meta: SessionMeta {
 469                        user_id: session.user_id,
 470                        device_id: session.device_id,
 471                    },
 472                    tokens: SessionTokens {
 473                        access_token: session.access_token,
 474                        refresh_token: session.refresh_token,
 475                    },
 476                },
 477            }))
 478        } else {
 479            AuthSession::Matrix(session.into())
 480        }
 481    }
 482}
 483
 484/// A device ID saved at logout so that the next login can reuse it.
 485///
 486/// The SDK store is keyed by user and device ID, so logging back in with
 487/// a freshly issued device ID would leave the existing store unusable
 488/// (#775). Saving the ID lets the next login ask the homeserver for the
 489/// same device and keep using that store.
 490#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
 491#[serde(untagged)]
 492pub enum SavedDevice {
 493    OAuth {
 494        user_id: OwnedUserId,
 495        device_id: OwnedDeviceId,
 496        client_id: ClientId,
 497    },
 498    MatrixAuth {
 499        user_id: OwnedUserId,
 500        device_id: OwnedDeviceId,
 501    },
 502}
 503
 504impl SavedDevice {
 505    pub fn device_id(&self) -> &DeviceId {
 506        match self {
 507            SavedDevice::OAuth { device_id, .. } => device_id,
 508            SavedDevice::MatrixAuth { device_id, .. } => device_id,
 509        }
 510    }
 511    pub fn client_id(&self) -> Option<&ClientId> {
 512        match self {
 513            SavedDevice::OAuth { client_id, .. } => Some(client_id),
 514            SavedDevice::MatrixAuth { .. } => None,
 515        }
 516    }
 517    pub fn is_user(&self, user: &UserId) -> bool {
 518        match self {
 519            SavedDevice::OAuth { user_id, .. } => user == user_id,
 520            SavedDevice::MatrixAuth { user_id, .. } => user == user_id,
 521        }
 522    }
 523}
 524
 525impl From<Session> for MatrixSession {
 526    fn from(session: Session) -> Self {
 527        MatrixSession {
 528            tokens: matrix_sdk::authentication::SessionTokens {
 529                access_token: session.access_token,
 530                refresh_token: session.refresh_token,
 531            },
 532            meta: matrix_sdk::SessionMeta {
 533                user_id: session.user_id,
 534                device_id: session.device_id,
 535            },
 536        }
 537    }
 538}
 539
 540impl From<MatrixSession> for Session {
 541    fn from(session: MatrixSession) -> Self {
 542        Session {
 543            access_token: session.tokens.access_token,
 544            refresh_token: session.tokens.refresh_token,
 545            user_id: session.meta.user_id,
 546            device_id: session.meta.device_id,
 547            client_id: None,
 548        }
 549    }
 550}
 551
 552impl From<OAuthSession> for Session {
 553    fn from(session: OAuthSession) -> Self {
 554        Session {
 555            access_token: session.user.tokens.access_token,
 556            refresh_token: session.user.tokens.refresh_token,
 557            user_id: session.user.meta.user_id,
 558            device_id: session.user.meta.device_id,
 559            client_id: Some(session.client_id),
 560        }
 561    }
 562}
 563
 564#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 565pub struct UserDisplayTunables {
 566    pub color: Option<Color>,
 567    pub name: Option<String>,
 568}
 569
 570pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
 571
 572#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash)]
 573#[serde(untagged)]
 574pub enum RoomOverrideKey {
 575    User(OwnedUserId),
 576    Room(OwnedRoomId),
 577    Alias(OwnedRoomAliasId),
 578}
 579
 580#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 581pub struct RoomOverrideTunables {
 582    pub name: Option<String>,
 583}
 584
 585pub type RoomOverrides = HashMap<RoomOverrideKey, RoomOverrideTunables>;
 586
 587#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 588pub struct RoomOverrideValues {
 589    pub rooms: HashMap<OwnedRoomId, RoomOverrideTunables>,
 590    pub aliases: HashMap<OwnedRoomAliasId, RoomOverrideTunables>,
 591    pub dms: HashMap<OwnedUserId, RoomOverrideTunables>,
 592}
 593
 594impl From<RoomOverrides> for RoomOverrideValues {
 595    fn from(value: RoomOverrides) -> Self {
 596        let mut rooms = HashMap::new();
 597        let mut aliases = HashMap::new();
 598        let mut dms = HashMap::new();
 599
 600        for (key, value) in value {
 601            match key {
 602                RoomOverrideKey::User(user_id) => dms.insert(user_id, value),
 603                RoomOverrideKey::Room(room_id) => rooms.insert(room_id, value),
 604                RoomOverrideKey::Alias(alias_id) => aliases.insert(alias_id, value),
 605            };
 606        }
 607
 608        Self { rooms, aliases, dms }
 609    }
 610}
 611
 612fn merge_maps<M, K, V>(profile: Option<M>, global: Option<M>) -> Option<M>
 613where
 614    M: Extend<(K, V)> + IntoIterator<Item = (K, V)>,
 615{
 616    match (global, profile) {
 617        (Some(m), None) | (None, Some(m)) => Some(m),
 618        (Some(mut global), Some(profile)) => {
 619            global.extend(profile);
 620            Some(global)
 621        },
 622        (None, None) => None,
 623    }
 624}
 625
 626fn merge_macros(profile: Option<Macros>, global: Option<Macros>) -> Option<Macros> {
 627    match (global, profile) {
 628        (Some(m), None) | (None, Some(m)) => Some(m),
 629        (Some(mut global), Some(profile)) => {
 630            for (mode, macros) in profile {
 631                match global.entry(mode) {
 632                    hash_map::Entry::Vacant(entry) => {
 633                        entry.insert(macros);
 634                    },
 635                    hash_map::Entry::Occupied(mut entry) => {
 636                        entry.get_mut().extend(macros);
 637                    },
 638                }
 639            }
 640
 641            Some(global)
 642        },
 643        (None, None) => None,
 644    }
 645}
 646
 647#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 648#[serde(rename_all = "kebab-case")]
 649#[repr(u8)]
 650pub enum ReadReceiptTrigger {
 651    /// Update read receipts for a room when a window for it is focused, and it is scrolled to the
 652    /// last message.
 653    #[default]
 654    Focused,
 655    /// Update read receipts for a room when a window for it is visible, and it is scrolled to the
 656    /// last message.
 657    Visible,
 658    /// Update read receipts for a room whenever some portion of its scrollback is rendered.
 659    Scrollback,
 660    /// Update read receipts for a room once the user sends a message to it.
 661    Message,
 662}
 663
 664impl ReadReceiptTrigger {
 665    /// Whether to update read receipts when a room is being rendered.
 666    pub fn on_render(&self, last_visible: bool, room_focused: bool) -> bool {
 667        match self {
 668            Self::Scrollback => true,
 669            Self::Focused => last_visible && room_focused,
 670            Self::Visible => last_visible,
 671            Self::Message => false,
 672        }
 673    }
 674
 675    pub fn on_message(&self) -> bool {
 676        matches!(self, Self::Message)
 677    }
 678}
 679
 680#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 681#[serde(rename_all = "kebab-case")]
 682#[repr(u8)]
 683pub enum EncryptionIndicator {
 684    /// Always indicate the room's encryption status.
 685    #[default]
 686    Enabled,
 687    /// Never indicate the room's encryption status.
 688    Disabled,
 689    /// Only indicate the room's encryption status when it is encrypted.
 690    OnlyEncrypted,
 691    /// Only indicate the room's encryption status when it is unencrypted.
 692    OnlyUnencrypted,
 693}
 694
 695bitflags::bitflags! {
 696    /// Available options for where to show the encryption status indicator.
 697    #[derive(Clone, Debug, Eq, PartialEq)]
 698    pub struct EncryptionIndicatorLocation: u8 {
 699        const NONE   = 0b00000000;
 700        const TITLE  = 0b00000001;
 701        const PROMPT = 0b00000010;
 702    }
 703}
 704
 705pub struct EncryptionIndicatorLocationVisitor;
 706
 707impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
 708    type Value = EncryptionIndicatorLocation;
 709
 710    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 711        formatter.write_str("a valid encryption indicator location (e.g. \"title\" or \"prompt\")")
 712    }
 713
 714    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 715    where
 716        E: SerdeError,
 717    {
 718        let mut location = EncryptionIndicatorLocation::NONE;
 719
 720        for value in value.split('|') {
 721            match value.to_ascii_lowercase().as_str() {
 722                "title" => location |= EncryptionIndicatorLocation::TITLE,
 723                "prompt" => location |= EncryptionIndicatorLocation::PROMPT,
 724                _ => {
 725                    return Err(E::custom("could not parse into an encryption indicator location"));
 726                },
 727            };
 728        }
 729
 730        Ok(location)
 731    }
 732}
 733
 734/// Types of room labels to display in room lists.
 735#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
 736#[serde(rename_all = "kebab-case")]
 737#[repr(u8)]
 738pub enum RoomLabel {
 739    Membership,
 740    Muted,
 741    Tags,
 742    Type,
 743    Unread,
 744}
 745
 746#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 747#[serde(rename_all = "lowercase")]
 748pub enum UserDisplayStyle {
 749    // The Matrix username for the sender (e.g., "@user:example.com").
 750    #[default]
 751    Username,
 752
 753    // The localpart of the Matrix username (e.g., "@user").
 754    LocalPart,
 755
 756    // The display name for the Matrix user, calculated according to the rules from the spec.
 757    //
 758    // This is usually something like "Ada Lovelace" if the user has configured a display name, but
 759    // it can wind up being the Matrix username if there are display name collisions in the room,
 760    // in order to avoid any confusion.
 761    DisplayName,
 762}
 763
 764#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
 765#[serde(rename_all = "lowercase")]
 766pub enum SplitDirection {
 767    #[default]
 768    Horizontal,
 769    Vertical,
 770}
 771
 772impl From<SplitDirection> for Axis {
 773    fn from(dir: SplitDirection) -> Axis {
 774        match dir {
 775            SplitDirection::Horizontal => Axis::Horizontal,
 776            SplitDirection::Vertical => Axis::Vertical,
 777        }
 778    }
 779}
 780
 781#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 782pub struct NotifyVia {
 783    /// Deliver notifications via terminal bell.
 784    pub bell: bool,
 785    /// Deliver notifications via desktop mechanism.
 786    #[cfg(feature = "desktop")]
 787    pub desktop: bool,
 788}
 789pub struct NotifyViaVisitor;
 790
 791impl Default for NotifyVia {
 792    fn default() -> Self {
 793        Self {
 794            bell: cfg!(not(feature = "desktop")),
 795            #[cfg(feature = "desktop")]
 796            desktop: true,
 797        }
 798    }
 799}
 800
 801impl Visitor<'_> for NotifyViaVisitor {
 802    type Value = NotifyVia;
 803
 804    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 805        formatter.write_str("a valid notify destination (e.g. \"bell\" or \"desktop\")")
 806    }
 807
 808    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 809    where
 810        E: SerdeError,
 811    {
 812        let mut via = NotifyVia {
 813            bell: false,
 814            #[cfg(feature = "desktop")]
 815            desktop: false,
 816        };
 817
 818        for value in value.split('|') {
 819            match value.to_ascii_lowercase().as_str() {
 820                "bell" => {
 821                    via.bell = true;
 822                },
 823                #[cfg(feature = "desktop")]
 824                "desktop" => {
 825                    via.desktop = true;
 826                },
 827                #[cfg(not(feature = "desktop"))]
 828                "desktop" => {
 829                    return Err(E::custom("desktop notification support was compiled out"));
 830                },
 831                _ => return Err(E::custom("could not parse into a notify destination")),
 832            };
 833        }
 834
 835        Ok(via)
 836    }
 837}
 838
 839#[derive(Clone, Debug, Default, Deserialize)]
 840pub struct Encryption {
 841    indicator: Option<EncryptionIndicator>,
 842    indicator_location: Option<EncryptionIndicatorLocation>,
 843    icon_encrypted: Option<String>,
 844    icon_unencrypted: Option<String>,
 845    icon_unknown: Option<String>,
 846}
 847
 848impl Encryption {
 849    fn merge(profile: Self, global: Self) -> Self {
 850        Encryption {
 851            indicator: profile.indicator.or(global.indicator),
 852            indicator_location: profile.indicator_location.or(global.indicator_location),
 853            icon_encrypted: profile.icon_encrypted.or(global.icon_encrypted),
 854            icon_unencrypted: profile.icon_unencrypted.or(global.icon_unencrypted),
 855            icon_unknown: profile.icon_unknown.or(global.icon_unknown),
 856        }
 857    }
 858
 859    pub fn values(self) -> EncryptionValues {
 860        EncryptionValues {
 861            indicator: self.indicator.unwrap_or_default(),
 862            indicator_location: self.indicator_location.unwrap_or(DEFAULT_ENC_INDICATOR_LOC),
 863            icon_encrypted: self.icon_encrypted.map(Cow::Owned).unwrap_or(DEFAULT_ICON_ENC),
 864            icon_unencrypted: self.icon_unencrypted.map(Cow::Owned).unwrap_or(DEFAULT_ICON_UNENC),
 865            icon_unknown: self.icon_unknown.map(Cow::Owned).unwrap_or(DEFAULT_ICON_UNKNOWN),
 866        }
 867    }
 868}
 869
 870#[derive(Clone, Debug)]
 871pub struct EncryptionValues {
 872    pub indicator: EncryptionIndicator,
 873    pub indicator_location: EncryptionIndicatorLocation,
 874    pub icon_encrypted: Cow<'static, str>,
 875    pub icon_unencrypted: Cow<'static, str>,
 876    pub icon_unknown: Cow<'static, str>,
 877}
 878
 879impl EncryptionValues {
 880    pub fn get_indicator(
 881        &self,
 882        location: EncryptionIndicatorLocation,
 883        state: EncryptionState,
 884        theme: &ThemeValues,
 885    ) -> Option<Span<'static>> {
 886        if !self.indicator_location.contains(location) {
 887            return None;
 888        }
 889
 890        let indicator = match (self.indicator, state) {
 891            (EncryptionIndicator::Disabled, _) |
 892            (EncryptionIndicator::OnlyUnencrypted, EncryptionState::Encrypted) |
 893            (EncryptionIndicator::OnlyEncrypted, EncryptionState::NotEncrypted) => {
 894                // User doesn't want to see anything:
 895                return None;
 896            },
 897            (
 898                EncryptionIndicator::Enabled | EncryptionIndicator::OnlyEncrypted,
 899                EncryptionState::Encrypted,
 900            ) => {
 901                // Green encrypted icon:
 902                Span::styled(self.icon_encrypted.clone(), theme.encryption.icon_encrypted)
 903            },
 904            (
 905                EncryptionIndicator::Enabled | EncryptionIndicator::OnlyUnencrypted,
 906                EncryptionState::NotEncrypted,
 907            ) => {
 908                // Red unencrypted icon:
 909                Span::styled(self.icon_unencrypted.clone(), theme.encryption.icon_unencrypted)
 910            },
 911
 912            (_, EncryptionState::Unknown) => {
 913                // Yellow unknown icon:
 914                Span::styled(self.icon_unknown.clone(), theme.encryption.icon_unknown)
 915            },
 916        };
 917
 918        Some(indicator)
 919    }
 920}
 921
 922#[derive(Clone, Debug, Default, Eq, PartialEq)]
 923pub enum ProxyUrl {
 924    Disabled,
 925    Endpoint(Url),
 926    #[default]
 927    System,
 928}
 929
 930pub struct ProxyUrlVisitor;
 931
 932impl Visitor<'_> for ProxyUrlVisitor {
 933    type Value = ProxyUrl;
 934
 935    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 936        formatter.write_str("a valid proxy URL (e.g. \"socks5://localhost:9050\")")
 937    }
 938
 939    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 940    where
 941        E: SerdeError,
 942    {
 943        if value.is_empty() {
 944            return Ok(ProxyUrl::Disabled);
 945        }
 946
 947        match Url::from_str(value) {
 948            Ok(uri) => Ok(ProxyUrl::Endpoint(uri)),
 949            Err(e) => Err(E::custom(format!("could not parse {value:?}: {e}"))),
 950        }
 951    }
 952}
 953
 954#[derive(Clone, Debug, Default, Deserialize)]
 955pub struct Proxy {
 956    /// How and where to proxy the client's requests to the homeserver.
 957    url: Option<ProxyUrl>,
 958
 959    /// An optional value to include in the `Proxy-Authorization` header.
 960    #[serde(default, deserialize_with = "deserialize_from_str_opt")]
 961    auth: Option<HeaderValue>,
 962
 963    /// Optional headers to include in requests sent to the proxy.
 964    #[serde(default, with = "http_serde::header_map")]
 965    headers: HeaderMap,
 966}
 967
 968impl Proxy {
 969    pub fn values(self) -> ProxyValues {
 970        ProxyValues {
 971            url: self.url.unwrap_or_default(),
 972            auth: self.auth,
 973            headers: self.headers,
 974        }
 975    }
 976}
 977
 978#[derive(Clone, Debug, Default)]
 979pub struct ProxyValues {
 980    pub url: ProxyUrl,
 981    pub auth: Option<HeaderValue>,
 982    pub headers: HeaderMap,
 983}
 984
 985#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 986pub struct Mouse {
 987    #[serde(default)]
 988    pub enabled: bool,
 989}
 990
 991#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 992pub struct Notifications {
 993    #[serde(default)]
 994    pub enabled: bool,
 995    #[serde(default)]
 996    pub via: NotifyVia,
 997    #[serde(default = "default_true")]
 998    pub show_message: bool,
 999    #[serde(default)]
1000    pub sound_hint: Option<String>,
1001}
1002
1003#[derive(Clone)]
1004pub struct ImagePreviewValues {
1005    pub enabled: bool,
1006    pub size: Size,
1007    pub protocol: ImagePreviewProtocolValues,
1008}
1009
1010#[derive(Clone, Debug, Default, Deserialize)]
1011pub struct ImagePreview {
1012    pub enabled: Option<bool>,
1013    pub size: Option<Size>,
1014    pub protocol: Option<ImagePreviewProtocolValues>,
1015}
1016
1017impl ImagePreview {
1018    pub fn values(self) -> ImagePreviewValues {
1019        ImagePreviewValues {
1020            enabled: self.enabled.unwrap_or(true),
1021            size: self.size.unwrap_or(Size { width: 66, height: 10 }),
1022            protocol: self.protocol.unwrap_or_default(),
1023        }
1024    }
1025}
1026
1027#[derive(Clone, Debug, Deserialize, Default)]
1028pub struct ImagePreviewProtocolValues {
1029    pub r#type: Option<ProtocolType>,
1030    pub filter: Option<FilterType>,
1031    pub font_size: Option<(u16, u16)>,
1032}
1033
1034#[derive(Clone)]
1035pub struct SortValues {
1036    pub chats: Vec<SortColumn<SortFieldRoom>>,
1037    pub dms: Vec<SortColumn<SortFieldRoom>>,
1038    pub rooms: Vec<SortColumn<SortFieldRoom>>,
1039    pub spaces: Vec<SortColumn<SortFieldRoom>>,
1040    pub members: Vec<SortColumn<SortFieldUser>>,
1041    pub space: Vec<SortColumn<SortFieldSpace>>,
1042}
1043
1044#[derive(Clone, Debug, Default, Deserialize)]
1045pub struct SortOverrides {
1046    pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
1047    pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
1048    pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
1049    pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
1050    pub members: Option<Vec<SortColumn<SortFieldUser>>>,
1051    pub space: Option<Vec<SortColumn<SortFieldSpace>>>,
1052}
1053
1054impl SortOverrides {
1055    fn merge(profile: Self, global: Self) -> Self {
1056        Self {
1057            chats: profile.chats.or(global.chats),
1058            dms: profile.dms.or(global.dms),
1059            rooms: profile.rooms.or(global.rooms),
1060            spaces: profile.spaces.or(global.spaces),
1061            members: profile.members.or(global.members),
1062            space: profile.space.or(global.space),
1063        }
1064    }
1065
1066    pub fn values(self) -> SortValues {
1067        let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
1068        let chats = self.chats.unwrap_or_else(|| rooms.clone());
1069        let dms = self.dms.unwrap_or_else(|| rooms.clone());
1070        let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
1071        let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
1072        let space = self.space.unwrap_or_else(|| Vec::from(DEFAULT_SPACE_SORT));
1073
1074        SortValues { rooms, members, chats, dms, spaces, space }
1075    }
1076}
1077
1078#[derive(Clone, Debug, Default, Deserialize)]
1079pub struct Terminal {
1080    pub cursor_shape: Option<CursorShape>,
1081    pub enable_extended_keys: Option<bool>,
1082    pub enable_title: Option<bool>,
1083}
1084
1085impl Terminal {
1086    fn merge(profile: Self, global: Self) -> Self {
1087        Self {
1088            cursor_shape: profile.cursor_shape.or(global.cursor_shape),
1089            enable_extended_keys: profile.enable_extended_keys.or(global.enable_extended_keys),
1090            enable_title: profile.enable_title.or(global.enable_title),
1091        }
1092    }
1093
1094    pub fn values(self) -> TerminalValues {
1095        TerminalValues {
1096            cursor_shape: self.cursor_shape.unwrap_or_default(),
1097            enable_extended_keys: self.enable_extended_keys,
1098            enable_title: self.enable_title.unwrap_or(DEFAULT_ENABLE_TITLE),
1099        }
1100    }
1101}
1102
1103#[derive(Clone, Debug)]
1104pub struct TerminalValues {
1105    pub cursor_shape: CursorShape,
1106    pub enable_extended_keys: Option<bool>,
1107    pub enable_title: bool,
1108}
1109
1110/// The configuration settings to run with, after merging the
1111/// per-profile overrides on top of the global settings.
1112#[derive(Clone)]
1113pub struct TunableValues {
1114    pub encryption: EncryptionValues,
1115    pub default_markup: MarkupFormat,
1116    pub ignorecase: bool,
1117    pub log_level: String,
1118    pub max_log_files: usize,
1119    pub message_formatted_display: bool,
1120    pub message_shortcode_display: bool,
1121    pub normal_after_send: bool,
1122    pub proxy: ProxyValues,
1123    pub reaction_display: bool,
1124    pub reaction_shortcode_display: bool,
1125    pub read_receipt_send: bool,
1126    pub read_receipt_trigger: ReadReceiptTrigger,
1127    pub read_receipt_display: bool,
1128    pub room_labels: Vec<RoomLabel>,
1129    pub request_timeout: u64,
1130    pub sort: SortValues,
1131    pub state_event_display: bool,
1132    pub sync_delay_ms: u64,
1133    pub theme: String,
1134    pub typing_notice_send: bool,
1135    pub typing_notice_display: bool,
1136    pub users: UserOverrides,
1137    pub rooms: RoomOverrideValues,
1138    pub username_display: UserDisplayStyle,
1139    pub message_user_color: bool,
1140    pub default_register: Option<Register>,
1141    pub default_room: Option<String>,
1142    pub default_via: HashSet<OwnedServerName>,
1143    pub open_command: Option<Vec<String>>,
1144    pub mouse: Mouse,
1145    pub notifications: Notifications,
1146    pub terminal: TerminalValues,
1147    pub image_preview: ImagePreviewValues,
1148    pub user_gutter_width: usize,
1149    pub external_edit_file_suffix: String,
1150    pub tabstop: usize,
1151    pub input_prompt: Option<String>,
1152    pub members_split: Option<SplitDirection>,
1153    pub default_split: SplitDirection,
1154    pub ssl_verify: bool,
1155    pub cache_policy: MediaRetentionPolicy,
1156    pub send_on_enter: bool,
1157    pub date_format: String,
1158    pub time_format: String,
1159    /// Display columns reserved for the time gutter, computed from
1160    /// `time_format` once when the settings are loaded.
1161    pub time_gutter_width: usize,
1162    pub reply_on_insert: bool,
1163}
1164
1165#[derive(Clone, Debug, Default, Deserialize)]
1166pub struct Tunables {
1167    /// Subsection for overriding encryption-related settings.
1168    #[serde(default)]
1169    pub encryption: Encryption,
1170
1171    /// Subsection for configuring an HTTP(S) proxy.
1172    pub proxy: Option<Proxy>,
1173
1174    /// Subsection for overriding sort orders in UI lists.
1175    #[serde(default)]
1176    pub sort: SortOverrides,
1177
1178    /// Subsection for overriding terminal settings.
1179    #[serde(default)]
1180    pub terminal: Terminal,
1181
1182    /// Subsection for overriding how specific Matrix users are rendered.
1183    pub users: Option<UserOverrides>,
1184    pub rooms: Option<RoomOverrides>,
1185
1186    pub default_markup: Option<MarkupFormat>,
1187    pub ignorecase: Option<bool>,
1188    pub log_level: Option<String>,
1189    pub max_log_files: Option<usize>,
1190    pub message_formatted_display: Option<bool>,
1191    pub message_shortcode_display: Option<bool>,
1192    pub normal_after_send: Option<bool>,
1193    pub reaction_display: Option<bool>,
1194    pub reaction_shortcode_display: Option<bool>,
1195    pub read_receipt_send: Option<bool>,
1196    pub read_receipt_trigger: Option<ReadReceiptTrigger>,
1197    pub read_receipt_display: Option<bool>,
1198    pub room_labels: Option<Vec<RoomLabel>>,
1199    pub request_timeout: Option<u64>,
1200    pub state_event_display: Option<bool>,
1201    pub sync_delay_ms: Option<u64>,
1202    pub theme: Option<String>,
1203    pub typing_notice_send: Option<bool>,
1204    pub typing_notice_display: Option<bool>,
1205    pub username_display: Option<UserDisplayStyle>,
1206    pub message_user_color: Option<bool>,
1207    #[serde(default, deserialize_with = "deserialize_register")]
1208    pub default_register: Option<Register>,
1209    pub default_room: Option<String>,
1210    pub default_via: Option<Vec<OwnedServerName>>,
1211    pub open_command: Option<Vec<String>>,
1212    pub mouse: Option<Mouse>,
1213    pub notifications: Option<Notifications>,
1214    pub image_preview: Option<ImagePreview>,
1215    pub user_gutter_width: Option<usize>,
1216    pub external_edit_file_suffix: Option<String>,
1217    pub tabstop: Option<usize>,
1218    pub input_prompt: Option<String>,
1219    pub members_split: Option<SplitDirection>,
1220    pub default_split: Option<SplitDirection>,
1221    pub ssl_verify: Option<bool>,
1222    pub cache_policy: Option<MediaRetentionPolicy>,
1223    pub send_on_enter: Option<bool>,
1224    #[serde(default, deserialize_with = "deserialize_strftime")]
1225    pub date_format: Option<String>,
1226    /// strftime string for the per-message time gutter, including any brackets
1227    /// or spacing. The column is as wide as a sample rendering of this string.
1228    /// An empty string hides the time.
1229    #[serde(default, deserialize_with = "deserialize_strftime")]
1230    pub time_format: Option<String>,
1231    pub reply_on_insert: Option<bool>,
1232}
1233
1234impl Tunables {
1235    fn merge(self, other: Self) -> Self {
1236        Tunables {
1237            encryption: Encryption::merge(self.encryption, other.encryption),
1238            sort: SortOverrides::merge(self.sort, other.sort),
1239            terminal: Terminal::merge(self.terminal, other.terminal),
1240            users: merge_maps(self.users, other.users),
1241            rooms: merge_maps(self.rooms, other.rooms),
1242
1243            // Proxy configuration sub-field do *not* get merged, so that a
1244            // per-profile override won't inherit auth or headers from the
1245            // global settings.
1246            proxy: self.proxy.or(other.proxy),
1247
1248            default_markup: self.default_markup.or(other.default_markup),
1249            ignorecase: self.ignorecase.or(other.ignorecase),
1250            log_level: self.log_level.or(other.log_level),
1251            max_log_files: self.max_log_files.or(other.max_log_files),
1252            message_formatted_display: self
1253                .message_formatted_display
1254                .or(other.message_formatted_display),
1255            message_shortcode_display: self
1256                .message_shortcode_display
1257                .or(other.message_shortcode_display),
1258            normal_after_send: self.normal_after_send.or(other.normal_after_send),
1259            reaction_display: self.reaction_display.or(other.reaction_display),
1260            reaction_shortcode_display: self
1261                .reaction_shortcode_display
1262                .or(other.reaction_shortcode_display),
1263            read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
1264            read_receipt_trigger: self.read_receipt_trigger.or(other.read_receipt_trigger),
1265            read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
1266            room_labels: self.room_labels.or(other.room_labels),
1267            request_timeout: self.request_timeout.or(other.request_timeout),
1268            state_event_display: self.state_event_display.or(other.state_event_display),
1269            sync_delay_ms: self.sync_delay_ms.or(other.sync_delay_ms),
1270            theme: self.theme.or(other.theme),
1271            typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
1272            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
1273            username_display: self.username_display.or(other.username_display),
1274            message_user_color: self.message_user_color.or(other.message_user_color),
1275            default_register: self.default_register.or(other.default_register),
1276            default_room: self.default_room.or(other.default_room),
1277            default_via: self.default_via.or(other.default_via),
1278            open_command: self.open_command.or(other.open_command),
1279            mouse: self.mouse.or(other.mouse),
1280            notifications: self.notifications.or(other.notifications),
1281            image_preview: self.image_preview.or(other.image_preview),
1282            user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
1283            external_edit_file_suffix: self
1284                .external_edit_file_suffix
1285                .or(other.external_edit_file_suffix),
1286            tabstop: self.tabstop.or(other.tabstop),
1287            input_prompt: self.input_prompt.or(other.input_prompt),
1288            members_split: self.members_split.or(other.members_split),
1289            default_split: self.default_split.or(other.default_split),
1290            ssl_verify: self.ssl_verify.or(other.ssl_verify),
1291            cache_policy: self.cache_policy.or(other.cache_policy),
1292            send_on_enter: self.send_on_enter.or(other.send_on_enter),
1293            date_format: self.date_format.or(other.date_format),
1294            time_format: self.time_format.or(other.time_format),
1295            reply_on_insert: self.reply_on_insert.or(other.reply_on_insert),
1296        }
1297    }
1298
1299    fn values(self) -> TunableValues {
1300        let time_format = self.time_format.unwrap_or_else(|| DEFAULT_TIME_FORMAT.to_owned());
1301        let time_gutter_width = time_gutter_width(&time_format);
1302
1303        TunableValues {
1304            encryption: self.encryption.values(),
1305            proxy: self.proxy.unwrap_or_default().values(),
1306            sort: self.sort.values(),
1307            terminal: self.terminal.values(),
1308            users: self.users.unwrap_or_default(),
1309            rooms: self.rooms.unwrap_or_default().into(),
1310
1311            default_markup: self.default_markup.unwrap_or_default(),
1312            log_level: self.log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_owned()),
1313            ignorecase: self.ignorecase.unwrap_or(false),
1314            max_log_files: self.max_log_files.unwrap_or(7),
1315            message_formatted_display: self.message_formatted_display.unwrap_or(true),
1316            message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
1317            normal_after_send: self.normal_after_send.unwrap_or(false),
1318            reaction_display: self.reaction_display.unwrap_or(true),
1319            reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
1320            read_receipt_send: self.read_receipt_send.unwrap_or(true),
1321            read_receipt_trigger: self.read_receipt_trigger.unwrap_or_default(),
1322            read_receipt_display: self.read_receipt_display.unwrap_or(true),
1323            room_labels: self.room_labels.unwrap_or_else(|| DEFAULT_ROOM_LABELS.to_vec()),
1324            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
1325            state_event_display: self.state_event_display.unwrap_or(true),
1326            sync_delay_ms: self.sync_delay_ms.unwrap_or(DEFAULT_SYNC_FREQUENCY),
1327            theme: self.theme.unwrap_or_else(|| "default".to_string()),
1328            typing_notice_send: self.typing_notice_send.unwrap_or(true),
1329            typing_notice_display: self.typing_notice_display.unwrap_or(true),
1330            username_display: self.username_display.unwrap_or_default(),
1331            message_user_color: self.message_user_color.unwrap_or(false),
1332            default_register: self.default_register,
1333            default_room: self.default_room,
1334            default_via: self
1335                .default_via
1336                .unwrap_or_else(|| vec![DEFAULT_VIA_SERVER.clone()])
1337                .into_iter()
1338                .collect(),
1339            open_command: self.open_command,
1340            mouse: self.mouse.unwrap_or_default(),
1341            notifications: self.notifications.unwrap_or_default(),
1342            image_preview: self.image_preview.unwrap_or_default().values(),
1343            user_gutter_width: self.user_gutter_width.unwrap_or(30),
1344            external_edit_file_suffix: self
1345                .external_edit_file_suffix
1346                .unwrap_or_else(|| ".md".to_string()),
1347            tabstop: self.tabstop.unwrap_or(4),
1348            input_prompt: self.input_prompt,
1349            members_split: self.members_split,
1350            default_split: self.default_split.unwrap_or_default(),
1351            ssl_verify: self.ssl_verify.unwrap_or(true),
1352            cache_policy: self.cache_policy.unwrap_or_default(),
1353            send_on_enter: self.send_on_enter.unwrap_or(true),
1354            date_format: self.date_format.unwrap_or_else(|| DEFAULT_DATE_FORMAT.to_owned()),
1355            time_format,
1356            time_gutter_width,
1357            reply_on_insert: self.reply_on_insert.unwrap_or_default(),
1358        }
1359    }
1360}
1361
1362#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1363#[serde(rename_all = "kebab-case")]
1364#[repr(u8)]
1365pub enum CursorShape {
1366    Default,
1367    Block,
1368    Line,
1369    Underline,
1370    #[default]
1371    Auto,
1372}
1373
1374impl From<CursorShape> for modalkit::crossterm::cursor::SetCursorStyle {
1375    fn from(shape: CursorShape) -> Self {
1376        match shape {
1377            CursorShape::Default => Self::DefaultUserShape,
1378            CursorShape::Block => Self::SteadyBlock,
1379            CursorShape::Line => Self::SteadyBar,
1380            CursorShape::Underline => Self::SteadyUnderScore,
1381
1382            // use steady block at startup and switch to the correct value on first render
1383            CursorShape::Auto => Self::SteadyBlock,
1384        }
1385    }
1386}
1387
1388#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1389#[serde(rename_all = "kebab-case")]
1390#[repr(u8)]
1391pub enum MarkupFormat {
1392    Html,
1393    #[default]
1394    Markdown,
1395    Plaintext,
1396}
1397
1398#[derive(Clone)]
1399pub struct DirectoryValues {
1400    pub cache: PathBuf,
1401    pub data: PathBuf,
1402    pub logs: PathBuf,
1403    pub downloads: Option<PathBuf>,
1404}
1405
1406impl DirectoryValues {
1407    fn create_dir_all(&self) -> std::io::Result<()> {
1408        use std::fs::create_dir_all;
1409
1410        let Self { cache, data, logs, downloads } = self;
1411
1412        create_dir_all(cache)?;
1413        create_dir_all(data)?;
1414        create_dir_all(logs)?;
1415
1416        if let Some(downloads) = downloads {
1417            create_dir_all(downloads)?;
1418        }
1419
1420        Ok(())
1421    }
1422}
1423
1424#[derive(Clone, Default, Deserialize)]
1425pub struct Directories {
1426    pub cache: Option<String>,
1427    pub data: Option<String>,
1428    pub logs: Option<String>,
1429    pub downloads: Option<String>,
1430}
1431
1432impl Directories {
1433    fn merge(self, other: Self) -> Self {
1434        Directories {
1435            cache: self.cache.or(other.cache),
1436            data: self.data.or(other.data),
1437            logs: self.logs.or(other.logs),
1438            downloads: self.downloads.or(other.downloads),
1439        }
1440    }
1441
1442    fn values(self) -> DirectoryValues {
1443        let cache = self
1444            .cache
1445            .map(|dir| {
1446                let dir = shellexpand::full(&dir)
1447                    .expect("unable to expand shell variables in dirs.cache");
1448                Path::new(dir.as_ref()).to_owned()
1449            })
1450            .or_else(|| {
1451                let mut dir = dirs::cache_dir()?;
1452                dir.push("iamb");
1453                dir.into()
1454            })
1455            .expect("no dirs.cache value configured!");
1456
1457        let data = self
1458            .data
1459            .map(|dir| {
1460                let dir = shellexpand::full(&dir)
1461                    .expect("unable to expand shell variables in dirs.cache");
1462                Path::new(dir.as_ref()).to_owned()
1463            })
1464            .or_else(|| {
1465                let mut dir = dirs::data_dir()?;
1466                dir.push("iamb");
1467                dir.into()
1468            })
1469            .expect("no dirs.data value configured!");
1470
1471        let logs = self
1472            .logs
1473            .map(|dir| {
1474                let dir = shellexpand::full(&dir)
1475                    .expect("unable to expand shell variables in dirs.cache");
1476                Path::new(dir.as_ref()).to_owned()
1477            })
1478            .unwrap_or_else(|| {
1479                let mut dir = cache.clone();
1480                dir.push("logs");
1481                dir
1482            });
1483
1484        let downloads = self
1485            .downloads
1486            .map(|dir| {
1487                let dir = shellexpand::full(&dir)
1488                    .expect("unable to expand shell variables in dirs.cache");
1489                Path::new(dir.as_ref()).to_owned()
1490            })
1491            .or_else(dirs::download_dir);
1492
1493        DirectoryValues { cache, data, logs, downloads }
1494    }
1495}
1496
1497#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1498#[serde(untagged)]
1499pub enum WindowPath {
1500    AliasId(OwnedRoomAliasId),
1501    RoomId(OwnedRoomId),
1502    UserId(OwnedUserId),
1503    Window(IambId),
1504}
1505
1506#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1507#[serde(untagged, deny_unknown_fields)]
1508pub enum WindowLayout {
1509    Window { window: WindowPath },
1510    Split { split: Vec<WindowLayout> },
1511}
1512
1513#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1514#[serde(rename_all = "lowercase", tag = "style")]
1515pub enum Layout {
1516    /// Restore the layout from the previous session.
1517    #[default]
1518    Restore,
1519
1520    /// Open a single window using the `default_room` value.
1521    New,
1522
1523    /// Open the window layouts described under `tabs`.
1524    Config { tabs: Vec<WindowLayout> },
1525}
1526
1527#[derive(Default, Clone, Deserialize)]
1528pub struct ProfileConfig {
1529    pub user_id: Option<OwnedUserId>,
1530    pub password_file: Option<PathBuf>,
1531    pub url: Option<Url>,
1532    pub settings: Option<Tunables>,
1533    pub theme: Option<theme::Theme>,
1534    pub dirs: Option<Directories>,
1535    pub layout: Option<Layout>,
1536    pub macros: Option<Macros>,
1537    pub aliases: Option<Aliases>,
1538}
1539
1540impl ProfileConfig {
1541    fn merge(self, other: Self) -> Self {
1542        let user_id = self.user_id.or(other.user_id);
1543        let password_file = self.password_file.or(other.password_file);
1544        let url = self.url.or(other.url);
1545        let settings = merge_options!(self.settings, other.settings);
1546        let theme = merge_options!(self.theme, other.theme);
1547        let dirs = merge_options!(self.dirs, other.dirs);
1548        let layout = self.layout.or(other.layout);
1549        let macros = merge_macros(self.macros, other.macros);
1550        let aliases = merge_maps(self.aliases, other.aliases);
1551
1552        Self {
1553            user_id,
1554            password_file,
1555            url,
1556            settings,
1557            theme,
1558            dirs,
1559            layout,
1560            macros,
1561            aliases,
1562        }
1563    }
1564}
1565
1566#[derive(Clone, Deserialize)]
1567pub struct IambConfig {
1568    #[serde(default)]
1569    include: Vec<String>,
1570
1571    #[serde(default)]
1572    pub profiles: BTreeMap<String, ProfileConfig>,
1573    pub default_profile: Option<String>,
1574    pub settings: Option<Tunables>,
1575    pub dirs: Option<Directories>,
1576    pub layout: Option<Layout>,
1577    pub macros: Option<Macros>,
1578    pub aliases: Option<Aliases>,
1579    pub theme: Option<theme::Theme>,
1580}
1581
1582impl IambConfig {
1583    pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
1584        let s = std::fs::read_to_string(path)?;
1585        let config = toml::from_str(&s)?;
1586
1587        Ok(config)
1588    }
1589
1590    pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
1591        let s = std::fs::read_to_string(path)?;
1592        let config = serde_json::from_str(&s)?;
1593
1594        Ok(config)
1595    }
1596
1597    /// If a value is present in both configs, `self` is prefered.
1598    fn merge(self, other: Self) -> Self {
1599        // transitive includes are not supported
1600        let include = vec![];
1601
1602        let mut profiles = self.profiles;
1603        for (name, profile) in other.profiles {
1604            match profiles.entry(name) {
1605                btree_map::Entry::Vacant(entry) => {
1606                    entry.insert(profile);
1607                },
1608                btree_map::Entry::Occupied(mut entry) => {
1609                    let profile = std::mem::take(entry.get_mut()).merge(profile);
1610                    entry.insert(profile);
1611                },
1612            }
1613        }
1614
1615        let default_profile = self.default_profile.or(other.default_profile);
1616        let settings = merge_options!(self.settings, other.settings);
1617        let dirs = merge_options!(self.dirs, other.dirs);
1618        let layout = self.layout.or(other.layout);
1619        let macros = merge_macros(self.macros, other.macros);
1620        let aliases = merge_maps(self.aliases, other.aliases);
1621        let theme = merge_options!(self.theme, other.theme);
1622
1623        Self {
1624            include,
1625            profiles,
1626            default_profile,
1627            settings,
1628            dirs,
1629            layout,
1630            macros,
1631            aliases,
1632            theme,
1633        }
1634    }
1635}
1636
1637#[derive(Clone)]
1638pub struct ApplicationSettings {
1639    pub layout_json: PathBuf,
1640    pub session_json: PathBuf,
1641    pub device_json: PathBuf,
1642    pub session_json_old: PathBuf,
1643    pub sled_dir: PathBuf,
1644    pub sqlite_dir: PathBuf,
1645    pub sqlite_cache_dir: PathBuf,
1646    pub profile_name: String,
1647    pub user_id: OwnedUserId,
1648    pub profile: ProfileConfig,
1649    pub theme: Arc<theme::ThemeValues>,
1650    pub themes: Arc<CompletionMap<String, theme::Theme>>,
1651    pub tunables: TunableValues,
1652    pub dirs: DirectoryValues,
1653    pub layout: Layout,
1654    pub macros: Macros,
1655    pub aliases: Aliases,
1656
1657    /// Whether to use the Kitty keyboard protocol. Resolved by
1658    /// [`ApplicationSettings::probe_enhanced_keys`] once the TUI starts, since
1659    /// it may require querying the terminal.
1660    pub enable_enhanced_keys: bool,
1661}
1662
1663impl ApplicationSettings {
1664    fn get_xdg_config_home() -> Option<PathBuf> {
1665        env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
1666    }
1667
1668    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
1669        let mut config_dir = cli
1670            .config_directory
1671            .or_else(Self::get_xdg_config_home)
1672            .or_else(dirs::config_dir)
1673            .unwrap_or_else(|| {
1674                usage!(
1675                    "No user configuration directory found;\
1676                    please specify one via -C.\n\n
1677                    For more information try '--help'"
1678                );
1679            });
1680
1681        config_dir.push("iamb");
1682        let config_json = config_dir.join("config.json");
1683        let config_toml = config_dir.join("config.toml");
1684
1685        let config = if config_toml.is_file() {
1686            IambConfig::load_toml(config_toml.as_path())?
1687        } else if config_json.is_file() {
1688            IambConfig::load_json(config_json.as_path())?
1689        } else {
1690            usage!(
1691                "Please create a configuration file at {}\n\n\
1692                For more information try '--help'",
1693                config_toml.display(),
1694            );
1695        };
1696
1697        let config = load_config_includes(config, &config_dir);
1698
1699        let IambConfig {
1700            mut profiles,
1701            default_profile,
1702            dirs,
1703            settings: global,
1704            layout,
1705            macros,
1706            aliases,
1707            theme,
1708            ..
1709        } = config;
1710
1711        validate_profile_names(&profiles);
1712
1713        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
1714            profiles.remove_entry(&profile).unwrap_or_else(|| {
1715                usage!(
1716                    "No configured profile with the name {:?} in {}",
1717                    profile,
1718                    config_json.display()
1719                );
1720            })
1721        } else if profiles.len() == 1 {
1722            profiles.into_iter().next().unwrap()
1723        } else {
1724            loop {
1725                println!("\nNo profile specified. Available profiles:");
1726                profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
1727
1728                print!("Select a number or 'q' to quit: ");
1729                let _ = std::io::stdout().flush();
1730
1731                let mut input = String::new();
1732                let _ = std::io::stdin().read_line(&mut input);
1733
1734                if input.trim() == "q" {
1735                    usage!(
1736                        "No profile specified. \
1737                        Please use -P or add \"default_profile\" to your configuration.\n\n\
1738                        For more information try '--help'",
1739                    );
1740                }
1741                if let Ok(i) = input.trim().parse::<usize>() &&
1742                    i < profiles.len()
1743                {
1744                    break profiles.into_iter().nth(i).unwrap();
1745                }
1746                println!("\nInvalid index.");
1747            }
1748        };
1749
1750        let user_id = profile.user_id.clone().expect("Active profile does not have a user id");
1751
1752        let aliases = merge_maps(profile.aliases.take(), aliases).unwrap_or_default();
1753        let macros = merge_macros(profile.macros.take(), macros).unwrap_or_default();
1754        let layout = profile.layout.take().or(layout).unwrap_or_default();
1755
1756        let tunables = global.unwrap_or_default();
1757        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
1758        let tunables = tunables.values();
1759
1760        let dirs = dirs.unwrap_or_default();
1761        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
1762        let dirs = dirs.values();
1763
1764        let themes_dir = config_dir.join("themes");
1765        let overrides = profile.theme.clone().unwrap_or_default().merge(theme.unwrap_or_default());
1766        let themes = Arc::new(load_themes(&themes_dir, overrides)?);
1767
1768        let theme = if let Some(theme) = themes.get(&tunables.theme) {
1769            Arc::new(theme.clone().values())
1770        } else {
1771            let err = anyhow!(
1772                "Could not find the {:?} theme; check {}?",
1773                tunables.theme,
1774                themes_dir.display()
1775            );
1776            return Err(err.into_boxed_dyn_error());
1777        };
1778
1779        // Create directories
1780        dirs.create_dir_all()?;
1781
1782        // Set up paths that live inside the profile's data directory.
1783        let mut profile_dir = config_dir.clone();
1784        profile_dir.push("profiles");
1785        profile_dir.push(profile_name.as_str());
1786
1787        let mut profile_data_dir = dirs.data.clone();
1788        profile_data_dir.push("profiles");
1789        profile_data_dir.push(profile_name.as_str());
1790
1791        let mut sled_dir = profile_dir.clone();
1792        sled_dir.push("matrix");
1793
1794        let mut sqlite_dir = profile_data_dir.clone();
1795        sqlite_dir.push("sqlite");
1796
1797        let mut session_json = profile_data_dir.clone();
1798        session_json.push("session.json");
1799
1800        let mut device_json = profile_data_dir;
1801        device_json.push("device.json");
1802
1803        let mut session_json_old = profile_dir;
1804        session_json_old.push("session.json");
1805
1806        // Set up paths that live inside the profile's cache directory.
1807        let mut cache_dir = dirs.cache.clone();
1808        cache_dir.push("profiles");
1809        cache_dir.push(profile_name.as_str());
1810
1811        let mut layout_json = cache_dir.clone();
1812        layout_json.push("layout.json");
1813
1814        let mut sqlite_cache_dir = cache_dir;
1815        sqlite_cache_dir.push("sqlite");
1816
1817        let settings = ApplicationSettings {
1818            sled_dir,
1819            layout_json,
1820            session_json,
1821            device_json,
1822            session_json_old,
1823            sqlite_dir,
1824            sqlite_cache_dir,
1825            profile_name,
1826            user_id,
1827            profile,
1828            themes,
1829            theme,
1830            tunables,
1831            dirs,
1832            layout,
1833            macros,
1834            aliases,
1835            enable_enhanced_keys: false,
1836        };
1837
1838        Ok(settings)
1839    }
1840
1841    /// Work out whether to use the Kitty keyboard protocol, asking the terminal
1842    /// when the user has not configured it explicitly.
1843    ///
1844    /// This queries the terminal, so it must only be called once, before the
1845    /// TUI starts reading input.
1846    pub fn probe_enhanced_keys(&mut self) {
1847        self.enable_enhanced_keys =
1848            self.tunables.terminal.enable_extended_keys.unwrap_or_else(|| {
1849                crossterm::terminal::supports_keyboard_enhancement()
1850                .inspect_err(|e| {
1851                    tracing::warn!(
1852                        err = %e,
1853                        "Failed to determine whether the terminal supports keyboard enhancements"
1854                    )
1855                })
1856                .unwrap_or_default()
1857            });
1858    }
1859
1860    pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1861        let file = File::open(path)?;
1862        let reader = BufReader::new(file);
1863        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1864        Ok(session)
1865    }
1866
1867    pub fn write_session(&self, session: impl Into<Session>) -> Result<(), IambError> {
1868        let file = File::create(self.session_json.as_path())?;
1869        let writer = BufWriter::new(file);
1870        let session: Session = session.into();
1871        serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1872        Ok(())
1873    }
1874
1875    /// The device ID saved at logout, if it was saved for this profile's
1876    /// user. A missing or stale file is not an error: the next login then
1877    /// simply gets a fresh device ID from the homeserver.
1878    pub fn read_saved_device(&self) -> Option<SavedDevice> {
1879        let file = File::open(self.device_json.as_path()).ok()?;
1880        let reader = BufReader::new(file);
1881        let saved: SavedDevice = serde_json::from_reader(reader).ok()?;
1882
1883        if saved.is_user(&self.user_id) {
1884            Some(saved)
1885        } else {
1886            None
1887        }
1888    }
1889
1890    pub fn write_saved_device(
1891        &self,
1892        device_id: &DeviceId,
1893        client_id: Option<ClientId>,
1894    ) -> Result<(), IambError> {
1895        let file = File::create(self.device_json.as_path())?;
1896        let writer = BufWriter::new(file);
1897
1898        let saved = match client_id {
1899            Some(client) => {
1900                SavedDevice::OAuth {
1901                    user_id: self.user_id.clone(),
1902                    device_id: device_id.to_owned(),
1903                    client_id: client,
1904                }
1905            },
1906            None => {
1907                SavedDevice::MatrixAuth {
1908                    user_id: self.user_id.clone(),
1909                    device_id: device_id.to_owned(),
1910                }
1911            },
1912        };
1913        serde_json::to_writer(writer, &saved).map_err(IambError::from)?;
1914        Ok(())
1915    }
1916
1917    pub fn get_user_char_span(&self, user_id: &UserId, info: &RoomInfo) -> Span<'_> {
1918        let (color, configured_name) = self
1919            .tunables
1920            .users
1921            .get(user_id)
1922            .map(|user| (user.color, user.name.as_deref()))
1923            .unwrap_or_default();
1924
1925        let style = self.theme.users.style(user_id.as_str(), color);
1926        let c = configured_name
1927            .and_then(|name| name.chars().next())
1928            .or_else(|| {
1929                info.display_names
1930                    .get(user_id)
1931                    .and_then(|name| name.chars().next())
1932                    .filter(char::is_ascii)
1933            })
1934            .unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1935
1936        Span::styled(String::from(c), style)
1937    }
1938
1939    pub fn get_user_overrides(
1940        &self,
1941        user_id: &UserId,
1942    ) -> (Option<Color>, Option<Cow<'static, str>>) {
1943        self.tunables
1944            .users
1945            .get(user_id)
1946            .map(|user| (user.color, user.name.clone().map(Cow::Owned)))
1947            .unwrap_or_default()
1948    }
1949
1950    pub fn get_user_color(&self, user_id: &UserId) -> Color {
1951        self.tunables
1952            .users
1953            .get(user_id)
1954            .and_then(|user| user.color)
1955            .unwrap_or_else(|| self.theme.users.color(user_id.as_str()))
1956    }
1957
1958    pub fn get_user_style(&self, user_id: &UserId) -> Style {
1959        let (color, _) = self.get_user_overrides(user_id);
1960        self.theme.users.style(user_id.as_str(), color)
1961    }
1962
1963    pub fn get_user_span<'a>(
1964        &self,
1965        user_id: &'a UserId,
1966        display_name: Option<Cow<'a, str>>,
1967    ) -> Span<'a> {
1968        let (color, name) = self.get_user_overrides(user_id);
1969
1970        let style = self.theme.users.style(user_id.as_str(), color);
1971        let name = match (name, &self.tunables.username_display) {
1972            (Some(name), _) => name,
1973            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1974            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1975            (None, UserDisplayStyle::DisplayName) => {
1976                display_name.unwrap_or(Cow::Borrowed(user_id.as_str()))
1977            },
1978        };
1979
1980        Span::styled(name, style)
1981    }
1982}
1983
1984#[cfg(test)]
1985mod tests {
1986    use super::*;
1987
1988    use std::convert::TryFrom;
1989
1990    use matrix_sdk::ruma::user_id;
1991
1992    use crate::tests::{TEST_USER1, mock_room, mock_settings};
1993
1994    #[test]
1995    fn test_get_user_span_borrowed() {
1996        // fix `StyleTreeNode::print` for `StyleTreeNode::UserId` if this breaks
1997        let info = mock_room();
1998        let settings = mock_settings();
1999        let span = settings.get_user_span(&TEST_USER1, info.display_names.get(&TEST_USER1));
2000
2001        assert!(matches!(span.content, Cow::Borrowed(_)));
2002    }
2003
2004    #[test]
2005    fn test_profile_name_invalid() {
2006        assert_eq!(validate_profile_name(""), false);
2007        assert_eq!(validate_profile_name(" "), false);
2008        assert_eq!(validate_profile_name("a b"), false);
2009        assert_eq!(validate_profile_name("foo^bar"), false);
2010        assert_eq!(validate_profile_name("FOO/BAR"), false);
2011        assert_eq!(validate_profile_name("-b-c"), false);
2012        assert_eq!(validate_profile_name("-B-c"), false);
2013        assert_eq!(validate_profile_name(".b-c"), false);
2014        assert_eq!(validate_profile_name(".B-c"), false);
2015    }
2016
2017    #[test]
2018    fn test_profile_name_valid() {
2019        assert_eq!(validate_profile_name("foo"), true);
2020        assert_eq!(validate_profile_name("FOO"), true);
2021        assert_eq!(validate_profile_name("a-b-c"), true);
2022        assert_eq!(validate_profile_name("a-B-c"), true);
2023        assert_eq!(validate_profile_name("a.b-c"), true);
2024        assert_eq!(validate_profile_name("a.B-c"), true);
2025    }
2026
2027    #[test]
2028    fn test_merge_users() {
2029        let a = None;
2030        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
2031            color: Some(Color::Red),
2032            name: Some("Hello".into()),
2033        })]
2034        .into_iter()
2035        .collect::<HashMap<_, _>>();
2036        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
2037            color: Some(Color::Green),
2038            name: Some("World".into()),
2039        })]
2040        .into_iter()
2041        .collect::<HashMap<_, _>>();
2042
2043        let res = merge_maps(a.clone(), a.clone());
2044        assert_eq!(res, None);
2045
2046        let res = merge_maps(a.clone(), Some(b.clone()));
2047        assert_eq!(res, Some(b.clone()));
2048
2049        let res = merge_maps(Some(b.clone()), a.clone());
2050        assert_eq!(res, Some(b.clone()));
2051
2052        let res = merge_maps(Some(b.clone()), Some(b.clone()));
2053        assert_eq!(res, Some(b.clone()));
2054
2055        let res = merge_maps(Some(b.clone()), Some(c.clone()));
2056        assert_eq!(res, Some(b.clone()));
2057
2058        let res = merge_maps(Some(c.clone()), Some(b.clone()));
2059        assert_eq!(res, Some(c.clone()));
2060    }
2061
2062    #[test]
2063    fn test_parse_tunables() {
2064        let res: Tunables = serde_json::from_str("{}").unwrap();
2065        assert_eq!(res.typing_notice_send, None);
2066        assert_eq!(res.typing_notice_display, None);
2067        assert_eq!(res.users, None);
2068
2069        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
2070        assert_eq!(res.typing_notice_send, Some(true));
2071        assert_eq!(res.typing_notice_display, None);
2072        assert_eq!(res.users, None);
2073
2074        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
2075        assert_eq!(res.typing_notice_send, Some(false));
2076        assert_eq!(res.typing_notice_display, None);
2077        assert_eq!(res.users, None);
2078
2079        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
2080        assert_eq!(res.typing_notice_send, None);
2081        assert_eq!(res.typing_notice_display, None);
2082        assert_eq!(res.users, Some(HashMap::new()));
2083    }
2084
2085    #[test]
2086    fn test_parse_user_colors() {
2087        let expect = |color| UserDisplayTunables { color: Some(color), name: Some("Tim".into()) };
2088
2089        // Unprefixed color:
2090        let res: Tunables = serde_json::from_str(
2091            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
2092        )
2093        .unwrap();
2094        assert_eq!(res.typing_notice_send, None);
2095        assert_eq!(res.typing_notice_display, None);
2096        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::Black))];
2097        assert_eq!(res.users, Some(users.into_iter().collect()));
2098
2099        // Color with `light-` prefix:
2100        let res: Tunables = serde_json::from_str(
2101            "{\"users\": {\"@a:b.c\": {\"color\": \"light-red\", \"name\": \"Tim\"}}}",
2102        )
2103        .unwrap();
2104        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightRed))];
2105        assert_eq!(res.users, Some(users.into_iter().collect()));
2106
2107        // Color name with `light-` prefix:
2108        let res: Tunables = serde_json::from_str(
2109            "{\"users\": {\"@a:b.c\": {\"color\": \"light-red\", \"name\": \"Tim\"}}}",
2110        )
2111        .unwrap();
2112        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightRed))];
2113        assert_eq!(res.users, Some(users.into_iter().collect()));
2114
2115        // Color name with `light` prefix, no hyphen:
2116        let res: Tunables = serde_json::from_str(
2117            "{\"users\": {\"@a:b.c\": {\"color\": \"lightblue\", \"name\": \"Tim\"}}}",
2118        )
2119        .unwrap();
2120        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightBlue))];
2121        assert_eq!(res.users, Some(users.into_iter().collect()));
2122
2123        // Hex color name:
2124        let res: Tunables = serde_json::from_str(
2125            "{\"users\": {\"@a:b.c\": {\"color\": \"#ff55bb\", \"name\": \"Tim\"}}}",
2126        )
2127        .unwrap();
2128        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::Rgb(0xff, 0x55, 0xbb)))];
2129        assert_eq!(res.users, Some(users.into_iter().collect()));
2130    }
2131
2132    fn parse_settings_toml(input: &str) -> Result<Tunables, toml::de::Error> {
2133        #[derive(Deserialize)]
2134        struct SettingsToml {
2135            settings: Tunables,
2136        }
2137
2138        toml::from_str::<SettingsToml>(input).map(|doc| doc.settings)
2139    }
2140
2141    #[test]
2142    fn test_parse_tunables_date_time_format() {
2143        let settings = parse_settings_toml(
2144            r#"
2145[settings]
2146date_format = "%Y-%m-%d"
2147time_format = "%H:%M"
2148"#,
2149        )
2150        .unwrap();
2151        assert_eq!(settings.date_format.as_deref(), Some("%Y-%m-%d"));
2152        assert_eq!(settings.time_format.as_deref(), Some("%H:%M"));
2153
2154        let values = settings.values();
2155        assert_eq!(values.date_format, "%Y-%m-%d");
2156        assert_eq!(values.time_format, "%H:%M");
2157        assert_eq!(values.time_gutter_width, 5);
2158
2159        // Absent keys keep today's formats.
2160        let settings = parse_settings_toml("[settings]\n").unwrap();
2161        assert_eq!(settings.date_format, None);
2162        assert_eq!(settings.time_format, None);
2163        let values = settings.values();
2164        assert_eq!(values.date_format, "%A, %B %d %Y");
2165        assert_eq!(values.time_format, "  [%T]");
2166        assert_eq!(values.time_gutter_width, 12);
2167
2168        // An empty format is valid and disables the time column.
2169        let settings = parse_settings_toml(
2170            r#"
2171[settings]
2172time_format = ""
2173"#,
2174        )
2175        .unwrap();
2176        assert_eq!(settings.time_format.as_deref(), Some(""));
2177        let values = settings.values();
2178        assert_eq!(values.time_format, "");
2179        assert_eq!(values.time_gutter_width, 0);
2180
2181        // Brackets and spacing are literal gutter text, not added later.
2182        let settings = parse_settings_toml(
2183            r#"
2184[settings]
2185time_format = "  [%H:%M]"
2186"#,
2187        )
2188        .unwrap();
2189        let values = settings.values();
2190        assert_eq!(values.time_format, "  [%H:%M]");
2191        assert_eq!(values.time_gutter_width, 9);
2192    }
2193
2194    #[test]
2195    fn test_parse_tunables_date_time_format_invalid() {
2196        let err = parse_settings_toml(
2197            r#"
2198[settings]
2199date_format = "%Q"
2200"#,
2201        )
2202        .unwrap_err();
2203        let msg = err.to_string();
2204        assert!(msg.contains("invalid strftime"), "{msg}");
2205
2206        let err = parse_settings_toml(
2207            r#"
2208[settings]
2209time_format = "%"
2210"#,
2211        )
2212        .unwrap_err();
2213        let msg = err.to_string();
2214        assert!(msg.contains("invalid strftime"), "{msg}");
2215    }
2216
2217    #[test]
2218    fn test_parse_tunables_username_display() {
2219        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
2220        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
2221
2222        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
2223        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
2224
2225        let res: Tunables =
2226            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
2227        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
2228    }
2229
2230    #[test]
2231    fn test_parse_tunables_sort() {
2232        let res: Tunables = serde_json::from_str(
2233            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
2234        )
2235        .unwrap();
2236        assert_eq!(
2237            res.sort.members,
2238            Some(vec![
2239                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
2240                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
2241            ])
2242        );
2243        assert_eq!(
2244            res.sort.spaces,
2245            Some(vec![
2246                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
2247                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
2248            ])
2249        );
2250        assert_eq!(res.sort.rooms, None);
2251        assert_eq!(res.sort.dms, None);
2252
2253        // Check that we get the right default "rooms" and "dms" values.
2254        let res = res.values();
2255        assert_eq!(res.sort.members, vec![
2256            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
2257            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
2258        ]);
2259        assert_eq!(res.sort.spaces, vec![
2260            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
2261            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
2262        ]);
2263        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
2264        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
2265    }
2266
2267    #[test]
2268    fn test_parse_default_members_sort() {
2269        let sort: Vec<SortColumn<SortFieldUser>> =
2270            serde_json::from_str(r#"["power","knock","~invite","id"]"#).unwrap();
2271        assert_eq!(sort.as_slice(), &DEFAULT_MEMBERS_SORT[..]);
2272    }
2273
2274    #[test]
2275    fn test_parse_default_rooms_sort() {
2276        let sort: Vec<SortColumn<SortFieldRoom>> =
2277            serde_json::from_str(r#"["favorite","invite","lowpriority","mentions","notifications","marked_unread","joined","space","dm","recent","name"]"#)
2278                .unwrap();
2279        assert_eq!(sort.as_slice(), &DEFAULT_ROOM_SORT[..]);
2280    }
2281
2282    #[test]
2283    fn test_parse_default_space_sort() {
2284        let sort: Vec<SortColumn<SortFieldSpace>> =
2285            serde_json::from_str(r#"["space","joined","spaceorder"]"#).unwrap();
2286        assert_eq!(sort.as_slice(), &DEFAULT_SPACE_SORT[..]);
2287    }
2288
2289    #[test]
2290    fn test_parse_tunables_proxy_invalid() {
2291        let res =
2292            serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();
2293
2294        // Should result in a validation error:
2295        assert_eq!(res.classify(), serde_json::error::Category::Data);
2296    }
2297
2298    #[test]
2299    fn test_parse_tunables_proxy_empty() {
2300        let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
2301        let proxy = res.proxy.unwrap();
2302        assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
2303    }
2304
2305    #[test]
2306    fn test_parse_tunables_proxy_socks5() {
2307        let res: Tunables =
2308            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
2309        let proxy = res.proxy.unwrap();
2310        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
2311            panic!("should parse ProxyUrl::Endpoint")
2312        };
2313
2314        assert_eq!(url.scheme(), "socks5");
2315        assert_eq!(url.host_str().unwrap(), "localhost");
2316        assert_eq!(url.port().unwrap(), 1080);
2317        assert_eq!(url.authority(), "localhost:1080");
2318    }
2319
2320    #[test]
2321    fn test_parse_tunables_proxy_https() {
2322        let res: Tunables = serde_json::from_str(
2323            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
2324        ).unwrap();
2325        let proxy = res.proxy.unwrap();
2326        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
2327            panic!("should parse ProxyUrl::Endpoint")
2328        };
2329
2330        // Verify URL fields:
2331        assert_eq!(url.scheme(), "https");
2332        assert_eq!(url.host_str().unwrap(), "localhost");
2333        assert_eq!(url.port().unwrap(), 8080);
2334        assert_eq!(url.authority(), "localhost:8080");
2335
2336        // Verify our `Proxy-Authorization` value:
2337        assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");
2338
2339        // Verify our custom header is present:
2340        assert_eq!(proxy.headers.len(), 1);
2341        assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
2342    }
2343
2344    #[test]
2345    fn test_parse_tunables_proxy_merge() {
2346        let global: Tunables = serde_json::from_str(
2347            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
2348        ).unwrap();
2349        let profile: Tunables =
2350            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
2351
2352        // The configuration merge should select the entirety of the profile proxy config,
2353        // and not merge subfields, to ensure that things like `auth` and `headers` are
2354        // not ever sent to a `url` they were meant for.
2355        let merged = profile.merge(global).values();
2356        let ProxyUrl::Endpoint(url) = merged.proxy.url else {
2357            panic!("should parse ProxyUrl::Endpoint")
2358        };
2359        assert_eq!(url.scheme(), "socks5");
2360        assert_eq!(url.authority(), "localhost:1080");
2361        assert_eq!(merged.proxy.auth, None);
2362        assert_eq!(merged.proxy.headers.is_empty(), true);
2363    }
2364
2365    #[test]
2366    fn test_parse_tunables_default_register() {
2367        let reg_a: Tunables = serde_json::from_str(r#"{"default_register": "a"}"#).unwrap();
2368        assert_eq!(reg_a.default_register, Some(Register::Named('a')));
2369
2370        let reg_z: Tunables = serde_json::from_str(r#"{"default_register": "z"}"#).unwrap();
2371        assert_eq!(reg_z.default_register, Some(Register::Named('z')));
2372
2373        let reg_blackhole: Tunables = serde_json::from_str(r#"{"default_register": "_"}"#).unwrap();
2374        assert_eq!(reg_blackhole.default_register, Some(Register::Blackhole));
2375
2376        let res: Result<Tunables, _> = serde_json::from_str(r#"{"default_register": "A"}"#);
2377        assert!(res.is_err());
2378
2379        let res: Result<Tunables, _> = serde_json::from_str(r#"{"default_register": "0"}"#);
2380        assert!(res.is_err());
2381    }
2382
2383    #[test]
2384    fn test_parse_layout() {
2385        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
2386        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
2387        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
2388        let dms = WindowPath::Window(IambId::DirectList);
2389        let welcome = WindowPath::Window(IambId::Welcome);
2390
2391        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
2392        assert_eq!(res, Layout::Restore);
2393
2394        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
2395        assert_eq!(res, Layout::New);
2396
2397        let res: Layout = serde_json::from_str(
2398            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
2399        )
2400        .unwrap();
2401        assert_eq!(res, Layout::Config {
2402            tabs: vec![WindowLayout::Window { window: user.clone() }]
2403        });
2404
2405        let res: Layout = serde_json::from_str(
2406            "{\
2407            \"style\": \"config\",\
2408            \"tabs\": [\
2409                {\"split\":[\
2410                    {\"window\":\"@user:example.com\"},\
2411                    {\"window\":\"#room:example.com\"}\
2412                ]},\
2413                {\"split\":[\
2414                    {\"window\":\"!room:example.com\"},\
2415                    {\"split\":[\
2416                        {\"window\":\"iamb://dms\"},\
2417                        {\"window\":\"iamb://welcome\"}\
2418                    ]}\
2419                ]}\
2420            ]}",
2421        )
2422        .unwrap();
2423        let split1 = WindowLayout::Split {
2424            split: vec![
2425                WindowLayout::Window { window: user.clone() },
2426                WindowLayout::Window { window: alias },
2427            ],
2428        };
2429        let split2 = WindowLayout::Split {
2430            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
2431                window: welcome,
2432            }],
2433        };
2434        let split3 = WindowLayout::Split {
2435            split: vec![WindowLayout::Window { window: room }, split2],
2436        };
2437        let tabs = vec![split1, split3];
2438        assert_eq!(res, Layout::Config { tabs });
2439    }
2440
2441    #[test]
2442    fn test_parse_aliases() {
2443        let res: Aliases = serde_json::from_str("{\"c\":\"chats\"}").unwrap();
2444        assert_eq!(res.len(), 1);
2445
2446        let aliased = res.get("c").unwrap();
2447        assert_eq!(aliased, "chats");
2448    }
2449
2450    #[test]
2451    fn test_parse_aliases_preserves_order() {
2452        // Aliases are registered in order, which allows alias to refer to earlier ones, so
2453        // ensure we register in user-specified order:
2454        let res: Aliases = toml::from_str("c = \"chats\"\ncc = \"c\"\nd = \"download\"").unwrap();
2455        let order = res.keys().map(String::as_str).collect::<Vec<_>>();
2456
2457        assert_eq!(order, vec!["c", "cc", "d"]);
2458    }
2459
2460    #[test]
2461    fn test_merge_aliases_preserves_order() {
2462        let profile: Aliases = toml::from_str("c = \"chats\"\nz = \"redact\"").unwrap();
2463        let global: Aliases = toml::from_str("c = \"cancel\"\nd = \"download\"").unwrap();
2464
2465        let res = merge_maps(Some(profile), Some(global)).unwrap();
2466        let order = res.keys().map(String::as_str).collect::<Vec<_>>();
2467
2468        // The profile wins for keys in both, but doesn't get to move them.
2469        assert_eq!(order, vec!["c", "d", "z"]);
2470        assert_eq!(res.get("c").unwrap(), "chats");
2471    }
2472
2473    #[test]
2474    fn test_parse_macros() {
2475        let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
2476        assert_eq!(res.len(), 1);
2477
2478        let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
2479        let mapped = res.get(&modes).unwrap();
2480        assert_eq!(mapped.len(), 1);
2481
2482        let j = "j".parse::<TerminalKey>().unwrap();
2483        let esc = "<Esc>".parse::<TerminalKey>().unwrap();
2484
2485        let jj = Keys(vec![j, j], "jj".into());
2486        let run = mapped.get(&jj).unwrap();
2487        let exp = Keys(vec![esc], "<Esc>".into());
2488        assert_eq!(run, &exp);
2489    }
2490
2491    #[test]
2492    fn test_parse_notify_via() {
2493        assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
2494        assert_eq!(
2495            NotifyVia { bell: false, desktop: true },
2496            serde_json::from_str(r#""desktop""#).unwrap()
2497        );
2498        assert_eq!(
2499            NotifyVia { bell: true, desktop: false },
2500            serde_json::from_str(r#""bell""#).unwrap()
2501        );
2502        assert_eq!(
2503            NotifyVia { bell: true, desktop: true },
2504            serde_json::from_str(r#""bell|desktop""#).unwrap()
2505        );
2506        assert_eq!(
2507            NotifyVia { bell: true, desktop: true },
2508            serde_json::from_str(r#""desktop|bell""#).unwrap()
2509        );
2510        assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
2511        assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
2512    }
2513
2514    #[test]
2515    fn test_parse_room_labels() {
2516        assert_eq!(RoomLabel::Membership, serde_json::from_str(r#""membership""#).unwrap());
2517        assert_eq!(RoomLabel::Tags, serde_json::from_str(r#""tags""#).unwrap());
2518        assert_eq!(RoomLabel::Type, serde_json::from_str(r#""type""#).unwrap());
2519    }
2520
2521    #[test]
2522    fn test_parse_cursor_shape() {
2523        assert_eq!(CursorShape::Auto, CursorShape::default());
2524        assert_eq!(CursorShape::Auto, serde_json::from_str(r#""auto""#).unwrap());
2525        assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap());
2526        assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap());
2527        assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap());
2528        assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap());
2529        assert!(serde_json::from_str::<CursorShape>(r#""beam""#).is_err());
2530    }
2531
2532    #[test]
2533    fn test_load_example_config_toml() {
2534        let path = PathBuf::from("config.full.toml");
2535        let config = IambConfig::load_toml(&path).expect("can load config.full.toml");
2536
2537        let IambConfig {
2538            profiles,
2539            default_profile,
2540            settings,
2541            dirs,
2542            layout,
2543            macros,
2544            aliases,
2545            theme,
2546            ..
2547        } = &config;
2548
2549        // There should be an example object for each top-level field.
2550        assert!(!profiles.is_empty());
2551        assert!(default_profile.is_some());
2552        assert!(settings.is_some());
2553        assert!(dirs.is_some());
2554        assert!(layout.is_some());
2555        assert!(macros.is_some());
2556        assert!(aliases.is_some());
2557        assert!(theme.is_some());
2558    }
2559
2560    #[test]
2561    fn test_encryption_indicator_enabled() {
2562        use EncryptionState::*;
2563
2564        let enc = Encryption {
2565            indicator: Some(EncryptionIndicator::Enabled),
2566            indicator_location: Some(EncryptionIndicatorLocation::TITLE),
2567            ..Default::default()
2568        };
2569        let enc = enc.values();
2570        let theme = theme::ThemeValues::default();
2571
2572        // Always shows in the title:
2573        assert!(
2574            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2575                .is_some()
2576        );
2577        assert!(
2578            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2579                .is_some()
2580        );
2581        assert!(
2582            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2583                .is_some()
2584        );
2585
2586        // Doesn't show in the prompt:
2587        assert!(
2588            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2589                .is_none()
2590        );
2591        assert!(
2592            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2593                .is_none()
2594        );
2595        assert!(
2596            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2597                .is_none()
2598        );
2599    }
2600
2601    #[test]
2602    fn test_encryption_indicator_disabled() {
2603        use EncryptionState::*;
2604
2605        let enc = Encryption {
2606            indicator: Some(EncryptionIndicator::Disabled),
2607            indicator_location: Some(EncryptionIndicatorLocation::TITLE),
2608            ..Default::default()
2609        };
2610        let enc = enc.values();
2611        let theme = theme::ThemeValues::default();
2612
2613        // Never shows in the title or the prompt:
2614        assert!(
2615            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2616                .is_none()
2617        );
2618        assert!(
2619            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2620                .is_none()
2621        );
2622        assert!(
2623            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2624                .is_none()
2625        );
2626        assert!(
2627            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2628                .is_none()
2629        );
2630        assert!(
2631            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2632                .is_none()
2633        );
2634        assert!(
2635            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2636                .is_none()
2637        );
2638    }
2639
2640    #[test]
2641    fn test_encryption_indicator_only_encrypted() {
2642        use EncryptionState::*;
2643
2644        let enc = Encryption {
2645            indicator: Some(EncryptionIndicator::OnlyEncrypted),
2646            indicator_location: Some(EncryptionIndicatorLocation::PROMPT),
2647            ..Default::default()
2648        };
2649        let enc = enc.values();
2650        let theme = theme::ThemeValues::default();
2651
2652        // Shows in the prompt when encrypted or unknown:
2653        assert!(
2654            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2655                .is_some()
2656        );
2657        assert!(
2658            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2659                .is_some()
2660        );
2661
2662        // But is hidden when unencrypted:
2663        assert!(
2664            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2665                .is_none()
2666        );
2667
2668        // Doesn't show in the title:
2669        assert!(
2670            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2671                .is_none()
2672        );
2673        assert!(
2674            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2675                .is_none()
2676        );
2677        assert!(
2678            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2679                .is_none()
2680        );
2681    }
2682    #[test]
2683    fn test_encryption_indicator_only_unencrypted() {
2684        use EncryptionState::*;
2685
2686        let enc = Encryption {
2687            indicator: Some(EncryptionIndicator::OnlyUnencrypted),
2688            indicator_location: Some(EncryptionIndicatorLocation::all()),
2689            ..Default::default()
2690        };
2691        let enc = enc.values();
2692        let theme = theme::ThemeValues::default();
2693
2694        // Shows in both the prompt and title when unencrypted or unknown:
2695        assert!(
2696            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2697                .is_some()
2698        );
2699        assert!(
2700            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2701                .is_some()
2702        );
2703        assert!(
2704            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2705                .is_some()
2706        );
2707        assert!(
2708            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2709                .is_some()
2710        );
2711
2712        // But is hidden when encrypted:
2713        assert!(
2714            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2715                .is_none()
2716        );
2717        assert!(
2718            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2719                .is_none()
2720        );
2721    }
2722}