src/config.rs

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