src/config.rs

1370 lines · 44871 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.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
 936
 937                print!("Select a number or 'q' to quit: ");
 938                let _ = std::io::stdout().flush();
 939
 940                let mut input = String::new();
 941                let _ = std::io::stdin().read_line(&mut input);
 942
 943                if input.trim() == "q" {
 944                    usage!(
 945                        "No profile specified. \
 946                        Please use -P or add \"default_profile\" to your configuration.\n\n\
 947                        For more information try '--help'",
 948                    );
 949                }
 950                if let Ok(i) = input.trim().parse::<usize>() {
 951                    if i < profiles.len() {
 952                        break profiles.into_iter().nth(i).unwrap();
 953                    }
 954                }
 955                println!("\nInvalid index.");
 956            }
 957        };
 958
 959        let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
 960        let layout = profile.layout.take().or(layout).unwrap_or_default();
 961
 962        let tunables = global.unwrap_or_default();
 963        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
 964        let tunables = tunables.values();
 965
 966        let dirs = dirs.unwrap_or_default();
 967        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
 968        let dirs = dirs.values();
 969
 970        // Create directories
 971        dirs.create_dir_all()?;
 972
 973        // Set up paths that live inside the profile's data directory.
 974        let mut profile_dir = config_dir.clone();
 975        profile_dir.push("profiles");
 976        profile_dir.push(profile_name.as_str());
 977
 978        let mut profile_data_dir = dirs.data.clone();
 979        profile_data_dir.push("profiles");
 980        profile_data_dir.push(profile_name.as_str());
 981
 982        let mut sled_dir = profile_dir.clone();
 983        sled_dir.push("matrix");
 984
 985        let mut sqlite_dir = profile_data_dir.clone();
 986        sqlite_dir.push("sqlite");
 987
 988        let mut session_json = profile_data_dir.clone();
 989        session_json.push("session.json");
 990
 991        let mut session_json_old = profile_dir;
 992        session_json_old.push("session.json");
 993
 994        // Set up paths that live inside the profile's cache directory.
 995        let mut cache_dir = dirs.cache.clone();
 996        cache_dir.push("profiles");
 997        cache_dir.push(profile_name.as_str());
 998
 999        let mut layout_json = cache_dir.clone();
1000        layout_json.push("layout.json");
1001
1002        let settings = ApplicationSettings {
1003            sled_dir,
1004            layout_json,
1005            session_json,
1006            session_json_old,
1007            sqlite_dir,
1008            profile_name,
1009            profile,
1010            tunables,
1011            dirs,
1012            layout,
1013            macros,
1014        };
1015
1016        Ok(settings)
1017    }
1018
1019    pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1020        let file = File::open(path)?;
1021        let reader = BufReader::new(file);
1022        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1023        Ok(session)
1024    }
1025
1026    pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
1027        let file = File::create(self.session_json.as_path())?;
1028        let writer = BufWriter::new(file);
1029        let session = Session::from(session);
1030        serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1031        Ok(())
1032    }
1033
1034    pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
1035        let (color, c) = self
1036            .tunables
1037            .users
1038            .get(user_id)
1039            .map(|user| {
1040                (
1041                    user.color.as_ref().map(|c| c.0),
1042                    user.name.as_ref().and_then(|s| s.chars().next()),
1043                )
1044            })
1045            .unwrap_or_default();
1046
1047        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1048        let style = user_style_from_color(color);
1049
1050        let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1051
1052        Span::styled(String::from(c), style)
1053    }
1054
1055    pub fn get_user_overrides(
1056        &self,
1057        user_id: &UserId,
1058    ) -> (Option<Color>, Option<Cow<'static, str>>) {
1059        self.tunables
1060            .users
1061            .get(user_id)
1062            .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1063            .unwrap_or_default()
1064    }
1065
1066    pub fn get_user_color(&self, user_id: &UserId) -> Color {
1067        self.tunables
1068            .users
1069            .get(user_id)
1070            .and_then(|user| user.color.as_ref().map(|c| c.0))
1071            .unwrap_or_else(|| user_color(user_id.as_str()))
1072    }
1073
1074    pub fn get_user_style(&self, user_id: &UserId) -> Style {
1075        user_style_from_color(self.get_user_color(user_id))
1076    }
1077
1078    pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1079        let (color, name) = self.get_user_overrides(user_id);
1080
1081        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1082        let style = user_style_from_color(color);
1083        let name = match (name, &self.tunables.username_display) {
1084            (Some(name), _) => name,
1085            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1086            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1087            (None, UserDisplayStyle::DisplayName) => {
1088                if let Some(display) = info.display_names.get(user_id) {
1089                    Cow::Borrowed(display.as_str())
1090                } else {
1091                    Cow::Borrowed(user_id.as_str())
1092                }
1093            },
1094        };
1095
1096        Span::styled(name, style)
1097    }
1098}
1099
1100#[cfg(test)]
1101mod tests {
1102    use super::*;
1103    use matrix_sdk::ruma::user_id;
1104    use std::convert::TryFrom;
1105
1106    #[test]
1107    fn test_profile_name_invalid() {
1108        assert_eq!(validate_profile_name(""), false);
1109        assert_eq!(validate_profile_name(" "), false);
1110        assert_eq!(validate_profile_name("a b"), false);
1111        assert_eq!(validate_profile_name("foo^bar"), false);
1112        assert_eq!(validate_profile_name("FOO/BAR"), false);
1113        assert_eq!(validate_profile_name("-b-c"), false);
1114        assert_eq!(validate_profile_name("-B-c"), false);
1115        assert_eq!(validate_profile_name(".b-c"), false);
1116        assert_eq!(validate_profile_name(".B-c"), false);
1117    }
1118
1119    #[test]
1120    fn test_profile_name_valid() {
1121        assert_eq!(validate_profile_name("foo"), true);
1122        assert_eq!(validate_profile_name("FOO"), true);
1123        assert_eq!(validate_profile_name("a-b-c"), true);
1124        assert_eq!(validate_profile_name("a-B-c"), true);
1125        assert_eq!(validate_profile_name("a.b-c"), true);
1126        assert_eq!(validate_profile_name("a.B-c"), true);
1127    }
1128
1129    #[test]
1130    fn test_merge_users() {
1131        let a = None;
1132        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1133            color: Some(UserColor(Color::Red)),
1134            name: Some("Hello".into()),
1135        })]
1136        .into_iter()
1137        .collect::<HashMap<_, _>>();
1138        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1139            color: Some(UserColor(Color::Green)),
1140            name: Some("World".into()),
1141        })]
1142        .into_iter()
1143        .collect::<HashMap<_, _>>();
1144
1145        let res = merge_maps(a.clone(), a.clone());
1146        assert_eq!(res, None);
1147
1148        let res = merge_maps(a.clone(), Some(b.clone()));
1149        assert_eq!(res, Some(b.clone()));
1150
1151        let res = merge_maps(Some(b.clone()), a.clone());
1152        assert_eq!(res, Some(b.clone()));
1153
1154        let res = merge_maps(Some(b.clone()), Some(b.clone()));
1155        assert_eq!(res, Some(b.clone()));
1156
1157        let res = merge_maps(Some(b.clone()), Some(c.clone()));
1158        assert_eq!(res, Some(b.clone()));
1159
1160        let res = merge_maps(Some(c.clone()), Some(b.clone()));
1161        assert_eq!(res, Some(c.clone()));
1162    }
1163
1164    #[test]
1165    fn test_parse_tunables() {
1166        let res: Tunables = serde_json::from_str("{}").unwrap();
1167        assert_eq!(res.typing_notice_send, None);
1168        assert_eq!(res.typing_notice_display, None);
1169        assert_eq!(res.users, None);
1170
1171        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1172        assert_eq!(res.typing_notice_send, Some(true));
1173        assert_eq!(res.typing_notice_display, None);
1174        assert_eq!(res.users, None);
1175
1176        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1177        assert_eq!(res.typing_notice_send, Some(false));
1178        assert_eq!(res.typing_notice_display, None);
1179        assert_eq!(res.users, None);
1180
1181        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1182        assert_eq!(res.typing_notice_send, None);
1183        assert_eq!(res.typing_notice_display, None);
1184        assert_eq!(res.users, Some(HashMap::new()));
1185
1186        let res: Tunables = serde_json::from_str(
1187            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1188        )
1189        .unwrap();
1190        assert_eq!(res.typing_notice_send, None);
1191        assert_eq!(res.typing_notice_display, None);
1192        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1193            color: Some(UserColor(Color::Black)),
1194            name: Some("Tim".into()),
1195        })];
1196        assert_eq!(res.users, Some(users.into_iter().collect()));
1197    }
1198
1199    #[test]
1200    fn test_parse_tunables_username_display() {
1201        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1202        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1203
1204        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1205        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1206
1207        let res: Tunables =
1208            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1209        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1210    }
1211
1212    #[test]
1213    fn test_parse_tunables_sort() {
1214        let res: Tunables = serde_json::from_str(
1215            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1216        )
1217        .unwrap();
1218        assert_eq!(
1219            res.sort.members,
1220            Some(vec![
1221                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1222                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1223            ])
1224        );
1225        assert_eq!(
1226            res.sort.spaces,
1227            Some(vec![
1228                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1229                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1230            ])
1231        );
1232        assert_eq!(res.sort.rooms, None);
1233        assert_eq!(res.sort.dms, None);
1234
1235        // Check that we get the right default "rooms" and "dms" values.
1236        let res = res.values();
1237        assert_eq!(res.sort.members, vec![
1238            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1239            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1240        ]);
1241        assert_eq!(res.sort.spaces, vec![
1242            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1243            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1244        ]);
1245        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1246        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1247    }
1248
1249    #[test]
1250    fn test_parse_layout() {
1251        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1252        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1253        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1254        let dms = WindowPath::Window(IambId::DirectList);
1255        let welcome = WindowPath::Window(IambId::Welcome);
1256
1257        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1258        assert_eq!(res, Layout::Restore);
1259
1260        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1261        assert_eq!(res, Layout::New);
1262
1263        let res: Layout = serde_json::from_str(
1264            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1265        )
1266        .unwrap();
1267        assert_eq!(res, Layout::Config {
1268            tabs: vec![WindowLayout::Window { window: user.clone() }]
1269        });
1270
1271        let res: Layout = serde_json::from_str(
1272            "{\
1273            \"style\": \"config\",\
1274            \"tabs\": [\
1275                {\"split\":[\
1276                    {\"window\":\"@user:example.com\"},\
1277                    {\"window\":\"#room:example.com\"}\
1278                ]},\
1279                {\"split\":[\
1280                    {\"window\":\"!room:example.com\"},\
1281                    {\"split\":[\
1282                        {\"window\":\"iamb://dms\"},\
1283                        {\"window\":\"iamb://welcome\"}\
1284                    ]}\
1285                ]}\
1286            ]}",
1287        )
1288        .unwrap();
1289        let split1 = WindowLayout::Split {
1290            split: vec![
1291                WindowLayout::Window { window: user.clone() },
1292                WindowLayout::Window { window: alias },
1293            ],
1294        };
1295        let split2 = WindowLayout::Split {
1296            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1297                window: welcome,
1298            }],
1299        };
1300        let split3 = WindowLayout::Split {
1301            split: vec![WindowLayout::Window { window: room }, split2],
1302        };
1303        let tabs = vec![split1, split3];
1304        assert_eq!(res, Layout::Config { tabs });
1305    }
1306
1307    #[test]
1308    fn test_parse_macros() {
1309        let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1310        assert_eq!(res.len(), 1);
1311
1312        let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1313        let mapped = res.get(&modes).unwrap();
1314        assert_eq!(mapped.len(), 1);
1315
1316        let j = "j".parse::<TerminalKey>().unwrap();
1317        let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1318
1319        let jj = Keys(vec![j, j], "jj".into());
1320        let run = mapped.get(&jj).unwrap();
1321        let exp = Keys(vec![esc], "<Esc>".into());
1322        assert_eq!(run, &exp);
1323    }
1324
1325    #[test]
1326    fn test_parse_notify_via() {
1327        assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1328        assert_eq!(
1329            NotifyVia { bell: false, desktop: true },
1330            serde_json::from_str(r#""desktop""#).unwrap()
1331        );
1332        assert_eq!(
1333            NotifyVia { bell: true, desktop: false },
1334            serde_json::from_str(r#""bell""#).unwrap()
1335        );
1336        assert_eq!(
1337            NotifyVia { bell: true, desktop: true },
1338            serde_json::from_str(r#""bell|desktop""#).unwrap()
1339        );
1340        assert_eq!(
1341            NotifyVia { bell: true, desktop: true },
1342            serde_json::from_str(r#""desktop|bell""#).unwrap()
1343        );
1344        assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1345        assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1346    }
1347
1348    #[test]
1349    fn test_load_example_config_toml() {
1350        let path = PathBuf::from("config.example.toml");
1351        let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1352
1353        let IambConfig {
1354            profiles,
1355            default_profile,
1356            settings,
1357            dirs,
1358            layout,
1359            macros,
1360        } = &config;
1361
1362        // There should be an example object for each top-level field.
1363        assert!(!profiles.is_empty());
1364        assert!(default_profile.is_some());
1365        assert!(settings.is_some());
1366        assert!(dirs.is_some());
1367        assert!(layout.is_some());
1368        assert!(macros.is_some());
1369    }
1370}