src/config.rs

907 lines · 29770 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        chats: b.chats.or(a.chats),
231        dms: b.dms.or(a.dms),
232        rooms: b.rooms.or(a.rooms),
233        spaces: b.spaces.or(a.spaces),
234        members: b.members.or(a.members),
235    }
236}
237
238fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
239    match (a, b) {
240        (Some(a), None) => Some(a),
241        (None, Some(b)) => Some(b),
242        (Some(mut a), Some(b)) => {
243            for (k, v) in b {
244                a.insert(k, v);
245            }
246
247            Some(a)
248        },
249        (None, None) => None,
250    }
251}
252
253#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
254#[serde(rename_all = "lowercase")]
255pub enum UserDisplayStyle {
256    // The Matrix username for the sender (e.g., "@user:example.com").
257    #[default]
258    Username,
259
260    // The localpart of the Matrix username (e.g., "@user").
261    LocalPart,
262
263    // The display name for the Matrix user, calculated according to the rules from the spec.
264    //
265    // This is usually something like "Ada Lovelace" if the user has configured a display name, but
266    // it can wind up being the Matrix username if there are display name collisions in the room,
267    // in order to avoid any confusion.
268    DisplayName,
269}
270
271#[derive(Clone)]
272pub struct ImagePreviewValues {
273    pub size: ImagePreviewSize,
274    pub protocol: Option<ImagePreviewProtocolValues>,
275}
276
277#[derive(Clone, Default, Deserialize)]
278pub struct ImagePreview {
279    pub size: Option<ImagePreviewSize>,
280    pub protocol: Option<ImagePreviewProtocolValues>,
281}
282
283impl ImagePreview {
284    fn values(self) -> ImagePreviewValues {
285        ImagePreviewValues {
286            size: self.size.unwrap_or_default(),
287            protocol: self.protocol,
288        }
289    }
290}
291
292#[derive(Clone, Deserialize)]
293pub struct ImagePreviewSize {
294    pub width: usize,
295    pub height: usize,
296}
297
298impl Default for ImagePreviewSize {
299    fn default() -> Self {
300        ImagePreviewSize { width: 66, height: 10 }
301    }
302}
303
304#[derive(Clone, Deserialize)]
305pub struct ImagePreviewProtocolValues {
306    pub r#type: Option<ProtocolType>,
307    pub font_size: Option<(u16, u16)>,
308}
309
310#[derive(Clone)]
311pub struct SortValues {
312    pub chats: Vec<SortColumn<SortFieldRoom>>,
313    pub dms: Vec<SortColumn<SortFieldRoom>>,
314    pub rooms: Vec<SortColumn<SortFieldRoom>>,
315    pub spaces: Vec<SortColumn<SortFieldRoom>>,
316    pub members: Vec<SortColumn<SortFieldUser>>,
317}
318
319#[derive(Clone, Default, Deserialize)]
320pub struct SortOverrides {
321    pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
322    pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
323    pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
324    pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
325    pub members: Option<Vec<SortColumn<SortFieldUser>>>,
326}
327
328impl SortOverrides {
329    pub fn values(self) -> SortValues {
330        let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
331        let chats = self.chats.unwrap_or_else(|| rooms.clone());
332        let dms = self.dms.unwrap_or_else(|| rooms.clone());
333        let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
334        let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
335
336        SortValues { rooms, members, chats, dms, spaces }
337    }
338}
339
340#[derive(Clone)]
341pub struct TunableValues {
342    pub log_level: Level,
343    pub reaction_display: bool,
344    pub reaction_shortcode_display: bool,
345    pub read_receipt_send: bool,
346    pub read_receipt_display: bool,
347    pub request_timeout: u64,
348    pub sort: SortValues,
349    pub typing_notice_send: bool,
350    pub typing_notice_display: bool,
351    pub users: UserOverrides,
352    pub username_display: UserDisplayStyle,
353    pub default_room: Option<String>,
354    pub open_command: Option<Vec<String>>,
355    pub image_preview: Option<ImagePreviewValues>,
356}
357
358#[derive(Clone, Default, Deserialize)]
359pub struct Tunables {
360    pub log_level: Option<LogLevel>,
361    pub reaction_display: Option<bool>,
362    pub reaction_shortcode_display: Option<bool>,
363    pub read_receipt_send: Option<bool>,
364    pub read_receipt_display: Option<bool>,
365    pub request_timeout: Option<u64>,
366    #[serde(default)]
367    pub sort: SortOverrides,
368    pub typing_notice_send: Option<bool>,
369    pub typing_notice_display: Option<bool>,
370    pub users: Option<UserOverrides>,
371    pub username_display: Option<UserDisplayStyle>,
372    pub default_room: Option<String>,
373    pub open_command: Option<Vec<String>>,
374    pub image_preview: Option<ImagePreview>,
375}
376
377impl Tunables {
378    fn merge(self, other: Self) -> Self {
379        Tunables {
380            log_level: self.log_level.or(other.log_level),
381            reaction_display: self.reaction_display.or(other.reaction_display),
382            reaction_shortcode_display: self
383                .reaction_shortcode_display
384                .or(other.reaction_shortcode_display),
385            read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
386            read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
387            request_timeout: self.request_timeout.or(other.request_timeout),
388            sort: merge_sorts(self.sort, other.sort),
389            typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
390            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
391            users: merge_users(self.users, other.users),
392            username_display: self.username_display.or(other.username_display),
393            default_room: self.default_room.or(other.default_room),
394            open_command: self.open_command.or(other.open_command),
395            image_preview: self.image_preview.or(other.image_preview),
396        }
397    }
398
399    fn values(self) -> TunableValues {
400        TunableValues {
401            log_level: self.log_level.map(Level::from).unwrap_or(Level::INFO),
402            reaction_display: self.reaction_display.unwrap_or(true),
403            reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
404            read_receipt_send: self.read_receipt_send.unwrap_or(true),
405            read_receipt_display: self.read_receipt_display.unwrap_or(true),
406            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
407            sort: self.sort.values(),
408            typing_notice_send: self.typing_notice_send.unwrap_or(true),
409            typing_notice_display: self.typing_notice_display.unwrap_or(true),
410            users: self.users.unwrap_or_default(),
411            username_display: self.username_display.unwrap_or_default(),
412            default_room: self.default_room,
413            open_command: self.open_command,
414            image_preview: self.image_preview.map(ImagePreview::values),
415        }
416    }
417}
418
419#[derive(Clone)]
420pub struct DirectoryValues {
421    pub cache: PathBuf,
422    pub logs: PathBuf,
423    pub downloads: Option<PathBuf>,
424    pub image_previews: PathBuf,
425}
426
427#[derive(Clone, Default, Deserialize)]
428pub struct Directories {
429    pub cache: Option<PathBuf>,
430    pub logs: Option<PathBuf>,
431    pub downloads: Option<PathBuf>,
432    pub image_previews: Option<PathBuf>,
433}
434
435impl Directories {
436    fn merge(self, other: Self) -> Self {
437        Directories {
438            cache: self.cache.or(other.cache),
439            logs: self.logs.or(other.logs),
440            downloads: self.downloads.or(other.downloads),
441            image_previews: self.image_previews.or(other.image_previews),
442        }
443    }
444
445    fn values(self) -> DirectoryValues {
446        let cache = self
447            .cache
448            .or_else(|| {
449                let mut dir = dirs::cache_dir()?;
450                dir.push("iamb");
451                dir.into()
452            })
453            .expect("no dirs.cache value configured!");
454
455        let logs = self.logs.unwrap_or_else(|| {
456            let mut dir = cache.clone();
457            dir.push("logs");
458            dir
459        });
460
461        let downloads = self.downloads.or_else(dirs::download_dir);
462
463        let image_previews = self.image_previews.unwrap_or_else(|| {
464            let mut dir = cache.clone();
465            dir.push("image_preview_downloads");
466            dir
467        });
468
469        DirectoryValues { cache, logs, downloads, image_previews }
470    }
471}
472
473#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
474#[serde(untagged)]
475pub enum WindowPath {
476    AliasId(OwnedRoomAliasId),
477    RoomId(OwnedRoomId),
478    UserId(OwnedUserId),
479    Window(IambId),
480}
481
482#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
483#[serde(untagged, deny_unknown_fields)]
484pub enum WindowLayout {
485    Window { window: WindowPath },
486    Split { split: Vec<WindowLayout> },
487}
488
489#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
490#[serde(rename_all = "lowercase", tag = "style")]
491pub enum Layout {
492    /// Restore the layout from the previous session.
493    #[default]
494    Restore,
495
496    /// Open a single window using the `default_room` value.
497    New,
498
499    /// Open the window layouts described under `tabs`.
500    Config { tabs: Vec<WindowLayout> },
501}
502
503#[derive(Clone, Deserialize)]
504pub struct ProfileConfig {
505    pub user_id: OwnedUserId,
506    pub url: Url,
507    pub settings: Option<Tunables>,
508    pub dirs: Option<Directories>,
509    pub layout: Option<Layout>,
510}
511
512#[derive(Clone, Deserialize)]
513pub struct IambConfig {
514    pub profiles: HashMap<String, ProfileConfig>,
515    pub default_profile: Option<String>,
516    pub settings: Option<Tunables>,
517    pub dirs: Option<Directories>,
518    pub layout: Option<Layout>,
519}
520
521impl IambConfig {
522    pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
523        if !config_json.is_file() {
524            usage!(
525                "Please create a configuration file at {}\n\n\
526                For more information try '--help'",
527                config_json.display(),
528            );
529        }
530
531        let file = File::open(config_json)?;
532        let reader = BufReader::new(file);
533        let config = serde_json::from_reader(reader)?;
534
535        Ok(config)
536    }
537}
538
539#[derive(Clone)]
540pub struct ApplicationSettings {
541    pub matrix_dir: PathBuf,
542    pub layout_json: PathBuf,
543    pub session_json: PathBuf,
544    pub profile_name: String,
545    pub profile: ProfileConfig,
546    pub tunables: TunableValues,
547    pub dirs: DirectoryValues,
548    pub layout: Layout,
549}
550
551impl ApplicationSettings {
552    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
553        let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
554            usage!(
555                "No user configuration directory found;\
556                please specify one via -C.\n\n
557                For more information try '--help'"
558            );
559        });
560        config_dir.push("iamb");
561        let mut config_json = config_dir.clone();
562        config_json.push("config.json");
563
564        let IambConfig {
565            mut profiles,
566            default_profile,
567            dirs,
568            settings: global,
569            layout,
570        } = IambConfig::load(config_json.as_path())?;
571
572        validate_profile_names(&profiles);
573
574        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
575            profiles.remove_entry(&profile).unwrap_or_else(|| {
576                usage!(
577                    "No configured profile with the name {:?} in {}",
578                    profile,
579                    config_json.display()
580                );
581            })
582        } else if profiles.len() == 1 {
583            profiles.into_iter().next().unwrap()
584        } else {
585            usage!(
586                "No profile specified. \
587                Please use -P or add \"default_profile\" to {}.\n\n\
588                For more information try '--help'",
589                config_json.display()
590            );
591        };
592
593        let layout = profile.layout.take().or(layout).unwrap_or_default();
594
595        let tunables = global.unwrap_or_default();
596        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
597        let tunables = tunables.values();
598
599        let dirs = dirs.unwrap_or_default();
600        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
601        let dirs = dirs.values();
602
603        // Set up paths that live inside the profile's data directory.
604        let mut profile_dir = config_dir.clone();
605        profile_dir.push("profiles");
606        profile_dir.push(profile_name.as_str());
607
608        let mut matrix_dir = profile_dir.clone();
609        matrix_dir.push("matrix");
610
611        let mut session_json = profile_dir;
612        session_json.push("session.json");
613
614        // Set up paths that live inside the profile's cache directory.
615        let mut cache_dir = dirs.cache.clone();
616        cache_dir.push("profiles");
617        cache_dir.push(profile_name.as_str());
618
619        let mut layout_json = cache_dir.clone();
620        layout_json.push("layout.json");
621
622        let settings = ApplicationSettings {
623            matrix_dir,
624            layout_json,
625            session_json,
626            profile_name,
627            profile,
628            tunables,
629            dirs,
630            layout,
631        };
632
633        Ok(settings)
634    }
635
636    pub fn get_user_char_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
637        let (color, c) = self
638            .tunables
639            .users
640            .get(user_id)
641            .map(|user| {
642                (
643                    user.color.as_ref().map(|c| c.0),
644                    user.name.as_ref().and_then(|s| s.chars().next()),
645                )
646            })
647            .unwrap_or_default();
648
649        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
650        let style = user_style_from_color(color);
651
652        let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
653
654        Span::styled(String::from(c), style)
655    }
656
657    pub fn get_user_overrides(
658        &self,
659        user_id: &UserId,
660    ) -> (Option<Color>, Option<Cow<'static, str>>) {
661        self.tunables
662            .users
663            .get(user_id)
664            .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
665            .unwrap_or_default()
666    }
667
668    pub fn get_user_style(&self, user_id: &UserId) -> Style {
669        let color = self
670            .tunables
671            .users
672            .get(user_id)
673            .and_then(|user| user.color.as_ref().map(|c| c.0))
674            .unwrap_or_else(|| user_color(user_id.as_str()));
675
676        user_style_from_color(color)
677    }
678
679    pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
680        let (color, name) = self.get_user_overrides(user_id);
681
682        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
683        let style = user_style_from_color(color);
684        let name = match (name, &self.tunables.username_display) {
685            (Some(name), _) => name,
686            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
687            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
688            (None, UserDisplayStyle::DisplayName) => {
689                if let Some(display) = info.display_names.get(user_id) {
690                    Cow::Borrowed(display.as_str())
691                } else {
692                    Cow::Borrowed(user_id.as_str())
693                }
694            },
695        };
696
697        Span::styled(name, style)
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704    use matrix_sdk::ruma::user_id;
705    use std::convert::TryFrom;
706
707    #[test]
708    fn test_profile_name_invalid() {
709        assert_eq!(validate_profile_name(""), false);
710        assert_eq!(validate_profile_name(" "), false);
711        assert_eq!(validate_profile_name("a b"), false);
712        assert_eq!(validate_profile_name("foo^bar"), false);
713        assert_eq!(validate_profile_name("FOO/BAR"), false);
714        assert_eq!(validate_profile_name("-b-c"), false);
715        assert_eq!(validate_profile_name("-B-c"), false);
716        assert_eq!(validate_profile_name(".b-c"), false);
717        assert_eq!(validate_profile_name(".B-c"), false);
718    }
719
720    #[test]
721    fn test_profile_name_valid() {
722        assert_eq!(validate_profile_name("foo"), true);
723        assert_eq!(validate_profile_name("FOO"), true);
724        assert_eq!(validate_profile_name("a-b-c"), true);
725        assert_eq!(validate_profile_name("a-B-c"), true);
726        assert_eq!(validate_profile_name("a.b-c"), true);
727        assert_eq!(validate_profile_name("a.B-c"), true);
728    }
729
730    #[test]
731    fn test_merge_users() {
732        let a = None;
733        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
734            color: Some(UserColor(Color::Red)),
735            name: Some("Hello".into()),
736        })]
737        .into_iter()
738        .collect::<HashMap<_, _>>();
739        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
740            color: Some(UserColor(Color::Green)),
741            name: Some("World".into()),
742        })]
743        .into_iter()
744        .collect::<HashMap<_, _>>();
745
746        let res = merge_users(a.clone(), a.clone());
747        assert_eq!(res, None);
748
749        let res = merge_users(a.clone(), Some(b.clone()));
750        assert_eq!(res, Some(b.clone()));
751
752        let res = merge_users(Some(b.clone()), a.clone());
753        assert_eq!(res, Some(b.clone()));
754
755        let res = merge_users(Some(b.clone()), Some(b.clone()));
756        assert_eq!(res, Some(b.clone()));
757
758        let res = merge_users(Some(b.clone()), Some(c.clone()));
759        assert_eq!(res, Some(c.clone()));
760
761        let res = merge_users(Some(c.clone()), Some(b.clone()));
762        assert_eq!(res, Some(b.clone()));
763    }
764
765    #[test]
766    fn test_parse_tunables() {
767        let res: Tunables = serde_json::from_str("{}").unwrap();
768        assert_eq!(res.typing_notice_send, None);
769        assert_eq!(res.typing_notice_display, None);
770        assert_eq!(res.users, None);
771
772        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
773        assert_eq!(res.typing_notice_send, Some(true));
774        assert_eq!(res.typing_notice_display, None);
775        assert_eq!(res.users, None);
776
777        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
778        assert_eq!(res.typing_notice_send, Some(false));
779        assert_eq!(res.typing_notice_display, None);
780        assert_eq!(res.users, None);
781
782        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
783        assert_eq!(res.typing_notice_send, None);
784        assert_eq!(res.typing_notice_display, None);
785        assert_eq!(res.users, Some(HashMap::new()));
786
787        let res: Tunables = serde_json::from_str(
788            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
789        )
790        .unwrap();
791        assert_eq!(res.typing_notice_send, None);
792        assert_eq!(res.typing_notice_display, None);
793        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
794            color: Some(UserColor(Color::Black)),
795            name: Some("Tim".into()),
796        })];
797        assert_eq!(res.users, Some(users.into_iter().collect()));
798    }
799
800    #[test]
801    fn test_parse_tunables_username_display() {
802        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
803        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
804
805        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
806        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
807
808        let res: Tunables =
809            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
810        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
811    }
812
813    #[test]
814    fn test_parse_tunables_sort() {
815        let res: Tunables = serde_json::from_str(
816            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
817        )
818        .unwrap();
819        assert_eq!(
820            res.sort.members,
821            Some(vec![
822                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
823                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
824            ])
825        );
826        assert_eq!(
827            res.sort.spaces,
828            Some(vec![
829                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
830                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
831            ])
832        );
833        assert_eq!(res.sort.rooms, None);
834        assert_eq!(res.sort.dms, None);
835
836        // Check that we get the right default "rooms" and "dms" values.
837        let res = res.values();
838        assert_eq!(res.sort.members, vec![
839            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
840            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
841        ]);
842        assert_eq!(res.sort.spaces, vec![
843            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
844            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
845        ]);
846        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
847        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
848    }
849
850    #[test]
851    fn test_parse_layout() {
852        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
853        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
854        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
855        let dms = WindowPath::Window(IambId::DirectList);
856        let welcome = WindowPath::Window(IambId::Welcome);
857
858        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
859        assert_eq!(res, Layout::Restore);
860
861        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
862        assert_eq!(res, Layout::New);
863
864        let res: Layout = serde_json::from_str(
865            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
866        )
867        .unwrap();
868        assert_eq!(res, Layout::Config {
869            tabs: vec![WindowLayout::Window { window: user.clone() }]
870        });
871
872        let res: Layout = serde_json::from_str(
873            "{\
874            \"style\": \"config\",\
875            \"tabs\": [\
876                {\"split\":[\
877                    {\"window\":\"@user:example.com\"},\
878                    {\"window\":\"#room:example.com\"}\
879                ]},\
880                {\"split\":[\
881                    {\"window\":\"!room:example.com\"},\
882                    {\"split\":[\
883                        {\"window\":\"iamb://dms\"},\
884                        {\"window\":\"iamb://welcome\"}\
885                    ]}\
886                ]}\
887            ]}",
888        )
889        .unwrap();
890        let split1 = WindowLayout::Split {
891            split: vec![
892                WindowLayout::Window { window: user.clone() },
893                WindowLayout::Window { window: alias },
894            ],
895        };
896        let split2 = WindowLayout::Split {
897            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
898                window: welcome,
899            }],
900        };
901        let split3 = WindowLayout::Split {
902            split: vec![WindowLayout::Window { window: room }, split2],
903        };
904        let tabs = vec![split1, split3];
905        assert_eq!(res, Layout::Config { tabs });
906    }
907}