src/config.rs

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