src/config.rs
760 lines · 24695 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: Option<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.downloads.or_else(dirs::download_dir);
358
359 DirectoryValues { cache, logs, downloads }
360 }
361}
362
363#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
364#[serde(untagged)]
365pub enum WindowPath {
366 AliasId(OwnedRoomAliasId),
367 RoomId(OwnedRoomId),
368 UserId(OwnedUserId),
369 Window(IambId),
370}
371
372#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
373#[serde(untagged, deny_unknown_fields)]
374pub enum WindowLayout {
375 Window { window: WindowPath },
376 Split { split: Vec<WindowLayout> },
377}
378
379#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
380#[serde(rename_all = "lowercase", tag = "style")]
381pub enum Layout {
382 /// Restore the layout from the previous session.
383 #[default]
384 Restore,
385
386 /// Open a single window using the `default_room` value.
387 New,
388
389 /// Open the window layouts described under `tabs`.
390 Config { tabs: Vec<WindowLayout> },
391}
392
393#[derive(Clone, Deserialize)]
394pub struct ProfileConfig {
395 pub user_id: OwnedUserId,
396 pub url: Url,
397 pub settings: Option<Tunables>,
398 pub dirs: Option<Directories>,
399 pub layout: Option<Layout>,
400}
401
402#[derive(Clone, Deserialize)]
403pub struct IambConfig {
404 pub profiles: HashMap<String, ProfileConfig>,
405 pub default_profile: Option<String>,
406 pub settings: Option<Tunables>,
407 pub dirs: Option<Directories>,
408 pub layout: Option<Layout>,
409}
410
411impl IambConfig {
412 pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
413 if !config_json.is_file() {
414 usage!(
415 "Please create a configuration file at {}\n\n\
416 For more information try '--help'",
417 config_json.display(),
418 );
419 }
420
421 let file = File::open(config_json)?;
422 let reader = BufReader::new(file);
423 let config = serde_json::from_reader(reader)?;
424
425 Ok(config)
426 }
427}
428
429#[derive(Clone)]
430pub struct ApplicationSettings {
431 pub matrix_dir: PathBuf,
432 pub layout_json: PathBuf,
433 pub session_json: PathBuf,
434 pub profile_name: String,
435 pub profile: ProfileConfig,
436 pub tunables: TunableValues,
437 pub dirs: DirectoryValues,
438 pub layout: Layout,
439}
440
441impl ApplicationSettings {
442 pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
443 let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
444 usage!(
445 "No user configuration directory found;\
446 please specify one via -C.\n\n
447 For more information try '--help'"
448 );
449 });
450 config_dir.push("iamb");
451 let mut config_json = config_dir.clone();
452 config_json.push("config.json");
453
454 let IambConfig {
455 mut profiles,
456 default_profile,
457 dirs,
458 settings: global,
459 layout,
460 } = IambConfig::load(config_json.as_path())?;
461
462 validate_profile_names(&profiles);
463
464 let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
465 profiles.remove_entry(&profile).unwrap_or_else(|| {
466 usage!(
467 "No configured profile with the name {:?} in {}",
468 profile,
469 config_json.display()
470 );
471 })
472 } else if profiles.len() == 1 {
473 profiles.into_iter().next().unwrap()
474 } else {
475 usage!(
476 "No profile specified. \
477 Please use -P or add \"default_profile\" to {}.\n\n\
478 For more information try '--help'",
479 config_json.display()
480 );
481 };
482
483 let layout = profile.layout.take().or(layout).unwrap_or_default();
484
485 let tunables = global.unwrap_or_default();
486 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
487 let tunables = tunables.values();
488
489 let dirs = dirs.unwrap_or_default();
490 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
491 let dirs = dirs.values();
492
493 // Set up paths that live inside the profile's data directory.
494 let mut profile_dir = config_dir.clone();
495 profile_dir.push("profiles");
496 profile_dir.push(profile_name.as_str());
497
498 let mut matrix_dir = profile_dir.clone();
499 matrix_dir.push("matrix");
500
501 let mut session_json = profile_dir;
502 session_json.push("session.json");
503
504 // Set up paths that live inside the profile's cache directory.
505 let mut cache_dir = dirs.cache.clone();
506 cache_dir.push("profiles");
507 cache_dir.push(profile_name.as_str());
508
509 let mut layout_json = cache_dir.clone();
510 layout_json.push("layout.json");
511
512 let settings = ApplicationSettings {
513 matrix_dir,
514 layout_json,
515 session_json,
516 profile_name,
517 profile,
518 tunables,
519 dirs,
520 layout,
521 };
522
523 Ok(settings)
524 }
525
526 pub fn get_user_char_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
527 let (color, c) = self
528 .tunables
529 .users
530 .get(user_id)
531 .map(|user| {
532 (
533 user.color.as_ref().map(|c| c.0),
534 user.name.as_ref().and_then(|s| s.chars().next()),
535 )
536 })
537 .unwrap_or_default();
538
539 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
540 let style = user_style_from_color(color);
541
542 let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
543
544 Span::styled(String::from(c), style)
545 }
546
547 pub fn get_user_overrides(
548 &self,
549 user_id: &UserId,
550 ) -> (Option<Color>, Option<Cow<'static, str>>) {
551 self.tunables
552 .users
553 .get(user_id)
554 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
555 .unwrap_or_default()
556 }
557
558 pub fn get_user_style(&self, user_id: &UserId) -> Style {
559 let color = self
560 .tunables
561 .users
562 .get(user_id)
563 .and_then(|user| user.color.as_ref().map(|c| c.0))
564 .unwrap_or_else(|| user_color(user_id.as_str()));
565
566 user_style_from_color(color)
567 }
568
569 pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
570 let (color, name) = self.get_user_overrides(user_id);
571
572 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
573 let style = user_style_from_color(color);
574 let name = match (name, &self.tunables.username_display) {
575 (Some(name), _) => name,
576 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
577 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
578 (None, UserDisplayStyle::DisplayName) => {
579 if let Some(display) = info.display_names.get(user_id) {
580 Cow::Borrowed(display.as_str())
581 } else {
582 Cow::Borrowed(user_id.as_str())
583 }
584 },
585 };
586
587 Span::styled(name, style)
588 }
589}
590
591#[cfg(test)]
592mod tests {
593 use super::*;
594 use matrix_sdk::ruma::user_id;
595 use std::convert::TryFrom;
596
597 #[test]
598 fn test_profile_name_invalid() {
599 assert_eq!(validate_profile_name(""), false);
600 assert_eq!(validate_profile_name(" "), false);
601 assert_eq!(validate_profile_name("a b"), false);
602 assert_eq!(validate_profile_name("foo^bar"), false);
603 assert_eq!(validate_profile_name("FOO/BAR"), false);
604 assert_eq!(validate_profile_name("-b-c"), false);
605 assert_eq!(validate_profile_name("-B-c"), false);
606 assert_eq!(validate_profile_name(".b-c"), false);
607 assert_eq!(validate_profile_name(".B-c"), false);
608 }
609
610 #[test]
611 fn test_profile_name_valid() {
612 assert_eq!(validate_profile_name("foo"), true);
613 assert_eq!(validate_profile_name("FOO"), true);
614 assert_eq!(validate_profile_name("a-b-c"), true);
615 assert_eq!(validate_profile_name("a-B-c"), true);
616 assert_eq!(validate_profile_name("a.b-c"), true);
617 assert_eq!(validate_profile_name("a.B-c"), true);
618 }
619
620 #[test]
621 fn test_merge_users() {
622 let a = None;
623 let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
624 color: Some(UserColor(Color::Red)),
625 name: Some("Hello".into()),
626 })]
627 .into_iter()
628 .collect::<HashMap<_, _>>();
629 let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
630 color: Some(UserColor(Color::Green)),
631 name: Some("World".into()),
632 })]
633 .into_iter()
634 .collect::<HashMap<_, _>>();
635
636 let res = merge_users(a.clone(), a.clone());
637 assert_eq!(res, None);
638
639 let res = merge_users(a.clone(), Some(b.clone()));
640 assert_eq!(res, Some(b.clone()));
641
642 let res = merge_users(Some(b.clone()), a.clone());
643 assert_eq!(res, Some(b.clone()));
644
645 let res = merge_users(Some(b.clone()), Some(b.clone()));
646 assert_eq!(res, Some(b.clone()));
647
648 let res = merge_users(Some(b.clone()), Some(c.clone()));
649 assert_eq!(res, Some(c.clone()));
650
651 let res = merge_users(Some(c.clone()), Some(b.clone()));
652 assert_eq!(res, Some(b.clone()));
653 }
654
655 #[test]
656 fn test_parse_tunables() {
657 let res: Tunables = serde_json::from_str("{}").unwrap();
658 assert_eq!(res.typing_notice_send, None);
659 assert_eq!(res.typing_notice_display, None);
660 assert_eq!(res.users, None);
661
662 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
663 assert_eq!(res.typing_notice_send, Some(true));
664 assert_eq!(res.typing_notice_display, None);
665 assert_eq!(res.users, None);
666
667 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
668 assert_eq!(res.typing_notice_send, Some(false));
669 assert_eq!(res.typing_notice_display, None);
670 assert_eq!(res.users, None);
671
672 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
673 assert_eq!(res.typing_notice_send, None);
674 assert_eq!(res.typing_notice_display, None);
675 assert_eq!(res.users, Some(HashMap::new()));
676
677 let res: Tunables = serde_json::from_str(
678 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
679 )
680 .unwrap();
681 assert_eq!(res.typing_notice_send, None);
682 assert_eq!(res.typing_notice_display, None);
683 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
684 color: Some(UserColor(Color::Black)),
685 name: Some("Tim".into()),
686 })];
687 assert_eq!(res.users, Some(users.into_iter().collect()));
688 }
689
690 #[test]
691 fn test_parse_tunables_username_display() {
692 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
693 assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
694
695 let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
696 assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
697
698 let res: Tunables =
699 serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
700 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
701 }
702
703 #[test]
704 fn test_parse_layout() {
705 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
706 let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
707 let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
708 let dms = WindowPath::Window(IambId::DirectList);
709 let welcome = WindowPath::Window(IambId::Welcome);
710
711 let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
712 assert_eq!(res, Layout::Restore);
713
714 let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
715 assert_eq!(res, Layout::New);
716
717 let res: Layout = serde_json::from_str(
718 "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
719 )
720 .unwrap();
721 assert_eq!(res, Layout::Config {
722 tabs: vec![WindowLayout::Window { window: user.clone() }]
723 });
724
725 let res: Layout = serde_json::from_str(
726 "{\
727 \"style\": \"config\",\
728 \"tabs\": [\
729 {\"split\":[\
730 {\"window\":\"@user:example.com\"},\
731 {\"window\":\"#room:example.com\"}\
732 ]},\
733 {\"split\":[\
734 {\"window\":\"!room:example.com\"},\
735 {\"split\":[\
736 {\"window\":\"iamb://dms\"},\
737 {\"window\":\"iamb://welcome\"}\
738 ]}\
739 ]}\
740 ]}",
741 )
742 .unwrap();
743 let split1 = WindowLayout::Split {
744 split: vec![
745 WindowLayout::Window { window: user.clone() },
746 WindowLayout::Window { window: alias },
747 ],
748 };
749 let split2 = WindowLayout::Split {
750 split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
751 window: welcome,
752 }],
753 };
754 let split3 = WindowLayout::Split {
755 split: vec![WindowLayout::Window { window: room }, split2],
756 };
757 let tabs = vec![split1, split3];
758 assert_eq!(res, Layout::Config { tabs });
759 }
760}