src/config.rs

763 lines · 24772 bytes

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