src/config.rs
1653 lines · 55272 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, Default, Deserialize, Eq, PartialEq)]
423#[serde(rename_all = "lowercase")]
424pub enum SplitDirection {
425 #[default]
426 Horizontal,
427 Vertical,
428}
429
430#[derive(Clone, Copy, Debug, Eq, PartialEq)]
431pub struct NotifyVia {
432 /// Deliver notifications via terminal bell.
433 pub bell: bool,
434 /// Deliver notifications via desktop mechanism.
435 #[cfg(feature = "desktop")]
436 pub desktop: bool,
437}
438pub struct NotifyViaVisitor;
439
440impl Default for NotifyVia {
441 fn default() -> Self {
442 Self {
443 bell: cfg!(not(feature = "desktop")),
444 #[cfg(feature = "desktop")]
445 desktop: true,
446 }
447 }
448}
449
450impl Visitor<'_> for NotifyViaVisitor {
451 type Value = NotifyVia;
452
453 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
454 formatter.write_str("a valid notify destination (e.g. \"bell\" or \"desktop\")")
455 }
456
457 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
458 where
459 E: SerdeError,
460 {
461 let mut via = NotifyVia {
462 bell: false,
463 #[cfg(feature = "desktop")]
464 desktop: false,
465 };
466
467 for value in value.split('|') {
468 match value.to_ascii_lowercase().as_str() {
469 "bell" => {
470 via.bell = true;
471 },
472 #[cfg(feature = "desktop")]
473 "desktop" => {
474 via.desktop = true;
475 },
476 #[cfg(not(feature = "desktop"))]
477 "desktop" => {
478 return Err(E::custom("desktop notification support was compiled out"))
479 },
480 _ => return Err(E::custom("could not parse into a notify destination")),
481 };
482 }
483
484 Ok(via)
485 }
486}
487
488impl<'de> Deserialize<'de> for NotifyVia {
489 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
490 where
491 D: Deserializer<'de>,
492 {
493 deserializer.deserialize_str(NotifyViaVisitor)
494 }
495}
496
497#[derive(Clone, Debug, Default, Deserialize)]
498pub struct Encryption {
499 indicator: Option<EncryptionIndicator>,
500 indicator_location: Option<EncryptionIndicatorLocation>,
501}
502
503impl Encryption {
504 fn merge(profile: Self, global: Self) -> Self {
505 Encryption {
506 indicator: profile.indicator.or(global.indicator),
507 indicator_location: profile.indicator_location.or(global.indicator_location),
508 }
509 }
510
511 pub fn values(self) -> EncryptionValues {
512 EncryptionValues {
513 indicator: self.indicator.unwrap_or_default(),
514 indicator_location: self.indicator_location.unwrap_or(DEFAULT_ENC_INDICATOR_LOC),
515 }
516 }
517}
518
519#[derive(Clone, Debug)]
520pub struct EncryptionValues {
521 pub indicator: EncryptionIndicator,
522 pub indicator_location: EncryptionIndicatorLocation,
523}
524
525impl EncryptionValues {
526 pub fn get_indicator(
527 &self,
528 location: EncryptionIndicatorLocation,
529 state: EncryptionState,
530 ) -> Option<Span<'static>> {
531 if !self.indicator_location.contains(location) {
532 return None;
533 }
534
535 let indicator = match (self.indicator, state) {
536 (EncryptionIndicator::Disabled, _) |
537 (EncryptionIndicator::OnlyUnencrypted, EncryptionState::Encrypted) |
538 (EncryptionIndicator::OnlyEncrypted, EncryptionState::NotEncrypted) => {
539 // User doesn't want to see anything:
540 return None;
541 },
542 (
543 EncryptionIndicator::Enabled | EncryptionIndicator::OnlyEncrypted,
544 EncryptionState::Encrypted,
545 ) => {
546 // Green lock:
547 Span::styled("\u{1F512}\u{FE0E} ", Style::new().fg(Color::LightGreen))
548 },
549 (
550 EncryptionIndicator::Enabled | EncryptionIndicator::OnlyUnencrypted,
551 EncryptionState::NotEncrypted,
552 ) => {
553 // Red unlocked lock:
554 Span::styled("\u{1F513}\u{FE0E} ", Style::new().fg(Color::Red))
555 },
556
557 (_, EncryptionState::Unknown) => {
558 // Yellow question mark:
559 Span::styled("? ", Style::new().fg(Color::Yellow))
560 },
561 };
562
563 Some(indicator)
564 }
565}
566
567#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
568pub struct Mouse {
569 #[serde(default)]
570 pub enabled: bool,
571}
572
573#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
574pub struct Notifications {
575 #[serde(default)]
576 pub enabled: bool,
577 #[serde(default)]
578 pub via: NotifyVia,
579 #[serde(default = "default_true")]
580 pub show_message: bool,
581 #[serde(default)]
582 pub sound_hint: Option<String>,
583}
584
585#[derive(Clone)]
586pub struct ImagePreviewValues {
587 pub lazy_load: bool,
588 pub size: ImagePreviewSize,
589 pub protocol: Option<ImagePreviewProtocolValues>,
590}
591
592#[derive(Clone, Default, Deserialize)]
593pub struct ImagePreview {
594 pub lazy_load: Option<bool>,
595 pub size: Option<ImagePreviewSize>,
596 pub protocol: Option<ImagePreviewProtocolValues>,
597}
598
599impl ImagePreview {
600 fn values(self) -> ImagePreviewValues {
601 ImagePreviewValues {
602 lazy_load: self.lazy_load.unwrap_or(true),
603 size: self.size.unwrap_or_default(),
604 protocol: self.protocol,
605 }
606 }
607}
608
609#[derive(Clone, Copy, Deserialize, Debug)]
610pub struct ImagePreviewSize {
611 pub width: usize,
612 pub height: usize,
613}
614
615impl Default for ImagePreviewSize {
616 fn default() -> Self {
617 ImagePreviewSize { width: 66, height: 10 }
618 }
619}
620
621#[derive(Clone, Deserialize)]
622pub struct ImagePreviewProtocolValues {
623 pub r#type: Option<ProtocolType>,
624 pub font_size: Option<(u16, u16)>,
625}
626
627#[derive(Clone)]
628pub struct SortValues {
629 pub chats: Vec<SortColumn<SortFieldRoom>>,
630 pub dms: Vec<SortColumn<SortFieldRoom>>,
631 pub rooms: Vec<SortColumn<SortFieldRoom>>,
632 pub spaces: Vec<SortColumn<SortFieldRoom>>,
633 pub members: Vec<SortColumn<SortFieldUser>>,
634}
635
636#[derive(Clone, Default, Deserialize)]
637pub struct SortOverrides {
638 pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
639 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
640 pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
641 pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
642 pub members: Option<Vec<SortColumn<SortFieldUser>>>,
643}
644
645impl SortOverrides {
646 fn merge(profile: Self, global: Self) -> Self {
647 Self {
648 chats: profile.chats.or(global.chats),
649 dms: profile.dms.or(global.dms),
650 rooms: profile.rooms.or(global.rooms),
651 spaces: profile.spaces.or(global.spaces),
652 members: profile.members.or(global.members),
653 }
654 }
655
656 pub fn values(self) -> SortValues {
657 let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
658 let chats = self.chats.unwrap_or_else(|| rooms.clone());
659 let dms = self.dms.unwrap_or_else(|| rooms.clone());
660 let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
661 let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
662
663 SortValues { rooms, members, chats, dms, spaces }
664 }
665}
666
667#[derive(Clone, Debug, Default, Deserialize)]
668pub struct Terminal {
669 pub cursor_shape: Option<CursorShape>,
670 pub enable_extended_keys: Option<bool>,
671 pub enable_title: Option<bool>,
672}
673
674impl Terminal {
675 fn merge(profile: Self, global: Self) -> Self {
676 Self {
677 cursor_shape: profile.cursor_shape.or(global.cursor_shape),
678 enable_extended_keys: profile.enable_extended_keys.or(global.enable_extended_keys),
679 enable_title: profile.enable_title.or(global.enable_title),
680 }
681 }
682
683 pub fn values(self) -> TerminalValues {
684 TerminalValues {
685 cursor_shape: self.cursor_shape.unwrap_or_default(),
686 enable_extended_keys: self.enable_extended_keys,
687 enable_title: self.enable_title.unwrap_or(DEFAULT_ENABLE_TITLE),
688 }
689 }
690}
691
692#[derive(Clone, Debug)]
693pub struct TerminalValues {
694 pub cursor_shape: CursorShape,
695 pub enable_extended_keys: Option<bool>,
696 pub enable_title: bool,
697}
698
699#[derive(Clone)]
700pub struct TunableValues {
701 pub encryption: EncryptionValues,
702 pub log_level: String,
703 pub max_log_files: usize,
704 pub message_shortcode_display: bool,
705 pub normal_after_send: bool,
706 pub reaction_display: bool,
707 pub reaction_shortcode_display: bool,
708 pub read_receipt_send: bool,
709 pub read_receipt_display: bool,
710 pub request_timeout: u64,
711 pub sort: SortValues,
712 pub state_event_display: bool,
713 pub typing_notice_send: bool,
714 pub typing_notice_display: bool,
715 pub users: UserOverrides,
716 pub username_display: UserDisplayStyle,
717 pub message_user_color: bool,
718 pub default_room: Option<String>,
719 pub open_command: Option<Vec<String>>,
720 pub mouse: Mouse,
721 pub notifications: Notifications,
722 pub terminal: TerminalValues,
723 pub image_preview: Option<ImagePreviewValues>,
724 pub user_gutter_width: usize,
725 pub external_edit_file_suffix: String,
726 pub tabstop: usize,
727 pub default_split: SplitDirection,
728 pub ssl_verify: bool,
729}
730
731#[derive(Clone, Default, Deserialize)]
732pub struct Tunables {
733 /// Subsection for overriding encryption-related settings.
734 #[serde(default)]
735 pub encryption: Encryption,
736
737 /// Subsection for overriding sort orders in UI lists.
738 #[serde(default)]
739 pub sort: SortOverrides,
740
741 /// Subsection for overriding terminal settings.
742 #[serde(default)]
743 pub terminal: Terminal,
744
745 /// Subsection for overriding how specific Matrix users are rendered.
746 pub users: Option<UserOverrides>,
747
748 pub log_level: Option<String>,
749 pub max_log_files: Option<usize>,
750 pub message_shortcode_display: Option<bool>,
751 pub normal_after_send: Option<bool>,
752 pub reaction_display: Option<bool>,
753 pub reaction_shortcode_display: Option<bool>,
754 pub read_receipt_send: Option<bool>,
755 pub read_receipt_display: Option<bool>,
756 pub request_timeout: Option<u64>,
757 pub state_event_display: Option<bool>,
758 pub typing_notice_send: Option<bool>,
759 pub typing_notice_display: Option<bool>,
760 pub username_display: Option<UserDisplayStyle>,
761 pub message_user_color: Option<bool>,
762 pub default_room: Option<String>,
763 pub open_command: Option<Vec<String>>,
764 pub mouse: Option<Mouse>,
765 pub notifications: Option<Notifications>,
766 pub image_preview: Option<ImagePreview>,
767 pub user_gutter_width: Option<usize>,
768 pub external_edit_file_suffix: Option<String>,
769 pub tabstop: Option<usize>,
770 pub default_split: Option<SplitDirection>,
771 pub ssl_verify: Option<bool>,
772}
773
774impl Tunables {
775 fn merge(self, other: Self) -> Self {
776 Tunables {
777 encryption: Encryption::merge(self.encryption, other.encryption),
778 sort: SortOverrides::merge(self.sort, other.sort),
779 terminal: Terminal::merge(self.terminal, other.terminal),
780 users: merge_maps(self.users, other.users),
781
782 log_level: self.log_level.or(other.log_level),
783 max_log_files: self.max_log_files.or(other.max_log_files),
784 message_shortcode_display: self
785 .message_shortcode_display
786 .or(other.message_shortcode_display),
787 normal_after_send: self.normal_after_send.or(other.normal_after_send),
788 reaction_display: self.reaction_display.or(other.reaction_display),
789 reaction_shortcode_display: self
790 .reaction_shortcode_display
791 .or(other.reaction_shortcode_display),
792 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
793 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
794 request_timeout: self.request_timeout.or(other.request_timeout),
795 state_event_display: self.state_event_display.or(other.state_event_display),
796 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
797 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
798 username_display: self.username_display.or(other.username_display),
799 message_user_color: self.message_user_color.or(other.message_user_color),
800 default_room: self.default_room.or(other.default_room),
801 open_command: self.open_command.or(other.open_command),
802 mouse: self.mouse.or(other.mouse),
803 notifications: self.notifications.or(other.notifications),
804 image_preview: self.image_preview.or(other.image_preview),
805 user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
806 external_edit_file_suffix: self
807 .external_edit_file_suffix
808 .or(other.external_edit_file_suffix),
809 tabstop: self.tabstop.or(other.tabstop),
810 default_split: self.default_split.or(other.default_split),
811 ssl_verify: self.ssl_verify.or(other.ssl_verify),
812 }
813 }
814
815 fn values(self) -> TunableValues {
816 TunableValues {
817 encryption: self.encryption.values(),
818 sort: self.sort.values(),
819 terminal: self.terminal.values(),
820
821 log_level: self.log_level.unwrap_or_else(|| "warn".to_string()),
822 max_log_files: self.max_log_files.unwrap_or(7),
823 message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
824 normal_after_send: self.normal_after_send.unwrap_or(false),
825 reaction_display: self.reaction_display.unwrap_or(true),
826 reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
827 read_receipt_send: self.read_receipt_send.unwrap_or(true),
828 read_receipt_display: self.read_receipt_display.unwrap_or(true),
829 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
830 state_event_display: self.state_event_display.unwrap_or(true),
831 typing_notice_send: self.typing_notice_send.unwrap_or(true),
832 typing_notice_display: self.typing_notice_display.unwrap_or(true),
833 users: self.users.unwrap_or_default(),
834 username_display: self.username_display.unwrap_or_default(),
835 message_user_color: self.message_user_color.unwrap_or(false),
836 default_room: self.default_room,
837 open_command: self.open_command,
838 mouse: self.mouse.unwrap_or_default(),
839 notifications: self.notifications.unwrap_or_default(),
840 image_preview: self.image_preview.map(ImagePreview::values),
841 user_gutter_width: self.user_gutter_width.unwrap_or(30),
842 external_edit_file_suffix: self
843 .external_edit_file_suffix
844 .unwrap_or_else(|| ".md".to_string()),
845 tabstop: self.tabstop.unwrap_or(4),
846 default_split: self.default_split.unwrap_or_default(),
847 ssl_verify: self.ssl_verify.unwrap_or(true),
848 }
849 }
850}
851
852#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
853#[serde(rename_all = "kebab-case")]
854#[repr(u8)]
855pub enum CursorShape {
856 #[default]
857 Default,
858 Block,
859 Line,
860 Underline,
861}
862
863impl From<CursorShape> for modalkit::crossterm::cursor::SetCursorStyle {
864 fn from(shape: CursorShape) -> Self {
865 match shape {
866 CursorShape::Default => Self::DefaultUserShape,
867 CursorShape::Block => Self::SteadyBlock,
868 CursorShape::Line => Self::SteadyBar,
869 CursorShape::Underline => Self::SteadyUnderScore,
870 }
871 }
872}
873
874#[derive(Clone)]
875pub struct DirectoryValues {
876 pub cache: PathBuf,
877 pub data: PathBuf,
878 pub logs: PathBuf,
879 pub downloads: Option<PathBuf>,
880}
881
882impl DirectoryValues {
883 fn create_dir_all(&self) -> std::io::Result<()> {
884 use std::fs::create_dir_all;
885
886 let Self { cache, data, logs, downloads } = self;
887
888 create_dir_all(cache)?;
889 create_dir_all(data)?;
890 create_dir_all(logs)?;
891
892 if let Some(downloads) = downloads {
893 create_dir_all(downloads)?;
894 }
895
896 Ok(())
897 }
898}
899
900#[derive(Clone, Default, Deserialize)]
901pub struct Directories {
902 pub cache: Option<String>,
903 pub data: Option<String>,
904 pub logs: Option<String>,
905 pub downloads: Option<String>,
906}
907
908impl Directories {
909 fn merge(self, other: Self) -> Self {
910 Directories {
911 cache: self.cache.or(other.cache),
912 data: self.data.or(other.data),
913 logs: self.logs.or(other.logs),
914 downloads: self.downloads.or(other.downloads),
915 }
916 }
917
918 fn values(self) -> DirectoryValues {
919 let cache = self
920 .cache
921 .map(|dir| {
922 let dir = shellexpand::full(&dir)
923 .expect("unable to expand shell variables in dirs.cache");
924 Path::new(dir.as_ref()).to_owned()
925 })
926 .or_else(|| {
927 let mut dir = dirs::cache_dir()?;
928 dir.push("iamb");
929 dir.into()
930 })
931 .expect("no dirs.cache value configured!");
932
933 let data = self
934 .data
935 .map(|dir| {
936 let dir = shellexpand::full(&dir)
937 .expect("unable to expand shell variables in dirs.cache");
938 Path::new(dir.as_ref()).to_owned()
939 })
940 .or_else(|| {
941 let mut dir = dirs::data_dir()?;
942 dir.push("iamb");
943 dir.into()
944 })
945 .expect("no dirs.data value configured!");
946
947 let logs = self
948 .logs
949 .map(|dir| {
950 let dir = shellexpand::full(&dir)
951 .expect("unable to expand shell variables in dirs.cache");
952 Path::new(dir.as_ref()).to_owned()
953 })
954 .unwrap_or_else(|| {
955 let mut dir = cache.clone();
956 dir.push("logs");
957 dir
958 });
959
960 let downloads = self
961 .downloads
962 .map(|dir| {
963 let dir = shellexpand::full(&dir)
964 .expect("unable to expand shell variables in dirs.cache");
965 Path::new(dir.as_ref()).to_owned()
966 })
967 .or_else(dirs::download_dir);
968
969 DirectoryValues { cache, data, logs, downloads }
970 }
971}
972
973#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
974#[serde(untagged)]
975pub enum WindowPath {
976 AliasId(OwnedRoomAliasId),
977 RoomId(OwnedRoomId),
978 UserId(OwnedUserId),
979 Window(IambId),
980}
981
982#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
983#[serde(untagged, deny_unknown_fields)]
984pub enum WindowLayout {
985 Window { window: WindowPath },
986 Split { split: Vec<WindowLayout> },
987}
988
989#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
990#[serde(rename_all = "lowercase", tag = "style")]
991pub enum Layout {
992 /// Restore the layout from the previous session.
993 #[default]
994 Restore,
995
996 /// Open a single window using the `default_room` value.
997 New,
998
999 /// Open the window layouts described under `tabs`.
1000 Config { tabs: Vec<WindowLayout> },
1001}
1002
1003#[derive(Clone, Deserialize)]
1004pub struct ProfileConfig {
1005 pub user_id: OwnedUserId,
1006 pub password_file: Option<PathBuf>,
1007 pub url: Option<Url>,
1008 pub settings: Option<Tunables>,
1009 pub dirs: Option<Directories>,
1010 pub layout: Option<Layout>,
1011 pub macros: Option<Macros>,
1012}
1013
1014#[derive(Clone, Deserialize)]
1015pub struct IambConfig {
1016 pub profiles: BTreeMap<String, ProfileConfig>,
1017 pub default_profile: Option<String>,
1018 pub settings: Option<Tunables>,
1019 pub dirs: Option<Directories>,
1020 pub layout: Option<Layout>,
1021 pub macros: Option<Macros>,
1022}
1023
1024impl IambConfig {
1025 pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
1026 let s = std::fs::read_to_string(path)?;
1027 let config = toml::from_str(&s)?;
1028
1029 Ok(config)
1030 }
1031
1032 pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
1033 let s = std::fs::read_to_string(path)?;
1034 let config = serde_json::from_str(&s)?;
1035
1036 Ok(config)
1037 }
1038}
1039
1040#[derive(Clone)]
1041pub struct ApplicationSettings {
1042 pub layout_json: PathBuf,
1043 pub session_json: PathBuf,
1044 pub session_json_old: PathBuf,
1045 pub sled_dir: PathBuf,
1046 pub sqlite_dir: PathBuf,
1047 pub profile_name: String,
1048 pub profile: ProfileConfig,
1049 pub tunables: TunableValues,
1050 pub dirs: DirectoryValues,
1051 pub layout: Layout,
1052 pub macros: Macros,
1053}
1054
1055impl ApplicationSettings {
1056 fn get_xdg_config_home() -> Option<PathBuf> {
1057 env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
1058 }
1059
1060 pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
1061 let mut config_dir = cli
1062 .config_directory
1063 .or_else(Self::get_xdg_config_home)
1064 .or_else(dirs::config_dir)
1065 .unwrap_or_else(|| {
1066 usage!(
1067 "No user configuration directory found;\
1068 please specify one via -C.\n\n
1069 For more information try '--help'"
1070 );
1071 });
1072
1073 config_dir.push("iamb");
1074 let config_json = config_dir.join("config.json");
1075 let config_toml = config_dir.join("config.toml");
1076
1077 let config = if config_toml.is_file() {
1078 IambConfig::load_toml(config_toml.as_path())?
1079 } else if config_json.is_file() {
1080 IambConfig::load_json(config_json.as_path())?
1081 } else {
1082 usage!(
1083 "Please create a configuration file at {}\n\n\
1084 For more information try '--help'",
1085 config_toml.display(),
1086 );
1087 };
1088
1089 let IambConfig {
1090 mut profiles,
1091 default_profile,
1092 dirs,
1093 settings: global,
1094 layout,
1095 macros,
1096 } = config;
1097
1098 validate_profile_names(&profiles);
1099
1100 let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
1101 profiles.remove_entry(&profile).unwrap_or_else(|| {
1102 usage!(
1103 "No configured profile with the name {:?} in {}",
1104 profile,
1105 config_json.display()
1106 );
1107 })
1108 } else if profiles.len() == 1 {
1109 profiles.into_iter().next().unwrap()
1110 } else {
1111 loop {
1112 println!("\nNo profile specified. Available profiles:");
1113 profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
1114
1115 print!("Select a number or 'q' to quit: ");
1116 let _ = std::io::stdout().flush();
1117
1118 let mut input = String::new();
1119 let _ = std::io::stdin().read_line(&mut input);
1120
1121 if input.trim() == "q" {
1122 usage!(
1123 "No profile specified. \
1124 Please use -P or add \"default_profile\" to your configuration.\n\n\
1125 For more information try '--help'",
1126 );
1127 }
1128 if let Ok(i) = input.trim().parse::<usize>() {
1129 if i < profiles.len() {
1130 break profiles.into_iter().nth(i).unwrap();
1131 }
1132 }
1133 println!("\nInvalid index.");
1134 }
1135 };
1136
1137 let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
1138 let layout = profile.layout.take().or(layout).unwrap_or_default();
1139
1140 let tunables = global.unwrap_or_default();
1141 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
1142 let tunables = tunables.values();
1143
1144 let dirs = dirs.unwrap_or_default();
1145 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
1146 let dirs = dirs.values();
1147
1148 // Create directories
1149 dirs.create_dir_all()?;
1150
1151 // Set up paths that live inside the profile's data directory.
1152 let mut profile_dir = config_dir.clone();
1153 profile_dir.push("profiles");
1154 profile_dir.push(profile_name.as_str());
1155
1156 let mut profile_data_dir = dirs.data.clone();
1157 profile_data_dir.push("profiles");
1158 profile_data_dir.push(profile_name.as_str());
1159
1160 let mut sled_dir = profile_dir.clone();
1161 sled_dir.push("matrix");
1162
1163 let mut sqlite_dir = profile_data_dir.clone();
1164 sqlite_dir.push("sqlite");
1165
1166 let mut session_json = profile_data_dir.clone();
1167 session_json.push("session.json");
1168
1169 let mut session_json_old = profile_dir;
1170 session_json_old.push("session.json");
1171
1172 // Set up paths that live inside the profile's cache directory.
1173 let mut cache_dir = dirs.cache.clone();
1174 cache_dir.push("profiles");
1175 cache_dir.push(profile_name.as_str());
1176
1177 let mut layout_json = cache_dir.clone();
1178 layout_json.push("layout.json");
1179
1180 let settings = ApplicationSettings {
1181 sled_dir,
1182 layout_json,
1183 session_json,
1184 session_json_old,
1185 sqlite_dir,
1186 profile_name,
1187 profile,
1188 tunables,
1189 dirs,
1190 layout,
1191 macros,
1192 };
1193
1194 Ok(settings)
1195 }
1196
1197 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1198 let file = File::open(path)?;
1199 let reader = BufReader::new(file);
1200 let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1201 Ok(session)
1202 }
1203
1204 pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
1205 let file = File::create(self.session_json.as_path())?;
1206 let writer = BufWriter::new(file);
1207 let session = Session::from(session);
1208 serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1209 Ok(())
1210 }
1211
1212 pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
1213 let (color, c) = self
1214 .tunables
1215 .users
1216 .get(user_id)
1217 .map(|user| {
1218 (
1219 user.color.as_ref().map(|c| c.0),
1220 user.name.as_ref().and_then(|s| s.chars().next()),
1221 )
1222 })
1223 .unwrap_or_default();
1224
1225 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1226 let style = user_style_from_color(color);
1227
1228 let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1229
1230 Span::styled(String::from(c), style)
1231 }
1232
1233 pub fn get_user_overrides(
1234 &self,
1235 user_id: &UserId,
1236 ) -> (Option<Color>, Option<Cow<'static, str>>) {
1237 self.tunables
1238 .users
1239 .get(user_id)
1240 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1241 .unwrap_or_default()
1242 }
1243
1244 pub fn get_user_color(&self, user_id: &UserId) -> Color {
1245 self.tunables
1246 .users
1247 .get(user_id)
1248 .and_then(|user| user.color.as_ref().map(|c| c.0))
1249 .unwrap_or_else(|| user_color(user_id.as_str()))
1250 }
1251
1252 pub fn get_user_style(&self, user_id: &UserId) -> Style {
1253 user_style_from_color(self.get_user_color(user_id))
1254 }
1255
1256 pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1257 let (color, name) = self.get_user_overrides(user_id);
1258
1259 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1260 let style = user_style_from_color(color);
1261 let name = match (name, &self.tunables.username_display) {
1262 (Some(name), _) => name,
1263 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1264 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1265 (None, UserDisplayStyle::DisplayName) => {
1266 if let Some(name) = info.display_names.get(user_id) {
1267 name
1268 } else {
1269 Cow::Borrowed(user_id.as_str())
1270 }
1271 },
1272 };
1273
1274 Span::styled(name, style)
1275 }
1276}
1277
1278#[cfg(test)]
1279mod tests {
1280 use super::*;
1281 use matrix_sdk::ruma::user_id;
1282 use std::convert::TryFrom;
1283
1284 #[test]
1285 fn test_profile_name_invalid() {
1286 assert_eq!(validate_profile_name(""), false);
1287 assert_eq!(validate_profile_name(" "), false);
1288 assert_eq!(validate_profile_name("a b"), false);
1289 assert_eq!(validate_profile_name("foo^bar"), false);
1290 assert_eq!(validate_profile_name("FOO/BAR"), false);
1291 assert_eq!(validate_profile_name("-b-c"), false);
1292 assert_eq!(validate_profile_name("-B-c"), false);
1293 assert_eq!(validate_profile_name(".b-c"), false);
1294 assert_eq!(validate_profile_name(".B-c"), false);
1295 }
1296
1297 #[test]
1298 fn test_profile_name_valid() {
1299 assert_eq!(validate_profile_name("foo"), true);
1300 assert_eq!(validate_profile_name("FOO"), true);
1301 assert_eq!(validate_profile_name("a-b-c"), true);
1302 assert_eq!(validate_profile_name("a-B-c"), true);
1303 assert_eq!(validate_profile_name("a.b-c"), true);
1304 assert_eq!(validate_profile_name("a.B-c"), true);
1305 }
1306
1307 #[test]
1308 fn test_merge_users() {
1309 let a = None;
1310 let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1311 color: Some(UserColor(Color::Red)),
1312 name: Some("Hello".into()),
1313 })]
1314 .into_iter()
1315 .collect::<HashMap<_, _>>();
1316 let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1317 color: Some(UserColor(Color::Green)),
1318 name: Some("World".into()),
1319 })]
1320 .into_iter()
1321 .collect::<HashMap<_, _>>();
1322
1323 let res = merge_maps(a.clone(), a.clone());
1324 assert_eq!(res, None);
1325
1326 let res = merge_maps(a.clone(), Some(b.clone()));
1327 assert_eq!(res, Some(b.clone()));
1328
1329 let res = merge_maps(Some(b.clone()), a.clone());
1330 assert_eq!(res, Some(b.clone()));
1331
1332 let res = merge_maps(Some(b.clone()), Some(b.clone()));
1333 assert_eq!(res, Some(b.clone()));
1334
1335 let res = merge_maps(Some(b.clone()), Some(c.clone()));
1336 assert_eq!(res, Some(b.clone()));
1337
1338 let res = merge_maps(Some(c.clone()), Some(b.clone()));
1339 assert_eq!(res, Some(c.clone()));
1340 }
1341
1342 #[test]
1343 fn test_parse_tunables() {
1344 let res: Tunables = serde_json::from_str("{}").unwrap();
1345 assert_eq!(res.typing_notice_send, None);
1346 assert_eq!(res.typing_notice_display, None);
1347 assert_eq!(res.users, None);
1348
1349 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1350 assert_eq!(res.typing_notice_send, Some(true));
1351 assert_eq!(res.typing_notice_display, None);
1352 assert_eq!(res.users, None);
1353
1354 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1355 assert_eq!(res.typing_notice_send, Some(false));
1356 assert_eq!(res.typing_notice_display, None);
1357 assert_eq!(res.users, None);
1358
1359 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1360 assert_eq!(res.typing_notice_send, None);
1361 assert_eq!(res.typing_notice_display, None);
1362 assert_eq!(res.users, Some(HashMap::new()));
1363
1364 let res: Tunables = serde_json::from_str(
1365 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1366 )
1367 .unwrap();
1368 assert_eq!(res.typing_notice_send, None);
1369 assert_eq!(res.typing_notice_display, None);
1370 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1371 color: Some(UserColor(Color::Black)),
1372 name: Some("Tim".into()),
1373 })];
1374 assert_eq!(res.users, Some(users.into_iter().collect()));
1375 }
1376
1377 #[test]
1378 fn test_parse_tunables_username_display() {
1379 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1380 assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1381
1382 let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1383 assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1384
1385 let res: Tunables =
1386 serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1387 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1388 }
1389
1390 #[test]
1391 fn test_parse_tunables_sort() {
1392 let res: Tunables = serde_json::from_str(
1393 r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1394 )
1395 .unwrap();
1396 assert_eq!(
1397 res.sort.members,
1398 Some(vec![
1399 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1400 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1401 ])
1402 );
1403 assert_eq!(
1404 res.sort.spaces,
1405 Some(vec![
1406 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1407 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1408 ])
1409 );
1410 assert_eq!(res.sort.rooms, None);
1411 assert_eq!(res.sort.dms, None);
1412
1413 // Check that we get the right default "rooms" and "dms" values.
1414 let res = res.values();
1415 assert_eq!(res.sort.members, vec![
1416 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1417 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1418 ]);
1419 assert_eq!(res.sort.spaces, vec![
1420 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1421 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1422 ]);
1423 assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1424 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1425 }
1426
1427 #[test]
1428 fn test_parse_layout() {
1429 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1430 let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1431 let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1432 let dms = WindowPath::Window(IambId::DirectList);
1433 let welcome = WindowPath::Window(IambId::Welcome);
1434
1435 let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1436 assert_eq!(res, Layout::Restore);
1437
1438 let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1439 assert_eq!(res, Layout::New);
1440
1441 let res: Layout = serde_json::from_str(
1442 "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1443 )
1444 .unwrap();
1445 assert_eq!(res, Layout::Config {
1446 tabs: vec![WindowLayout::Window { window: user.clone() }]
1447 });
1448
1449 let res: Layout = serde_json::from_str(
1450 "{\
1451 \"style\": \"config\",\
1452 \"tabs\": [\
1453 {\"split\":[\
1454 {\"window\":\"@user:example.com\"},\
1455 {\"window\":\"#room:example.com\"}\
1456 ]},\
1457 {\"split\":[\
1458 {\"window\":\"!room:example.com\"},\
1459 {\"split\":[\
1460 {\"window\":\"iamb://dms\"},\
1461 {\"window\":\"iamb://welcome\"}\
1462 ]}\
1463 ]}\
1464 ]}",
1465 )
1466 .unwrap();
1467 let split1 = WindowLayout::Split {
1468 split: vec![
1469 WindowLayout::Window { window: user.clone() },
1470 WindowLayout::Window { window: alias },
1471 ],
1472 };
1473 let split2 = WindowLayout::Split {
1474 split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1475 window: welcome,
1476 }],
1477 };
1478 let split3 = WindowLayout::Split {
1479 split: vec![WindowLayout::Window { window: room }, split2],
1480 };
1481 let tabs = vec![split1, split3];
1482 assert_eq!(res, Layout::Config { tabs });
1483 }
1484
1485 #[test]
1486 fn test_parse_macros() {
1487 let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1488 assert_eq!(res.len(), 1);
1489
1490 let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1491 let mapped = res.get(&modes).unwrap();
1492 assert_eq!(mapped.len(), 1);
1493
1494 let j = "j".parse::<TerminalKey>().unwrap();
1495 let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1496
1497 let jj = Keys(vec![j, j], "jj".into());
1498 let run = mapped.get(&jj).unwrap();
1499 let exp = Keys(vec![esc], "<Esc>".into());
1500 assert_eq!(run, &exp);
1501 }
1502
1503 #[test]
1504 fn test_parse_notify_via() {
1505 assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1506 assert_eq!(
1507 NotifyVia { bell: false, desktop: true },
1508 serde_json::from_str(r#""desktop""#).unwrap()
1509 );
1510 assert_eq!(
1511 NotifyVia { bell: true, desktop: false },
1512 serde_json::from_str(r#""bell""#).unwrap()
1513 );
1514 assert_eq!(
1515 NotifyVia { bell: true, desktop: true },
1516 serde_json::from_str(r#""bell|desktop""#).unwrap()
1517 );
1518 assert_eq!(
1519 NotifyVia { bell: true, desktop: true },
1520 serde_json::from_str(r#""desktop|bell""#).unwrap()
1521 );
1522 assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1523 assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1524 }
1525
1526 #[test]
1527 fn test_parse_cursor_shape() {
1528 assert_eq!(CursorShape::Default, CursorShape::default());
1529 assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap());
1530 assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap());
1531 assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap());
1532 assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap());
1533 assert!(serde_json::from_str::<CursorShape>(r#""beam""#).is_err());
1534 }
1535
1536 #[test]
1537 fn test_load_example_config_toml() {
1538 let path = PathBuf::from("config.example.toml");
1539 let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1540
1541 let IambConfig {
1542 profiles,
1543 default_profile,
1544 settings,
1545 dirs,
1546 layout,
1547 macros,
1548 } = &config;
1549
1550 // There should be an example object for each top-level field.
1551 assert!(!profiles.is_empty());
1552 assert!(default_profile.is_some());
1553 assert!(settings.is_some());
1554 assert!(dirs.is_some());
1555 assert!(layout.is_some());
1556 assert!(macros.is_some());
1557 }
1558
1559 #[test]
1560 fn test_encryption_indicator_enabled() {
1561 use EncryptionState::*;
1562
1563 let enc = EncryptionValues {
1564 indicator: EncryptionIndicator::Enabled,
1565 indicator_location: EncryptionIndicatorLocation::TITLE,
1566 };
1567
1568 // Always shows in the title:
1569 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
1570 assert!(enc
1571 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1572 .is_some());
1573 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1574
1575 // Doesn't show in the prompt:
1576 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1577 assert!(enc
1578 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1579 .is_none());
1580 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1581 }
1582
1583 #[test]
1584 fn test_encryption_indicator_disabled() {
1585 use EncryptionState::*;
1586
1587 let enc = EncryptionValues {
1588 indicator: EncryptionIndicator::Disabled,
1589 indicator_location: EncryptionIndicatorLocation::TITLE,
1590 };
1591
1592 // Never shows in the title or the prompt:
1593 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1594 assert!(enc
1595 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1596 .is_none());
1597 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1598 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1599 assert!(enc
1600 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1601 .is_none());
1602 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1603 }
1604
1605 #[test]
1606 fn test_encryption_indicator_only_encrypted() {
1607 use EncryptionState::*;
1608
1609 let enc = EncryptionValues {
1610 indicator: EncryptionIndicator::OnlyEncrypted,
1611 indicator_location: EncryptionIndicatorLocation::PROMPT,
1612 };
1613
1614 // Shows in the prompt when encrypted or unknown:
1615 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_some());
1616 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1617
1618 // But is hidden when unencrypted:
1619 assert!(enc
1620 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1621 .is_none());
1622
1623 // Doesn't show in the title:
1624 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1625 assert!(enc
1626 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1627 .is_none());
1628 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1629 }
1630 #[test]
1631 fn test_encryption_indicator_only_unencrypted() {
1632 use EncryptionState::*;
1633
1634 let enc = EncryptionValues {
1635 indicator: EncryptionIndicator::OnlyUnencrypted,
1636 indicator_location: EncryptionIndicatorLocation::all(),
1637 };
1638
1639 // Shows in both the prompt and title when unencrypted or unknown:
1640 assert!(enc
1641 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1642 .is_some());
1643 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1644 assert!(enc
1645 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1646 .is_some());
1647 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1648
1649 // But is hidden when encrypted:
1650 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1651 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1652 }
1653}