src/config.rs
1619 lines · 54069 bytes
1//! # Logic for loading and validating application configuration
2use std::borrow::Cow;
3use std::collections::hash_map::DefaultHasher;
4use std::collections::{BTreeMap, HashMap};
5use std::env;
6use std::fmt;
7use std::fs::File;
8use std::hash::{Hash, Hasher};
9use std::io::{BufReader, BufWriter, Write};
10use std::path::{Path, PathBuf};
11use std::process;
12
13use clap::Parser;
14use matrix_sdk::authentication::matrix::MatrixSession;
15use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
16use matrix_sdk::EncryptionState;
17use ratatui::style::{Color, Modifier as StyleModifier, Style};
18use ratatui::text::Span;
19use ratatui_image::picker::ProtocolType;
20use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer, Serialize};
21use url::Url;
22
23use modalkit::{env::vim::VimMode, key::TerminalKey, keybindings::InputKey};
24
25use super::base::{
26 IambError,
27 IambId,
28 RoomInfo,
29 SortColumn,
30 SortFieldRoom,
31 SortFieldUser,
32 SortOrder,
33};
34
35type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
36
37macro_rules! usage {
38 ( $($args: tt)* ) => {
39 println!($($args)*);
40 process::exit(2);
41 }
42}
43
44const DEFAULT_MEMBERS_SORT: [SortColumn<SortFieldUser>; 2] = [
45 SortColumn(SortFieldUser::PowerLevel, SortOrder::Ascending),
46 SortColumn(SortFieldUser::UserId, SortOrder::Ascending),
47];
48
49const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 5] = [
50 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
51 SortColumn(SortFieldRoom::Invite, SortOrder::Ascending),
52 SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending),
53 SortColumn(SortFieldRoom::Unread, SortOrder::Ascending),
54 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
55];
56
57const DEFAULT_ENABLE_TITLE: bool = true;
58const DEFAULT_ENC_INDICATOR_LOC: EncryptionIndicatorLocation = EncryptionIndicatorLocation::PROMPT;
59const DEFAULT_REQ_TIMEOUT: u64 = 120;
60
61const COLORS: [Color; 13] = [
62 Color::Blue,
63 Color::Cyan,
64 Color::Green,
65 Color::LightBlue,
66 Color::LightGreen,
67 Color::LightCyan,
68 Color::LightMagenta,
69 Color::LightRed,
70 Color::LightYellow,
71 Color::Magenta,
72 Color::Red,
73 Color::Reset,
74 Color::Yellow,
75];
76
77pub fn user_color(user: &str) -> Color {
78 let mut hasher = DefaultHasher::new();
79 user.hash(&mut hasher);
80 let color = hasher.finish() as usize % COLORS.len();
81
82 COLORS[color]
83}
84
85pub fn user_style_from_color(color: Color) -> Style {
86 Style::default().fg(color).add_modifier(StyleModifier::BOLD)
87}
88
89fn is_profile_char(c: char) -> bool {
90 c.is_ascii_alphanumeric() || c == '.' || c == '-'
91}
92
93fn default_true() -> bool {
94 true
95}
96
97fn validate_profile_name(name: &str) -> bool {
98 if name.is_empty() {
99 return false;
100 }
101
102 let mut chars = name.chars();
103
104 if !chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) {
105 return false;
106 }
107
108 name.chars().all(is_profile_char)
109}
110
111fn validate_profile_names(names: &BTreeMap<String, ProfileConfig>) {
112 for name in names.keys() {
113 if validate_profile_name(name.as_str()) {
114 continue;
115 }
116
117 usage!(
118 "{:?} is not a valid profile name.\n\n\
119 Profile names can only contain the characters \
120 a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
121 name
122 );
123 }
124}
125
126const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
127 None => env!("CARGO_PKG_VERSION"),
128 Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
129};
130
131#[derive(Parser)]
132#[clap(version = VERSION, about, long_about = None)]
133#[clap(propagate_version = true)]
134pub struct Iamb {
135 #[clap(long, value_parser)]
136 pub completions: Option<clap_complete::Shell>,
137
138 #[clap(short = 'P', long, value_parser)]
139 pub profile: Option<String>,
140
141 #[clap(short = 'C', long, value_parser)]
142 pub config_directory: Option<PathBuf>,
143}
144
145#[derive(thiserror::Error, Debug)]
146pub enum ConfigError {
147 #[error("Error reading configuration file: {0}")]
148 IO(#[from] std::io::Error),
149
150 #[error("Error loading configuration file: {0}")]
151 Invalid(#[from] toml::de::Error),
152
153 #[error("Error loading JSON configuration file: {0}")]
154 InvalidJSON(#[from] serde_json::Error),
155}
156
157#[derive(Clone, Debug, Eq, Hash, PartialEq)]
158pub struct Keys(pub Vec<TerminalKey>, pub String);
159pub struct KeysVisitor;
160
161impl Visitor<'_> for KeysVisitor {
162 type Value = Keys;
163
164 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
165 formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
166 }
167
168 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
169 where
170 E: SerdeError,
171 {
172 match TerminalKey::from_macro_str(value) {
173 Ok(keys) => Ok(Keys(keys, value.to_string())),
174 Err(e) => Err(E::custom(format!("Could not parse key sequence: {e}"))),
175 }
176 }
177}
178
179impl<'de> Deserialize<'de> for Keys {
180 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
181 where
182 D: Deserializer<'de>,
183 {
184 deserializer.deserialize_str(KeysVisitor)
185 }
186}
187
188#[derive(Clone, Debug, Eq, Hash, PartialEq)]
189pub struct VimModes(pub Vec<VimMode>);
190pub struct VimModesVisitor;
191
192impl Visitor<'_> for VimModesVisitor {
193 type Value = VimModes;
194
195 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
196 formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
197 }
198
199 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
200 where
201 E: SerdeError,
202 {
203 let mut modes = vec![];
204
205 for mode in value.split('|') {
206 let mode = match mode.to_ascii_lowercase().as_str() {
207 "insert" | "i" => VimMode::Insert,
208 "normal" | "n" => VimMode::Normal,
209 "visual" | "v" => VimMode::Visual,
210 "command" | "c" => VimMode::Command,
211 "select" => VimMode::Select,
212 "operator-pending" => VimMode::OperationPending,
213 _ => return Err(E::custom("Could not parse into a Vim mode")),
214 };
215
216 modes.push(mode);
217 }
218
219 Ok(VimModes(modes))
220 }
221}
222
223impl<'de> Deserialize<'de> for VimModes {
224 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225 where
226 D: Deserializer<'de>,
227 {
228 deserializer.deserialize_str(VimModesVisitor)
229 }
230}
231
232#[derive(Clone, Debug, Eq, PartialEq)]
233pub struct UserColor(pub Color);
234pub struct UserColorVisitor;
235
236impl Visitor<'_> for UserColorVisitor {
237 type Value = UserColor;
238
239 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
240 formatter.write_str("a valid color")
241 }
242
243 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
244 where
245 E: SerdeError,
246 {
247 match value {
248 "none" => Ok(UserColor(Color::Reset)),
249 "red" => Ok(UserColor(Color::Red)),
250 "black" => Ok(UserColor(Color::Black)),
251 "green" => Ok(UserColor(Color::Green)),
252 "yellow" => Ok(UserColor(Color::Yellow)),
253 "blue" => Ok(UserColor(Color::Blue)),
254 "magenta" => Ok(UserColor(Color::Magenta)),
255 "cyan" => Ok(UserColor(Color::Cyan)),
256 "gray" => Ok(UserColor(Color::Gray)),
257 "dark-gray" => Ok(UserColor(Color::DarkGray)),
258 "light-red" => Ok(UserColor(Color::LightRed)),
259 "light-green" => Ok(UserColor(Color::LightGreen)),
260 "light-yellow" => Ok(UserColor(Color::LightYellow)),
261 "light-blue" => Ok(UserColor(Color::LightBlue)),
262 "light-magenta" => Ok(UserColor(Color::LightMagenta)),
263 "light-cyan" => Ok(UserColor(Color::LightCyan)),
264 "white" => Ok(UserColor(Color::White)),
265 _ => Err(E::custom("Could not parse color")),
266 }
267 }
268}
269
270impl<'de> Deserialize<'de> for UserColor {
271 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
272 where
273 D: Deserializer<'de>,
274 {
275 deserializer.deserialize_str(UserColorVisitor)
276 }
277}
278
279#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
280pub struct Session {
281 access_token: String,
282 refresh_token: Option<String>,
283 user_id: OwnedUserId,
284 device_id: OwnedDeviceId,
285}
286
287impl From<Session> for MatrixSession {
288 fn from(session: Session) -> Self {
289 MatrixSession {
290 tokens: matrix_sdk::authentication::SessionTokens {
291 access_token: session.access_token,
292 refresh_token: session.refresh_token,
293 },
294 meta: matrix_sdk::SessionMeta {
295 user_id: session.user_id,
296 device_id: session.device_id,
297 },
298 }
299 }
300}
301
302impl From<MatrixSession> for Session {
303 fn from(session: MatrixSession) -> Self {
304 Session {
305 access_token: session.tokens.access_token,
306 refresh_token: session.tokens.refresh_token,
307 user_id: session.meta.user_id,
308 device_id: session.meta.device_id,
309 }
310 }
311}
312
313#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
314pub struct UserDisplayTunables {
315 pub color: Option<UserColor>,
316 pub name: Option<String>,
317}
318
319pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
320
321fn merge_maps<K, V>(
322 profile: Option<HashMap<K, V>>,
323 global: Option<HashMap<K, V>>,
324) -> Option<HashMap<K, V>>
325where
326 K: Eq + Hash,
327{
328 match (global, profile) {
329 (Some(m), None) | (None, Some(m)) => Some(m),
330 (Some(mut global), Some(profile)) => {
331 for (k, v) in profile {
332 global.insert(k, v);
333 }
334
335 Some(global)
336 },
337 (None, None) => None,
338 }
339}
340
341#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
342#[serde(rename_all = "kebab-case")]
343#[repr(u8)]
344pub enum EncryptionIndicator {
345 /// Always indicate the room's encryption status.
346 #[default]
347 Enabled,
348 /// Never indicate the room's encryption status.
349 Disabled,
350 /// Only indicate the room's encryption status when it is encrypted.
351 OnlyEncrypted,
352 /// Only indicate the room's encryption status when it is unencrypted.
353 OnlyUnencrypted,
354}
355
356bitflags::bitflags! {
357 /// Available options for where to show the encryption status indicator.
358 #[derive(Clone, Debug, Eq, PartialEq)]
359 pub struct EncryptionIndicatorLocation: u8 {
360 const NONE = 0b00000000;
361 const TITLE = 0b00000001;
362 const PROMPT = 0b00000010;
363 }
364}
365
366pub struct EncryptionIndicatorLocationVisitor;
367
368impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
369 type Value = EncryptionIndicatorLocation;
370
371 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
372 formatter.write_str("a valid encryption indicator location (e.g. \"title\" or \"prompt\")")
373 }
374
375 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
376 where
377 E: SerdeError,
378 {
379 let mut location = EncryptionIndicatorLocation::NONE;
380
381 for value in value.split('|') {
382 match value.to_ascii_lowercase().as_str() {
383 "title" => location |= EncryptionIndicatorLocation::TITLE,
384 "prompt" => location |= EncryptionIndicatorLocation::PROMPT,
385 _ => {
386 return Err(E::custom("could not parse into an encryption indicator location"))
387 },
388 };
389 }
390
391 Ok(location)
392 }
393}
394
395impl<'de> Deserialize<'de> for EncryptionIndicatorLocation {
396 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
397 where
398 D: Deserializer<'de>,
399 {
400 deserializer.deserialize_str(EncryptionIndicatorLocationVisitor)
401 }
402}
403
404#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
405#[serde(rename_all = "lowercase")]
406pub enum UserDisplayStyle {
407 // The Matrix username for the sender (e.g., "@user:example.com").
408 #[default]
409 Username,
410
411 // The localpart of the Matrix username (e.g., "@user").
412 LocalPart,
413
414 // The display name for the Matrix user, calculated according to the rules from the spec.
415 //
416 // This is usually something like "Ada Lovelace" if the user has configured a display name, but
417 // it can wind up being the Matrix username if there are display name collisions in the room,
418 // in order to avoid any confusion.
419 DisplayName,
420}
421
422#[derive(Clone, Copy, Debug, Eq, PartialEq)]
423pub struct NotifyVia {
424 /// Deliver notifications via terminal bell.
425 pub bell: bool,
426 /// Deliver notifications via desktop mechanism.
427 #[cfg(feature = "desktop")]
428 pub desktop: bool,
429}
430pub struct NotifyViaVisitor;
431
432impl Default for NotifyVia {
433 fn default() -> Self {
434 Self {
435 bell: cfg!(not(feature = "desktop")),
436 #[cfg(feature = "desktop")]
437 desktop: true,
438 }
439 }
440}
441
442impl Visitor<'_> for NotifyViaVisitor {
443 type Value = NotifyVia;
444
445 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
446 formatter.write_str("a valid notify destination (e.g. \"bell\" or \"desktop\")")
447 }
448
449 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
450 where
451 E: SerdeError,
452 {
453 let mut via = NotifyVia {
454 bell: false,
455 #[cfg(feature = "desktop")]
456 desktop: false,
457 };
458
459 for value in value.split('|') {
460 match value.to_ascii_lowercase().as_str() {
461 "bell" => {
462 via.bell = true;
463 },
464 #[cfg(feature = "desktop")]
465 "desktop" => {
466 via.desktop = true;
467 },
468 #[cfg(not(feature = "desktop"))]
469 "desktop" => {
470 return Err(E::custom("desktop notification support was compiled out"))
471 },
472 _ => return Err(E::custom("could not parse into a notify destination")),
473 };
474 }
475
476 Ok(via)
477 }
478}
479
480impl<'de> Deserialize<'de> for NotifyVia {
481 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
482 where
483 D: Deserializer<'de>,
484 {
485 deserializer.deserialize_str(NotifyViaVisitor)
486 }
487}
488
489#[derive(Clone, Debug, Default, Deserialize)]
490pub struct Encryption {
491 indicator: Option<EncryptionIndicator>,
492 indicator_location: Option<EncryptionIndicatorLocation>,
493}
494
495impl Encryption {
496 fn merge(profile: Self, global: Self) -> Self {
497 Encryption {
498 indicator: profile.indicator.or(global.indicator),
499 indicator_location: profile.indicator_location.or(global.indicator_location),
500 }
501 }
502
503 pub fn values(self) -> EncryptionValues {
504 EncryptionValues {
505 indicator: self.indicator.unwrap_or_default(),
506 indicator_location: self.indicator_location.unwrap_or(DEFAULT_ENC_INDICATOR_LOC),
507 }
508 }
509}
510
511#[derive(Clone, Debug)]
512pub struct EncryptionValues {
513 pub indicator: EncryptionIndicator,
514 pub indicator_location: EncryptionIndicatorLocation,
515}
516
517impl EncryptionValues {
518 pub fn get_indicator(
519 &self,
520 location: EncryptionIndicatorLocation,
521 state: EncryptionState,
522 ) -> Option<Span<'static>> {
523 if !self.indicator_location.contains(location) {
524 return None;
525 }
526
527 let indicator = match (self.indicator, state) {
528 (EncryptionIndicator::Disabled, _) |
529 (EncryptionIndicator::OnlyUnencrypted, EncryptionState::Encrypted) |
530 (EncryptionIndicator::OnlyEncrypted, EncryptionState::NotEncrypted) => {
531 // User doesn't want to see anything:
532 return None;
533 },
534 (
535 EncryptionIndicator::Enabled | EncryptionIndicator::OnlyEncrypted,
536 EncryptionState::Encrypted,
537 ) => {
538 // Green lock:
539 Span::styled("\u{1F512}\u{FE0E} ", Style::new().fg(Color::LightGreen))
540 },
541 (
542 EncryptionIndicator::Enabled | EncryptionIndicator::OnlyUnencrypted,
543 EncryptionState::NotEncrypted,
544 ) => {
545 // Red unlocked lock:
546 Span::styled("\u{1F513}\u{FE0E} ", Style::new().fg(Color::Red))
547 },
548
549 (_, EncryptionState::Unknown) => {
550 // Yellow question mark:
551 Span::styled("? ", Style::new().fg(Color::Yellow))
552 },
553 };
554
555 Some(indicator)
556 }
557}
558
559#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
560pub struct Mouse {
561 #[serde(default)]
562 pub enabled: bool,
563}
564
565#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
566pub struct Notifications {
567 #[serde(default)]
568 pub enabled: bool,
569 #[serde(default)]
570 pub via: NotifyVia,
571 #[serde(default = "default_true")]
572 pub show_message: bool,
573 #[serde(default)]
574 pub sound_hint: Option<String>,
575}
576
577#[derive(Clone)]
578pub struct ImagePreviewValues {
579 pub size: ImagePreviewSize,
580 pub protocol: Option<ImagePreviewProtocolValues>,
581}
582
583#[derive(Clone, Default, Deserialize)]
584pub struct ImagePreview {
585 pub size: Option<ImagePreviewSize>,
586 pub protocol: Option<ImagePreviewProtocolValues>,
587}
588
589impl ImagePreview {
590 fn values(self) -> ImagePreviewValues {
591 ImagePreviewValues {
592 size: self.size.unwrap_or_default(),
593 protocol: self.protocol,
594 }
595 }
596}
597
598#[derive(Clone, Deserialize)]
599pub struct ImagePreviewSize {
600 pub width: usize,
601 pub height: usize,
602}
603
604impl Default for ImagePreviewSize {
605 fn default() -> Self {
606 ImagePreviewSize { width: 66, height: 10 }
607 }
608}
609
610#[derive(Clone, Deserialize)]
611pub struct ImagePreviewProtocolValues {
612 pub r#type: Option<ProtocolType>,
613 pub font_size: Option<(u16, u16)>,
614}
615
616#[derive(Clone)]
617pub struct SortValues {
618 pub chats: Vec<SortColumn<SortFieldRoom>>,
619 pub dms: Vec<SortColumn<SortFieldRoom>>,
620 pub rooms: Vec<SortColumn<SortFieldRoom>>,
621 pub spaces: Vec<SortColumn<SortFieldRoom>>,
622 pub members: Vec<SortColumn<SortFieldUser>>,
623}
624
625#[derive(Clone, Default, Deserialize)]
626pub struct SortOverrides {
627 pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
628 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
629 pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
630 pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
631 pub members: Option<Vec<SortColumn<SortFieldUser>>>,
632}
633
634impl SortOverrides {
635 fn merge(profile: Self, global: Self) -> Self {
636 Self {
637 chats: profile.chats.or(global.chats),
638 dms: profile.dms.or(global.dms),
639 rooms: profile.rooms.or(global.rooms),
640 spaces: profile.spaces.or(global.spaces),
641 members: profile.members.or(global.members),
642 }
643 }
644
645 pub fn values(self) -> SortValues {
646 let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
647 let chats = self.chats.unwrap_or_else(|| rooms.clone());
648 let dms = self.dms.unwrap_or_else(|| rooms.clone());
649 let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
650 let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
651
652 SortValues { rooms, members, chats, dms, spaces }
653 }
654}
655
656#[derive(Clone, Debug, Default, Deserialize)]
657pub struct Terminal {
658 pub enable_extended_keys: Option<bool>,
659 pub enable_title: Option<bool>,
660}
661
662impl Terminal {
663 fn merge(profile: Self, global: Self) -> Self {
664 Self {
665 enable_extended_keys: profile.enable_extended_keys.or(global.enable_extended_keys),
666 enable_title: profile.enable_title.or(global.enable_title),
667 }
668 }
669
670 pub fn values(self) -> TerminalValues {
671 TerminalValues {
672 enable_extended_keys: self.enable_extended_keys,
673 enable_title: self.enable_title.unwrap_or(DEFAULT_ENABLE_TITLE),
674 }
675 }
676}
677
678#[derive(Clone, Debug)]
679pub struct TerminalValues {
680 pub enable_extended_keys: Option<bool>,
681 pub enable_title: bool,
682}
683
684#[derive(Clone)]
685pub struct TunableValues {
686 pub encryption: EncryptionValues,
687 pub log_level: String,
688 pub max_log_files: usize,
689 pub message_shortcode_display: bool,
690 pub normal_after_send: bool,
691 pub reaction_display: bool,
692 pub reaction_shortcode_display: bool,
693 pub read_receipt_send: bool,
694 pub read_receipt_display: bool,
695 pub request_timeout: u64,
696 pub sort: SortValues,
697 pub state_event_display: bool,
698 pub typing_notice_send: bool,
699 pub typing_notice_display: bool,
700 pub users: UserOverrides,
701 pub username_display: UserDisplayStyle,
702 pub message_user_color: bool,
703 pub default_room: Option<String>,
704 pub open_command: Option<Vec<String>>,
705 pub mouse: Mouse,
706 pub notifications: Notifications,
707 pub terminal: TerminalValues,
708 pub image_preview: Option<ImagePreviewValues>,
709 pub user_gutter_width: usize,
710 pub external_edit_file_suffix: String,
711 pub tabstop: usize,
712 pub ssl_verify: bool,
713}
714
715#[derive(Clone, Default, Deserialize)]
716pub struct Tunables {
717 /// Subsection for overriding encryption-related settings.
718 #[serde(default)]
719 pub encryption: Encryption,
720
721 /// Subsection for overriding sort orders in UI lists.
722 #[serde(default)]
723 pub sort: SortOverrides,
724
725 /// Subsection for overriding terminal settings.
726 #[serde(default)]
727 pub terminal: Terminal,
728
729 /// Subsection for overriding how specific Matrix users are rendered.
730 pub users: Option<UserOverrides>,
731
732 pub log_level: Option<String>,
733 pub max_log_files: Option<usize>,
734 pub message_shortcode_display: Option<bool>,
735 pub normal_after_send: Option<bool>,
736 pub reaction_display: Option<bool>,
737 pub reaction_shortcode_display: Option<bool>,
738 pub read_receipt_send: Option<bool>,
739 pub read_receipt_display: Option<bool>,
740 pub request_timeout: Option<u64>,
741 pub state_event_display: Option<bool>,
742 pub typing_notice_send: Option<bool>,
743 pub typing_notice_display: Option<bool>,
744 pub username_display: Option<UserDisplayStyle>,
745 pub message_user_color: Option<bool>,
746 pub default_room: Option<String>,
747 pub open_command: Option<Vec<String>>,
748 pub mouse: Option<Mouse>,
749 pub notifications: Option<Notifications>,
750 pub image_preview: Option<ImagePreview>,
751 pub user_gutter_width: Option<usize>,
752 pub external_edit_file_suffix: Option<String>,
753 pub tabstop: Option<usize>,
754 pub ssl_verify: Option<bool>,
755}
756
757impl Tunables {
758 fn merge(self, other: Self) -> Self {
759 Tunables {
760 encryption: Encryption::merge(self.encryption, other.encryption),
761 sort: SortOverrides::merge(self.sort, other.sort),
762 terminal: Terminal::merge(self.terminal, other.terminal),
763 users: merge_maps(self.users, other.users),
764
765 log_level: self.log_level.or(other.log_level),
766 max_log_files: self.max_log_files.or(other.max_log_files),
767 message_shortcode_display: self
768 .message_shortcode_display
769 .or(other.message_shortcode_display),
770 normal_after_send: self.normal_after_send.or(other.normal_after_send),
771 reaction_display: self.reaction_display.or(other.reaction_display),
772 reaction_shortcode_display: self
773 .reaction_shortcode_display
774 .or(other.reaction_shortcode_display),
775 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
776 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
777 request_timeout: self.request_timeout.or(other.request_timeout),
778 state_event_display: self.state_event_display.or(other.state_event_display),
779 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
780 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
781 username_display: self.username_display.or(other.username_display),
782 message_user_color: self.message_user_color.or(other.message_user_color),
783 default_room: self.default_room.or(other.default_room),
784 open_command: self.open_command.or(other.open_command),
785 mouse: self.mouse.or(other.mouse),
786 notifications: self.notifications.or(other.notifications),
787 image_preview: self.image_preview.or(other.image_preview),
788 user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
789 external_edit_file_suffix: self
790 .external_edit_file_suffix
791 .or(other.external_edit_file_suffix),
792 tabstop: self.tabstop.or(other.tabstop),
793 ssl_verify: self.ssl_verify.or(other.ssl_verify),
794 }
795 }
796
797 fn values(self) -> TunableValues {
798 TunableValues {
799 encryption: self.encryption.values(),
800 sort: self.sort.values(),
801 terminal: self.terminal.values(),
802
803 log_level: self.log_level.unwrap_or_else(|| "warn".to_string()),
804 max_log_files: self.max_log_files.unwrap_or(7),
805 message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
806 normal_after_send: self.normal_after_send.unwrap_or(false),
807 reaction_display: self.reaction_display.unwrap_or(true),
808 reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
809 read_receipt_send: self.read_receipt_send.unwrap_or(true),
810 read_receipt_display: self.read_receipt_display.unwrap_or(true),
811 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
812 state_event_display: self.state_event_display.unwrap_or(true),
813 typing_notice_send: self.typing_notice_send.unwrap_or(true),
814 typing_notice_display: self.typing_notice_display.unwrap_or(true),
815 users: self.users.unwrap_or_default(),
816 username_display: self.username_display.unwrap_or_default(),
817 message_user_color: self.message_user_color.unwrap_or(false),
818 default_room: self.default_room,
819 open_command: self.open_command,
820 mouse: self.mouse.unwrap_or_default(),
821 notifications: self.notifications.unwrap_or_default(),
822 image_preview: self.image_preview.map(ImagePreview::values),
823 user_gutter_width: self.user_gutter_width.unwrap_or(30),
824 external_edit_file_suffix: self
825 .external_edit_file_suffix
826 .unwrap_or_else(|| ".md".to_string()),
827 tabstop: self.tabstop.unwrap_or(4),
828 ssl_verify: self.ssl_verify.unwrap_or(true),
829 }
830 }
831}
832
833#[derive(Clone)]
834pub struct DirectoryValues {
835 pub cache: PathBuf,
836 pub data: PathBuf,
837 pub logs: PathBuf,
838 pub downloads: Option<PathBuf>,
839 pub image_previews: PathBuf,
840}
841
842impl DirectoryValues {
843 fn create_dir_all(&self) -> std::io::Result<()> {
844 use std::fs::create_dir_all;
845
846 let Self { cache, data, logs, downloads, image_previews } = self;
847
848 create_dir_all(cache)?;
849 create_dir_all(data)?;
850 create_dir_all(logs)?;
851 create_dir_all(image_previews)?;
852
853 if let Some(downloads) = downloads {
854 create_dir_all(downloads)?;
855 }
856
857 Ok(())
858 }
859}
860
861#[derive(Clone, Default, Deserialize)]
862pub struct Directories {
863 pub cache: Option<String>,
864 pub data: Option<String>,
865 pub logs: Option<String>,
866 pub downloads: Option<String>,
867 pub image_previews: Option<String>,
868}
869
870impl Directories {
871 fn merge(self, other: Self) -> Self {
872 Directories {
873 cache: self.cache.or(other.cache),
874 data: self.data.or(other.data),
875 logs: self.logs.or(other.logs),
876 downloads: self.downloads.or(other.downloads),
877 image_previews: self.image_previews.or(other.image_previews),
878 }
879 }
880
881 fn values(self) -> DirectoryValues {
882 let cache = self
883 .cache
884 .map(|dir| {
885 let dir = shellexpand::full(&dir)
886 .expect("unable to expand shell variables in dirs.cache");
887 Path::new(dir.as_ref()).to_owned()
888 })
889 .or_else(|| {
890 let mut dir = dirs::cache_dir()?;
891 dir.push("iamb");
892 dir.into()
893 })
894 .expect("no dirs.cache value configured!");
895
896 let data = self
897 .data
898 .map(|dir| {
899 let dir = shellexpand::full(&dir)
900 .expect("unable to expand shell variables in dirs.cache");
901 Path::new(dir.as_ref()).to_owned()
902 })
903 .or_else(|| {
904 let mut dir = dirs::data_dir()?;
905 dir.push("iamb");
906 dir.into()
907 })
908 .expect("no dirs.data value configured!");
909
910 let logs = self
911 .logs
912 .map(|dir| {
913 let dir = shellexpand::full(&dir)
914 .expect("unable to expand shell variables in dirs.cache");
915 Path::new(dir.as_ref()).to_owned()
916 })
917 .unwrap_or_else(|| {
918 let mut dir = cache.clone();
919 dir.push("logs");
920 dir
921 });
922
923 let downloads = self
924 .downloads
925 .map(|dir| {
926 let dir = shellexpand::full(&dir)
927 .expect("unable to expand shell variables in dirs.cache");
928 Path::new(dir.as_ref()).to_owned()
929 })
930 .or_else(dirs::download_dir);
931
932 let image_previews = self
933 .image_previews
934 .map(|dir| {
935 let dir = shellexpand::full(&dir)
936 .expect("unable to expand shell variables in dirs.cache");
937 Path::new(dir.as_ref()).to_owned()
938 })
939 .unwrap_or_else(|| {
940 let mut dir = cache.clone();
941 dir.push("image_preview_downloads");
942 dir
943 });
944
945 DirectoryValues { cache, data, logs, downloads, image_previews }
946 }
947}
948
949#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
950#[serde(untagged)]
951pub enum WindowPath {
952 AliasId(OwnedRoomAliasId),
953 RoomId(OwnedRoomId),
954 UserId(OwnedUserId),
955 Window(IambId),
956}
957
958#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
959#[serde(untagged, deny_unknown_fields)]
960pub enum WindowLayout {
961 Window { window: WindowPath },
962 Split { split: Vec<WindowLayout> },
963}
964
965#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
966#[serde(rename_all = "lowercase", tag = "style")]
967pub enum Layout {
968 /// Restore the layout from the previous session.
969 #[default]
970 Restore,
971
972 /// Open a single window using the `default_room` value.
973 New,
974
975 /// Open the window layouts described under `tabs`.
976 Config { tabs: Vec<WindowLayout> },
977}
978
979#[derive(Clone, Deserialize)]
980pub struct ProfileConfig {
981 pub user_id: OwnedUserId,
982 pub password_file: Option<PathBuf>,
983 pub url: Option<Url>,
984 pub settings: Option<Tunables>,
985 pub dirs: Option<Directories>,
986 pub layout: Option<Layout>,
987 pub macros: Option<Macros>,
988}
989
990#[derive(Clone, Deserialize)]
991pub struct IambConfig {
992 pub profiles: BTreeMap<String, ProfileConfig>,
993 pub default_profile: Option<String>,
994 pub settings: Option<Tunables>,
995 pub dirs: Option<Directories>,
996 pub layout: Option<Layout>,
997 pub macros: Option<Macros>,
998}
999
1000impl IambConfig {
1001 pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
1002 let s = std::fs::read_to_string(path)?;
1003 let config = toml::from_str(&s)?;
1004
1005 Ok(config)
1006 }
1007
1008 pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
1009 let s = std::fs::read_to_string(path)?;
1010 let config = serde_json::from_str(&s)?;
1011
1012 Ok(config)
1013 }
1014}
1015
1016#[derive(Clone)]
1017pub struct ApplicationSettings {
1018 pub layout_json: PathBuf,
1019 pub session_json: PathBuf,
1020 pub session_json_old: PathBuf,
1021 pub sled_dir: PathBuf,
1022 pub sqlite_dir: PathBuf,
1023 pub profile_name: String,
1024 pub profile: ProfileConfig,
1025 pub tunables: TunableValues,
1026 pub dirs: DirectoryValues,
1027 pub layout: Layout,
1028 pub macros: Macros,
1029}
1030
1031impl ApplicationSettings {
1032 fn get_xdg_config_home() -> Option<PathBuf> {
1033 env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
1034 }
1035
1036 pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
1037 let mut config_dir = cli
1038 .config_directory
1039 .or_else(Self::get_xdg_config_home)
1040 .or_else(dirs::config_dir)
1041 .unwrap_or_else(|| {
1042 usage!(
1043 "No user configuration directory found;\
1044 please specify one via -C.\n\n
1045 For more information try '--help'"
1046 );
1047 });
1048
1049 config_dir.push("iamb");
1050 let config_json = config_dir.join("config.json");
1051 let config_toml = config_dir.join("config.toml");
1052
1053 let config = if config_toml.is_file() {
1054 IambConfig::load_toml(config_toml.as_path())?
1055 } else if config_json.is_file() {
1056 IambConfig::load_json(config_json.as_path())?
1057 } else {
1058 usage!(
1059 "Please create a configuration file at {}\n\n\
1060 For more information try '--help'",
1061 config_toml.display(),
1062 );
1063 };
1064
1065 let IambConfig {
1066 mut profiles,
1067 default_profile,
1068 dirs,
1069 settings: global,
1070 layout,
1071 macros,
1072 } = config;
1073
1074 validate_profile_names(&profiles);
1075
1076 let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
1077 profiles.remove_entry(&profile).unwrap_or_else(|| {
1078 usage!(
1079 "No configured profile with the name {:?} in {}",
1080 profile,
1081 config_json.display()
1082 );
1083 })
1084 } else if profiles.len() == 1 {
1085 profiles.into_iter().next().unwrap()
1086 } else {
1087 loop {
1088 println!("\nNo profile specified. Available profiles:");
1089 profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
1090
1091 print!("Select a number or 'q' to quit: ");
1092 let _ = std::io::stdout().flush();
1093
1094 let mut input = String::new();
1095 let _ = std::io::stdin().read_line(&mut input);
1096
1097 if input.trim() == "q" {
1098 usage!(
1099 "No profile specified. \
1100 Please use -P or add \"default_profile\" to your configuration.\n\n\
1101 For more information try '--help'",
1102 );
1103 }
1104 if let Ok(i) = input.trim().parse::<usize>() {
1105 if i < profiles.len() {
1106 break profiles.into_iter().nth(i).unwrap();
1107 }
1108 }
1109 println!("\nInvalid index.");
1110 }
1111 };
1112
1113 let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
1114 let layout = profile.layout.take().or(layout).unwrap_or_default();
1115
1116 let tunables = global.unwrap_or_default();
1117 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
1118 let tunables = tunables.values();
1119
1120 let dirs = dirs.unwrap_or_default();
1121 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
1122 let dirs = dirs.values();
1123
1124 // Create directories
1125 dirs.create_dir_all()?;
1126
1127 // Set up paths that live inside the profile's data directory.
1128 let mut profile_dir = config_dir.clone();
1129 profile_dir.push("profiles");
1130 profile_dir.push(profile_name.as_str());
1131
1132 let mut profile_data_dir = dirs.data.clone();
1133 profile_data_dir.push("profiles");
1134 profile_data_dir.push(profile_name.as_str());
1135
1136 let mut sled_dir = profile_dir.clone();
1137 sled_dir.push("matrix");
1138
1139 let mut sqlite_dir = profile_data_dir.clone();
1140 sqlite_dir.push("sqlite");
1141
1142 let mut session_json = profile_data_dir.clone();
1143 session_json.push("session.json");
1144
1145 let mut session_json_old = profile_dir;
1146 session_json_old.push("session.json");
1147
1148 // Set up paths that live inside the profile's cache directory.
1149 let mut cache_dir = dirs.cache.clone();
1150 cache_dir.push("profiles");
1151 cache_dir.push(profile_name.as_str());
1152
1153 let mut layout_json = cache_dir.clone();
1154 layout_json.push("layout.json");
1155
1156 let settings = ApplicationSettings {
1157 sled_dir,
1158 layout_json,
1159 session_json,
1160 session_json_old,
1161 sqlite_dir,
1162 profile_name,
1163 profile,
1164 tunables,
1165 dirs,
1166 layout,
1167 macros,
1168 };
1169
1170 Ok(settings)
1171 }
1172
1173 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1174 let file = File::open(path)?;
1175 let reader = BufReader::new(file);
1176 let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1177 Ok(session)
1178 }
1179
1180 pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
1181 let file = File::create(self.session_json.as_path())?;
1182 let writer = BufWriter::new(file);
1183 let session = Session::from(session);
1184 serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1185 Ok(())
1186 }
1187
1188 pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
1189 let (color, c) = self
1190 .tunables
1191 .users
1192 .get(user_id)
1193 .map(|user| {
1194 (
1195 user.color.as_ref().map(|c| c.0),
1196 user.name.as_ref().and_then(|s| s.chars().next()),
1197 )
1198 })
1199 .unwrap_or_default();
1200
1201 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1202 let style = user_style_from_color(color);
1203
1204 let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1205
1206 Span::styled(String::from(c), style)
1207 }
1208
1209 pub fn get_user_overrides(
1210 &self,
1211 user_id: &UserId,
1212 ) -> (Option<Color>, Option<Cow<'static, str>>) {
1213 self.tunables
1214 .users
1215 .get(user_id)
1216 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1217 .unwrap_or_default()
1218 }
1219
1220 pub fn get_user_color(&self, user_id: &UserId) -> Color {
1221 self.tunables
1222 .users
1223 .get(user_id)
1224 .and_then(|user| user.color.as_ref().map(|c| c.0))
1225 .unwrap_or_else(|| user_color(user_id.as_str()))
1226 }
1227
1228 pub fn get_user_style(&self, user_id: &UserId) -> Style {
1229 user_style_from_color(self.get_user_color(user_id))
1230 }
1231
1232 pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1233 let (color, name) = self.get_user_overrides(user_id);
1234
1235 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1236 let style = user_style_from_color(color);
1237 let name = match (name, &self.tunables.username_display) {
1238 (Some(name), _) => name,
1239 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1240 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1241 (None, UserDisplayStyle::DisplayName) => {
1242 if let Some(name) = info.display_names.get(user_id) {
1243 name
1244 } else {
1245 Cow::Borrowed(user_id.as_str())
1246 }
1247 },
1248 };
1249
1250 Span::styled(name, style)
1251 }
1252}
1253
1254#[cfg(test)]
1255mod tests {
1256 use super::*;
1257 use matrix_sdk::ruma::user_id;
1258 use std::convert::TryFrom;
1259
1260 #[test]
1261 fn test_profile_name_invalid() {
1262 assert_eq!(validate_profile_name(""), false);
1263 assert_eq!(validate_profile_name(" "), false);
1264 assert_eq!(validate_profile_name("a b"), false);
1265 assert_eq!(validate_profile_name("foo^bar"), false);
1266 assert_eq!(validate_profile_name("FOO/BAR"), false);
1267 assert_eq!(validate_profile_name("-b-c"), false);
1268 assert_eq!(validate_profile_name("-B-c"), false);
1269 assert_eq!(validate_profile_name(".b-c"), false);
1270 assert_eq!(validate_profile_name(".B-c"), false);
1271 }
1272
1273 #[test]
1274 fn test_profile_name_valid() {
1275 assert_eq!(validate_profile_name("foo"), true);
1276 assert_eq!(validate_profile_name("FOO"), true);
1277 assert_eq!(validate_profile_name("a-b-c"), true);
1278 assert_eq!(validate_profile_name("a-B-c"), true);
1279 assert_eq!(validate_profile_name("a.b-c"), true);
1280 assert_eq!(validate_profile_name("a.B-c"), true);
1281 }
1282
1283 #[test]
1284 fn test_merge_users() {
1285 let a = None;
1286 let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1287 color: Some(UserColor(Color::Red)),
1288 name: Some("Hello".into()),
1289 })]
1290 .into_iter()
1291 .collect::<HashMap<_, _>>();
1292 let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1293 color: Some(UserColor(Color::Green)),
1294 name: Some("World".into()),
1295 })]
1296 .into_iter()
1297 .collect::<HashMap<_, _>>();
1298
1299 let res = merge_maps(a.clone(), a.clone());
1300 assert_eq!(res, None);
1301
1302 let res = merge_maps(a.clone(), Some(b.clone()));
1303 assert_eq!(res, Some(b.clone()));
1304
1305 let res = merge_maps(Some(b.clone()), a.clone());
1306 assert_eq!(res, Some(b.clone()));
1307
1308 let res = merge_maps(Some(b.clone()), Some(b.clone()));
1309 assert_eq!(res, Some(b.clone()));
1310
1311 let res = merge_maps(Some(b.clone()), Some(c.clone()));
1312 assert_eq!(res, Some(b.clone()));
1313
1314 let res = merge_maps(Some(c.clone()), Some(b.clone()));
1315 assert_eq!(res, Some(c.clone()));
1316 }
1317
1318 #[test]
1319 fn test_parse_tunables() {
1320 let res: Tunables = serde_json::from_str("{}").unwrap();
1321 assert_eq!(res.typing_notice_send, None);
1322 assert_eq!(res.typing_notice_display, None);
1323 assert_eq!(res.users, None);
1324
1325 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1326 assert_eq!(res.typing_notice_send, Some(true));
1327 assert_eq!(res.typing_notice_display, None);
1328 assert_eq!(res.users, None);
1329
1330 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1331 assert_eq!(res.typing_notice_send, Some(false));
1332 assert_eq!(res.typing_notice_display, None);
1333 assert_eq!(res.users, None);
1334
1335 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1336 assert_eq!(res.typing_notice_send, None);
1337 assert_eq!(res.typing_notice_display, None);
1338 assert_eq!(res.users, Some(HashMap::new()));
1339
1340 let res: Tunables = serde_json::from_str(
1341 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1342 )
1343 .unwrap();
1344 assert_eq!(res.typing_notice_send, None);
1345 assert_eq!(res.typing_notice_display, None);
1346 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1347 color: Some(UserColor(Color::Black)),
1348 name: Some("Tim".into()),
1349 })];
1350 assert_eq!(res.users, Some(users.into_iter().collect()));
1351 }
1352
1353 #[test]
1354 fn test_parse_tunables_username_display() {
1355 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1356 assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1357
1358 let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1359 assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1360
1361 let res: Tunables =
1362 serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1363 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1364 }
1365
1366 #[test]
1367 fn test_parse_tunables_sort() {
1368 let res: Tunables = serde_json::from_str(
1369 r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1370 )
1371 .unwrap();
1372 assert_eq!(
1373 res.sort.members,
1374 Some(vec![
1375 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1376 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1377 ])
1378 );
1379 assert_eq!(
1380 res.sort.spaces,
1381 Some(vec![
1382 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1383 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1384 ])
1385 );
1386 assert_eq!(res.sort.rooms, None);
1387 assert_eq!(res.sort.dms, None);
1388
1389 // Check that we get the right default "rooms" and "dms" values.
1390 let res = res.values();
1391 assert_eq!(res.sort.members, vec![
1392 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1393 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1394 ]);
1395 assert_eq!(res.sort.spaces, vec![
1396 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1397 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1398 ]);
1399 assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1400 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1401 }
1402
1403 #[test]
1404 fn test_parse_layout() {
1405 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1406 let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1407 let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1408 let dms = WindowPath::Window(IambId::DirectList);
1409 let welcome = WindowPath::Window(IambId::Welcome);
1410
1411 let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1412 assert_eq!(res, Layout::Restore);
1413
1414 let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1415 assert_eq!(res, Layout::New);
1416
1417 let res: Layout = serde_json::from_str(
1418 "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1419 )
1420 .unwrap();
1421 assert_eq!(res, Layout::Config {
1422 tabs: vec![WindowLayout::Window { window: user.clone() }]
1423 });
1424
1425 let res: Layout = serde_json::from_str(
1426 "{\
1427 \"style\": \"config\",\
1428 \"tabs\": [\
1429 {\"split\":[\
1430 {\"window\":\"@user:example.com\"},\
1431 {\"window\":\"#room:example.com\"}\
1432 ]},\
1433 {\"split\":[\
1434 {\"window\":\"!room:example.com\"},\
1435 {\"split\":[\
1436 {\"window\":\"iamb://dms\"},\
1437 {\"window\":\"iamb://welcome\"}\
1438 ]}\
1439 ]}\
1440 ]}",
1441 )
1442 .unwrap();
1443 let split1 = WindowLayout::Split {
1444 split: vec![
1445 WindowLayout::Window { window: user.clone() },
1446 WindowLayout::Window { window: alias },
1447 ],
1448 };
1449 let split2 = WindowLayout::Split {
1450 split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1451 window: welcome,
1452 }],
1453 };
1454 let split3 = WindowLayout::Split {
1455 split: vec![WindowLayout::Window { window: room }, split2],
1456 };
1457 let tabs = vec![split1, split3];
1458 assert_eq!(res, Layout::Config { tabs });
1459 }
1460
1461 #[test]
1462 fn test_parse_macros() {
1463 let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1464 assert_eq!(res.len(), 1);
1465
1466 let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1467 let mapped = res.get(&modes).unwrap();
1468 assert_eq!(mapped.len(), 1);
1469
1470 let j = "j".parse::<TerminalKey>().unwrap();
1471 let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1472
1473 let jj = Keys(vec![j, j], "jj".into());
1474 let run = mapped.get(&jj).unwrap();
1475 let exp = Keys(vec![esc], "<Esc>".into());
1476 assert_eq!(run, &exp);
1477 }
1478
1479 #[test]
1480 fn test_parse_notify_via() {
1481 assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1482 assert_eq!(
1483 NotifyVia { bell: false, desktop: true },
1484 serde_json::from_str(r#""desktop""#).unwrap()
1485 );
1486 assert_eq!(
1487 NotifyVia { bell: true, desktop: false },
1488 serde_json::from_str(r#""bell""#).unwrap()
1489 );
1490 assert_eq!(
1491 NotifyVia { bell: true, desktop: true },
1492 serde_json::from_str(r#""bell|desktop""#).unwrap()
1493 );
1494 assert_eq!(
1495 NotifyVia { bell: true, desktop: true },
1496 serde_json::from_str(r#""desktop|bell""#).unwrap()
1497 );
1498 assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1499 assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1500 }
1501
1502 #[test]
1503 fn test_load_example_config_toml() {
1504 let path = PathBuf::from("config.example.toml");
1505 let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1506
1507 let IambConfig {
1508 profiles,
1509 default_profile,
1510 settings,
1511 dirs,
1512 layout,
1513 macros,
1514 } = &config;
1515
1516 // There should be an example object for each top-level field.
1517 assert!(!profiles.is_empty());
1518 assert!(default_profile.is_some());
1519 assert!(settings.is_some());
1520 assert!(dirs.is_some());
1521 assert!(layout.is_some());
1522 assert!(macros.is_some());
1523 }
1524
1525 #[test]
1526 fn test_encryption_indicator_enabled() {
1527 use EncryptionState::*;
1528
1529 let enc = EncryptionValues {
1530 indicator: EncryptionIndicator::Enabled,
1531 indicator_location: EncryptionIndicatorLocation::TITLE,
1532 };
1533
1534 // Always shows in the title:
1535 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
1536 assert!(enc
1537 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1538 .is_some());
1539 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1540
1541 // Doesn't show in the prompt:
1542 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1543 assert!(enc
1544 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1545 .is_none());
1546 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1547 }
1548
1549 #[test]
1550 fn test_encryption_indicator_disabled() {
1551 use EncryptionState::*;
1552
1553 let enc = EncryptionValues {
1554 indicator: EncryptionIndicator::Disabled,
1555 indicator_location: EncryptionIndicatorLocation::TITLE,
1556 };
1557
1558 // Never shows in the title or the prompt:
1559 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1560 assert!(enc
1561 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1562 .is_none());
1563 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1564 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1565 assert!(enc
1566 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1567 .is_none());
1568 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1569 }
1570
1571 #[test]
1572 fn test_encryption_indicator_only_encrypted() {
1573 use EncryptionState::*;
1574
1575 let enc = EncryptionValues {
1576 indicator: EncryptionIndicator::OnlyEncrypted,
1577 indicator_location: EncryptionIndicatorLocation::PROMPT,
1578 };
1579
1580 // Shows in the prompt when encrypted or unknown:
1581 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_some());
1582 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1583
1584 // But is hidden when unencrypted:
1585 assert!(enc
1586 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1587 .is_none());
1588
1589 // Doesn't show in the title:
1590 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1591 assert!(enc
1592 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1593 .is_none());
1594 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1595 }
1596 #[test]
1597 fn test_encryption_indicator_only_unencrypted() {
1598 use EncryptionState::*;
1599
1600 let enc = EncryptionValues {
1601 indicator: EncryptionIndicator::OnlyUnencrypted,
1602 indicator_location: EncryptionIndicatorLocation::all(),
1603 };
1604
1605 // Shows in both the prompt and title when unencrypted or unknown:
1606 assert!(enc
1607 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1608 .is_some());
1609 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1610 assert!(enc
1611 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1612 .is_some());
1613 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1614
1615 // But is hidden when encrypted:
1616 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1617 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1618 }
1619}