src/config.rs

1795 lines · 60584 bytes

   1//! # Logic for loading and validating application configuration
   2use std::borrow::Cow;
   3use std::collections::hash_map::DefaultHasher;
   4use std::collections::{BTreeMap, HashMap};
   5use std::env;
   6use std::fmt;
   7use std::fs::File;
   8use std::hash::{Hash, Hasher};
   9use std::io::{BufReader, BufWriter, Write};
  10use std::path::{Path, PathBuf};
  11use std::process;
  12use std::str::FromStr;
  13
  14use clap::Parser;
  15use matrix_sdk::authentication::matrix::MatrixSession;
  16use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
  17use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
  18use matrix_sdk::EncryptionState;
  19use ratatui::style::{Color, Modifier as StyleModifier, Style};
  20use ratatui::text::Span;
  21use ratatui_image::picker::ProtocolType;
  22use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer, Serialize};
  23use url::Url;
  24
  25use modalkit::{env::vim::VimMode, key::TerminalKey, keybindings::InputKey};
  26
  27use super::base::{
  28    IambError,
  29    IambId,
  30    RoomInfo,
  31    SortColumn,
  32    SortFieldRoom,
  33    SortFieldUser,
  34    SortOrder,
  35};
  36
  37type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
  38
  39macro_rules! usage {
  40    ( $($args: tt)* ) => {
  41        println!($($args)*);
  42        process::exit(2);
  43    }
  44}
  45
  46const DEFAULT_MEMBERS_SORT: [SortColumn<SortFieldUser>; 2] = [
  47    SortColumn(SortFieldUser::PowerLevel, SortOrder::Ascending),
  48    SortColumn(SortFieldUser::UserId, SortOrder::Ascending),
  49];
  50
  51const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 5] = [
  52    SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
  53    SortColumn(SortFieldRoom::Invite, SortOrder::Ascending),
  54    SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending),
  55    SortColumn(SortFieldRoom::Unread, SortOrder::Ascending),
  56    SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
  57];
  58
  59const DEFAULT_ENABLE_TITLE: bool = true;
  60const DEFAULT_ENC_INDICATOR_LOC: EncryptionIndicatorLocation = EncryptionIndicatorLocation::PROMPT;
  61const DEFAULT_REQ_TIMEOUT: u64 = 120;
  62
  63const COLORS: [Color; 13] = [
  64    Color::Blue,
  65    Color::Cyan,
  66    Color::Green,
  67    Color::LightBlue,
  68    Color::LightGreen,
  69    Color::LightCyan,
  70    Color::LightMagenta,
  71    Color::LightRed,
  72    Color::LightYellow,
  73    Color::Magenta,
  74    Color::Red,
  75    Color::Reset,
  76    Color::Yellow,
  77];
  78
  79pub fn user_color(user: &str) -> Color {
  80    let mut hasher = DefaultHasher::new();
  81    user.hash(&mut hasher);
  82    let color = hasher.finish() as usize % COLORS.len();
  83
  84    COLORS[color]
  85}
  86
  87pub fn user_style_from_color(color: Color) -> Style {
  88    Style::default().fg(color).add_modifier(StyleModifier::BOLD)
  89}
  90
  91fn is_profile_char(c: char) -> bool {
  92    c.is_ascii_alphanumeric() || c == '.' || c == '-'
  93}
  94
  95fn default_true() -> bool {
  96    true
  97}
  98
  99fn validate_profile_name(name: &str) -> bool {
 100    if name.is_empty() {
 101        return false;
 102    }
 103
 104    let mut chars = name.chars();
 105
 106    if !chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) {
 107        return false;
 108    }
 109
 110    name.chars().all(is_profile_char)
 111}
 112
 113fn validate_profile_names(names: &BTreeMap<String, ProfileConfig>) {
 114    for name in names.keys() {
 115        if validate_profile_name(name.as_str()) {
 116            continue;
 117        }
 118
 119        usage!(
 120            "{:?} is not a valid profile name.\n\n\
 121            Profile names can only contain the characters \
 122            a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
 123            name
 124        );
 125    }
 126}
 127
 128fn deserialize_from_str_opt<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
 129where
 130    D: serde::de::Deserializer<'de>,
 131    T: FromStr,
 132    <T as FromStr>::Err: fmt::Display,
 133{
 134    <Option<&'de str>>::deserialize(deserializer)?
 135        .map(|s| {
 136            let t = T::from_str(s);
 137            t.map_err(|e| D::Error::custom(format!("failed to parse string: {e}")))
 138        })
 139        .transpose()
 140}
 141
 142const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
 143    None => env!("CARGO_PKG_VERSION"),
 144    Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
 145};
 146
 147#[derive(Parser)]
 148#[clap(version = VERSION, about, long_about = None)]
 149#[clap(propagate_version = true)]
 150pub struct Iamb {
 151    #[clap(long, value_parser)]
 152    pub completions: Option<clap_complete::Shell>,
 153
 154    #[clap(short = 'P', long, value_parser)]
 155    pub profile: Option<String>,
 156
 157    #[clap(short = 'C', long, value_parser)]
 158    pub config_directory: Option<PathBuf>,
 159}
 160
 161#[derive(thiserror::Error, Debug)]
 162pub enum ConfigError {
 163    #[error("Error reading configuration file: {0}")]
 164    IO(#[from] std::io::Error),
 165
 166    #[error("Error loading configuration file: {0}")]
 167    Invalid(#[from] toml::de::Error),
 168
 169    #[error("Error loading JSON configuration file: {0}")]
 170    InvalidJSON(#[from] serde_json::Error),
 171}
 172
 173macro_rules! deserialize_str_with_visitor {
 174    ($t: ident, $v: ident) => {
 175        impl<'de> Deserialize<'de> for $t {
 176            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 177            where
 178                D: Deserializer<'de>,
 179            {
 180                deserializer.deserialize_str($v)
 181            }
 182        }
 183    };
 184}
 185
 186deserialize_str_with_visitor!(Keys, KeysVisitor);
 187deserialize_str_with_visitor!(VimModes, VimModesVisitor);
 188deserialize_str_with_visitor!(UserColor, UserColorVisitor);
 189deserialize_str_with_visitor!(EncryptionIndicatorLocation, EncryptionIndicatorLocationVisitor);
 190deserialize_str_with_visitor!(NotifyVia, NotifyViaVisitor);
 191deserialize_str_with_visitor!(ProxyUrl, ProxyUrlVisitor);
 192
 193#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 194pub struct Keys(pub Vec<TerminalKey>, pub String);
 195pub struct KeysVisitor;
 196
 197impl Visitor<'_> for KeysVisitor {
 198    type Value = Keys;
 199
 200    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 201        formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
 202    }
 203
 204    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 205    where
 206        E: SerdeError,
 207    {
 208        match TerminalKey::from_macro_str(value) {
 209            Ok(keys) => Ok(Keys(keys, value.to_string())),
 210            Err(e) => Err(E::custom(format!("Could not parse key sequence: {e}"))),
 211        }
 212    }
 213}
 214
 215#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 216pub struct VimModes(pub Vec<VimMode>);
 217pub struct VimModesVisitor;
 218
 219impl Visitor<'_> for VimModesVisitor {
 220    type Value = VimModes;
 221
 222    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 223        formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
 224    }
 225
 226    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 227    where
 228        E: SerdeError,
 229    {
 230        let mut modes = vec![];
 231
 232        for mode in value.split('|') {
 233            let mode = match mode.to_ascii_lowercase().as_str() {
 234                "insert" | "i" => VimMode::Insert,
 235                "normal" | "n" => VimMode::Normal,
 236                "visual" | "v" => VimMode::Visual,
 237                "command" | "c" => VimMode::Command,
 238                "select" => VimMode::Select,
 239                "operator-pending" => VimMode::OperationPending,
 240                _ => return Err(E::custom("Could not parse into a Vim mode")),
 241            };
 242
 243            modes.push(mode);
 244        }
 245
 246        Ok(VimModes(modes))
 247    }
 248}
 249
 250#[derive(Clone, Debug, Eq, PartialEq)]
 251pub struct UserColor(pub Color);
 252pub struct UserColorVisitor;
 253
 254impl Visitor<'_> for UserColorVisitor {
 255    type Value = UserColor;
 256
 257    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 258        formatter.write_str("a valid color")
 259    }
 260
 261    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 262    where
 263        E: SerdeError,
 264    {
 265        match value {
 266            "none" => Ok(UserColor(Color::Reset)),
 267            "red" => Ok(UserColor(Color::Red)),
 268            "black" => Ok(UserColor(Color::Black)),
 269            "green" => Ok(UserColor(Color::Green)),
 270            "yellow" => Ok(UserColor(Color::Yellow)),
 271            "blue" => Ok(UserColor(Color::Blue)),
 272            "magenta" => Ok(UserColor(Color::Magenta)),
 273            "cyan" => Ok(UserColor(Color::Cyan)),
 274            "gray" => Ok(UserColor(Color::Gray)),
 275            "dark-gray" => Ok(UserColor(Color::DarkGray)),
 276            "light-red" => Ok(UserColor(Color::LightRed)),
 277            "light-green" => Ok(UserColor(Color::LightGreen)),
 278            "light-yellow" => Ok(UserColor(Color::LightYellow)),
 279            "light-blue" => Ok(UserColor(Color::LightBlue)),
 280            "light-magenta" => Ok(UserColor(Color::LightMagenta)),
 281            "light-cyan" => Ok(UserColor(Color::LightCyan)),
 282            "white" => Ok(UserColor(Color::White)),
 283            _ => Err(E::custom("Could not parse color")),
 284        }
 285    }
 286}
 287
 288#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
 289pub struct Session {
 290    access_token: String,
 291    refresh_token: Option<String>,
 292    user_id: OwnedUserId,
 293    device_id: OwnedDeviceId,
 294}
 295
 296impl From<Session> for MatrixSession {
 297    fn from(session: Session) -> Self {
 298        MatrixSession {
 299            tokens: matrix_sdk::authentication::SessionTokens {
 300                access_token: session.access_token,
 301                refresh_token: session.refresh_token,
 302            },
 303            meta: matrix_sdk::SessionMeta {
 304                user_id: session.user_id,
 305                device_id: session.device_id,
 306            },
 307        }
 308    }
 309}
 310
 311impl From<MatrixSession> for Session {
 312    fn from(session: MatrixSession) -> Self {
 313        Session {
 314            access_token: session.tokens.access_token,
 315            refresh_token: session.tokens.refresh_token,
 316            user_id: session.meta.user_id,
 317            device_id: session.meta.device_id,
 318        }
 319    }
 320}
 321
 322#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 323pub struct UserDisplayTunables {
 324    pub color: Option<UserColor>,
 325    pub name: Option<String>,
 326}
 327
 328pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
 329
 330fn merge_maps<K, V>(
 331    profile: Option<HashMap<K, V>>,
 332    global: Option<HashMap<K, V>>,
 333) -> Option<HashMap<K, V>>
 334where
 335    K: Eq + Hash,
 336{
 337    match (global, profile) {
 338        (Some(m), None) | (None, Some(m)) => Some(m),
 339        (Some(mut global), Some(profile)) => {
 340            for (k, v) in profile {
 341                global.insert(k, v);
 342            }
 343
 344            Some(global)
 345        },
 346        (None, None) => None,
 347    }
 348}
 349
 350#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 351#[serde(rename_all = "kebab-case")]
 352#[repr(u8)]
 353pub enum EncryptionIndicator {
 354    /// Always indicate the room's encryption status.
 355    #[default]
 356    Enabled,
 357    /// Never indicate the room's encryption status.
 358    Disabled,
 359    /// Only indicate the room's encryption status when it is encrypted.
 360    OnlyEncrypted,
 361    /// Only indicate the room's encryption status when it is unencrypted.
 362    OnlyUnencrypted,
 363}
 364
 365bitflags::bitflags! {
 366    /// Available options for where to show the encryption status indicator.
 367    #[derive(Clone, Debug, Eq, PartialEq)]
 368    pub struct EncryptionIndicatorLocation: u8 {
 369        const NONE   = 0b00000000;
 370        const TITLE  = 0b00000001;
 371        const PROMPT = 0b00000010;
 372    }
 373}
 374
 375pub struct EncryptionIndicatorLocationVisitor;
 376
 377impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
 378    type Value = EncryptionIndicatorLocation;
 379
 380    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 381        formatter.write_str("a valid encryption indicator location (e.g. \"title\" or \"prompt\")")
 382    }
 383
 384    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 385    where
 386        E: SerdeError,
 387    {
 388        let mut location = EncryptionIndicatorLocation::NONE;
 389
 390        for value in value.split('|') {
 391            match value.to_ascii_lowercase().as_str() {
 392                "title" => location |= EncryptionIndicatorLocation::TITLE,
 393                "prompt" => location |= EncryptionIndicatorLocation::PROMPT,
 394                _ => {
 395                    return Err(E::custom("could not parse into an encryption indicator location"))
 396                },
 397            };
 398        }
 399
 400        Ok(location)
 401    }
 402}
 403
 404#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 405#[serde(rename_all = "lowercase")]
 406pub enum UserDisplayStyle {
 407    // The Matrix username for the sender (e.g., "@user:example.com").
 408    #[default]
 409    Username,
 410
 411    // The localpart of the Matrix username (e.g., "@user").
 412    LocalPart,
 413
 414    // The display name for the Matrix user, calculated according to the rules from the spec.
 415    //
 416    // This is usually something like "Ada Lovelace" if the user has configured a display name, but
 417    // it can wind up being the Matrix username if there are display name collisions in the room,
 418    // in order to avoid any confusion.
 419    DisplayName,
 420}
 421
 422#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
 423#[serde(rename_all = "lowercase")]
 424pub enum SplitDirection {
 425    #[default]
 426    Horizontal,
 427    Vertical,
 428}
 429
 430#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 431pub struct NotifyVia {
 432    /// Deliver notifications via terminal bell.
 433    pub bell: bool,
 434    /// Deliver notifications via desktop mechanism.
 435    #[cfg(feature = "desktop")]
 436    pub desktop: bool,
 437}
 438pub struct NotifyViaVisitor;
 439
 440impl Default for NotifyVia {
 441    fn default() -> Self {
 442        Self {
 443            bell: cfg!(not(feature = "desktop")),
 444            #[cfg(feature = "desktop")]
 445            desktop: true,
 446        }
 447    }
 448}
 449
 450impl Visitor<'_> for NotifyViaVisitor {
 451    type Value = NotifyVia;
 452
 453    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 454        formatter.write_str("a valid notify destination (e.g. \"bell\" or \"desktop\")")
 455    }
 456
 457    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 458    where
 459        E: SerdeError,
 460    {
 461        let mut via = NotifyVia {
 462            bell: false,
 463            #[cfg(feature = "desktop")]
 464            desktop: false,
 465        };
 466
 467        for value in value.split('|') {
 468            match value.to_ascii_lowercase().as_str() {
 469                "bell" => {
 470                    via.bell = true;
 471                },
 472                #[cfg(feature = "desktop")]
 473                "desktop" => {
 474                    via.desktop = true;
 475                },
 476                #[cfg(not(feature = "desktop"))]
 477                "desktop" => {
 478                    return Err(E::custom("desktop notification support was compiled out"))
 479                },
 480                _ => return Err(E::custom("could not parse into a notify destination")),
 481            };
 482        }
 483
 484        Ok(via)
 485    }
 486}
 487
 488#[derive(Clone, Debug, Default, Deserialize)]
 489pub struct Encryption {
 490    indicator: Option<EncryptionIndicator>,
 491    indicator_location: Option<EncryptionIndicatorLocation>,
 492}
 493
 494impl Encryption {
 495    fn merge(profile: Self, global: Self) -> Self {
 496        Encryption {
 497            indicator: profile.indicator.or(global.indicator),
 498            indicator_location: profile.indicator_location.or(global.indicator_location),
 499        }
 500    }
 501
 502    pub fn values(self) -> EncryptionValues {
 503        EncryptionValues {
 504            indicator: self.indicator.unwrap_or_default(),
 505            indicator_location: self.indicator_location.unwrap_or(DEFAULT_ENC_INDICATOR_LOC),
 506        }
 507    }
 508}
 509
 510#[derive(Clone, Debug)]
 511pub struct EncryptionValues {
 512    pub indicator: EncryptionIndicator,
 513    pub indicator_location: EncryptionIndicatorLocation,
 514}
 515
 516impl EncryptionValues {
 517    pub fn get_indicator(
 518        &self,
 519        location: EncryptionIndicatorLocation,
 520        state: EncryptionState,
 521    ) -> Option<Span<'static>> {
 522        if !self.indicator_location.contains(location) {
 523            return None;
 524        }
 525
 526        let indicator = match (self.indicator, state) {
 527            (EncryptionIndicator::Disabled, _) |
 528            (EncryptionIndicator::OnlyUnencrypted, EncryptionState::Encrypted) |
 529            (EncryptionIndicator::OnlyEncrypted, EncryptionState::NotEncrypted) => {
 530                // User doesn't want to see anything:
 531                return None;
 532            },
 533            (
 534                EncryptionIndicator::Enabled | EncryptionIndicator::OnlyEncrypted,
 535                EncryptionState::Encrypted,
 536            ) => {
 537                // Green lock:
 538                Span::styled("\u{1F512}\u{FE0E} ", Style::new().fg(Color::LightGreen))
 539            },
 540            (
 541                EncryptionIndicator::Enabled | EncryptionIndicator::OnlyUnencrypted,
 542                EncryptionState::NotEncrypted,
 543            ) => {
 544                // Red unlocked lock:
 545                Span::styled("\u{1F513}\u{FE0E} ", Style::new().fg(Color::Red))
 546            },
 547
 548            (_, EncryptionState::Unknown) => {
 549                // Yellow question mark:
 550                Span::styled("? ", Style::new().fg(Color::Yellow))
 551            },
 552        };
 553
 554        Some(indicator)
 555    }
 556}
 557
 558#[derive(Clone, Debug, Default, Eq, PartialEq)]
 559pub enum ProxyUrl {
 560    Disabled,
 561    Endpoint(Url),
 562    #[default]
 563    System,
 564}
 565
 566pub struct ProxyUrlVisitor;
 567
 568impl Visitor<'_> for ProxyUrlVisitor {
 569    type Value = ProxyUrl;
 570
 571    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 572        formatter.write_str("a valid proxy URL (e.g. \"socks5://localhost:9050\")")
 573    }
 574
 575    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 576    where
 577        E: SerdeError,
 578    {
 579        if value.is_empty() {
 580            return Ok(ProxyUrl::Disabled);
 581        }
 582
 583        match Url::from_str(value) {
 584            Ok(uri) => Ok(ProxyUrl::Endpoint(uri)),
 585            Err(e) => Err(E::custom(format!("could not parse {value:?}: {e}"))),
 586        }
 587    }
 588}
 589
 590#[derive(Clone, Debug, Default, Deserialize)]
 591pub struct Proxy {
 592    /// How and where to proxy the client's requests to the homeserver.
 593    url: Option<ProxyUrl>,
 594
 595    /// An optional value to include in the `Proxy-Authorization` header.
 596    #[serde(default, deserialize_with = "deserialize_from_str_opt")]
 597    auth: Option<HeaderValue>,
 598
 599    /// Optional headers to include in requests sent to the proxy.
 600    #[serde(default, with = "http_serde::header_map")]
 601    headers: HeaderMap,
 602}
 603
 604impl Proxy {
 605    pub fn values(self) -> ProxyValues {
 606        ProxyValues {
 607            url: self.url.unwrap_or_default(),
 608            auth: self.auth,
 609            headers: self.headers,
 610        }
 611    }
 612}
 613
 614#[derive(Clone, Debug, Default)]
 615pub struct ProxyValues {
 616    pub url: ProxyUrl,
 617    pub auth: Option<HeaderValue>,
 618    pub headers: HeaderMap,
 619}
 620
 621#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 622pub struct Mouse {
 623    #[serde(default)]
 624    pub enabled: bool,
 625}
 626
 627#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 628pub struct Notifications {
 629    #[serde(default)]
 630    pub enabled: bool,
 631    #[serde(default)]
 632    pub via: NotifyVia,
 633    #[serde(default = "default_true")]
 634    pub show_message: bool,
 635    #[serde(default)]
 636    pub sound_hint: Option<String>,
 637}
 638
 639#[derive(Clone)]
 640pub struct ImagePreviewValues {
 641    pub lazy_load: bool,
 642    pub size: ImagePreviewSize,
 643    pub protocol: Option<ImagePreviewProtocolValues>,
 644}
 645
 646#[derive(Clone, Debug, Default, Deserialize)]
 647pub struct ImagePreview {
 648    pub lazy_load: Option<bool>,
 649    pub size: Option<ImagePreviewSize>,
 650    pub protocol: Option<ImagePreviewProtocolValues>,
 651}
 652
 653impl ImagePreview {
 654    fn values(self) -> ImagePreviewValues {
 655        ImagePreviewValues {
 656            lazy_load: self.lazy_load.unwrap_or(true),
 657            size: self.size.unwrap_or_default(),
 658            protocol: self.protocol,
 659        }
 660    }
 661}
 662
 663#[derive(Clone, Copy, Deserialize, Debug)]
 664pub struct ImagePreviewSize {
 665    pub width: usize,
 666    pub height: usize,
 667}
 668
 669impl Default for ImagePreviewSize {
 670    fn default() -> Self {
 671        ImagePreviewSize { width: 66, height: 10 }
 672    }
 673}
 674
 675#[derive(Clone, Debug, Deserialize)]
 676pub struct ImagePreviewProtocolValues {
 677    pub r#type: Option<ProtocolType>,
 678    pub font_size: Option<(u16, u16)>,
 679}
 680
 681#[derive(Clone)]
 682pub struct SortValues {
 683    pub chats: Vec<SortColumn<SortFieldRoom>>,
 684    pub dms: Vec<SortColumn<SortFieldRoom>>,
 685    pub rooms: Vec<SortColumn<SortFieldRoom>>,
 686    pub spaces: Vec<SortColumn<SortFieldRoom>>,
 687    pub members: Vec<SortColumn<SortFieldUser>>,
 688}
 689
 690#[derive(Clone, Debug, Default, Deserialize)]
 691pub struct SortOverrides {
 692    pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
 693    pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
 694    pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
 695    pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
 696    pub members: Option<Vec<SortColumn<SortFieldUser>>>,
 697}
 698
 699impl SortOverrides {
 700    fn merge(profile: Self, global: Self) -> Self {
 701        Self {
 702            chats: profile.chats.or(global.chats),
 703            dms: profile.dms.or(global.dms),
 704            rooms: profile.rooms.or(global.rooms),
 705            spaces: profile.spaces.or(global.spaces),
 706            members: profile.members.or(global.members),
 707        }
 708    }
 709
 710    pub fn values(self) -> SortValues {
 711        let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
 712        let chats = self.chats.unwrap_or_else(|| rooms.clone());
 713        let dms = self.dms.unwrap_or_else(|| rooms.clone());
 714        let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
 715        let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
 716
 717        SortValues { rooms, members, chats, dms, spaces }
 718    }
 719}
 720
 721#[derive(Clone, Debug, Default, Deserialize)]
 722pub struct Terminal {
 723    pub cursor_shape: Option<CursorShape>,
 724    pub enable_extended_keys: Option<bool>,
 725    pub enable_title: Option<bool>,
 726}
 727
 728impl Terminal {
 729    fn merge(profile: Self, global: Self) -> Self {
 730        Self {
 731            cursor_shape: profile.cursor_shape.or(global.cursor_shape),
 732            enable_extended_keys: profile.enable_extended_keys.or(global.enable_extended_keys),
 733            enable_title: profile.enable_title.or(global.enable_title),
 734        }
 735    }
 736
 737    pub fn values(self) -> TerminalValues {
 738        TerminalValues {
 739            cursor_shape: self.cursor_shape.unwrap_or_default(),
 740            enable_extended_keys: self.enable_extended_keys,
 741            enable_title: self.enable_title.unwrap_or(DEFAULT_ENABLE_TITLE),
 742        }
 743    }
 744}
 745
 746#[derive(Clone, Debug)]
 747pub struct TerminalValues {
 748    pub cursor_shape: CursorShape,
 749    pub enable_extended_keys: Option<bool>,
 750    pub enable_title: bool,
 751}
 752
 753/// The configuration settings to run with, after merging the
 754/// per-profile overrides on top of the global settings.
 755#[derive(Clone)]
 756pub struct TunableValues {
 757    pub encryption: EncryptionValues,
 758    pub log_level: String,
 759    pub max_log_files: usize,
 760    pub message_shortcode_display: bool,
 761    pub normal_after_send: bool,
 762    pub proxy: ProxyValues,
 763    pub reaction_display: bool,
 764    pub reaction_shortcode_display: bool,
 765    pub read_receipt_send: bool,
 766    pub read_receipt_display: bool,
 767    pub request_timeout: u64,
 768    pub sort: SortValues,
 769    pub state_event_display: bool,
 770    pub typing_notice_send: bool,
 771    pub typing_notice_display: bool,
 772    pub users: UserOverrides,
 773    pub username_display: UserDisplayStyle,
 774    pub message_user_color: bool,
 775    pub default_room: Option<String>,
 776    pub open_command: Option<Vec<String>>,
 777    pub mouse: Mouse,
 778    pub notifications: Notifications,
 779    pub terminal: TerminalValues,
 780    pub image_preview: Option<ImagePreviewValues>,
 781    pub user_gutter_width: usize,
 782    pub external_edit_file_suffix: String,
 783    pub tabstop: usize,
 784    pub default_split: SplitDirection,
 785    pub ssl_verify: bool,
 786}
 787
 788#[derive(Clone, Debug, Default, Deserialize)]
 789pub struct Tunables {
 790    /// Subsection for overriding encryption-related settings.
 791    #[serde(default)]
 792    pub encryption: Encryption,
 793
 794    /// Subsection for configuring an HTTP(S) proxy.
 795    pub proxy: Option<Proxy>,
 796
 797    /// Subsection for overriding sort orders in UI lists.
 798    #[serde(default)]
 799    pub sort: SortOverrides,
 800
 801    /// Subsection for overriding terminal settings.
 802    #[serde(default)]
 803    pub terminal: Terminal,
 804
 805    /// Subsection for overriding how specific Matrix users are rendered.
 806    pub users: Option<UserOverrides>,
 807
 808    pub log_level: Option<String>,
 809    pub max_log_files: Option<usize>,
 810    pub message_shortcode_display: Option<bool>,
 811    pub normal_after_send: Option<bool>,
 812    pub reaction_display: Option<bool>,
 813    pub reaction_shortcode_display: Option<bool>,
 814    pub read_receipt_send: Option<bool>,
 815    pub read_receipt_display: Option<bool>,
 816    pub request_timeout: Option<u64>,
 817    pub state_event_display: Option<bool>,
 818    pub typing_notice_send: Option<bool>,
 819    pub typing_notice_display: Option<bool>,
 820    pub username_display: Option<UserDisplayStyle>,
 821    pub message_user_color: Option<bool>,
 822    pub default_room: Option<String>,
 823    pub open_command: Option<Vec<String>>,
 824    pub mouse: Option<Mouse>,
 825    pub notifications: Option<Notifications>,
 826    pub image_preview: Option<ImagePreview>,
 827    pub user_gutter_width: Option<usize>,
 828    pub external_edit_file_suffix: Option<String>,
 829    pub tabstop: Option<usize>,
 830    pub default_split: Option<SplitDirection>,
 831    pub ssl_verify: Option<bool>,
 832}
 833
 834impl Tunables {
 835    fn merge(self, other: Self) -> Self {
 836        Tunables {
 837            encryption: Encryption::merge(self.encryption, other.encryption),
 838            sort: SortOverrides::merge(self.sort, other.sort),
 839            terminal: Terminal::merge(self.terminal, other.terminal),
 840            users: merge_maps(self.users, other.users),
 841
 842            // Proxy configuration sub-field do *not* get merged, so that a
 843            // per-profile override won't inherit auth or headers from the
 844            // global settings.
 845            proxy: self.proxy.or(other.proxy),
 846
 847            log_level: self.log_level.or(other.log_level),
 848            max_log_files: self.max_log_files.or(other.max_log_files),
 849            message_shortcode_display: self
 850                .message_shortcode_display
 851                .or(other.message_shortcode_display),
 852            normal_after_send: self.normal_after_send.or(other.normal_after_send),
 853            reaction_display: self.reaction_display.or(other.reaction_display),
 854            reaction_shortcode_display: self
 855                .reaction_shortcode_display
 856                .or(other.reaction_shortcode_display),
 857            read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
 858            read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
 859            request_timeout: self.request_timeout.or(other.request_timeout),
 860            state_event_display: self.state_event_display.or(other.state_event_display),
 861            typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
 862            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
 863            username_display: self.username_display.or(other.username_display),
 864            message_user_color: self.message_user_color.or(other.message_user_color),
 865            default_room: self.default_room.or(other.default_room),
 866            open_command: self.open_command.or(other.open_command),
 867            mouse: self.mouse.or(other.mouse),
 868            notifications: self.notifications.or(other.notifications),
 869            image_preview: self.image_preview.or(other.image_preview),
 870            user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
 871            external_edit_file_suffix: self
 872                .external_edit_file_suffix
 873                .or(other.external_edit_file_suffix),
 874            tabstop: self.tabstop.or(other.tabstop),
 875            default_split: self.default_split.or(other.default_split),
 876            ssl_verify: self.ssl_verify.or(other.ssl_verify),
 877        }
 878    }
 879
 880    fn values(self) -> TunableValues {
 881        TunableValues {
 882            encryption: self.encryption.values(),
 883            proxy: self.proxy.unwrap_or_default().values(),
 884            sort: self.sort.values(),
 885            terminal: self.terminal.values(),
 886            users: self.users.unwrap_or_default(),
 887
 888            log_level: self.log_level.unwrap_or_else(|| "warn".to_string()),
 889            max_log_files: self.max_log_files.unwrap_or(7),
 890            message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
 891            normal_after_send: self.normal_after_send.unwrap_or(false),
 892            reaction_display: self.reaction_display.unwrap_or(true),
 893            reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
 894            read_receipt_send: self.read_receipt_send.unwrap_or(true),
 895            read_receipt_display: self.read_receipt_display.unwrap_or(true),
 896            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
 897            state_event_display: self.state_event_display.unwrap_or(true),
 898            typing_notice_send: self.typing_notice_send.unwrap_or(true),
 899            typing_notice_display: self.typing_notice_display.unwrap_or(true),
 900            username_display: self.username_display.unwrap_or_default(),
 901            message_user_color: self.message_user_color.unwrap_or(false),
 902            default_room: self.default_room,
 903            open_command: self.open_command,
 904            mouse: self.mouse.unwrap_or_default(),
 905            notifications: self.notifications.unwrap_or_default(),
 906            image_preview: self.image_preview.map(ImagePreview::values),
 907            user_gutter_width: self.user_gutter_width.unwrap_or(30),
 908            external_edit_file_suffix: self
 909                .external_edit_file_suffix
 910                .unwrap_or_else(|| ".md".to_string()),
 911            tabstop: self.tabstop.unwrap_or(4),
 912            default_split: self.default_split.unwrap_or_default(),
 913            ssl_verify: self.ssl_verify.unwrap_or(true),
 914        }
 915    }
 916}
 917
 918#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 919#[serde(rename_all = "kebab-case")]
 920#[repr(u8)]
 921pub enum CursorShape {
 922    #[default]
 923    Default,
 924    Block,
 925    Line,
 926    Underline,
 927}
 928
 929impl From<CursorShape> for modalkit::crossterm::cursor::SetCursorStyle {
 930    fn from(shape: CursorShape) -> Self {
 931        match shape {
 932            CursorShape::Default => Self::DefaultUserShape,
 933            CursorShape::Block => Self::SteadyBlock,
 934            CursorShape::Line => Self::SteadyBar,
 935            CursorShape::Underline => Self::SteadyUnderScore,
 936        }
 937    }
 938}
 939
 940#[derive(Clone)]
 941pub struct DirectoryValues {
 942    pub cache: PathBuf,
 943    pub data: PathBuf,
 944    pub logs: PathBuf,
 945    pub downloads: Option<PathBuf>,
 946}
 947
 948impl DirectoryValues {
 949    fn create_dir_all(&self) -> std::io::Result<()> {
 950        use std::fs::create_dir_all;
 951
 952        let Self { cache, data, logs, downloads } = self;
 953
 954        create_dir_all(cache)?;
 955        create_dir_all(data)?;
 956        create_dir_all(logs)?;
 957
 958        if let Some(downloads) = downloads {
 959            create_dir_all(downloads)?;
 960        }
 961
 962        Ok(())
 963    }
 964}
 965
 966#[derive(Clone, Default, Deserialize)]
 967pub struct Directories {
 968    pub cache: Option<String>,
 969    pub data: Option<String>,
 970    pub logs: Option<String>,
 971    pub downloads: Option<String>,
 972}
 973
 974impl Directories {
 975    fn merge(self, other: Self) -> Self {
 976        Directories {
 977            cache: self.cache.or(other.cache),
 978            data: self.data.or(other.data),
 979            logs: self.logs.or(other.logs),
 980            downloads: self.downloads.or(other.downloads),
 981        }
 982    }
 983
 984    fn values(self) -> DirectoryValues {
 985        let cache = self
 986            .cache
 987            .map(|dir| {
 988                let dir = shellexpand::full(&dir)
 989                    .expect("unable to expand shell variables in dirs.cache");
 990                Path::new(dir.as_ref()).to_owned()
 991            })
 992            .or_else(|| {
 993                let mut dir = dirs::cache_dir()?;
 994                dir.push("iamb");
 995                dir.into()
 996            })
 997            .expect("no dirs.cache value configured!");
 998
 999        let data = self
1000            .data
1001            .map(|dir| {
1002                let dir = shellexpand::full(&dir)
1003                    .expect("unable to expand shell variables in dirs.cache");
1004                Path::new(dir.as_ref()).to_owned()
1005            })
1006            .or_else(|| {
1007                let mut dir = dirs::data_dir()?;
1008                dir.push("iamb");
1009                dir.into()
1010            })
1011            .expect("no dirs.data value configured!");
1012
1013        let logs = self
1014            .logs
1015            .map(|dir| {
1016                let dir = shellexpand::full(&dir)
1017                    .expect("unable to expand shell variables in dirs.cache");
1018                Path::new(dir.as_ref()).to_owned()
1019            })
1020            .unwrap_or_else(|| {
1021                let mut dir = cache.clone();
1022                dir.push("logs");
1023                dir
1024            });
1025
1026        let downloads = self
1027            .downloads
1028            .map(|dir| {
1029                let dir = shellexpand::full(&dir)
1030                    .expect("unable to expand shell variables in dirs.cache");
1031                Path::new(dir.as_ref()).to_owned()
1032            })
1033            .or_else(dirs::download_dir);
1034
1035        DirectoryValues { cache, data, logs, downloads }
1036    }
1037}
1038
1039#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1040#[serde(untagged)]
1041pub enum WindowPath {
1042    AliasId(OwnedRoomAliasId),
1043    RoomId(OwnedRoomId),
1044    UserId(OwnedUserId),
1045    Window(IambId),
1046}
1047
1048#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1049#[serde(untagged, deny_unknown_fields)]
1050pub enum WindowLayout {
1051    Window { window: WindowPath },
1052    Split { split: Vec<WindowLayout> },
1053}
1054
1055#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1056#[serde(rename_all = "lowercase", tag = "style")]
1057pub enum Layout {
1058    /// Restore the layout from the previous session.
1059    #[default]
1060    Restore,
1061
1062    /// Open a single window using the `default_room` value.
1063    New,
1064
1065    /// Open the window layouts described under `tabs`.
1066    Config { tabs: Vec<WindowLayout> },
1067}
1068
1069#[derive(Clone, Deserialize)]
1070pub struct ProfileConfig {
1071    pub user_id: OwnedUserId,
1072    pub password_file: Option<PathBuf>,
1073    pub url: Option<Url>,
1074    pub settings: Option<Tunables>,
1075    pub dirs: Option<Directories>,
1076    pub layout: Option<Layout>,
1077    pub macros: Option<Macros>,
1078}
1079
1080#[derive(Clone, Deserialize)]
1081pub struct IambConfig {
1082    pub profiles: BTreeMap<String, ProfileConfig>,
1083    pub default_profile: Option<String>,
1084    pub settings: Option<Tunables>,
1085    pub dirs: Option<Directories>,
1086    pub layout: Option<Layout>,
1087    pub macros: Option<Macros>,
1088}
1089
1090impl IambConfig {
1091    pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
1092        let s = std::fs::read_to_string(path)?;
1093        let config = toml::from_str(&s)?;
1094
1095        Ok(config)
1096    }
1097
1098    pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
1099        let s = std::fs::read_to_string(path)?;
1100        let config = serde_json::from_str(&s)?;
1101
1102        Ok(config)
1103    }
1104}
1105
1106#[derive(Clone)]
1107pub struct ApplicationSettings {
1108    pub layout_json: PathBuf,
1109    pub session_json: PathBuf,
1110    pub session_json_old: PathBuf,
1111    pub sled_dir: PathBuf,
1112    pub sqlite_dir: PathBuf,
1113    pub profile_name: String,
1114    pub profile: ProfileConfig,
1115    pub tunables: TunableValues,
1116    pub dirs: DirectoryValues,
1117    pub layout: Layout,
1118    pub macros: Macros,
1119}
1120
1121impl ApplicationSettings {
1122    fn get_xdg_config_home() -> Option<PathBuf> {
1123        env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
1124    }
1125
1126    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
1127        let mut config_dir = cli
1128            .config_directory
1129            .or_else(Self::get_xdg_config_home)
1130            .or_else(dirs::config_dir)
1131            .unwrap_or_else(|| {
1132                usage!(
1133                    "No user configuration directory found;\
1134                    please specify one via -C.\n\n
1135                    For more information try '--help'"
1136                );
1137            });
1138
1139        config_dir.push("iamb");
1140        let config_json = config_dir.join("config.json");
1141        let config_toml = config_dir.join("config.toml");
1142
1143        let config = if config_toml.is_file() {
1144            IambConfig::load_toml(config_toml.as_path())?
1145        } else if config_json.is_file() {
1146            IambConfig::load_json(config_json.as_path())?
1147        } else {
1148            usage!(
1149                "Please create a configuration file at {}\n\n\
1150                For more information try '--help'",
1151                config_toml.display(),
1152            );
1153        };
1154
1155        let IambConfig {
1156            mut profiles,
1157            default_profile,
1158            dirs,
1159            settings: global,
1160            layout,
1161            macros,
1162        } = config;
1163
1164        validate_profile_names(&profiles);
1165
1166        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
1167            profiles.remove_entry(&profile).unwrap_or_else(|| {
1168                usage!(
1169                    "No configured profile with the name {:?} in {}",
1170                    profile,
1171                    config_json.display()
1172                );
1173            })
1174        } else if profiles.len() == 1 {
1175            profiles.into_iter().next().unwrap()
1176        } else {
1177            loop {
1178                println!("\nNo profile specified. Available profiles:");
1179                profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
1180
1181                print!("Select a number or 'q' to quit: ");
1182                let _ = std::io::stdout().flush();
1183
1184                let mut input = String::new();
1185                let _ = std::io::stdin().read_line(&mut input);
1186
1187                if input.trim() == "q" {
1188                    usage!(
1189                        "No profile specified. \
1190                        Please use -P or add \"default_profile\" to your configuration.\n\n\
1191                        For more information try '--help'",
1192                    );
1193                }
1194                if let Ok(i) = input.trim().parse::<usize>() {
1195                    if i < profiles.len() {
1196                        break profiles.into_iter().nth(i).unwrap();
1197                    }
1198                }
1199                println!("\nInvalid index.");
1200            }
1201        };
1202
1203        let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
1204        let layout = profile.layout.take().or(layout).unwrap_or_default();
1205
1206        let tunables = global.unwrap_or_default();
1207        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
1208        let tunables = tunables.values();
1209
1210        let dirs = dirs.unwrap_or_default();
1211        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
1212        let dirs = dirs.values();
1213
1214        // Create directories
1215        dirs.create_dir_all()?;
1216
1217        // Set up paths that live inside the profile's data directory.
1218        let mut profile_dir = config_dir.clone();
1219        profile_dir.push("profiles");
1220        profile_dir.push(profile_name.as_str());
1221
1222        let mut profile_data_dir = dirs.data.clone();
1223        profile_data_dir.push("profiles");
1224        profile_data_dir.push(profile_name.as_str());
1225
1226        let mut sled_dir = profile_dir.clone();
1227        sled_dir.push("matrix");
1228
1229        let mut sqlite_dir = profile_data_dir.clone();
1230        sqlite_dir.push("sqlite");
1231
1232        let mut session_json = profile_data_dir.clone();
1233        session_json.push("session.json");
1234
1235        let mut session_json_old = profile_dir;
1236        session_json_old.push("session.json");
1237
1238        // Set up paths that live inside the profile's cache directory.
1239        let mut cache_dir = dirs.cache.clone();
1240        cache_dir.push("profiles");
1241        cache_dir.push(profile_name.as_str());
1242
1243        let mut layout_json = cache_dir.clone();
1244        layout_json.push("layout.json");
1245
1246        let settings = ApplicationSettings {
1247            sled_dir,
1248            layout_json,
1249            session_json,
1250            session_json_old,
1251            sqlite_dir,
1252            profile_name,
1253            profile,
1254            tunables,
1255            dirs,
1256            layout,
1257            macros,
1258        };
1259
1260        Ok(settings)
1261    }
1262
1263    pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1264        let file = File::open(path)?;
1265        let reader = BufReader::new(file);
1266        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1267        Ok(session)
1268    }
1269
1270    pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
1271        let file = File::create(self.session_json.as_path())?;
1272        let writer = BufWriter::new(file);
1273        let session = Session::from(session);
1274        serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1275        Ok(())
1276    }
1277
1278    pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
1279        let (color, c) = self
1280            .tunables
1281            .users
1282            .get(user_id)
1283            .map(|user| {
1284                (
1285                    user.color.as_ref().map(|c| c.0),
1286                    user.name.as_ref().and_then(|s| s.chars().next()),
1287                )
1288            })
1289            .unwrap_or_default();
1290
1291        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1292        let style = user_style_from_color(color);
1293
1294        let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1295
1296        Span::styled(String::from(c), style)
1297    }
1298
1299    pub fn get_user_overrides(
1300        &self,
1301        user_id: &UserId,
1302    ) -> (Option<Color>, Option<Cow<'static, str>>) {
1303        self.tunables
1304            .users
1305            .get(user_id)
1306            .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1307            .unwrap_or_default()
1308    }
1309
1310    pub fn get_user_color(&self, user_id: &UserId) -> Color {
1311        self.tunables
1312            .users
1313            .get(user_id)
1314            .and_then(|user| user.color.as_ref().map(|c| c.0))
1315            .unwrap_or_else(|| user_color(user_id.as_str()))
1316    }
1317
1318    pub fn get_user_style(&self, user_id: &UserId) -> Style {
1319        user_style_from_color(self.get_user_color(user_id))
1320    }
1321
1322    pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1323        let (color, name) = self.get_user_overrides(user_id);
1324
1325        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1326        let style = user_style_from_color(color);
1327        let name = match (name, &self.tunables.username_display) {
1328            (Some(name), _) => name,
1329            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1330            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1331            (None, UserDisplayStyle::DisplayName) => {
1332                if let Some(name) = info.display_names.get(user_id) {
1333                    name
1334                } else {
1335                    Cow::Borrowed(user_id.as_str())
1336                }
1337            },
1338        };
1339
1340        Span::styled(name, style)
1341    }
1342}
1343
1344#[cfg(test)]
1345mod tests {
1346    use super::*;
1347    use matrix_sdk::ruma::user_id;
1348    use std::convert::TryFrom;
1349
1350    #[test]
1351    fn test_profile_name_invalid() {
1352        assert_eq!(validate_profile_name(""), false);
1353        assert_eq!(validate_profile_name(" "), false);
1354        assert_eq!(validate_profile_name("a b"), false);
1355        assert_eq!(validate_profile_name("foo^bar"), false);
1356        assert_eq!(validate_profile_name("FOO/BAR"), false);
1357        assert_eq!(validate_profile_name("-b-c"), false);
1358        assert_eq!(validate_profile_name("-B-c"), false);
1359        assert_eq!(validate_profile_name(".b-c"), false);
1360        assert_eq!(validate_profile_name(".B-c"), false);
1361    }
1362
1363    #[test]
1364    fn test_profile_name_valid() {
1365        assert_eq!(validate_profile_name("foo"), true);
1366        assert_eq!(validate_profile_name("FOO"), true);
1367        assert_eq!(validate_profile_name("a-b-c"), true);
1368        assert_eq!(validate_profile_name("a-B-c"), true);
1369        assert_eq!(validate_profile_name("a.b-c"), true);
1370        assert_eq!(validate_profile_name("a.B-c"), true);
1371    }
1372
1373    #[test]
1374    fn test_merge_users() {
1375        let a = None;
1376        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1377            color: Some(UserColor(Color::Red)),
1378            name: Some("Hello".into()),
1379        })]
1380        .into_iter()
1381        .collect::<HashMap<_, _>>();
1382        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1383            color: Some(UserColor(Color::Green)),
1384            name: Some("World".into()),
1385        })]
1386        .into_iter()
1387        .collect::<HashMap<_, _>>();
1388
1389        let res = merge_maps(a.clone(), a.clone());
1390        assert_eq!(res, None);
1391
1392        let res = merge_maps(a.clone(), Some(b.clone()));
1393        assert_eq!(res, Some(b.clone()));
1394
1395        let res = merge_maps(Some(b.clone()), a.clone());
1396        assert_eq!(res, Some(b.clone()));
1397
1398        let res = merge_maps(Some(b.clone()), Some(b.clone()));
1399        assert_eq!(res, Some(b.clone()));
1400
1401        let res = merge_maps(Some(b.clone()), Some(c.clone()));
1402        assert_eq!(res, Some(b.clone()));
1403
1404        let res = merge_maps(Some(c.clone()), Some(b.clone()));
1405        assert_eq!(res, Some(c.clone()));
1406    }
1407
1408    #[test]
1409    fn test_parse_tunables() {
1410        let res: Tunables = serde_json::from_str("{}").unwrap();
1411        assert_eq!(res.typing_notice_send, None);
1412        assert_eq!(res.typing_notice_display, None);
1413        assert_eq!(res.users, None);
1414
1415        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1416        assert_eq!(res.typing_notice_send, Some(true));
1417        assert_eq!(res.typing_notice_display, None);
1418        assert_eq!(res.users, None);
1419
1420        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1421        assert_eq!(res.typing_notice_send, Some(false));
1422        assert_eq!(res.typing_notice_display, None);
1423        assert_eq!(res.users, None);
1424
1425        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1426        assert_eq!(res.typing_notice_send, None);
1427        assert_eq!(res.typing_notice_display, None);
1428        assert_eq!(res.users, Some(HashMap::new()));
1429
1430        let res: Tunables = serde_json::from_str(
1431            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1432        )
1433        .unwrap();
1434        assert_eq!(res.typing_notice_send, None);
1435        assert_eq!(res.typing_notice_display, None);
1436        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1437            color: Some(UserColor(Color::Black)),
1438            name: Some("Tim".into()),
1439        })];
1440        assert_eq!(res.users, Some(users.into_iter().collect()));
1441    }
1442
1443    #[test]
1444    fn test_parse_tunables_username_display() {
1445        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1446        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1447
1448        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1449        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1450
1451        let res: Tunables =
1452            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1453        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1454    }
1455
1456    #[test]
1457    fn test_parse_tunables_sort() {
1458        let res: Tunables = serde_json::from_str(
1459            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1460        )
1461        .unwrap();
1462        assert_eq!(
1463            res.sort.members,
1464            Some(vec![
1465                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1466                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1467            ])
1468        );
1469        assert_eq!(
1470            res.sort.spaces,
1471            Some(vec![
1472                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1473                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1474            ])
1475        );
1476        assert_eq!(res.sort.rooms, None);
1477        assert_eq!(res.sort.dms, None);
1478
1479        // Check that we get the right default "rooms" and "dms" values.
1480        let res = res.values();
1481        assert_eq!(res.sort.members, vec![
1482            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1483            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1484        ]);
1485        assert_eq!(res.sort.spaces, vec![
1486            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1487            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1488        ]);
1489        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1490        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1491    }
1492
1493    #[test]
1494    fn test_parse_tunables_proxy_invalid() {
1495        let res =
1496            serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();
1497
1498        // Should result in a validation error:
1499        assert_eq!(res.classify(), serde_json::error::Category::Data);
1500    }
1501
1502    #[test]
1503    fn test_parse_tunables_proxy_empty() {
1504        let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
1505        let proxy = res.proxy.unwrap();
1506        assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
1507    }
1508
1509    #[test]
1510    fn test_parse_tunables_proxy_socks5() {
1511        let res: Tunables =
1512            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1513        let proxy = res.proxy.unwrap();
1514        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1515            panic!("should parse ProxyUrl::Endpoint")
1516        };
1517
1518        assert_eq!(url.scheme(), "socks5");
1519        assert_eq!(url.host_str().unwrap(), "localhost");
1520        assert_eq!(url.port().unwrap(), 1080);
1521        assert_eq!(url.authority(), "localhost:1080");
1522    }
1523
1524    #[test]
1525    fn test_parse_tunables_proxy_https() {
1526        let res: Tunables = serde_json::from_str(
1527            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1528        ).unwrap();
1529        let proxy = res.proxy.unwrap();
1530        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1531            panic!("should parse ProxyUrl::Endpoint")
1532        };
1533
1534        // Verify URL fields:
1535        assert_eq!(url.scheme(), "https");
1536        assert_eq!(url.host_str().unwrap(), "localhost");
1537        assert_eq!(url.port().unwrap(), 8080);
1538        assert_eq!(url.authority(), "localhost:8080");
1539
1540        // Verify our `Proxy-Authorization` value:
1541        assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");
1542
1543        // Verify our custom header is present:
1544        assert_eq!(proxy.headers.len(), 1);
1545        assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
1546    }
1547
1548    #[test]
1549    fn test_parse_tunables_proxy_merge() {
1550        let global: Tunables = serde_json::from_str(
1551            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1552        ).unwrap();
1553        let profile: Tunables =
1554            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1555
1556        // The configuration merge should select the entirety of the profile proxy config,
1557        // and not merge subfields, to ensure that things like `auth` and `headers` are
1558        // not ever sent to a `url` they were meant for.
1559        let merged = profile.merge(global).values();
1560        let ProxyUrl::Endpoint(url) = merged.proxy.url else {
1561            panic!("should parse ProxyUrl::Endpoint")
1562        };
1563        assert_eq!(url.scheme(), "socks5");
1564        assert_eq!(url.authority(), "localhost:1080");
1565        assert_eq!(merged.proxy.auth, None);
1566        assert_eq!(merged.proxy.headers.is_empty(), true);
1567    }
1568
1569    #[test]
1570    fn test_parse_layout() {
1571        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1572        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1573        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1574        let dms = WindowPath::Window(IambId::DirectList);
1575        let welcome = WindowPath::Window(IambId::Welcome);
1576
1577        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1578        assert_eq!(res, Layout::Restore);
1579
1580        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1581        assert_eq!(res, Layout::New);
1582
1583        let res: Layout = serde_json::from_str(
1584            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1585        )
1586        .unwrap();
1587        assert_eq!(res, Layout::Config {
1588            tabs: vec![WindowLayout::Window { window: user.clone() }]
1589        });
1590
1591        let res: Layout = serde_json::from_str(
1592            "{\
1593            \"style\": \"config\",\
1594            \"tabs\": [\
1595                {\"split\":[\
1596                    {\"window\":\"@user:example.com\"},\
1597                    {\"window\":\"#room:example.com\"}\
1598                ]},\
1599                {\"split\":[\
1600                    {\"window\":\"!room:example.com\"},\
1601                    {\"split\":[\
1602                        {\"window\":\"iamb://dms\"},\
1603                        {\"window\":\"iamb://welcome\"}\
1604                    ]}\
1605                ]}\
1606            ]}",
1607        )
1608        .unwrap();
1609        let split1 = WindowLayout::Split {
1610            split: vec![
1611                WindowLayout::Window { window: user.clone() },
1612                WindowLayout::Window { window: alias },
1613            ],
1614        };
1615        let split2 = WindowLayout::Split {
1616            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1617                window: welcome,
1618            }],
1619        };
1620        let split3 = WindowLayout::Split {
1621            split: vec![WindowLayout::Window { window: room }, split2],
1622        };
1623        let tabs = vec![split1, split3];
1624        assert_eq!(res, Layout::Config { tabs });
1625    }
1626
1627    #[test]
1628    fn test_parse_macros() {
1629        let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1630        assert_eq!(res.len(), 1);
1631
1632        let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1633        let mapped = res.get(&modes).unwrap();
1634        assert_eq!(mapped.len(), 1);
1635
1636        let j = "j".parse::<TerminalKey>().unwrap();
1637        let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1638
1639        let jj = Keys(vec![j, j], "jj".into());
1640        let run = mapped.get(&jj).unwrap();
1641        let exp = Keys(vec![esc], "<Esc>".into());
1642        assert_eq!(run, &exp);
1643    }
1644
1645    #[test]
1646    fn test_parse_notify_via() {
1647        assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1648        assert_eq!(
1649            NotifyVia { bell: false, desktop: true },
1650            serde_json::from_str(r#""desktop""#).unwrap()
1651        );
1652        assert_eq!(
1653            NotifyVia { bell: true, desktop: false },
1654            serde_json::from_str(r#""bell""#).unwrap()
1655        );
1656        assert_eq!(
1657            NotifyVia { bell: true, desktop: true },
1658            serde_json::from_str(r#""bell|desktop""#).unwrap()
1659        );
1660        assert_eq!(
1661            NotifyVia { bell: true, desktop: true },
1662            serde_json::from_str(r#""desktop|bell""#).unwrap()
1663        );
1664        assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1665        assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1666    }
1667
1668    #[test]
1669    fn test_parse_cursor_shape() {
1670        assert_eq!(CursorShape::Default, CursorShape::default());
1671        assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap());
1672        assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap());
1673        assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap());
1674        assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap());
1675        assert!(serde_json::from_str::<CursorShape>(r#""beam""#).is_err());
1676    }
1677
1678    #[test]
1679    fn test_load_example_config_toml() {
1680        let path = PathBuf::from("config.example.toml");
1681        let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1682
1683        let IambConfig {
1684            profiles,
1685            default_profile,
1686            settings,
1687            dirs,
1688            layout,
1689            macros,
1690        } = &config;
1691
1692        // There should be an example object for each top-level field.
1693        assert!(!profiles.is_empty());
1694        assert!(default_profile.is_some());
1695        assert!(settings.is_some());
1696        assert!(dirs.is_some());
1697        assert!(layout.is_some());
1698        assert!(macros.is_some());
1699    }
1700
1701    #[test]
1702    fn test_encryption_indicator_enabled() {
1703        use EncryptionState::*;
1704
1705        let enc = EncryptionValues {
1706            indicator: EncryptionIndicator::Enabled,
1707            indicator_location: EncryptionIndicatorLocation::TITLE,
1708        };
1709
1710        // Always shows in the title:
1711        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
1712        assert!(enc
1713            .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1714            .is_some());
1715        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1716
1717        // Doesn't show in the prompt:
1718        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1719        assert!(enc
1720            .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1721            .is_none());
1722        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1723    }
1724
1725    #[test]
1726    fn test_encryption_indicator_disabled() {
1727        use EncryptionState::*;
1728
1729        let enc = EncryptionValues {
1730            indicator: EncryptionIndicator::Disabled,
1731            indicator_location: EncryptionIndicatorLocation::TITLE,
1732        };
1733
1734        // Never shows in the title or the prompt:
1735        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1736        assert!(enc
1737            .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1738            .is_none());
1739        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1740        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1741        assert!(enc
1742            .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1743            .is_none());
1744        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1745    }
1746
1747    #[test]
1748    fn test_encryption_indicator_only_encrypted() {
1749        use EncryptionState::*;
1750
1751        let enc = EncryptionValues {
1752            indicator: EncryptionIndicator::OnlyEncrypted,
1753            indicator_location: EncryptionIndicatorLocation::PROMPT,
1754        };
1755
1756        // Shows in the prompt when encrypted or unknown:
1757        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_some());
1758        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1759
1760        // But is hidden when unencrypted:
1761        assert!(enc
1762            .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1763            .is_none());
1764
1765        // Doesn't show in the title:
1766        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1767        assert!(enc
1768            .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1769            .is_none());
1770        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1771    }
1772    #[test]
1773    fn test_encryption_indicator_only_unencrypted() {
1774        use EncryptionState::*;
1775
1776        let enc = EncryptionValues {
1777            indicator: EncryptionIndicator::OnlyUnencrypted,
1778            indicator_location: EncryptionIndicatorLocation::all(),
1779        };
1780
1781        // Shows in both the prompt and title when unencrypted or unknown:
1782        assert!(enc
1783            .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1784            .is_some());
1785        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1786        assert!(enc
1787            .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1788            .is_some());
1789        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1790
1791        // But is hidden when encrypted:
1792        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1793        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1794    }
1795}