src/config.rs

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