src/config/mod.rs

2718 lines · 93777 bytes

   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}
1163
1164#[derive(Clone, Debug, Default, Deserialize)]
1165pub struct Tunables {
1166    /// Subsection for overriding encryption-related settings.
1167    #[serde(default)]
1168    pub encryption: Encryption,
1169
1170    /// Subsection for configuring an HTTP(S) proxy.
1171    pub proxy: Option<Proxy>,
1172
1173    /// Subsection for overriding sort orders in UI lists.
1174    #[serde(default)]
1175    pub sort: SortOverrides,
1176
1177    /// Subsection for overriding terminal settings.
1178    #[serde(default)]
1179    pub terminal: Terminal,
1180
1181    /// Subsection for overriding how specific Matrix users are rendered.
1182    pub users: Option<UserOverrides>,
1183    pub rooms: Option<RoomOverrides>,
1184
1185    pub default_markup: Option<MarkupFormat>,
1186    pub ignorecase: Option<bool>,
1187    pub log_level: Option<String>,
1188    pub max_log_files: Option<usize>,
1189    pub message_formatted_display: Option<bool>,
1190    pub message_shortcode_display: Option<bool>,
1191    pub normal_after_send: Option<bool>,
1192    pub reaction_display: Option<bool>,
1193    pub reaction_shortcode_display: Option<bool>,
1194    pub read_receipt_send: Option<bool>,
1195    pub read_receipt_trigger: Option<ReadReceiptTrigger>,
1196    pub read_receipt_display: Option<bool>,
1197    pub room_labels: Option<Vec<RoomLabel>>,
1198    pub request_timeout: Option<u64>,
1199    pub state_event_display: Option<bool>,
1200    pub sync_delay_ms: Option<u64>,
1201    pub theme: Option<String>,
1202    pub typing_notice_send: Option<bool>,
1203    pub typing_notice_display: Option<bool>,
1204    pub username_display: Option<UserDisplayStyle>,
1205    pub message_user_color: Option<bool>,
1206    #[serde(default, deserialize_with = "deserialize_register")]
1207    pub default_register: Option<Register>,
1208    pub default_room: Option<String>,
1209    pub default_via: Option<Vec<OwnedServerName>>,
1210    pub open_command: Option<Vec<String>>,
1211    pub mouse: Option<Mouse>,
1212    pub notifications: Option<Notifications>,
1213    pub image_preview: Option<ImagePreview>,
1214    pub user_gutter_width: Option<usize>,
1215    pub external_edit_file_suffix: Option<String>,
1216    pub tabstop: Option<usize>,
1217    pub input_prompt: Option<String>,
1218    pub members_split: Option<SplitDirection>,
1219    pub default_split: Option<SplitDirection>,
1220    pub ssl_verify: Option<bool>,
1221    pub cache_policy: Option<MediaRetentionPolicy>,
1222    pub send_on_enter: Option<bool>,
1223    #[serde(default, deserialize_with = "deserialize_strftime")]
1224    pub date_format: Option<String>,
1225    /// strftime string for the per-message time gutter, including any brackets
1226    /// or spacing. The column is as wide as a sample rendering of this string.
1227    /// An empty string hides the time.
1228    #[serde(default, deserialize_with = "deserialize_strftime")]
1229    pub time_format: Option<String>,
1230}
1231
1232impl Tunables {
1233    fn merge(self, other: Self) -> Self {
1234        Tunables {
1235            encryption: Encryption::merge(self.encryption, other.encryption),
1236            sort: SortOverrides::merge(self.sort, other.sort),
1237            terminal: Terminal::merge(self.terminal, other.terminal),
1238            users: merge_maps(self.users, other.users),
1239            rooms: merge_maps(self.rooms, other.rooms),
1240
1241            // Proxy configuration sub-field do *not* get merged, so that a
1242            // per-profile override won't inherit auth or headers from the
1243            // global settings.
1244            proxy: self.proxy.or(other.proxy),
1245
1246            default_markup: self.default_markup.or(other.default_markup),
1247            ignorecase: self.ignorecase.or(other.ignorecase),
1248            log_level: self.log_level.or(other.log_level),
1249            max_log_files: self.max_log_files.or(other.max_log_files),
1250            message_formatted_display: self
1251                .message_formatted_display
1252                .or(other.message_formatted_display),
1253            message_shortcode_display: self
1254                .message_shortcode_display
1255                .or(other.message_shortcode_display),
1256            normal_after_send: self.normal_after_send.or(other.normal_after_send),
1257            reaction_display: self.reaction_display.or(other.reaction_display),
1258            reaction_shortcode_display: self
1259                .reaction_shortcode_display
1260                .or(other.reaction_shortcode_display),
1261            read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
1262            read_receipt_trigger: self.read_receipt_trigger.or(other.read_receipt_trigger),
1263            read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
1264            room_labels: self.room_labels.or(other.room_labels),
1265            request_timeout: self.request_timeout.or(other.request_timeout),
1266            state_event_display: self.state_event_display.or(other.state_event_display),
1267            sync_delay_ms: self.sync_delay_ms.or(other.sync_delay_ms),
1268            theme: self.theme.or(other.theme),
1269            typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
1270            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
1271            username_display: self.username_display.or(other.username_display),
1272            message_user_color: self.message_user_color.or(other.message_user_color),
1273            default_register: self.default_register.or(other.default_register),
1274            default_room: self.default_room.or(other.default_room),
1275            default_via: self.default_via.or(other.default_via),
1276            open_command: self.open_command.or(other.open_command),
1277            mouse: self.mouse.or(other.mouse),
1278            notifications: self.notifications.or(other.notifications),
1279            image_preview: self.image_preview.or(other.image_preview),
1280            user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
1281            external_edit_file_suffix: self
1282                .external_edit_file_suffix
1283                .or(other.external_edit_file_suffix),
1284            tabstop: self.tabstop.or(other.tabstop),
1285            input_prompt: self.input_prompt.or(other.input_prompt),
1286            members_split: self.members_split.or(other.members_split),
1287            default_split: self.default_split.or(other.default_split),
1288            ssl_verify: self.ssl_verify.or(other.ssl_verify),
1289            cache_policy: self.cache_policy.or(other.cache_policy),
1290            send_on_enter: self.send_on_enter.or(other.send_on_enter),
1291            date_format: self.date_format.or(other.date_format),
1292            time_format: self.time_format.or(other.time_format),
1293        }
1294    }
1295
1296    fn values(self) -> TunableValues {
1297        let time_format = self.time_format.unwrap_or_else(|| DEFAULT_TIME_FORMAT.to_owned());
1298        let time_gutter_width = time_gutter_width(&time_format);
1299
1300        TunableValues {
1301            encryption: self.encryption.values(),
1302            proxy: self.proxy.unwrap_or_default().values(),
1303            sort: self.sort.values(),
1304            terminal: self.terminal.values(),
1305            users: self.users.unwrap_or_default(),
1306            rooms: self.rooms.unwrap_or_default().into(),
1307
1308            default_markup: self.default_markup.unwrap_or_default(),
1309            log_level: self.log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_owned()),
1310            ignorecase: self.ignorecase.unwrap_or(false),
1311            max_log_files: self.max_log_files.unwrap_or(7),
1312            message_formatted_display: self.message_formatted_display.unwrap_or(true),
1313            message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
1314            normal_after_send: self.normal_after_send.unwrap_or(false),
1315            reaction_display: self.reaction_display.unwrap_or(true),
1316            reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
1317            read_receipt_send: self.read_receipt_send.unwrap_or(true),
1318            read_receipt_trigger: self.read_receipt_trigger.unwrap_or_default(),
1319            read_receipt_display: self.read_receipt_display.unwrap_or(true),
1320            room_labels: self.room_labels.unwrap_or_else(|| DEFAULT_ROOM_LABELS.to_vec()),
1321            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
1322            state_event_display: self.state_event_display.unwrap_or(true),
1323            sync_delay_ms: self.sync_delay_ms.unwrap_or(DEFAULT_SYNC_FREQUENCY),
1324            theme: self.theme.unwrap_or_else(|| "default".to_string()),
1325            typing_notice_send: self.typing_notice_send.unwrap_or(true),
1326            typing_notice_display: self.typing_notice_display.unwrap_or(true),
1327            username_display: self.username_display.unwrap_or_default(),
1328            message_user_color: self.message_user_color.unwrap_or(false),
1329            default_register: self.default_register,
1330            default_room: self.default_room,
1331            default_via: self
1332                .default_via
1333                .unwrap_or_else(|| vec![DEFAULT_VIA_SERVER.clone()])
1334                .into_iter()
1335                .collect(),
1336            open_command: self.open_command,
1337            mouse: self.mouse.unwrap_or_default(),
1338            notifications: self.notifications.unwrap_or_default(),
1339            image_preview: self.image_preview.unwrap_or_default().values(),
1340            user_gutter_width: self.user_gutter_width.unwrap_or(30),
1341            external_edit_file_suffix: self
1342                .external_edit_file_suffix
1343                .unwrap_or_else(|| ".md".to_string()),
1344            tabstop: self.tabstop.unwrap_or(4),
1345            input_prompt: self.input_prompt,
1346            members_split: self.members_split,
1347            default_split: self.default_split.unwrap_or_default(),
1348            ssl_verify: self.ssl_verify.unwrap_or(true),
1349            cache_policy: self.cache_policy.unwrap_or_default(),
1350            send_on_enter: self.send_on_enter.unwrap_or(true),
1351            date_format: self.date_format.unwrap_or_else(|| DEFAULT_DATE_FORMAT.to_owned()),
1352            time_format,
1353            time_gutter_width,
1354        }
1355    }
1356}
1357
1358#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1359#[serde(rename_all = "kebab-case")]
1360#[repr(u8)]
1361pub enum CursorShape {
1362    Default,
1363    Block,
1364    Line,
1365    Underline,
1366    #[default]
1367    Auto,
1368}
1369
1370impl From<CursorShape> for modalkit::crossterm::cursor::SetCursorStyle {
1371    fn from(shape: CursorShape) -> Self {
1372        match shape {
1373            CursorShape::Default => Self::DefaultUserShape,
1374            CursorShape::Block => Self::SteadyBlock,
1375            CursorShape::Line => Self::SteadyBar,
1376            CursorShape::Underline => Self::SteadyUnderScore,
1377
1378            // use steady block at startup and switch to the correct value on first render
1379            CursorShape::Auto => Self::SteadyBlock,
1380        }
1381    }
1382}
1383
1384#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1385#[serde(rename_all = "kebab-case")]
1386#[repr(u8)]
1387pub enum MarkupFormat {
1388    Html,
1389    #[default]
1390    Markdown,
1391    Plaintext,
1392}
1393
1394#[derive(Clone)]
1395pub struct DirectoryValues {
1396    pub cache: PathBuf,
1397    pub data: PathBuf,
1398    pub logs: PathBuf,
1399    pub downloads: Option<PathBuf>,
1400}
1401
1402impl DirectoryValues {
1403    fn create_dir_all(&self) -> std::io::Result<()> {
1404        use std::fs::create_dir_all;
1405
1406        let Self { cache, data, logs, downloads } = self;
1407
1408        create_dir_all(cache)?;
1409        create_dir_all(data)?;
1410        create_dir_all(logs)?;
1411
1412        if let Some(downloads) = downloads {
1413            create_dir_all(downloads)?;
1414        }
1415
1416        Ok(())
1417    }
1418}
1419
1420#[derive(Clone, Default, Deserialize)]
1421pub struct Directories {
1422    pub cache: Option<String>,
1423    pub data: Option<String>,
1424    pub logs: Option<String>,
1425    pub downloads: Option<String>,
1426}
1427
1428impl Directories {
1429    fn merge(self, other: Self) -> Self {
1430        Directories {
1431            cache: self.cache.or(other.cache),
1432            data: self.data.or(other.data),
1433            logs: self.logs.or(other.logs),
1434            downloads: self.downloads.or(other.downloads),
1435        }
1436    }
1437
1438    fn values(self) -> DirectoryValues {
1439        let cache = self
1440            .cache
1441            .map(|dir| {
1442                let dir = shellexpand::full(&dir)
1443                    .expect("unable to expand shell variables in dirs.cache");
1444                Path::new(dir.as_ref()).to_owned()
1445            })
1446            .or_else(|| {
1447                let mut dir = dirs::cache_dir()?;
1448                dir.push("iamb");
1449                dir.into()
1450            })
1451            .expect("no dirs.cache value configured!");
1452
1453        let data = self
1454            .data
1455            .map(|dir| {
1456                let dir = shellexpand::full(&dir)
1457                    .expect("unable to expand shell variables in dirs.cache");
1458                Path::new(dir.as_ref()).to_owned()
1459            })
1460            .or_else(|| {
1461                let mut dir = dirs::data_dir()?;
1462                dir.push("iamb");
1463                dir.into()
1464            })
1465            .expect("no dirs.data value configured!");
1466
1467        let logs = self
1468            .logs
1469            .map(|dir| {
1470                let dir = shellexpand::full(&dir)
1471                    .expect("unable to expand shell variables in dirs.cache");
1472                Path::new(dir.as_ref()).to_owned()
1473            })
1474            .unwrap_or_else(|| {
1475                let mut dir = cache.clone();
1476                dir.push("logs");
1477                dir
1478            });
1479
1480        let downloads = self
1481            .downloads
1482            .map(|dir| {
1483                let dir = shellexpand::full(&dir)
1484                    .expect("unable to expand shell variables in dirs.cache");
1485                Path::new(dir.as_ref()).to_owned()
1486            })
1487            .or_else(dirs::download_dir);
1488
1489        DirectoryValues { cache, data, logs, downloads }
1490    }
1491}
1492
1493#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1494#[serde(untagged)]
1495pub enum WindowPath {
1496    AliasId(OwnedRoomAliasId),
1497    RoomId(OwnedRoomId),
1498    UserId(OwnedUserId),
1499    Window(IambId),
1500}
1501
1502#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1503#[serde(untagged, deny_unknown_fields)]
1504pub enum WindowLayout {
1505    Window { window: WindowPath },
1506    Split { split: Vec<WindowLayout> },
1507}
1508
1509#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1510#[serde(rename_all = "lowercase", tag = "style")]
1511pub enum Layout {
1512    /// Restore the layout from the previous session.
1513    #[default]
1514    Restore,
1515
1516    /// Open a single window using the `default_room` value.
1517    New,
1518
1519    /// Open the window layouts described under `tabs`.
1520    Config { tabs: Vec<WindowLayout> },
1521}
1522
1523#[derive(Default, Clone, Deserialize)]
1524pub struct ProfileConfig {
1525    pub user_id: Option<OwnedUserId>,
1526    pub password_file: Option<PathBuf>,
1527    pub url: Option<Url>,
1528    pub settings: Option<Tunables>,
1529    pub theme: Option<theme::Theme>,
1530    pub dirs: Option<Directories>,
1531    pub layout: Option<Layout>,
1532    pub macros: Option<Macros>,
1533    pub aliases: Option<Aliases>,
1534}
1535
1536impl ProfileConfig {
1537    fn merge(self, other: Self) -> Self {
1538        let user_id = self.user_id.or(other.user_id);
1539        let password_file = self.password_file.or(other.password_file);
1540        let url = self.url.or(other.url);
1541        let settings = merge_options!(self.settings, other.settings);
1542        let theme = merge_options!(self.theme, other.theme);
1543        let dirs = merge_options!(self.dirs, other.dirs);
1544        let layout = self.layout.or(other.layout);
1545        let macros = merge_macros(self.macros, other.macros);
1546        let aliases = merge_maps(self.aliases, other.aliases);
1547
1548        Self {
1549            user_id,
1550            password_file,
1551            url,
1552            settings,
1553            theme,
1554            dirs,
1555            layout,
1556            macros,
1557            aliases,
1558        }
1559    }
1560}
1561
1562#[derive(Clone, Deserialize)]
1563pub struct IambConfig {
1564    #[serde(default)]
1565    include: Vec<String>,
1566
1567    #[serde(default)]
1568    pub profiles: BTreeMap<String, ProfileConfig>,
1569    pub default_profile: Option<String>,
1570    pub settings: Option<Tunables>,
1571    pub dirs: Option<Directories>,
1572    pub layout: Option<Layout>,
1573    pub macros: Option<Macros>,
1574    pub aliases: Option<Aliases>,
1575    pub theme: Option<theme::Theme>,
1576}
1577
1578impl IambConfig {
1579    pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
1580        let s = std::fs::read_to_string(path)?;
1581        let config = toml::from_str(&s)?;
1582
1583        Ok(config)
1584    }
1585
1586    pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
1587        let s = std::fs::read_to_string(path)?;
1588        let config = serde_json::from_str(&s)?;
1589
1590        Ok(config)
1591    }
1592
1593    /// If a value is present in both configs, `self` is prefered.
1594    fn merge(self, other: Self) -> Self {
1595        // transitive includes are not supported
1596        let include = vec![];
1597
1598        let mut profiles = self.profiles;
1599        for (name, profile) in other.profiles {
1600            match profiles.entry(name) {
1601                btree_map::Entry::Vacant(entry) => {
1602                    entry.insert(profile);
1603                },
1604                btree_map::Entry::Occupied(mut entry) => {
1605                    let profile = std::mem::take(entry.get_mut()).merge(profile);
1606                    entry.insert(profile);
1607                },
1608            }
1609        }
1610
1611        let default_profile = self.default_profile.or(other.default_profile);
1612        let settings = merge_options!(self.settings, other.settings);
1613        let dirs = merge_options!(self.dirs, other.dirs);
1614        let layout = self.layout.or(other.layout);
1615        let macros = merge_macros(self.macros, other.macros);
1616        let aliases = merge_maps(self.aliases, other.aliases);
1617        let theme = merge_options!(self.theme, other.theme);
1618
1619        Self {
1620            include,
1621            profiles,
1622            default_profile,
1623            settings,
1624            dirs,
1625            layout,
1626            macros,
1627            aliases,
1628            theme,
1629        }
1630    }
1631}
1632
1633#[derive(Clone)]
1634pub struct ApplicationSettings {
1635    pub layout_json: PathBuf,
1636    pub session_json: PathBuf,
1637    pub device_json: PathBuf,
1638    pub session_json_old: PathBuf,
1639    pub sled_dir: PathBuf,
1640    pub sqlite_dir: PathBuf,
1641    pub sqlite_cache_dir: PathBuf,
1642    pub profile_name: String,
1643    pub user_id: OwnedUserId,
1644    pub profile: ProfileConfig,
1645    pub theme: Arc<theme::ThemeValues>,
1646    pub themes: Arc<CompletionMap<String, theme::Theme>>,
1647    pub tunables: TunableValues,
1648    pub dirs: DirectoryValues,
1649    pub layout: Layout,
1650    pub macros: Macros,
1651    pub aliases: Aliases,
1652
1653    /// Whether to use the Kitty keyboard protocol. Resolved by
1654    /// [`ApplicationSettings::probe_enhanced_keys`] once the TUI starts, since
1655    /// it may require querying the terminal.
1656    pub enable_enhanced_keys: bool,
1657}
1658
1659impl ApplicationSettings {
1660    fn get_xdg_config_home() -> Option<PathBuf> {
1661        env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
1662    }
1663
1664    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
1665        let mut config_dir = cli
1666            .config_directory
1667            .or_else(Self::get_xdg_config_home)
1668            .or_else(dirs::config_dir)
1669            .unwrap_or_else(|| {
1670                usage!(
1671                    "No user configuration directory found;\
1672                    please specify one via -C.\n\n
1673                    For more information try '--help'"
1674                );
1675            });
1676
1677        config_dir.push("iamb");
1678        let config_json = config_dir.join("config.json");
1679        let config_toml = config_dir.join("config.toml");
1680
1681        let config = if config_toml.is_file() {
1682            IambConfig::load_toml(config_toml.as_path())?
1683        } else if config_json.is_file() {
1684            IambConfig::load_json(config_json.as_path())?
1685        } else {
1686            usage!(
1687                "Please create a configuration file at {}\n\n\
1688                For more information try '--help'",
1689                config_toml.display(),
1690            );
1691        };
1692
1693        let config = load_config_includes(config, &config_dir);
1694
1695        let IambConfig {
1696            mut profiles,
1697            default_profile,
1698            dirs,
1699            settings: global,
1700            layout,
1701            macros,
1702            aliases,
1703            theme,
1704            ..
1705        } = config;
1706
1707        validate_profile_names(&profiles);
1708
1709        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
1710            profiles.remove_entry(&profile).unwrap_or_else(|| {
1711                usage!(
1712                    "No configured profile with the name {:?} in {}",
1713                    profile,
1714                    config_json.display()
1715                );
1716            })
1717        } else if profiles.len() == 1 {
1718            profiles.into_iter().next().unwrap()
1719        } else {
1720            loop {
1721                println!("\nNo profile specified. Available profiles:");
1722                profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
1723
1724                print!("Select a number or 'q' to quit: ");
1725                let _ = std::io::stdout().flush();
1726
1727                let mut input = String::new();
1728                let _ = std::io::stdin().read_line(&mut input);
1729
1730                if input.trim() == "q" {
1731                    usage!(
1732                        "No profile specified. \
1733                        Please use -P or add \"default_profile\" to your configuration.\n\n\
1734                        For more information try '--help'",
1735                    );
1736                }
1737                if let Ok(i) = input.trim().parse::<usize>() &&
1738                    i < profiles.len()
1739                {
1740                    break profiles.into_iter().nth(i).unwrap();
1741                }
1742                println!("\nInvalid index.");
1743            }
1744        };
1745
1746        let user_id = profile.user_id.clone().expect("Active profile does not have a user id");
1747
1748        let aliases = merge_maps(profile.aliases.take(), aliases).unwrap_or_default();
1749        let macros = merge_macros(profile.macros.take(), macros).unwrap_or_default();
1750        let layout = profile.layout.take().or(layout).unwrap_or_default();
1751
1752        let tunables = global.unwrap_or_default();
1753        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
1754        let tunables = tunables.values();
1755
1756        let dirs = dirs.unwrap_or_default();
1757        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
1758        let dirs = dirs.values();
1759
1760        let themes_dir = config_dir.join("themes");
1761        let overrides = profile.theme.clone().unwrap_or_default().merge(theme.unwrap_or_default());
1762        let themes = Arc::new(load_themes(&themes_dir, overrides)?);
1763
1764        let theme = if let Some(theme) = themes.get(&tunables.theme) {
1765            Arc::new(theme.clone().values())
1766        } else {
1767            let err = anyhow!(
1768                "Could not find the {:?} theme; check {}?",
1769                tunables.theme,
1770                themes_dir.display()
1771            );
1772            return Err(err.into_boxed_dyn_error());
1773        };
1774
1775        // Create directories
1776        dirs.create_dir_all()?;
1777
1778        // Set up paths that live inside the profile's data directory.
1779        let mut profile_dir = config_dir.clone();
1780        profile_dir.push("profiles");
1781        profile_dir.push(profile_name.as_str());
1782
1783        let mut profile_data_dir = dirs.data.clone();
1784        profile_data_dir.push("profiles");
1785        profile_data_dir.push(profile_name.as_str());
1786
1787        let mut sled_dir = profile_dir.clone();
1788        sled_dir.push("matrix");
1789
1790        let mut sqlite_dir = profile_data_dir.clone();
1791        sqlite_dir.push("sqlite");
1792
1793        let mut session_json = profile_data_dir.clone();
1794        session_json.push("session.json");
1795
1796        let mut device_json = profile_data_dir;
1797        device_json.push("device.json");
1798
1799        let mut session_json_old = profile_dir;
1800        session_json_old.push("session.json");
1801
1802        // Set up paths that live inside the profile's cache directory.
1803        let mut cache_dir = dirs.cache.clone();
1804        cache_dir.push("profiles");
1805        cache_dir.push(profile_name.as_str());
1806
1807        let mut layout_json = cache_dir.clone();
1808        layout_json.push("layout.json");
1809
1810        let mut sqlite_cache_dir = cache_dir;
1811        sqlite_cache_dir.push("sqlite");
1812
1813        let settings = ApplicationSettings {
1814            sled_dir,
1815            layout_json,
1816            session_json,
1817            device_json,
1818            session_json_old,
1819            sqlite_dir,
1820            sqlite_cache_dir,
1821            profile_name,
1822            user_id,
1823            profile,
1824            themes,
1825            theme,
1826            tunables,
1827            dirs,
1828            layout,
1829            macros,
1830            aliases,
1831            enable_enhanced_keys: false,
1832        };
1833
1834        Ok(settings)
1835    }
1836
1837    /// Work out whether to use the Kitty keyboard protocol, asking the terminal
1838    /// when the user has not configured it explicitly.
1839    ///
1840    /// This queries the terminal, so it must only be called once, before the
1841    /// TUI starts reading input.
1842    pub fn probe_enhanced_keys(&mut self) {
1843        self.enable_enhanced_keys =
1844            self.tunables.terminal.enable_extended_keys.unwrap_or_else(|| {
1845                crossterm::terminal::supports_keyboard_enhancement()
1846                .inspect_err(|e| {
1847                    tracing::warn!(
1848                        err = %e,
1849                        "Failed to determine whether the terminal supports keyboard enhancements"
1850                    )
1851                })
1852                .unwrap_or_default()
1853            });
1854    }
1855
1856    pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1857        let file = File::open(path)?;
1858        let reader = BufReader::new(file);
1859        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1860        Ok(session)
1861    }
1862
1863    pub fn write_session(&self, session: impl Into<Session>) -> Result<(), IambError> {
1864        let file = File::create(self.session_json.as_path())?;
1865        let writer = BufWriter::new(file);
1866        let session: Session = session.into();
1867        serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1868        Ok(())
1869    }
1870
1871    /// The device ID saved at logout, if it was saved for this profile's
1872    /// user. A missing or stale file is not an error: the next login then
1873    /// simply gets a fresh device ID from the homeserver.
1874    pub fn read_saved_device(&self) -> Option<SavedDevice> {
1875        let file = File::open(self.device_json.as_path()).ok()?;
1876        let reader = BufReader::new(file);
1877        let saved: SavedDevice = serde_json::from_reader(reader).ok()?;
1878
1879        if saved.is_user(&self.user_id) {
1880            Some(saved)
1881        } else {
1882            None
1883        }
1884    }
1885
1886    pub fn write_saved_device(
1887        &self,
1888        device_id: &DeviceId,
1889        client_id: Option<ClientId>,
1890    ) -> Result<(), IambError> {
1891        let file = File::create(self.device_json.as_path())?;
1892        let writer = BufWriter::new(file);
1893
1894        let saved = match client_id {
1895            Some(client) => {
1896                SavedDevice::OAuth {
1897                    user_id: self.user_id.clone(),
1898                    device_id: device_id.to_owned(),
1899                    client_id: client,
1900                }
1901            },
1902            None => {
1903                SavedDevice::MatrixAuth {
1904                    user_id: self.user_id.clone(),
1905                    device_id: device_id.to_owned(),
1906                }
1907            },
1908        };
1909        serde_json::to_writer(writer, &saved).map_err(IambError::from)?;
1910        Ok(())
1911    }
1912
1913    pub fn get_user_char_span(&self, user_id: &UserId, info: &RoomInfo) -> Span<'_> {
1914        let (color, configured_name) = self
1915            .tunables
1916            .users
1917            .get(user_id)
1918            .map(|user| (user.color, user.name.as_deref()))
1919            .unwrap_or_default();
1920
1921        let style = self.theme.users.style(user_id.as_str(), color);
1922        let c = configured_name
1923            .and_then(|name| name.chars().next())
1924            .or_else(|| {
1925                info.display_names
1926                    .get(user_id)
1927                    .and_then(|name| name.chars().next())
1928                    .filter(char::is_ascii)
1929            })
1930            .unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1931
1932        Span::styled(String::from(c), style)
1933    }
1934
1935    pub fn get_user_overrides(
1936        &self,
1937        user_id: &UserId,
1938    ) -> (Option<Color>, Option<Cow<'static, str>>) {
1939        self.tunables
1940            .users
1941            .get(user_id)
1942            .map(|user| (user.color, user.name.clone().map(Cow::Owned)))
1943            .unwrap_or_default()
1944    }
1945
1946    pub fn get_user_color(&self, user_id: &UserId) -> Color {
1947        self.tunables
1948            .users
1949            .get(user_id)
1950            .and_then(|user| user.color)
1951            .unwrap_or_else(|| self.theme.users.color(user_id.as_str()))
1952    }
1953
1954    pub fn get_user_style(&self, user_id: &UserId) -> Style {
1955        let (color, _) = self.get_user_overrides(user_id);
1956        self.theme.users.style(user_id.as_str(), color)
1957    }
1958
1959    pub fn get_user_span<'a>(
1960        &self,
1961        user_id: &'a UserId,
1962        display_name: Option<Cow<'a, str>>,
1963    ) -> Span<'a> {
1964        let (color, name) = self.get_user_overrides(user_id);
1965
1966        let style = self.theme.users.style(user_id.as_str(), color);
1967        let name = match (name, &self.tunables.username_display) {
1968            (Some(name), _) => name,
1969            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1970            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1971            (None, UserDisplayStyle::DisplayName) => {
1972                display_name.unwrap_or(Cow::Borrowed(user_id.as_str()))
1973            },
1974        };
1975
1976        Span::styled(name, style)
1977    }
1978}
1979
1980#[cfg(test)]
1981mod tests {
1982    use super::*;
1983
1984    use std::convert::TryFrom;
1985
1986    use matrix_sdk::ruma::user_id;
1987
1988    use crate::tests::{TEST_USER1, mock_room, mock_settings};
1989
1990    #[test]
1991    fn test_get_user_span_borrowed() {
1992        // fix `StyleTreeNode::print` for `StyleTreeNode::UserId` if this breaks
1993        let info = mock_room();
1994        let settings = mock_settings();
1995        let span = settings.get_user_span(&TEST_USER1, info.display_names.get(&TEST_USER1));
1996
1997        assert!(matches!(span.content, Cow::Borrowed(_)));
1998    }
1999
2000    #[test]
2001    fn test_profile_name_invalid() {
2002        assert_eq!(validate_profile_name(""), false);
2003        assert_eq!(validate_profile_name(" "), false);
2004        assert_eq!(validate_profile_name("a b"), false);
2005        assert_eq!(validate_profile_name("foo^bar"), false);
2006        assert_eq!(validate_profile_name("FOO/BAR"), false);
2007        assert_eq!(validate_profile_name("-b-c"), false);
2008        assert_eq!(validate_profile_name("-B-c"), false);
2009        assert_eq!(validate_profile_name(".b-c"), false);
2010        assert_eq!(validate_profile_name(".B-c"), false);
2011    }
2012
2013    #[test]
2014    fn test_profile_name_valid() {
2015        assert_eq!(validate_profile_name("foo"), true);
2016        assert_eq!(validate_profile_name("FOO"), true);
2017        assert_eq!(validate_profile_name("a-b-c"), true);
2018        assert_eq!(validate_profile_name("a-B-c"), true);
2019        assert_eq!(validate_profile_name("a.b-c"), true);
2020        assert_eq!(validate_profile_name("a.B-c"), true);
2021    }
2022
2023    #[test]
2024    fn test_merge_users() {
2025        let a = None;
2026        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
2027            color: Some(Color::Red),
2028            name: Some("Hello".into()),
2029        })]
2030        .into_iter()
2031        .collect::<HashMap<_, _>>();
2032        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
2033            color: Some(Color::Green),
2034            name: Some("World".into()),
2035        })]
2036        .into_iter()
2037        .collect::<HashMap<_, _>>();
2038
2039        let res = merge_maps(a.clone(), a.clone());
2040        assert_eq!(res, None);
2041
2042        let res = merge_maps(a.clone(), Some(b.clone()));
2043        assert_eq!(res, Some(b.clone()));
2044
2045        let res = merge_maps(Some(b.clone()), a.clone());
2046        assert_eq!(res, Some(b.clone()));
2047
2048        let res = merge_maps(Some(b.clone()), Some(b.clone()));
2049        assert_eq!(res, Some(b.clone()));
2050
2051        let res = merge_maps(Some(b.clone()), Some(c.clone()));
2052        assert_eq!(res, Some(b.clone()));
2053
2054        let res = merge_maps(Some(c.clone()), Some(b.clone()));
2055        assert_eq!(res, Some(c.clone()));
2056    }
2057
2058    #[test]
2059    fn test_parse_tunables() {
2060        let res: Tunables = serde_json::from_str("{}").unwrap();
2061        assert_eq!(res.typing_notice_send, None);
2062        assert_eq!(res.typing_notice_display, None);
2063        assert_eq!(res.users, None);
2064
2065        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
2066        assert_eq!(res.typing_notice_send, Some(true));
2067        assert_eq!(res.typing_notice_display, None);
2068        assert_eq!(res.users, None);
2069
2070        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
2071        assert_eq!(res.typing_notice_send, Some(false));
2072        assert_eq!(res.typing_notice_display, None);
2073        assert_eq!(res.users, None);
2074
2075        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
2076        assert_eq!(res.typing_notice_send, None);
2077        assert_eq!(res.typing_notice_display, None);
2078        assert_eq!(res.users, Some(HashMap::new()));
2079    }
2080
2081    #[test]
2082    fn test_parse_user_colors() {
2083        let expect = |color| UserDisplayTunables { color: Some(color), name: Some("Tim".into()) };
2084
2085        // Unprefixed color:
2086        let res: Tunables = serde_json::from_str(
2087            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
2088        )
2089        .unwrap();
2090        assert_eq!(res.typing_notice_send, None);
2091        assert_eq!(res.typing_notice_display, None);
2092        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::Black))];
2093        assert_eq!(res.users, Some(users.into_iter().collect()));
2094
2095        // Color with `light-` prefix:
2096        let res: Tunables = serde_json::from_str(
2097            "{\"users\": {\"@a:b.c\": {\"color\": \"light-red\", \"name\": \"Tim\"}}}",
2098        )
2099        .unwrap();
2100        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightRed))];
2101        assert_eq!(res.users, Some(users.into_iter().collect()));
2102
2103        // Color name with `light-` prefix:
2104        let res: Tunables = serde_json::from_str(
2105            "{\"users\": {\"@a:b.c\": {\"color\": \"light-red\", \"name\": \"Tim\"}}}",
2106        )
2107        .unwrap();
2108        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightRed))];
2109        assert_eq!(res.users, Some(users.into_iter().collect()));
2110
2111        // Color name with `light` prefix, no hyphen:
2112        let res: Tunables = serde_json::from_str(
2113            "{\"users\": {\"@a:b.c\": {\"color\": \"lightblue\", \"name\": \"Tim\"}}}",
2114        )
2115        .unwrap();
2116        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::LightBlue))];
2117        assert_eq!(res.users, Some(users.into_iter().collect()));
2118
2119        // Hex color name:
2120        let res: Tunables = serde_json::from_str(
2121            "{\"users\": {\"@a:b.c\": {\"color\": \"#ff55bb\", \"name\": \"Tim\"}}}",
2122        )
2123        .unwrap();
2124        let users = vec![(user_id!("@a:b.c").to_owned(), expect(Color::Rgb(0xff, 0x55, 0xbb)))];
2125        assert_eq!(res.users, Some(users.into_iter().collect()));
2126    }
2127
2128    fn parse_settings_toml(input: &str) -> Result<Tunables, toml::de::Error> {
2129        #[derive(Deserialize)]
2130        struct SettingsToml {
2131            settings: Tunables,
2132        }
2133
2134        toml::from_str::<SettingsToml>(input).map(|doc| doc.settings)
2135    }
2136
2137    #[test]
2138    fn test_parse_tunables_date_time_format() {
2139        let settings = parse_settings_toml(
2140            r#"
2141[settings]
2142date_format = "%Y-%m-%d"
2143time_format = "%H:%M"
2144"#,
2145        )
2146        .unwrap();
2147        assert_eq!(settings.date_format.as_deref(), Some("%Y-%m-%d"));
2148        assert_eq!(settings.time_format.as_deref(), Some("%H:%M"));
2149
2150        let values = settings.values();
2151        assert_eq!(values.date_format, "%Y-%m-%d");
2152        assert_eq!(values.time_format, "%H:%M");
2153        assert_eq!(values.time_gutter_width, 5);
2154
2155        // Absent keys keep today's formats.
2156        let settings = parse_settings_toml("[settings]\n").unwrap();
2157        assert_eq!(settings.date_format, None);
2158        assert_eq!(settings.time_format, None);
2159        let values = settings.values();
2160        assert_eq!(values.date_format, "%A, %B %d %Y");
2161        assert_eq!(values.time_format, "  [%T]");
2162        assert_eq!(values.time_gutter_width, 12);
2163
2164        // An empty format is valid and disables the time column.
2165        let settings = parse_settings_toml(
2166            r#"
2167[settings]
2168time_format = ""
2169"#,
2170        )
2171        .unwrap();
2172        assert_eq!(settings.time_format.as_deref(), Some(""));
2173        let values = settings.values();
2174        assert_eq!(values.time_format, "");
2175        assert_eq!(values.time_gutter_width, 0);
2176
2177        // Brackets and spacing are literal gutter text, not added later.
2178        let settings = parse_settings_toml(
2179            r#"
2180[settings]
2181time_format = "  [%H:%M]"
2182"#,
2183        )
2184        .unwrap();
2185        let values = settings.values();
2186        assert_eq!(values.time_format, "  [%H:%M]");
2187        assert_eq!(values.time_gutter_width, 9);
2188    }
2189
2190    #[test]
2191    fn test_parse_tunables_date_time_format_invalid() {
2192        let err = parse_settings_toml(
2193            r#"
2194[settings]
2195date_format = "%Q"
2196"#,
2197        )
2198        .unwrap_err();
2199        let msg = err.to_string();
2200        assert!(msg.contains("invalid strftime"), "{msg}");
2201
2202        let err = parse_settings_toml(
2203            r#"
2204[settings]
2205time_format = "%"
2206"#,
2207        )
2208        .unwrap_err();
2209        let msg = err.to_string();
2210        assert!(msg.contains("invalid strftime"), "{msg}");
2211    }
2212
2213    #[test]
2214    fn test_parse_tunables_username_display() {
2215        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
2216        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
2217
2218        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
2219        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
2220
2221        let res: Tunables =
2222            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
2223        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
2224    }
2225
2226    #[test]
2227    fn test_parse_tunables_sort() {
2228        let res: Tunables = serde_json::from_str(
2229            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
2230        )
2231        .unwrap();
2232        assert_eq!(
2233            res.sort.members,
2234            Some(vec![
2235                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
2236                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
2237            ])
2238        );
2239        assert_eq!(
2240            res.sort.spaces,
2241            Some(vec![
2242                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
2243                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
2244            ])
2245        );
2246        assert_eq!(res.sort.rooms, None);
2247        assert_eq!(res.sort.dms, None);
2248
2249        // Check that we get the right default "rooms" and "dms" values.
2250        let res = res.values();
2251        assert_eq!(res.sort.members, vec![
2252            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
2253            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
2254        ]);
2255        assert_eq!(res.sort.spaces, vec![
2256            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
2257            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
2258        ]);
2259        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
2260        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
2261    }
2262
2263    #[test]
2264    fn test_parse_default_members_sort() {
2265        let sort: Vec<SortColumn<SortFieldUser>> =
2266            serde_json::from_str(r#"["power","knock","~invite","id"]"#).unwrap();
2267        assert_eq!(sort.as_slice(), &DEFAULT_MEMBERS_SORT[..]);
2268    }
2269
2270    #[test]
2271    fn test_parse_default_rooms_sort() {
2272        let sort: Vec<SortColumn<SortFieldRoom>> =
2273            serde_json::from_str(r#"["favorite","invite","lowpriority","mentions","notifications","marked_unread","joined","space","dm","recent","name"]"#)
2274                .unwrap();
2275        assert_eq!(sort.as_slice(), &DEFAULT_ROOM_SORT[..]);
2276    }
2277
2278    #[test]
2279    fn test_parse_default_space_sort() {
2280        let sort: Vec<SortColumn<SortFieldSpace>> =
2281            serde_json::from_str(r#"["space","joined","spaceorder"]"#).unwrap();
2282        assert_eq!(sort.as_slice(), &DEFAULT_SPACE_SORT[..]);
2283    }
2284
2285    #[test]
2286    fn test_parse_tunables_proxy_invalid() {
2287        let res =
2288            serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();
2289
2290        // Should result in a validation error:
2291        assert_eq!(res.classify(), serde_json::error::Category::Data);
2292    }
2293
2294    #[test]
2295    fn test_parse_tunables_proxy_empty() {
2296        let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
2297        let proxy = res.proxy.unwrap();
2298        assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
2299    }
2300
2301    #[test]
2302    fn test_parse_tunables_proxy_socks5() {
2303        let res: Tunables =
2304            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
2305        let proxy = res.proxy.unwrap();
2306        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
2307            panic!("should parse ProxyUrl::Endpoint")
2308        };
2309
2310        assert_eq!(url.scheme(), "socks5");
2311        assert_eq!(url.host_str().unwrap(), "localhost");
2312        assert_eq!(url.port().unwrap(), 1080);
2313        assert_eq!(url.authority(), "localhost:1080");
2314    }
2315
2316    #[test]
2317    fn test_parse_tunables_proxy_https() {
2318        let res: Tunables = serde_json::from_str(
2319            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
2320        ).unwrap();
2321        let proxy = res.proxy.unwrap();
2322        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
2323            panic!("should parse ProxyUrl::Endpoint")
2324        };
2325
2326        // Verify URL fields:
2327        assert_eq!(url.scheme(), "https");
2328        assert_eq!(url.host_str().unwrap(), "localhost");
2329        assert_eq!(url.port().unwrap(), 8080);
2330        assert_eq!(url.authority(), "localhost:8080");
2331
2332        // Verify our `Proxy-Authorization` value:
2333        assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");
2334
2335        // Verify our custom header is present:
2336        assert_eq!(proxy.headers.len(), 1);
2337        assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
2338    }
2339
2340    #[test]
2341    fn test_parse_tunables_proxy_merge() {
2342        let global: Tunables = serde_json::from_str(
2343            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
2344        ).unwrap();
2345        let profile: Tunables =
2346            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
2347
2348        // The configuration merge should select the entirety of the profile proxy config,
2349        // and not merge subfields, to ensure that things like `auth` and `headers` are
2350        // not ever sent to a `url` they were meant for.
2351        let merged = profile.merge(global).values();
2352        let ProxyUrl::Endpoint(url) = merged.proxy.url else {
2353            panic!("should parse ProxyUrl::Endpoint")
2354        };
2355        assert_eq!(url.scheme(), "socks5");
2356        assert_eq!(url.authority(), "localhost:1080");
2357        assert_eq!(merged.proxy.auth, None);
2358        assert_eq!(merged.proxy.headers.is_empty(), true);
2359    }
2360
2361    #[test]
2362    fn test_parse_tunables_default_register() {
2363        let reg_a: Tunables = serde_json::from_str(r#"{"default_register": "a"}"#).unwrap();
2364        assert_eq!(reg_a.default_register, Some(Register::Named('a')));
2365
2366        let reg_z: Tunables = serde_json::from_str(r#"{"default_register": "z"}"#).unwrap();
2367        assert_eq!(reg_z.default_register, Some(Register::Named('z')));
2368
2369        let reg_blackhole: Tunables = serde_json::from_str(r#"{"default_register": "_"}"#).unwrap();
2370        assert_eq!(reg_blackhole.default_register, Some(Register::Blackhole));
2371
2372        let res: Result<Tunables, _> = serde_json::from_str(r#"{"default_register": "A"}"#);
2373        assert!(res.is_err());
2374
2375        let res: Result<Tunables, _> = serde_json::from_str(r#"{"default_register": "0"}"#);
2376        assert!(res.is_err());
2377    }
2378
2379    #[test]
2380    fn test_parse_layout() {
2381        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
2382        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
2383        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
2384        let dms = WindowPath::Window(IambId::DirectList);
2385        let welcome = WindowPath::Window(IambId::Welcome);
2386
2387        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
2388        assert_eq!(res, Layout::Restore);
2389
2390        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
2391        assert_eq!(res, Layout::New);
2392
2393        let res: Layout = serde_json::from_str(
2394            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
2395        )
2396        .unwrap();
2397        assert_eq!(res, Layout::Config {
2398            tabs: vec![WindowLayout::Window { window: user.clone() }]
2399        });
2400
2401        let res: Layout = serde_json::from_str(
2402            "{\
2403            \"style\": \"config\",\
2404            \"tabs\": [\
2405                {\"split\":[\
2406                    {\"window\":\"@user:example.com\"},\
2407                    {\"window\":\"#room:example.com\"}\
2408                ]},\
2409                {\"split\":[\
2410                    {\"window\":\"!room:example.com\"},\
2411                    {\"split\":[\
2412                        {\"window\":\"iamb://dms\"},\
2413                        {\"window\":\"iamb://welcome\"}\
2414                    ]}\
2415                ]}\
2416            ]}",
2417        )
2418        .unwrap();
2419        let split1 = WindowLayout::Split {
2420            split: vec![
2421                WindowLayout::Window { window: user.clone() },
2422                WindowLayout::Window { window: alias },
2423            ],
2424        };
2425        let split2 = WindowLayout::Split {
2426            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
2427                window: welcome,
2428            }],
2429        };
2430        let split3 = WindowLayout::Split {
2431            split: vec![WindowLayout::Window { window: room }, split2],
2432        };
2433        let tabs = vec![split1, split3];
2434        assert_eq!(res, Layout::Config { tabs });
2435    }
2436
2437    #[test]
2438    fn test_parse_aliases() {
2439        let res: Aliases = serde_json::from_str("{\"c\":\"chats\"}").unwrap();
2440        assert_eq!(res.len(), 1);
2441
2442        let aliased = res.get("c").unwrap();
2443        assert_eq!(aliased, "chats");
2444    }
2445
2446    #[test]
2447    fn test_parse_aliases_preserves_order() {
2448        // Aliases are registered in order, which allows alias to refer to earlier ones, so
2449        // ensure we register in user-specified order:
2450        let res: Aliases = toml::from_str("c = \"chats\"\ncc = \"c\"\nd = \"download\"").unwrap();
2451        let order = res.keys().map(String::as_str).collect::<Vec<_>>();
2452
2453        assert_eq!(order, vec!["c", "cc", "d"]);
2454    }
2455
2456    #[test]
2457    fn test_merge_aliases_preserves_order() {
2458        let profile: Aliases = toml::from_str("c = \"chats\"\nz = \"redact\"").unwrap();
2459        let global: Aliases = toml::from_str("c = \"cancel\"\nd = \"download\"").unwrap();
2460
2461        let res = merge_maps(Some(profile), Some(global)).unwrap();
2462        let order = res.keys().map(String::as_str).collect::<Vec<_>>();
2463
2464        // The profile wins for keys in both, but doesn't get to move them.
2465        assert_eq!(order, vec!["c", "d", "z"]);
2466        assert_eq!(res.get("c").unwrap(), "chats");
2467    }
2468
2469    #[test]
2470    fn test_parse_macros() {
2471        let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
2472        assert_eq!(res.len(), 1);
2473
2474        let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
2475        let mapped = res.get(&modes).unwrap();
2476        assert_eq!(mapped.len(), 1);
2477
2478        let j = "j".parse::<TerminalKey>().unwrap();
2479        let esc = "<Esc>".parse::<TerminalKey>().unwrap();
2480
2481        let jj = Keys(vec![j, j], "jj".into());
2482        let run = mapped.get(&jj).unwrap();
2483        let exp = Keys(vec![esc], "<Esc>".into());
2484        assert_eq!(run, &exp);
2485    }
2486
2487    #[test]
2488    fn test_parse_notify_via() {
2489        assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
2490        assert_eq!(
2491            NotifyVia { bell: false, desktop: true },
2492            serde_json::from_str(r#""desktop""#).unwrap()
2493        );
2494        assert_eq!(
2495            NotifyVia { bell: true, desktop: false },
2496            serde_json::from_str(r#""bell""#).unwrap()
2497        );
2498        assert_eq!(
2499            NotifyVia { bell: true, desktop: true },
2500            serde_json::from_str(r#""bell|desktop""#).unwrap()
2501        );
2502        assert_eq!(
2503            NotifyVia { bell: true, desktop: true },
2504            serde_json::from_str(r#""desktop|bell""#).unwrap()
2505        );
2506        assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
2507        assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
2508    }
2509
2510    #[test]
2511    fn test_parse_room_labels() {
2512        assert_eq!(RoomLabel::Membership, serde_json::from_str(r#""membership""#).unwrap());
2513        assert_eq!(RoomLabel::Tags, serde_json::from_str(r#""tags""#).unwrap());
2514        assert_eq!(RoomLabel::Type, serde_json::from_str(r#""type""#).unwrap());
2515    }
2516
2517    #[test]
2518    fn test_parse_cursor_shape() {
2519        assert_eq!(CursorShape::Auto, CursorShape::default());
2520        assert_eq!(CursorShape::Auto, serde_json::from_str(r#""auto""#).unwrap());
2521        assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap());
2522        assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap());
2523        assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap());
2524        assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap());
2525        assert!(serde_json::from_str::<CursorShape>(r#""beam""#).is_err());
2526    }
2527
2528    #[test]
2529    fn test_load_example_config_toml() {
2530        let path = PathBuf::from("config.full.toml");
2531        let config = IambConfig::load_toml(&path).expect("can load config.full.toml");
2532
2533        let IambConfig {
2534            profiles,
2535            default_profile,
2536            settings,
2537            dirs,
2538            layout,
2539            macros,
2540            aliases,
2541            theme,
2542            ..
2543        } = &config;
2544
2545        // There should be an example object for each top-level field.
2546        assert!(!profiles.is_empty());
2547        assert!(default_profile.is_some());
2548        assert!(settings.is_some());
2549        assert!(dirs.is_some());
2550        assert!(layout.is_some());
2551        assert!(macros.is_some());
2552        assert!(aliases.is_some());
2553        assert!(theme.is_some());
2554    }
2555
2556    #[test]
2557    fn test_encryption_indicator_enabled() {
2558        use EncryptionState::*;
2559
2560        let enc = Encryption {
2561            indicator: Some(EncryptionIndicator::Enabled),
2562            indicator_location: Some(EncryptionIndicatorLocation::TITLE),
2563            ..Default::default()
2564        };
2565        let enc = enc.values();
2566        let theme = theme::ThemeValues::default();
2567
2568        // Always shows in the title:
2569        assert!(
2570            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2571                .is_some()
2572        );
2573        assert!(
2574            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2575                .is_some()
2576        );
2577        assert!(
2578            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2579                .is_some()
2580        );
2581
2582        // Doesn't show in the prompt:
2583        assert!(
2584            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2585                .is_none()
2586        );
2587        assert!(
2588            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2589                .is_none()
2590        );
2591        assert!(
2592            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2593                .is_none()
2594        );
2595    }
2596
2597    #[test]
2598    fn test_encryption_indicator_disabled() {
2599        use EncryptionState::*;
2600
2601        let enc = Encryption {
2602            indicator: Some(EncryptionIndicator::Disabled),
2603            indicator_location: Some(EncryptionIndicatorLocation::TITLE),
2604            ..Default::default()
2605        };
2606        let enc = enc.values();
2607        let theme = theme::ThemeValues::default();
2608
2609        // Never shows in the title or the prompt:
2610        assert!(
2611            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2612                .is_none()
2613        );
2614        assert!(
2615            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2616                .is_none()
2617        );
2618        assert!(
2619            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2620                .is_none()
2621        );
2622        assert!(
2623            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2624                .is_none()
2625        );
2626        assert!(
2627            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2628                .is_none()
2629        );
2630        assert!(
2631            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2632                .is_none()
2633        );
2634    }
2635
2636    #[test]
2637    fn test_encryption_indicator_only_encrypted() {
2638        use EncryptionState::*;
2639
2640        let enc = Encryption {
2641            indicator: Some(EncryptionIndicator::OnlyEncrypted),
2642            indicator_location: Some(EncryptionIndicatorLocation::PROMPT),
2643            ..Default::default()
2644        };
2645        let enc = enc.values();
2646        let theme = theme::ThemeValues::default();
2647
2648        // Shows in the prompt when encrypted or unknown:
2649        assert!(
2650            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2651                .is_some()
2652        );
2653        assert!(
2654            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2655                .is_some()
2656        );
2657
2658        // But is hidden when unencrypted:
2659        assert!(
2660            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2661                .is_none()
2662        );
2663
2664        // Doesn't show in the title:
2665        assert!(
2666            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2667                .is_none()
2668        );
2669        assert!(
2670            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2671                .is_none()
2672        );
2673        assert!(
2674            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2675                .is_none()
2676        );
2677    }
2678    #[test]
2679    fn test_encryption_indicator_only_unencrypted() {
2680        use EncryptionState::*;
2681
2682        let enc = Encryption {
2683            indicator: Some(EncryptionIndicator::OnlyUnencrypted),
2684            indicator_location: Some(EncryptionIndicatorLocation::all()),
2685            ..Default::default()
2686        };
2687        let enc = enc.values();
2688        let theme = theme::ThemeValues::default();
2689
2690        // Shows in both the prompt and title when unencrypted or unknown:
2691        assert!(
2692            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted, &theme)
2693                .is_some()
2694        );
2695        assert!(
2696            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown, &theme)
2697                .is_some()
2698        );
2699        assert!(
2700            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted, &theme)
2701                .is_some()
2702        );
2703        assert!(
2704            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown, &theme)
2705                .is_some()
2706        );
2707
2708        // But is hidden when encrypted:
2709        assert!(
2710            enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted, &theme)
2711                .is_none()
2712        );
2713        assert!(
2714            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted, &theme)
2715                .is_none()
2716        );
2717    }
2718}