src/config.rs

1892 lines · 63832 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 ignorecase: bool,
 819    pub log_level: String,
 820    pub max_log_files: usize,
 821    pub message_shortcode_display: bool,
 822    pub normal_after_send: bool,
 823    pub proxy: ProxyValues,
 824    pub reaction_display: bool,
 825    pub reaction_shortcode_display: bool,
 826    pub read_receipt_send: bool,
 827    pub read_receipt_trigger: ReadReceiptTrigger,
 828    pub read_receipt_display: bool,
 829    pub request_timeout: u64,
 830    pub sort: SortValues,
 831    pub state_event_display: bool,
 832    pub typing_notice_send: bool,
 833    pub typing_notice_display: bool,
 834    pub users: UserOverrides,
 835    pub username_display: UserDisplayStyle,
 836    pub message_user_color: bool,
 837    pub default_room: Option<String>,
 838    pub open_command: Option<Vec<String>>,
 839    pub mouse: Mouse,
 840    pub notifications: Notifications,
 841    pub terminal: TerminalValues,
 842    pub image_preview: ImagePreviewValues,
 843    pub user_gutter_width: usize,
 844    pub external_edit_file_suffix: String,
 845    pub tabstop: usize,
 846    pub members_split: Option<SplitDirection>,
 847    pub default_split: SplitDirection,
 848    pub ssl_verify: bool,
 849    pub cache_policy: MediaRetentionPolicy,
 850}
 851
 852#[derive(Clone, Debug, Default, Deserialize)]
 853pub struct Tunables {
 854    /// Subsection for overriding encryption-related settings.
 855    #[serde(default)]
 856    pub encryption: Encryption,
 857
 858    /// Subsection for configuring an HTTP(S) proxy.
 859    pub proxy: Option<Proxy>,
 860
 861    /// Subsection for overriding sort orders in UI lists.
 862    #[serde(default)]
 863    pub sort: SortOverrides,
 864
 865    /// Subsection for overriding terminal settings.
 866    #[serde(default)]
 867    pub terminal: Terminal,
 868
 869    /// Subsection for overriding how specific Matrix users are rendered.
 870    pub users: Option<UserOverrides>,
 871
 872    pub default_markup: Option<MarkupFormat>,
 873    pub ignorecase: Option<bool>,
 874    pub log_level: Option<String>,
 875    pub max_log_files: Option<usize>,
 876    pub message_shortcode_display: Option<bool>,
 877    pub normal_after_send: Option<bool>,
 878    pub reaction_display: Option<bool>,
 879    pub reaction_shortcode_display: Option<bool>,
 880    pub read_receipt_send: Option<bool>,
 881    pub read_receipt_trigger: Option<ReadReceiptTrigger>,
 882    pub read_receipt_display: Option<bool>,
 883    pub request_timeout: Option<u64>,
 884    pub state_event_display: Option<bool>,
 885    pub typing_notice_send: Option<bool>,
 886    pub typing_notice_display: Option<bool>,
 887    pub username_display: Option<UserDisplayStyle>,
 888    pub message_user_color: Option<bool>,
 889    pub default_room: Option<String>,
 890    pub open_command: Option<Vec<String>>,
 891    pub mouse: Option<Mouse>,
 892    pub notifications: Option<Notifications>,
 893    pub image_preview: Option<ImagePreview>,
 894    pub user_gutter_width: Option<usize>,
 895    pub external_edit_file_suffix: Option<String>,
 896    pub tabstop: Option<usize>,
 897    pub members_split: Option<SplitDirection>,
 898    pub default_split: Option<SplitDirection>,
 899    pub ssl_verify: Option<bool>,
 900    pub cache_policy: Option<MediaRetentionPolicy>,
 901}
 902
 903impl Tunables {
 904    fn merge(self, other: Self) -> Self {
 905        Tunables {
 906            encryption: Encryption::merge(self.encryption, other.encryption),
 907            sort: SortOverrides::merge(self.sort, other.sort),
 908            terminal: Terminal::merge(self.terminal, other.terminal),
 909            users: merge_maps(self.users, other.users),
 910
 911            // Proxy configuration sub-field do *not* get merged, so that a
 912            // per-profile override won't inherit auth or headers from the
 913            // global settings.
 914            proxy: self.proxy.or(other.proxy),
 915
 916            default_markup: self.default_markup.or(other.default_markup),
 917            ignorecase: self.ignorecase.or(other.ignorecase),
 918            log_level: self.log_level.or(other.log_level),
 919            max_log_files: self.max_log_files.or(other.max_log_files),
 920            message_shortcode_display: self
 921                .message_shortcode_display
 922                .or(other.message_shortcode_display),
 923            normal_after_send: self.normal_after_send.or(other.normal_after_send),
 924            reaction_display: self.reaction_display.or(other.reaction_display),
 925            reaction_shortcode_display: self
 926                .reaction_shortcode_display
 927                .or(other.reaction_shortcode_display),
 928            read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
 929            read_receipt_trigger: self.read_receipt_trigger.or(other.read_receipt_trigger),
 930            read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
 931            request_timeout: self.request_timeout.or(other.request_timeout),
 932            state_event_display: self.state_event_display.or(other.state_event_display),
 933            typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
 934            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
 935            username_display: self.username_display.or(other.username_display),
 936            message_user_color: self.message_user_color.or(other.message_user_color),
 937            default_room: self.default_room.or(other.default_room),
 938            open_command: self.open_command.or(other.open_command),
 939            mouse: self.mouse.or(other.mouse),
 940            notifications: self.notifications.or(other.notifications),
 941            image_preview: self.image_preview.or(other.image_preview),
 942            user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
 943            external_edit_file_suffix: self
 944                .external_edit_file_suffix
 945                .or(other.external_edit_file_suffix),
 946            tabstop: self.tabstop.or(other.tabstop),
 947            members_split: self.members_split.or(other.members_split),
 948            default_split: self.default_split.or(other.default_split),
 949            ssl_verify: self.ssl_verify.or(other.ssl_verify),
 950            cache_policy: self.cache_policy.or(other.cache_policy),
 951        }
 952    }
 953
 954    fn values(self) -> TunableValues {
 955        TunableValues {
 956            encryption: self.encryption.values(),
 957            proxy: self.proxy.unwrap_or_default().values(),
 958            sort: self.sort.values(),
 959            terminal: self.terminal.values(),
 960            users: self.users.unwrap_or_default(),
 961
 962            default_markup: self.default_markup.unwrap_or_default(),
 963            log_level: self.log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_owned()),
 964            ignorecase: self.ignorecase.unwrap_or(false),
 965            max_log_files: self.max_log_files.unwrap_or(7),
 966            message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
 967            normal_after_send: self.normal_after_send.unwrap_or(false),
 968            reaction_display: self.reaction_display.unwrap_or(true),
 969            reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
 970            read_receipt_send: self.read_receipt_send.unwrap_or(true),
 971            read_receipt_trigger: self.read_receipt_trigger.unwrap_or_default(),
 972            read_receipt_display: self.read_receipt_display.unwrap_or(true),
 973            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
 974            state_event_display: self.state_event_display.unwrap_or(true),
 975            typing_notice_send: self.typing_notice_send.unwrap_or(true),
 976            typing_notice_display: self.typing_notice_display.unwrap_or(true),
 977            username_display: self.username_display.unwrap_or_default(),
 978            message_user_color: self.message_user_color.unwrap_or(false),
 979            default_room: self.default_room,
 980            open_command: self.open_command,
 981            mouse: self.mouse.unwrap_or_default(),
 982            notifications: self.notifications.unwrap_or_default(),
 983            image_preview: self.image_preview.unwrap_or_default().values(),
 984            user_gutter_width: self.user_gutter_width.unwrap_or(30),
 985            external_edit_file_suffix: self
 986                .external_edit_file_suffix
 987                .unwrap_or_else(|| ".md".to_string()),
 988            tabstop: self.tabstop.unwrap_or(4),
 989            members_split: self.members_split,
 990            default_split: self.default_split.unwrap_or_default(),
 991            ssl_verify: self.ssl_verify.unwrap_or(true),
 992            cache_policy: self.cache_policy.unwrap_or_default(),
 993        }
 994    }
 995}
 996
 997#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 998#[serde(rename_all = "kebab-case")]
 999#[repr(u8)]
1000pub enum CursorShape {
1001    #[default]
1002    Default,
1003    Block,
1004    Line,
1005    Underline,
1006}
1007
1008impl From<CursorShape> for modalkit::crossterm::cursor::SetCursorStyle {
1009    fn from(shape: CursorShape) -> Self {
1010        match shape {
1011            CursorShape::Default => Self::DefaultUserShape,
1012            CursorShape::Block => Self::SteadyBlock,
1013            CursorShape::Line => Self::SteadyBar,
1014            CursorShape::Underline => Self::SteadyUnderScore,
1015        }
1016    }
1017}
1018
1019#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1020#[serde(rename_all = "kebab-case")]
1021#[repr(u8)]
1022pub enum MarkupFormat {
1023    Html,
1024    #[default]
1025    Markdown,
1026    Plaintext,
1027}
1028
1029#[derive(Clone)]
1030pub struct DirectoryValues {
1031    pub cache: PathBuf,
1032    pub data: PathBuf,
1033    pub logs: PathBuf,
1034    pub downloads: Option<PathBuf>,
1035}
1036
1037impl DirectoryValues {
1038    fn create_dir_all(&self) -> std::io::Result<()> {
1039        use std::fs::create_dir_all;
1040
1041        let Self { cache, data, logs, downloads } = self;
1042
1043        create_dir_all(cache)?;
1044        create_dir_all(data)?;
1045        create_dir_all(logs)?;
1046
1047        if let Some(downloads) = downloads {
1048            create_dir_all(downloads)?;
1049        }
1050
1051        Ok(())
1052    }
1053}
1054
1055#[derive(Clone, Default, Deserialize)]
1056pub struct Directories {
1057    pub cache: Option<String>,
1058    pub data: Option<String>,
1059    pub logs: Option<String>,
1060    pub downloads: Option<String>,
1061}
1062
1063impl Directories {
1064    fn merge(self, other: Self) -> Self {
1065        Directories {
1066            cache: self.cache.or(other.cache),
1067            data: self.data.or(other.data),
1068            logs: self.logs.or(other.logs),
1069            downloads: self.downloads.or(other.downloads),
1070        }
1071    }
1072
1073    fn values(self) -> DirectoryValues {
1074        let cache = self
1075            .cache
1076            .map(|dir| {
1077                let dir = shellexpand::full(&dir)
1078                    .expect("unable to expand shell variables in dirs.cache");
1079                Path::new(dir.as_ref()).to_owned()
1080            })
1081            .or_else(|| {
1082                let mut dir = dirs::cache_dir()?;
1083                dir.push("iamb");
1084                dir.into()
1085            })
1086            .expect("no dirs.cache value configured!");
1087
1088        let data = self
1089            .data
1090            .map(|dir| {
1091                let dir = shellexpand::full(&dir)
1092                    .expect("unable to expand shell variables in dirs.cache");
1093                Path::new(dir.as_ref()).to_owned()
1094            })
1095            .or_else(|| {
1096                let mut dir = dirs::data_dir()?;
1097                dir.push("iamb");
1098                dir.into()
1099            })
1100            .expect("no dirs.data value configured!");
1101
1102        let logs = self
1103            .logs
1104            .map(|dir| {
1105                let dir = shellexpand::full(&dir)
1106                    .expect("unable to expand shell variables in dirs.cache");
1107                Path::new(dir.as_ref()).to_owned()
1108            })
1109            .unwrap_or_else(|| {
1110                let mut dir = cache.clone();
1111                dir.push("logs");
1112                dir
1113            });
1114
1115        let downloads = self
1116            .downloads
1117            .map(|dir| {
1118                let dir = shellexpand::full(&dir)
1119                    .expect("unable to expand shell variables in dirs.cache");
1120                Path::new(dir.as_ref()).to_owned()
1121            })
1122            .or_else(dirs::download_dir);
1123
1124        DirectoryValues { cache, data, logs, downloads }
1125    }
1126}
1127
1128#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1129#[serde(untagged)]
1130pub enum WindowPath {
1131    AliasId(OwnedRoomAliasId),
1132    RoomId(OwnedRoomId),
1133    UserId(OwnedUserId),
1134    Window(IambId),
1135}
1136
1137#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1138#[serde(untagged, deny_unknown_fields)]
1139pub enum WindowLayout {
1140    Window { window: WindowPath },
1141    Split { split: Vec<WindowLayout> },
1142}
1143
1144#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1145#[serde(rename_all = "lowercase", tag = "style")]
1146pub enum Layout {
1147    /// Restore the layout from the previous session.
1148    #[default]
1149    Restore,
1150
1151    /// Open a single window using the `default_room` value.
1152    New,
1153
1154    /// Open the window layouts described under `tabs`.
1155    Config { tabs: Vec<WindowLayout> },
1156}
1157
1158#[derive(Clone, Deserialize)]
1159pub struct ProfileConfig {
1160    pub user_id: OwnedUserId,
1161    pub password_file: Option<PathBuf>,
1162    pub url: Option<Url>,
1163    pub settings: Option<Tunables>,
1164    pub dirs: Option<Directories>,
1165    pub layout: Option<Layout>,
1166    pub macros: Option<Macros>,
1167}
1168
1169#[derive(Clone, Deserialize)]
1170pub struct IambConfig {
1171    pub profiles: BTreeMap<String, ProfileConfig>,
1172    pub default_profile: Option<String>,
1173    pub settings: Option<Tunables>,
1174    pub dirs: Option<Directories>,
1175    pub layout: Option<Layout>,
1176    pub macros: Option<Macros>,
1177}
1178
1179impl IambConfig {
1180    pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
1181        let s = std::fs::read_to_string(path)?;
1182        let config = toml::from_str(&s)?;
1183
1184        Ok(config)
1185    }
1186
1187    pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
1188        let s = std::fs::read_to_string(path)?;
1189        let config = serde_json::from_str(&s)?;
1190
1191        Ok(config)
1192    }
1193}
1194
1195#[derive(Clone)]
1196pub struct ApplicationSettings {
1197    pub layout_json: PathBuf,
1198    pub session_json: PathBuf,
1199    pub session_json_old: PathBuf,
1200    pub sled_dir: PathBuf,
1201    pub sqlite_dir: PathBuf,
1202    pub profile_name: String,
1203    pub profile: ProfileConfig,
1204    pub tunables: TunableValues,
1205    pub dirs: DirectoryValues,
1206    pub layout: Layout,
1207    pub macros: Macros,
1208}
1209
1210impl ApplicationSettings {
1211    fn get_xdg_config_home() -> Option<PathBuf> {
1212        env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
1213    }
1214
1215    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
1216        let mut config_dir = cli
1217            .config_directory
1218            .or_else(Self::get_xdg_config_home)
1219            .or_else(dirs::config_dir)
1220            .unwrap_or_else(|| {
1221                usage!(
1222                    "No user configuration directory found;\
1223                    please specify one via -C.\n\n
1224                    For more information try '--help'"
1225                );
1226            });
1227
1228        config_dir.push("iamb");
1229        let config_json = config_dir.join("config.json");
1230        let config_toml = config_dir.join("config.toml");
1231
1232        let config = if config_toml.is_file() {
1233            IambConfig::load_toml(config_toml.as_path())?
1234        } else if config_json.is_file() {
1235            IambConfig::load_json(config_json.as_path())?
1236        } else {
1237            usage!(
1238                "Please create a configuration file at {}\n\n\
1239                For more information try '--help'",
1240                config_toml.display(),
1241            );
1242        };
1243
1244        let IambConfig {
1245            mut profiles,
1246            default_profile,
1247            dirs,
1248            settings: global,
1249            layout,
1250            macros,
1251        } = config;
1252
1253        validate_profile_names(&profiles);
1254
1255        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
1256            profiles.remove_entry(&profile).unwrap_or_else(|| {
1257                usage!(
1258                    "No configured profile with the name {:?} in {}",
1259                    profile,
1260                    config_json.display()
1261                );
1262            })
1263        } else if profiles.len() == 1 {
1264            profiles.into_iter().next().unwrap()
1265        } else {
1266            loop {
1267                println!("\nNo profile specified. Available profiles:");
1268                profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
1269
1270                print!("Select a number or 'q' to quit: ");
1271                let _ = std::io::stdout().flush();
1272
1273                let mut input = String::new();
1274                let _ = std::io::stdin().read_line(&mut input);
1275
1276                if input.trim() == "q" {
1277                    usage!(
1278                        "No profile specified. \
1279                        Please use -P or add \"default_profile\" to your configuration.\n\n\
1280                        For more information try '--help'",
1281                    );
1282                }
1283                if let Ok(i) = input.trim().parse::<usize>() &&
1284                    i < profiles.len()
1285                {
1286                    break profiles.into_iter().nth(i).unwrap();
1287                }
1288                println!("\nInvalid index.");
1289            }
1290        };
1291
1292        let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
1293        let layout = profile.layout.take().or(layout).unwrap_or_default();
1294
1295        let tunables = global.unwrap_or_default();
1296        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
1297        let tunables = tunables.values();
1298
1299        let dirs = dirs.unwrap_or_default();
1300        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
1301        let dirs = dirs.values();
1302
1303        // Create directories
1304        dirs.create_dir_all()?;
1305
1306        // Set up paths that live inside the profile's data directory.
1307        let mut profile_dir = config_dir.clone();
1308        profile_dir.push("profiles");
1309        profile_dir.push(profile_name.as_str());
1310
1311        let mut profile_data_dir = dirs.data.clone();
1312        profile_data_dir.push("profiles");
1313        profile_data_dir.push(profile_name.as_str());
1314
1315        let mut sled_dir = profile_dir.clone();
1316        sled_dir.push("matrix");
1317
1318        let mut sqlite_dir = profile_data_dir.clone();
1319        sqlite_dir.push("sqlite");
1320
1321        let mut session_json = profile_data_dir.clone();
1322        session_json.push("session.json");
1323
1324        let mut session_json_old = profile_dir;
1325        session_json_old.push("session.json");
1326
1327        // Set up paths that live inside the profile's cache directory.
1328        let mut cache_dir = dirs.cache.clone();
1329        cache_dir.push("profiles");
1330        cache_dir.push(profile_name.as_str());
1331
1332        let mut layout_json = cache_dir.clone();
1333        layout_json.push("layout.json");
1334
1335        let settings = ApplicationSettings {
1336            sled_dir,
1337            layout_json,
1338            session_json,
1339            session_json_old,
1340            sqlite_dir,
1341            profile_name,
1342            profile,
1343            tunables,
1344            dirs,
1345            layout,
1346            macros,
1347        };
1348
1349        Ok(settings)
1350    }
1351
1352    pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1353        let file = File::open(path)?;
1354        let reader = BufReader::new(file);
1355        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1356        Ok(session)
1357    }
1358
1359    pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
1360        let file = File::create(self.session_json.as_path())?;
1361        let writer = BufWriter::new(file);
1362        let session = Session::from(session);
1363        serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1364        Ok(())
1365    }
1366
1367    pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
1368        let (color, c) = self
1369            .tunables
1370            .users
1371            .get(user_id)
1372            .map(|user| {
1373                (
1374                    user.color.as_ref().map(|c| c.0),
1375                    user.name.as_ref().and_then(|s| s.chars().next()),
1376                )
1377            })
1378            .unwrap_or_default();
1379
1380        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1381        let style = user_style_from_color(color);
1382
1383        let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1384
1385        Span::styled(String::from(c), style)
1386    }
1387
1388    pub fn get_user_overrides(
1389        &self,
1390        user_id: &UserId,
1391    ) -> (Option<Color>, Option<Cow<'static, str>>) {
1392        self.tunables
1393            .users
1394            .get(user_id)
1395            .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1396            .unwrap_or_default()
1397    }
1398
1399    pub fn get_user_color(&self, user_id: &UserId) -> Color {
1400        self.tunables
1401            .users
1402            .get(user_id)
1403            .and_then(|user| user.color.as_ref().map(|c| c.0))
1404            .unwrap_or_else(|| user_color(user_id.as_str()))
1405    }
1406
1407    pub fn get_user_style(&self, user_id: &UserId) -> Style {
1408        user_style_from_color(self.get_user_color(user_id))
1409    }
1410
1411    pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1412        let (color, name) = self.get_user_overrides(user_id);
1413
1414        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1415        let style = user_style_from_color(color);
1416        let name = match (name, &self.tunables.username_display) {
1417            (Some(name), _) => name,
1418            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1419            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1420            (None, UserDisplayStyle::DisplayName) => {
1421                if let Some(name) = info.display_names.get(user_id) {
1422                    name
1423                } else {
1424                    Cow::Borrowed(user_id.as_str())
1425                }
1426            },
1427        };
1428
1429        Span::styled(name, style)
1430    }
1431}
1432
1433#[cfg(test)]
1434mod tests {
1435    use super::*;
1436    use matrix_sdk::ruma::user_id;
1437    use std::convert::TryFrom;
1438
1439    #[test]
1440    fn test_profile_name_invalid() {
1441        assert_eq!(validate_profile_name(""), false);
1442        assert_eq!(validate_profile_name(" "), false);
1443        assert_eq!(validate_profile_name("a b"), false);
1444        assert_eq!(validate_profile_name("foo^bar"), false);
1445        assert_eq!(validate_profile_name("FOO/BAR"), false);
1446        assert_eq!(validate_profile_name("-b-c"), false);
1447        assert_eq!(validate_profile_name("-B-c"), false);
1448        assert_eq!(validate_profile_name(".b-c"), false);
1449        assert_eq!(validate_profile_name(".B-c"), false);
1450    }
1451
1452    #[test]
1453    fn test_profile_name_valid() {
1454        assert_eq!(validate_profile_name("foo"), true);
1455        assert_eq!(validate_profile_name("FOO"), true);
1456        assert_eq!(validate_profile_name("a-b-c"), true);
1457        assert_eq!(validate_profile_name("a-B-c"), true);
1458        assert_eq!(validate_profile_name("a.b-c"), true);
1459        assert_eq!(validate_profile_name("a.B-c"), true);
1460    }
1461
1462    #[test]
1463    fn test_merge_users() {
1464        let a = None;
1465        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1466            color: Some(UserColor(Color::Red)),
1467            name: Some("Hello".into()),
1468        })]
1469        .into_iter()
1470        .collect::<HashMap<_, _>>();
1471        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1472            color: Some(UserColor(Color::Green)),
1473            name: Some("World".into()),
1474        })]
1475        .into_iter()
1476        .collect::<HashMap<_, _>>();
1477
1478        let res = merge_maps(a.clone(), a.clone());
1479        assert_eq!(res, None);
1480
1481        let res = merge_maps(a.clone(), Some(b.clone()));
1482        assert_eq!(res, Some(b.clone()));
1483
1484        let res = merge_maps(Some(b.clone()), a.clone());
1485        assert_eq!(res, Some(b.clone()));
1486
1487        let res = merge_maps(Some(b.clone()), Some(b.clone()));
1488        assert_eq!(res, Some(b.clone()));
1489
1490        let res = merge_maps(Some(b.clone()), Some(c.clone()));
1491        assert_eq!(res, Some(b.clone()));
1492
1493        let res = merge_maps(Some(c.clone()), Some(b.clone()));
1494        assert_eq!(res, Some(c.clone()));
1495    }
1496
1497    #[test]
1498    fn test_parse_tunables() {
1499        let res: Tunables = serde_json::from_str("{}").unwrap();
1500        assert_eq!(res.typing_notice_send, None);
1501        assert_eq!(res.typing_notice_display, None);
1502        assert_eq!(res.users, None);
1503
1504        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1505        assert_eq!(res.typing_notice_send, Some(true));
1506        assert_eq!(res.typing_notice_display, None);
1507        assert_eq!(res.users, None);
1508
1509        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1510        assert_eq!(res.typing_notice_send, Some(false));
1511        assert_eq!(res.typing_notice_display, None);
1512        assert_eq!(res.users, None);
1513
1514        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1515        assert_eq!(res.typing_notice_send, None);
1516        assert_eq!(res.typing_notice_display, None);
1517        assert_eq!(res.users, Some(HashMap::new()));
1518
1519        let res: Tunables = serde_json::from_str(
1520            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1521        )
1522        .unwrap();
1523        assert_eq!(res.typing_notice_send, None);
1524        assert_eq!(res.typing_notice_display, None);
1525        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1526            color: Some(UserColor(Color::Black)),
1527            name: Some("Tim".into()),
1528        })];
1529        assert_eq!(res.users, Some(users.into_iter().collect()));
1530    }
1531
1532    #[test]
1533    fn test_parse_tunables_username_display() {
1534        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1535        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1536
1537        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1538        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1539
1540        let res: Tunables =
1541            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1542        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1543    }
1544
1545    #[test]
1546    fn test_parse_tunables_sort() {
1547        let res: Tunables = serde_json::from_str(
1548            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1549        )
1550        .unwrap();
1551        assert_eq!(
1552            res.sort.members,
1553            Some(vec![
1554                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1555                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1556            ])
1557        );
1558        assert_eq!(
1559            res.sort.spaces,
1560            Some(vec![
1561                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1562                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1563            ])
1564        );
1565        assert_eq!(res.sort.rooms, None);
1566        assert_eq!(res.sort.dms, None);
1567
1568        // Check that we get the right default "rooms" and "dms" values.
1569        let res = res.values();
1570        assert_eq!(res.sort.members, vec![
1571            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1572            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1573        ]);
1574        assert_eq!(res.sort.spaces, vec![
1575            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1576            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1577        ]);
1578        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1579        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1580    }
1581
1582    #[test]
1583    fn test_parse_tunables_proxy_invalid() {
1584        let res =
1585            serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();
1586
1587        // Should result in a validation error:
1588        assert_eq!(res.classify(), serde_json::error::Category::Data);
1589    }
1590
1591    #[test]
1592    fn test_parse_tunables_proxy_empty() {
1593        let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
1594        let proxy = res.proxy.unwrap();
1595        assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
1596    }
1597
1598    #[test]
1599    fn test_parse_tunables_proxy_socks5() {
1600        let res: Tunables =
1601            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1602        let proxy = res.proxy.unwrap();
1603        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1604            panic!("should parse ProxyUrl::Endpoint")
1605        };
1606
1607        assert_eq!(url.scheme(), "socks5");
1608        assert_eq!(url.host_str().unwrap(), "localhost");
1609        assert_eq!(url.port().unwrap(), 1080);
1610        assert_eq!(url.authority(), "localhost:1080");
1611    }
1612
1613    #[test]
1614    fn test_parse_tunables_proxy_https() {
1615        let res: Tunables = serde_json::from_str(
1616            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1617        ).unwrap();
1618        let proxy = res.proxy.unwrap();
1619        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1620            panic!("should parse ProxyUrl::Endpoint")
1621        };
1622
1623        // Verify URL fields:
1624        assert_eq!(url.scheme(), "https");
1625        assert_eq!(url.host_str().unwrap(), "localhost");
1626        assert_eq!(url.port().unwrap(), 8080);
1627        assert_eq!(url.authority(), "localhost:8080");
1628
1629        // Verify our `Proxy-Authorization` value:
1630        assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");
1631
1632        // Verify our custom header is present:
1633        assert_eq!(proxy.headers.len(), 1);
1634        assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
1635    }
1636
1637    #[test]
1638    fn test_parse_tunables_proxy_merge() {
1639        let global: Tunables = serde_json::from_str(
1640            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1641        ).unwrap();
1642        let profile: Tunables =
1643            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1644
1645        // The configuration merge should select the entirety of the profile proxy config,
1646        // and not merge subfields, to ensure that things like `auth` and `headers` are
1647        // not ever sent to a `url` they were meant for.
1648        let merged = profile.merge(global).values();
1649        let ProxyUrl::Endpoint(url) = merged.proxy.url else {
1650            panic!("should parse ProxyUrl::Endpoint")
1651        };
1652        assert_eq!(url.scheme(), "socks5");
1653        assert_eq!(url.authority(), "localhost:1080");
1654        assert_eq!(merged.proxy.auth, None);
1655        assert_eq!(merged.proxy.headers.is_empty(), true);
1656    }
1657
1658    #[test]
1659    fn test_parse_layout() {
1660        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1661        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1662        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1663        let dms = WindowPath::Window(IambId::DirectList);
1664        let welcome = WindowPath::Window(IambId::Welcome);
1665
1666        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1667        assert_eq!(res, Layout::Restore);
1668
1669        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1670        assert_eq!(res, Layout::New);
1671
1672        let res: Layout = serde_json::from_str(
1673            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1674        )
1675        .unwrap();
1676        assert_eq!(res, Layout::Config {
1677            tabs: vec![WindowLayout::Window { window: user.clone() }]
1678        });
1679
1680        let res: Layout = serde_json::from_str(
1681            "{\
1682            \"style\": \"config\",\
1683            \"tabs\": [\
1684                {\"split\":[\
1685                    {\"window\":\"@user:example.com\"},\
1686                    {\"window\":\"#room:example.com\"}\
1687                ]},\
1688                {\"split\":[\
1689                    {\"window\":\"!room:example.com\"},\
1690                    {\"split\":[\
1691                        {\"window\":\"iamb://dms\"},\
1692                        {\"window\":\"iamb://welcome\"}\
1693                    ]}\
1694                ]}\
1695            ]}",
1696        )
1697        .unwrap();
1698        let split1 = WindowLayout::Split {
1699            split: vec![
1700                WindowLayout::Window { window: user.clone() },
1701                WindowLayout::Window { window: alias },
1702            ],
1703        };
1704        let split2 = WindowLayout::Split {
1705            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1706                window: welcome,
1707            }],
1708        };
1709        let split3 = WindowLayout::Split {
1710            split: vec![WindowLayout::Window { window: room }, split2],
1711        };
1712        let tabs = vec![split1, split3];
1713        assert_eq!(res, Layout::Config { tabs });
1714    }
1715
1716    #[test]
1717    fn test_parse_macros() {
1718        let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1719        assert_eq!(res.len(), 1);
1720
1721        let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1722        let mapped = res.get(&modes).unwrap();
1723        assert_eq!(mapped.len(), 1);
1724
1725        let j = "j".parse::<TerminalKey>().unwrap();
1726        let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1727
1728        let jj = Keys(vec![j, j], "jj".into());
1729        let run = mapped.get(&jj).unwrap();
1730        let exp = Keys(vec![esc], "<Esc>".into());
1731        assert_eq!(run, &exp);
1732    }
1733
1734    #[test]
1735    fn test_parse_notify_via() {
1736        assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1737        assert_eq!(
1738            NotifyVia { bell: false, desktop: true },
1739            serde_json::from_str(r#""desktop""#).unwrap()
1740        );
1741        assert_eq!(
1742            NotifyVia { bell: true, desktop: false },
1743            serde_json::from_str(r#""bell""#).unwrap()
1744        );
1745        assert_eq!(
1746            NotifyVia { bell: true, desktop: true },
1747            serde_json::from_str(r#""bell|desktop""#).unwrap()
1748        );
1749        assert_eq!(
1750            NotifyVia { bell: true, desktop: true },
1751            serde_json::from_str(r#""desktop|bell""#).unwrap()
1752        );
1753        assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1754        assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1755    }
1756
1757    #[test]
1758    fn test_parse_cursor_shape() {
1759        assert_eq!(CursorShape::Default, CursorShape::default());
1760        assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap());
1761        assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap());
1762        assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap());
1763        assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap());
1764        assert!(serde_json::from_str::<CursorShape>(r#""beam""#).is_err());
1765    }
1766
1767    #[test]
1768    fn test_load_example_config_toml() {
1769        let path = PathBuf::from("config.example.toml");
1770        let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1771
1772        let IambConfig {
1773            profiles,
1774            default_profile,
1775            settings,
1776            dirs,
1777            layout,
1778            macros,
1779        } = &config;
1780
1781        // There should be an example object for each top-level field.
1782        assert!(!profiles.is_empty());
1783        assert!(default_profile.is_some());
1784        assert!(settings.is_some());
1785        assert!(dirs.is_some());
1786        assert!(layout.is_some());
1787        assert!(macros.is_some());
1788    }
1789
1790    #[test]
1791    fn test_encryption_indicator_enabled() {
1792        use EncryptionState::*;
1793
1794        let enc = EncryptionValues {
1795            indicator: EncryptionIndicator::Enabled,
1796            indicator_location: EncryptionIndicatorLocation::TITLE,
1797        };
1798
1799        // Always shows in the title:
1800        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
1801        assert!(
1802            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1803                .is_some()
1804        );
1805        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1806
1807        // Doesn't show in the prompt:
1808        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1809        assert!(
1810            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1811                .is_none()
1812        );
1813        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1814    }
1815
1816    #[test]
1817    fn test_encryption_indicator_disabled() {
1818        use EncryptionState::*;
1819
1820        let enc = EncryptionValues {
1821            indicator: EncryptionIndicator::Disabled,
1822            indicator_location: EncryptionIndicatorLocation::TITLE,
1823        };
1824
1825        // Never shows in the title or the prompt:
1826        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1827        assert!(
1828            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1829                .is_none()
1830        );
1831        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1832        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1833        assert!(
1834            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1835                .is_none()
1836        );
1837        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1838    }
1839
1840    #[test]
1841    fn test_encryption_indicator_only_encrypted() {
1842        use EncryptionState::*;
1843
1844        let enc = EncryptionValues {
1845            indicator: EncryptionIndicator::OnlyEncrypted,
1846            indicator_location: EncryptionIndicatorLocation::PROMPT,
1847        };
1848
1849        // Shows in the prompt when encrypted or unknown:
1850        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_some());
1851        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1852
1853        // But is hidden when unencrypted:
1854        assert!(
1855            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1856                .is_none()
1857        );
1858
1859        // Doesn't show in the title:
1860        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1861        assert!(
1862            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1863                .is_none()
1864        );
1865        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1866    }
1867    #[test]
1868    fn test_encryption_indicator_only_unencrypted() {
1869        use EncryptionState::*;
1870
1871        let enc = EncryptionValues {
1872            indicator: EncryptionIndicator::OnlyUnencrypted,
1873            indicator_location: EncryptionIndicatorLocation::all(),
1874        };
1875
1876        // Shows in both the prompt and title when unencrypted or unknown:
1877        assert!(
1878            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1879                .is_some()
1880        );
1881        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1882        assert!(
1883            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1884                .is_some()
1885        );
1886        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1887
1888        // But is hidden when encrypted:
1889        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1890        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1891    }
1892}