src/config.rs

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