src/config.rs

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