src/config.rs

1285 lines · 41570 bytes

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