src/config.rs

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