src/config.rs

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