src/config.rs

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