src/config.rs

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