src/config.rs

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