src/config.rs

1342 lines · 43733 bytes

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