src/config.rs

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