src/config.rs

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