src/config.rs

1373 lines · 44938 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<String>,
 711    pub data: Option<String>,
 712    pub logs: Option<String>,
 713    pub downloads: Option<String>,
 714    pub image_previews: Option<String>,
 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            .map(|dir| {
 732                let dir = shellexpand::full(&dir)
 733                    .expect("unable to expand shell variables in dirs.cache");
 734                Path::new(dir.as_ref()).to_owned()
 735            })
 736            .or_else(|| {
 737                let mut dir = dirs::cache_dir()?;
 738                dir.push("iamb");
 739                dir.into()
 740            })
 741            .expect("no dirs.cache value configured!");
 742
 743        let data = self
 744            .data
 745            .map(|dir| {
 746                let dir = shellexpand::full(&dir)
 747                    .expect("unable to expand shell variables in dirs.cache");
 748                Path::new(dir.as_ref()).to_owned()
 749            })
 750            .or_else(|| {
 751                let mut dir = dirs::data_dir()?;
 752                dir.push("iamb");
 753                dir.into()
 754            })
 755            .expect("no dirs.data value configured!");
 756
 757        let logs = self
 758            .logs
 759            .map(|dir| {
 760                let dir = shellexpand::full(&dir)
 761                    .expect("unable to expand shell variables in dirs.cache");
 762                Path::new(dir.as_ref()).to_owned()
 763            })
 764            .unwrap_or_else(|| {
 765                let mut dir = cache.clone();
 766                dir.push("logs");
 767                dir
 768            });
 769
 770        let downloads = self
 771            .downloads
 772            .map(|dir| {
 773                let dir = shellexpand::full(&dir)
 774                    .expect("unable to expand shell variables in dirs.cache");
 775                Path::new(dir.as_ref()).to_owned()
 776            })
 777            .or_else(dirs::download_dir);
 778
 779        let image_previews = self
 780            .image_previews
 781            .map(|dir| {
 782                let dir = shellexpand::full(&dir)
 783                    .expect("unable to expand shell variables in dirs.cache");
 784                Path::new(dir.as_ref()).to_owned()
 785            })
 786            .unwrap_or_else(|| {
 787                let mut dir = cache.clone();
 788                dir.push("image_preview_downloads");
 789                dir
 790            });
 791
 792        DirectoryValues { cache, data, logs, downloads, image_previews }
 793    }
 794}
 795
 796#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
 797#[serde(untagged)]
 798pub enum WindowPath {
 799    AliasId(OwnedRoomAliasId),
 800    RoomId(OwnedRoomId),
 801    UserId(OwnedUserId),
 802    Window(IambId),
 803}
 804
 805#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
 806#[serde(untagged, deny_unknown_fields)]
 807pub enum WindowLayout {
 808    Window { window: WindowPath },
 809    Split { split: Vec<WindowLayout> },
 810}
 811
 812#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
 813#[serde(rename_all = "lowercase", tag = "style")]
 814pub enum Layout {
 815    /// Restore the layout from the previous session.
 816    #[default]
 817    Restore,
 818
 819    /// Open a single window using the `default_room` value.
 820    New,
 821
 822    /// Open the window layouts described under `tabs`.
 823    Config { tabs: Vec<WindowLayout> },
 824}
 825
 826#[derive(Clone, Deserialize)]
 827pub struct ProfileConfig {
 828    pub user_id: OwnedUserId,
 829    pub url: Option<Url>,
 830    pub settings: Option<Tunables>,
 831    pub dirs: Option<Directories>,
 832    pub layout: Option<Layout>,
 833    pub macros: Option<Macros>,
 834}
 835
 836#[derive(Clone, Deserialize)]
 837pub struct IambConfig {
 838    pub profiles: BTreeMap<String, ProfileConfig>,
 839    pub default_profile: Option<String>,
 840    pub settings: Option<Tunables>,
 841    pub dirs: Option<Directories>,
 842    pub layout: Option<Layout>,
 843    pub macros: Option<Macros>,
 844}
 845
 846impl IambConfig {
 847    pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
 848        let s = std::fs::read_to_string(path)?;
 849        let config = toml::from_str(&s)?;
 850
 851        Ok(config)
 852    }
 853
 854    pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
 855        let s = std::fs::read_to_string(path)?;
 856        let config = serde_json::from_str(&s)?;
 857
 858        Ok(config)
 859    }
 860}
 861
 862#[derive(Clone)]
 863pub struct ApplicationSettings {
 864    pub layout_json: PathBuf,
 865    pub session_json: PathBuf,
 866    pub session_json_old: PathBuf,
 867    pub sled_dir: PathBuf,
 868    pub sqlite_dir: PathBuf,
 869    pub profile_name: String,
 870    pub profile: ProfileConfig,
 871    pub tunables: TunableValues,
 872    pub dirs: DirectoryValues,
 873    pub layout: Layout,
 874    pub macros: Macros,
 875}
 876
 877impl ApplicationSettings {
 878    fn get_xdg_config_home() -> Option<PathBuf> {
 879        env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
 880    }
 881
 882    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
 883        let mut config_dir = cli
 884            .config_directory
 885            .or_else(Self::get_xdg_config_home)
 886            .or_else(dirs::config_dir)
 887            .unwrap_or_else(|| {
 888                usage!(
 889                    "No user configuration directory found;\
 890                    please specify one via -C.\n\n
 891                    For more information try '--help'"
 892                );
 893            });
 894
 895        config_dir.push("iamb");
 896        let config_json = config_dir.join("config.json");
 897        let config_toml = config_dir.join("config.toml");
 898
 899        let config = if config_toml.is_file() {
 900            IambConfig::load_toml(config_toml.as_path())?
 901        } else if config_json.is_file() {
 902            IambConfig::load_json(config_json.as_path())?
 903        } else {
 904            usage!(
 905                "Please create a configuration file at {}\n\n\
 906                For more information try '--help'",
 907                config_toml.display(),
 908            );
 909        };
 910
 911        let IambConfig {
 912            mut profiles,
 913            default_profile,
 914            dirs,
 915            settings: global,
 916            layout,
 917            macros,
 918        } = config;
 919
 920        validate_profile_names(&profiles);
 921
 922        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
 923            profiles.remove_entry(&profile).unwrap_or_else(|| {
 924                usage!(
 925                    "No configured profile with the name {:?} in {}",
 926                    profile,
 927                    config_json.display()
 928                );
 929            })
 930        } else if profiles.len() == 1 {
 931            profiles.into_iter().next().unwrap()
 932        } else {
 933            loop {
 934                println!("\nNo profile specified. Available profiles:");
 935                profiles
 936                    .keys()
 937                    .enumerate()
 938                    .for_each(|(i, name)| println!("{}: {}", i, name));
 939
 940                print!("Select a number or 'q' to quit: ");
 941                let _ = std::io::stdout().flush();
 942
 943                let mut input = String::new();
 944                let _ = std::io::stdin().read_line(&mut input);
 945
 946                if input.trim() == "q" {
 947                    usage!(
 948                        "No profile specified. \
 949                        Please use -P or add \"default_profile\" to your configuration.\n\n\
 950                        For more information try '--help'",
 951                    );
 952                }
 953                if let Ok(i) = input.trim().parse::<usize>() {
 954                    if i < profiles.len() {
 955                        break profiles.into_iter().nth(i).unwrap();
 956                    }
 957                }
 958                println!("\nInvalid index.");
 959            }
 960        };
 961
 962        let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
 963        let layout = profile.layout.take().or(layout).unwrap_or_default();
 964
 965        let tunables = global.unwrap_or_default();
 966        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
 967        let tunables = tunables.values();
 968
 969        let dirs = dirs.unwrap_or_default();
 970        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
 971        let dirs = dirs.values();
 972
 973        // Create directories
 974        dirs.create_dir_all()?;
 975
 976        // Set up paths that live inside the profile's data directory.
 977        let mut profile_dir = config_dir.clone();
 978        profile_dir.push("profiles");
 979        profile_dir.push(profile_name.as_str());
 980
 981        let mut profile_data_dir = dirs.data.clone();
 982        profile_data_dir.push("profiles");
 983        profile_data_dir.push(profile_name.as_str());
 984
 985        let mut sled_dir = profile_dir.clone();
 986        sled_dir.push("matrix");
 987
 988        let mut sqlite_dir = profile_data_dir.clone();
 989        sqlite_dir.push("sqlite");
 990
 991        let mut session_json = profile_data_dir.clone();
 992        session_json.push("session.json");
 993
 994        let mut session_json_old = profile_dir;
 995        session_json_old.push("session.json");
 996
 997        // Set up paths that live inside the profile's cache directory.
 998        let mut cache_dir = dirs.cache.clone();
 999        cache_dir.push("profiles");
1000        cache_dir.push(profile_name.as_str());
1001
1002        let mut layout_json = cache_dir.clone();
1003        layout_json.push("layout.json");
1004
1005        let settings = ApplicationSettings {
1006            sled_dir,
1007            layout_json,
1008            session_json,
1009            session_json_old,
1010            sqlite_dir,
1011            profile_name,
1012            profile,
1013            tunables,
1014            dirs,
1015            layout,
1016            macros,
1017        };
1018
1019        Ok(settings)
1020    }
1021
1022    pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1023        let file = File::open(path)?;
1024        let reader = BufReader::new(file);
1025        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1026        Ok(session)
1027    }
1028
1029    pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
1030        let file = File::create(self.session_json.as_path())?;
1031        let writer = BufWriter::new(file);
1032        let session = Session::from(session);
1033        serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1034        Ok(())
1035    }
1036
1037    pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
1038        let (color, c) = self
1039            .tunables
1040            .users
1041            .get(user_id)
1042            .map(|user| {
1043                (
1044                    user.color.as_ref().map(|c| c.0),
1045                    user.name.as_ref().and_then(|s| s.chars().next()),
1046                )
1047            })
1048            .unwrap_or_default();
1049
1050        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1051        let style = user_style_from_color(color);
1052
1053        let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1054
1055        Span::styled(String::from(c), style)
1056    }
1057
1058    pub fn get_user_overrides(
1059        &self,
1060        user_id: &UserId,
1061    ) -> (Option<Color>, Option<Cow<'static, str>>) {
1062        self.tunables
1063            .users
1064            .get(user_id)
1065            .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1066            .unwrap_or_default()
1067    }
1068
1069    pub fn get_user_color(&self, user_id: &UserId) -> Color {
1070        self.tunables
1071            .users
1072            .get(user_id)
1073            .and_then(|user| user.color.as_ref().map(|c| c.0))
1074            .unwrap_or_else(|| user_color(user_id.as_str()))
1075    }
1076
1077    pub fn get_user_style(&self, user_id: &UserId) -> Style {
1078        user_style_from_color(self.get_user_color(user_id))
1079    }
1080
1081    pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1082        let (color, name) = self.get_user_overrides(user_id);
1083
1084        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1085        let style = user_style_from_color(color);
1086        let name = match (name, &self.tunables.username_display) {
1087            (Some(name), _) => name,
1088            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1089            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1090            (None, UserDisplayStyle::DisplayName) => {
1091                if let Some(display) = info.display_names.get(user_id) {
1092                    Cow::Borrowed(display.as_str())
1093                } else {
1094                    Cow::Borrowed(user_id.as_str())
1095                }
1096            },
1097        };
1098
1099        Span::styled(name, style)
1100    }
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105    use super::*;
1106    use matrix_sdk::ruma::user_id;
1107    use std::convert::TryFrom;
1108
1109    #[test]
1110    fn test_profile_name_invalid() {
1111        assert_eq!(validate_profile_name(""), false);
1112        assert_eq!(validate_profile_name(" "), false);
1113        assert_eq!(validate_profile_name("a b"), false);
1114        assert_eq!(validate_profile_name("foo^bar"), false);
1115        assert_eq!(validate_profile_name("FOO/BAR"), false);
1116        assert_eq!(validate_profile_name("-b-c"), false);
1117        assert_eq!(validate_profile_name("-B-c"), false);
1118        assert_eq!(validate_profile_name(".b-c"), false);
1119        assert_eq!(validate_profile_name(".B-c"), false);
1120    }
1121
1122    #[test]
1123    fn test_profile_name_valid() {
1124        assert_eq!(validate_profile_name("foo"), true);
1125        assert_eq!(validate_profile_name("FOO"), true);
1126        assert_eq!(validate_profile_name("a-b-c"), true);
1127        assert_eq!(validate_profile_name("a-B-c"), true);
1128        assert_eq!(validate_profile_name("a.b-c"), true);
1129        assert_eq!(validate_profile_name("a.B-c"), true);
1130    }
1131
1132    #[test]
1133    fn test_merge_users() {
1134        let a = None;
1135        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1136            color: Some(UserColor(Color::Red)),
1137            name: Some("Hello".into()),
1138        })]
1139        .into_iter()
1140        .collect::<HashMap<_, _>>();
1141        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1142            color: Some(UserColor(Color::Green)),
1143            name: Some("World".into()),
1144        })]
1145        .into_iter()
1146        .collect::<HashMap<_, _>>();
1147
1148        let res = merge_maps(a.clone(), a.clone());
1149        assert_eq!(res, None);
1150
1151        let res = merge_maps(a.clone(), Some(b.clone()));
1152        assert_eq!(res, Some(b.clone()));
1153
1154        let res = merge_maps(Some(b.clone()), a.clone());
1155        assert_eq!(res, Some(b.clone()));
1156
1157        let res = merge_maps(Some(b.clone()), Some(b.clone()));
1158        assert_eq!(res, Some(b.clone()));
1159
1160        let res = merge_maps(Some(b.clone()), Some(c.clone()));
1161        assert_eq!(res, Some(b.clone()));
1162
1163        let res = merge_maps(Some(c.clone()), Some(b.clone()));
1164        assert_eq!(res, Some(c.clone()));
1165    }
1166
1167    #[test]
1168    fn test_parse_tunables() {
1169        let res: Tunables = serde_json::from_str("{}").unwrap();
1170        assert_eq!(res.typing_notice_send, None);
1171        assert_eq!(res.typing_notice_display, None);
1172        assert_eq!(res.users, None);
1173
1174        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1175        assert_eq!(res.typing_notice_send, Some(true));
1176        assert_eq!(res.typing_notice_display, None);
1177        assert_eq!(res.users, None);
1178
1179        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1180        assert_eq!(res.typing_notice_send, Some(false));
1181        assert_eq!(res.typing_notice_display, None);
1182        assert_eq!(res.users, None);
1183
1184        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1185        assert_eq!(res.typing_notice_send, None);
1186        assert_eq!(res.typing_notice_display, None);
1187        assert_eq!(res.users, Some(HashMap::new()));
1188
1189        let res: Tunables = serde_json::from_str(
1190            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1191        )
1192        .unwrap();
1193        assert_eq!(res.typing_notice_send, None);
1194        assert_eq!(res.typing_notice_display, None);
1195        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1196            color: Some(UserColor(Color::Black)),
1197            name: Some("Tim".into()),
1198        })];
1199        assert_eq!(res.users, Some(users.into_iter().collect()));
1200    }
1201
1202    #[test]
1203    fn test_parse_tunables_username_display() {
1204        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1205        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1206
1207        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1208        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1209
1210        let res: Tunables =
1211            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1212        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1213    }
1214
1215    #[test]
1216    fn test_parse_tunables_sort() {
1217        let res: Tunables = serde_json::from_str(
1218            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1219        )
1220        .unwrap();
1221        assert_eq!(
1222            res.sort.members,
1223            Some(vec![
1224                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1225                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1226            ])
1227        );
1228        assert_eq!(
1229            res.sort.spaces,
1230            Some(vec![
1231                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1232                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1233            ])
1234        );
1235        assert_eq!(res.sort.rooms, None);
1236        assert_eq!(res.sort.dms, None);
1237
1238        // Check that we get the right default "rooms" and "dms" values.
1239        let res = res.values();
1240        assert_eq!(res.sort.members, vec![
1241            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1242            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1243        ]);
1244        assert_eq!(res.sort.spaces, vec![
1245            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1246            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1247        ]);
1248        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1249        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1250    }
1251
1252    #[test]
1253    fn test_parse_layout() {
1254        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1255        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1256        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1257        let dms = WindowPath::Window(IambId::DirectList);
1258        let welcome = WindowPath::Window(IambId::Welcome);
1259
1260        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1261        assert_eq!(res, Layout::Restore);
1262
1263        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1264        assert_eq!(res, Layout::New);
1265
1266        let res: Layout = serde_json::from_str(
1267            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1268        )
1269        .unwrap();
1270        assert_eq!(res, Layout::Config {
1271            tabs: vec![WindowLayout::Window { window: user.clone() }]
1272        });
1273
1274        let res: Layout = serde_json::from_str(
1275            "{\
1276            \"style\": \"config\",\
1277            \"tabs\": [\
1278                {\"split\":[\
1279                    {\"window\":\"@user:example.com\"},\
1280                    {\"window\":\"#room:example.com\"}\
1281                ]},\
1282                {\"split\":[\
1283                    {\"window\":\"!room:example.com\"},\
1284                    {\"split\":[\
1285                        {\"window\":\"iamb://dms\"},\
1286                        {\"window\":\"iamb://welcome\"}\
1287                    ]}\
1288                ]}\
1289            ]}",
1290        )
1291        .unwrap();
1292        let split1 = WindowLayout::Split {
1293            split: vec![
1294                WindowLayout::Window { window: user.clone() },
1295                WindowLayout::Window { window: alias },
1296            ],
1297        };
1298        let split2 = WindowLayout::Split {
1299            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1300                window: welcome,
1301            }],
1302        };
1303        let split3 = WindowLayout::Split {
1304            split: vec![WindowLayout::Window { window: room }, split2],
1305        };
1306        let tabs = vec![split1, split3];
1307        assert_eq!(res, Layout::Config { tabs });
1308    }
1309
1310    #[test]
1311    fn test_parse_macros() {
1312        let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1313        assert_eq!(res.len(), 1);
1314
1315        let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1316        let mapped = res.get(&modes).unwrap();
1317        assert_eq!(mapped.len(), 1);
1318
1319        let j = "j".parse::<TerminalKey>().unwrap();
1320        let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1321
1322        let jj = Keys(vec![j, j], "jj".into());
1323        let run = mapped.get(&jj).unwrap();
1324        let exp = Keys(vec![esc], "<Esc>".into());
1325        assert_eq!(run, &exp);
1326    }
1327
1328    #[test]
1329    fn test_parse_notify_via() {
1330        assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1331        assert_eq!(
1332            NotifyVia { bell: false, desktop: true },
1333            serde_json::from_str(r#""desktop""#).unwrap()
1334        );
1335        assert_eq!(
1336            NotifyVia { bell: true, desktop: false },
1337            serde_json::from_str(r#""bell""#).unwrap()
1338        );
1339        assert_eq!(
1340            NotifyVia { bell: true, desktop: true },
1341            serde_json::from_str(r#""bell|desktop""#).unwrap()
1342        );
1343        assert_eq!(
1344            NotifyVia { bell: true, desktop: true },
1345            serde_json::from_str(r#""desktop|bell""#).unwrap()
1346        );
1347        assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1348        assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1349    }
1350
1351    #[test]
1352    fn test_load_example_config_toml() {
1353        let path = PathBuf::from("config.example.toml");
1354        let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1355
1356        let IambConfig {
1357            profiles,
1358            default_profile,
1359            settings,
1360            dirs,
1361            layout,
1362            macros,
1363        } = &config;
1364
1365        // There should be an example object for each top-level field.
1366        assert!(!profiles.is_empty());
1367        assert!(default_profile.is_some());
1368        assert!(settings.is_some());
1369        assert!(dirs.is_some());
1370        assert!(layout.is_some());
1371        assert!(macros.is_some());
1372    }
1373}