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