src/config.rs
2040 lines · 70515 bytes
1//! # Logic for loading and validating application configuration
2
3use std::collections::hash_map::DefaultHasher;
4use std::env;
5use std::fs::File;
6use std::hash::{Hash, Hasher};
7use std::io::{BufReader, BufWriter, Write as _};
8use std::process;
9
10use clap::Parser;
11use indexmap::IndexMap;
12use lazy_static::lazy_static;
13use matrix_sdk::EncryptionState;
14use matrix_sdk::authentication::matrix::MatrixSession;
15use matrix_sdk::media::MediaRetentionPolicy;
16use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
17use matrix_sdk::ruma::{OwnedDeviceId, owned_server_name};
18use modalkit::crossterm;
19use modalkit::env::vim::VimMode;
20use modalkit::keybindings::InputKey;
21use ratatui_image::FilterType;
22use ratatui_image::picker::ProtocolType;
23use serde::de::Error as SerdeError;
24use serde::de::Visitor;
25use serde::{Deserialize, Deserializer, Serialize};
26
27use crate::base::{SortColumn, SortFieldRoom, SortFieldUser, SortOrder};
28use crate::prelude::*;
29
30pub type Aliases = IndexMap<String, String>;
31type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
32
33macro_rules! usage {
34 ( $($args: tt)* ) => {
35 println!($($args)*);
36 process::exit(2);
37 }
38}
39
40lazy_static! {
41 pub static ref DEFAULT_VIA_SERVER: OwnedServerName = owned_server_name!("matrix.org");
42}
43
44const DEFAULT_MEMBERS_SORT: [SortColumn<SortFieldUser>; 4] = [
45 SortColumn(SortFieldUser::PowerLevel, SortOrder::Ascending),
46 SortColumn(SortFieldUser::Knock, SortOrder::Ascending),
47 SortColumn(SortFieldUser::Invite, SortOrder::Descending),
48 SortColumn(SortFieldUser::UserId, SortOrder::Ascending),
49];
50
51const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 5] = [
52 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
53 SortColumn(SortFieldRoom::Invite, SortOrder::Ascending),
54 SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending),
55 SortColumn(SortFieldRoom::Unread, SortOrder::Ascending),
56 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
57];
58
59const DEFAULT_ENABLE_TITLE: bool = true;
60const DEFAULT_REQ_TIMEOUT: u64 = 120;
61
62const DEFAULT_ENC_INDICATOR_LOC: EncryptionIndicatorLocation = EncryptionIndicatorLocation::PROMPT;
63const DEFAULT_ICON_ENC: Cow<'static, str> = Cow::Borrowed("[E] ");
64const DEFAULT_ICON_UNENC: Cow<'static, str> = Cow::Borrowed("[U] ");
65const DEFAULT_ICON_UNKNOWN: Cow<'static, str> = Cow::Borrowed("[?] ");
66
67const DEFAULT_LOG_LEVEL: &str = if cfg!(feature = "max_level_error") {
68 "error"
69} else {
70 "warn"
71};
72
73const COLORS: [Color; 13] = [
74 Color::Blue,
75 Color::Cyan,
76 Color::Green,
77 Color::LightBlue,
78 Color::LightGreen,
79 Color::LightCyan,
80 Color::LightMagenta,
81 Color::LightRed,
82 Color::LightYellow,
83 Color::Magenta,
84 Color::Red,
85 Color::Reset,
86 Color::Yellow,
87];
88
89pub fn user_color(user: &str) -> Color {
90 let mut hasher = DefaultHasher::new();
91 user.hash(&mut hasher);
92 let color = hasher.finish() as usize % COLORS.len();
93
94 COLORS[color]
95}
96
97pub fn user_style_from_color(color: Color) -> Style {
98 Style::default().fg(color).add_modifier(StyleModifier::BOLD)
99}
100
101fn is_profile_char(c: char) -> bool {
102 c.is_ascii_alphanumeric() || c == '.' || c == '-'
103}
104
105fn default_true() -> bool {
106 true
107}
108
109fn validate_profile_name(name: &str) -> bool {
110 if name.is_empty() {
111 return false;
112 }
113
114 let mut chars = name.chars();
115
116 if !chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) {
117 return false;
118 }
119
120 name.chars().all(is_profile_char)
121}
122
123fn validate_profile_names(names: &BTreeMap<String, ProfileConfig>) {
124 for name in names.keys() {
125 if validate_profile_name(name.as_str()) {
126 continue;
127 }
128
129 usage!(
130 "{:?} is not a valid profile name.\n\n\
131 Profile names can only contain the characters \
132 a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
133 name
134 );
135 }
136}
137
138fn deserialize_from_str_opt<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
139where
140 D: serde::de::Deserializer<'de>,
141 T: FromStr,
142 <T as FromStr>::Err: fmt::Display,
143{
144 <Option<&'de str>>::deserialize(deserializer)?
145 .map(|s| {
146 let t = T::from_str(s);
147 t.map_err(|e| D::Error::custom(format!("failed to parse string: {e}")))
148 })
149 .transpose()
150}
151
152fn deserialize_register<'de, D>(deserializer: D) -> Result<Option<Register>, D::Error>
153where
154 D: serde::de::Deserializer<'de>,
155{
156 let r = <&'de str>::deserialize(deserializer)?;
157
158 if r.len() > 1 {
159 return Err(D::Error::custom("expected a single character to specify a register"));
160 }
161
162 let r = match r.chars().next() {
163 Some(c @ 'a'..='z') => Register::Named(c),
164 Some('_') => Register::Blackhole,
165 Some('*') => Register::SelectionPrimary,
166 Some('+') => Register::SelectionClipboard,
167 Some('"') => Register::Unnamed,
168 Some(c) => {
169 return Err(D::Error::custom(format!(
170 "expected one of a-z, \", _, *, or + for the register, not {c:?}"
171 )));
172 },
173 None => {
174 return Err(D::Error::custom("expected a single character to specify a register"));
175 },
176 };
177
178 Ok(Some(r))
179}
180
181const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
182 None => env!("CARGO_PKG_VERSION"),
183 Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
184};
185
186#[derive(Parser)]
187#[clap(version = VERSION, about, long_about = None)]
188#[clap(propagate_version = true)]
189pub struct Iamb {
190 #[clap(long, value_parser)]
191 pub completions: Option<clap_complete::Shell>,
192
193 #[clap(short = 'P', long, value_parser)]
194 pub profile: Option<String>,
195
196 #[clap(short = 'C', long, value_parser)]
197 pub config_directory: Option<PathBuf>,
198
199 /// `matrix:` uri or `https://matrix.to` link to open
200 pub uri: Option<String>,
201}
202
203#[derive(thiserror::Error, Debug)]
204pub enum ConfigError {
205 #[error("Error reading configuration file: {0}")]
206 IO(#[from] std::io::Error),
207
208 #[error("Error loading configuration file: {0}")]
209 Invalid(#[from] toml::de::Error),
210
211 #[error("Error loading JSON configuration file: {0}")]
212 InvalidJSON(#[from] serde_json::Error),
213}
214
215macro_rules! deserialize_str_with_visitor {
216 ($t: ident, $v: ident) => {
217 impl<'de> Deserialize<'de> for $t {
218 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
219 where
220 D: Deserializer<'de>,
221 {
222 deserializer.deserialize_str($v)
223 }
224 }
225 };
226}
227
228deserialize_str_with_visitor!(Keys, KeysVisitor);
229deserialize_str_with_visitor!(VimModes, VimModesVisitor);
230deserialize_str_with_visitor!(UserColor, UserColorVisitor);
231deserialize_str_with_visitor!(EncryptionIndicatorLocation, EncryptionIndicatorLocationVisitor);
232deserialize_str_with_visitor!(NotifyVia, NotifyViaVisitor);
233deserialize_str_with_visitor!(ProxyUrl, ProxyUrlVisitor);
234
235#[derive(Clone, Debug, Eq, Hash, PartialEq)]
236pub struct Keys(pub Vec<TerminalKey>, pub String);
237pub struct KeysVisitor;
238
239impl Visitor<'_> for KeysVisitor {
240 type Value = Keys;
241
242 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
243 formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
244 }
245
246 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
247 where
248 E: SerdeError,
249 {
250 match TerminalKey::from_macro_str(value) {
251 Ok(keys) => Ok(Keys(keys, value.to_string())),
252 Err(e) => Err(E::custom(format!("Could not parse key sequence: {e}"))),
253 }
254 }
255}
256
257#[derive(Clone, Debug, Eq, Hash, PartialEq)]
258pub struct VimModes(pub Vec<VimMode>);
259pub struct VimModesVisitor;
260
261impl Visitor<'_> for VimModesVisitor {
262 type Value = VimModes;
263
264 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
265 formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
266 }
267
268 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
269 where
270 E: SerdeError,
271 {
272 let mut modes = vec![];
273
274 for mode in value.split('|') {
275 let mode = match mode.to_ascii_lowercase().as_str() {
276 "insert" | "i" => VimMode::Insert,
277 "normal" | "n" => VimMode::Normal,
278 "visual" | "v" => VimMode::Visual,
279 "command" | "c" => VimMode::Command,
280 "select" => VimMode::Select,
281 "operator-pending" => VimMode::OperationPending,
282 _ => return Err(E::custom("Could not parse into a Vim mode")),
283 };
284
285 modes.push(mode);
286 }
287
288 Ok(VimModes(modes))
289 }
290}
291
292#[derive(Clone, Debug, Eq, PartialEq)]
293pub struct UserColor(pub Color);
294pub struct UserColorVisitor;
295
296impl Visitor<'_> for UserColorVisitor {
297 type Value = UserColor;
298
299 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
300 formatter.write_str("a valid color")
301 }
302
303 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
304 where
305 E: SerdeError,
306 {
307 match value {
308 "none" => Ok(UserColor(Color::Reset)),
309 "red" => Ok(UserColor(Color::Red)),
310 "black" => Ok(UserColor(Color::Black)),
311 "green" => Ok(UserColor(Color::Green)),
312 "yellow" => Ok(UserColor(Color::Yellow)),
313 "blue" => Ok(UserColor(Color::Blue)),
314 "magenta" => Ok(UserColor(Color::Magenta)),
315 "cyan" => Ok(UserColor(Color::Cyan)),
316 "gray" => Ok(UserColor(Color::Gray)),
317 "dark-gray" => Ok(UserColor(Color::DarkGray)),
318 "light-red" => Ok(UserColor(Color::LightRed)),
319 "light-green" => Ok(UserColor(Color::LightGreen)),
320 "light-yellow" => Ok(UserColor(Color::LightYellow)),
321 "light-blue" => Ok(UserColor(Color::LightBlue)),
322 "light-magenta" => Ok(UserColor(Color::LightMagenta)),
323 "light-cyan" => Ok(UserColor(Color::LightCyan)),
324 "white" => Ok(UserColor(Color::White)),
325 _ => Err(E::custom("Could not parse color")),
326 }
327 }
328}
329
330#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
331pub struct Session {
332 access_token: String,
333 refresh_token: Option<String>,
334 user_id: OwnedUserId,
335 device_id: OwnedDeviceId,
336}
337
338impl From<Session> for MatrixSession {
339 fn from(session: Session) -> Self {
340 MatrixSession {
341 tokens: matrix_sdk::authentication::SessionTokens {
342 access_token: session.access_token,
343 refresh_token: session.refresh_token,
344 },
345 meta: matrix_sdk::SessionMeta {
346 user_id: session.user_id,
347 device_id: session.device_id,
348 },
349 }
350 }
351}
352
353impl From<MatrixSession> for Session {
354 fn from(session: MatrixSession) -> Self {
355 Session {
356 access_token: session.tokens.access_token,
357 refresh_token: session.tokens.refresh_token,
358 user_id: session.meta.user_id,
359 device_id: session.meta.device_id,
360 }
361 }
362}
363
364#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
365pub struct UserDisplayTunables {
366 pub color: Option<UserColor>,
367 pub name: Option<String>,
368}
369
370pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
371
372fn merge_maps<M, K, V>(profile: Option<M>, global: Option<M>) -> Option<M>
373where
374 M: Extend<(K, V)> + IntoIterator<Item = (K, V)>,
375{
376 match (global, profile) {
377 (Some(m), None) | (None, Some(m)) => Some(m),
378 (Some(mut global), Some(profile)) => {
379 global.extend(profile);
380 Some(global)
381 },
382 (None, None) => None,
383 }
384}
385
386#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
387#[serde(rename_all = "kebab-case")]
388#[repr(u8)]
389pub enum ReadReceiptTrigger {
390 /// Update read receipts for a room when a window for it is focused, and it is scrolled to the
391 /// last message.
392 #[default]
393 Focused,
394 /// Update read receipts for a room when a window for it is visible, and it is scrolled to the
395 /// last message.
396 Visible,
397 /// Update read receipts for a room whenever some portion of its scrollback is rendered.
398 Scrollback,
399 /// Update read receipts for a room once the user sends a message to it.
400 Message,
401}
402
403impl ReadReceiptTrigger {
404 /// Whether to update read receipts when a room is being rendered.
405 pub fn on_render(&self, last_visible: bool, room_focused: bool) -> bool {
406 match self {
407 Self::Scrollback => true,
408 Self::Focused => last_visible && room_focused,
409 Self::Visible => last_visible,
410 Self::Message => false,
411 }
412 }
413
414 pub fn on_message(&self) -> bool {
415 matches!(self, Self::Message)
416 }
417}
418
419#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
420#[serde(rename_all = "kebab-case")]
421#[repr(u8)]
422pub enum EncryptionIndicator {
423 /// Always indicate the room's encryption status.
424 #[default]
425 Enabled,
426 /// Never indicate the room's encryption status.
427 Disabled,
428 /// Only indicate the room's encryption status when it is encrypted.
429 OnlyEncrypted,
430 /// Only indicate the room's encryption status when it is unencrypted.
431 OnlyUnencrypted,
432}
433
434bitflags::bitflags! {
435 /// Available options for where to show the encryption status indicator.
436 #[derive(Clone, Debug, Eq, PartialEq)]
437 pub struct EncryptionIndicatorLocation: u8 {
438 const NONE = 0b00000000;
439 const TITLE = 0b00000001;
440 const PROMPT = 0b00000010;
441 }
442}
443
444pub struct EncryptionIndicatorLocationVisitor;
445
446impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
447 type Value = EncryptionIndicatorLocation;
448
449 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
450 formatter.write_str("a valid encryption indicator location (e.g. \"title\" or \"prompt\")")
451 }
452
453 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
454 where
455 E: SerdeError,
456 {
457 let mut location = EncryptionIndicatorLocation::NONE;
458
459 for value in value.split('|') {
460 match value.to_ascii_lowercase().as_str() {
461 "title" => location |= EncryptionIndicatorLocation::TITLE,
462 "prompt" => location |= EncryptionIndicatorLocation::PROMPT,
463 _ => {
464 return Err(E::custom("could not parse into an encryption indicator location"));
465 },
466 };
467 }
468
469 Ok(location)
470 }
471}
472
473#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
474#[serde(rename_all = "lowercase")]
475pub enum UserDisplayStyle {
476 // The Matrix username for the sender (e.g., "@user:example.com").
477 #[default]
478 Username,
479
480 // The localpart of the Matrix username (e.g., "@user").
481 LocalPart,
482
483 // The display name for the Matrix user, calculated according to the rules from the spec.
484 //
485 // This is usually something like "Ada Lovelace" if the user has configured a display name, but
486 // it can wind up being the Matrix username if there are display name collisions in the room,
487 // in order to avoid any confusion.
488 DisplayName,
489}
490
491#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
492#[serde(rename_all = "lowercase")]
493pub enum SplitDirection {
494 #[default]
495 Horizontal,
496 Vertical,
497}
498
499impl SplitDirection {
500 pub fn to_axis(self) -> Axis {
501 match self {
502 Self::Horizontal => Axis::Horizontal,
503 Self::Vertical => Axis::Vertical,
504 }
505 }
506}
507
508#[derive(Clone, Copy, Debug, Eq, PartialEq)]
509pub struct NotifyVia {
510 /// Deliver notifications via terminal bell.
511 pub bell: bool,
512 /// Deliver notifications via desktop mechanism.
513 #[cfg(feature = "desktop")]
514 pub desktop: bool,
515}
516pub struct NotifyViaVisitor;
517
518impl Default for NotifyVia {
519 fn default() -> Self {
520 Self {
521 bell: cfg!(not(feature = "desktop")),
522 #[cfg(feature = "desktop")]
523 desktop: true,
524 }
525 }
526}
527
528impl Visitor<'_> for NotifyViaVisitor {
529 type Value = NotifyVia;
530
531 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
532 formatter.write_str("a valid notify destination (e.g. \"bell\" or \"desktop\")")
533 }
534
535 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
536 where
537 E: SerdeError,
538 {
539 let mut via = NotifyVia {
540 bell: false,
541 #[cfg(feature = "desktop")]
542 desktop: false,
543 };
544
545 for value in value.split('|') {
546 match value.to_ascii_lowercase().as_str() {
547 "bell" => {
548 via.bell = true;
549 },
550 #[cfg(feature = "desktop")]
551 "desktop" => {
552 via.desktop = true;
553 },
554 #[cfg(not(feature = "desktop"))]
555 "desktop" => {
556 return Err(E::custom("desktop notification support was compiled out"));
557 },
558 _ => return Err(E::custom("could not parse into a notify destination")),
559 };
560 }
561
562 Ok(via)
563 }
564}
565
566#[derive(Clone, Debug, Default, Deserialize)]
567pub struct Encryption {
568 indicator: Option<EncryptionIndicator>,
569 indicator_location: Option<EncryptionIndicatorLocation>,
570 icon_encrypted: Option<String>,
571 icon_unencrypted: Option<String>,
572 icon_unknown: Option<String>,
573}
574
575impl Encryption {
576 fn merge(profile: Self, global: Self) -> Self {
577 Encryption {
578 indicator: profile.indicator.or(global.indicator),
579 indicator_location: profile.indicator_location.or(global.indicator_location),
580 icon_encrypted: profile.icon_encrypted.or(global.icon_encrypted),
581 icon_unencrypted: profile.icon_unencrypted.or(global.icon_unencrypted),
582 icon_unknown: profile.icon_unknown.or(global.icon_unknown),
583 }
584 }
585
586 pub fn values(self) -> EncryptionValues {
587 EncryptionValues {
588 indicator: self.indicator.unwrap_or_default(),
589 indicator_location: self.indicator_location.unwrap_or(DEFAULT_ENC_INDICATOR_LOC),
590 icon_encrypted: self.icon_encrypted.map(Cow::Owned).unwrap_or(DEFAULT_ICON_ENC),
591 icon_unencrypted: self.icon_unencrypted.map(Cow::Owned).unwrap_or(DEFAULT_ICON_UNENC),
592 icon_unknown: self.icon_unknown.map(Cow::Owned).unwrap_or(DEFAULT_ICON_UNKNOWN),
593 }
594 }
595}
596
597#[derive(Clone, Debug)]
598pub struct EncryptionValues {
599 pub indicator: EncryptionIndicator,
600 pub indicator_location: EncryptionIndicatorLocation,
601 pub icon_encrypted: Cow<'static, str>,
602 pub icon_unencrypted: Cow<'static, str>,
603 pub icon_unknown: Cow<'static, str>,
604}
605
606impl EncryptionValues {
607 pub fn get_indicator(
608 &self,
609 location: EncryptionIndicatorLocation,
610 state: EncryptionState,
611 ) -> Option<Span<'static>> {
612 if !self.indicator_location.contains(location) {
613 return None;
614 }
615
616 let indicator = match (self.indicator, state) {
617 (EncryptionIndicator::Disabled, _) |
618 (EncryptionIndicator::OnlyUnencrypted, EncryptionState::Encrypted) |
619 (EncryptionIndicator::OnlyEncrypted, EncryptionState::NotEncrypted) => {
620 // User doesn't want to see anything:
621 return None;
622 },
623 (
624 EncryptionIndicator::Enabled | EncryptionIndicator::OnlyEncrypted,
625 EncryptionState::Encrypted,
626 ) => {
627 // Green encrypted icon:
628 Span::styled(self.icon_encrypted.clone(), Style::new().fg(Color::LightGreen))
629 },
630 (
631 EncryptionIndicator::Enabled | EncryptionIndicator::OnlyUnencrypted,
632 EncryptionState::NotEncrypted,
633 ) => {
634 // Red unencrypted icon:
635 Span::styled(self.icon_unencrypted.clone(), Style::new().fg(Color::Red))
636 },
637
638 (_, EncryptionState::Unknown) => {
639 // Yellow unknown icon:
640 Span::styled(self.icon_unknown.clone(), Style::new().fg(Color::Yellow))
641 },
642 };
643
644 Some(indicator)
645 }
646}
647
648#[derive(Clone, Debug, Default, Eq, PartialEq)]
649pub enum ProxyUrl {
650 Disabled,
651 Endpoint(Url),
652 #[default]
653 System,
654}
655
656pub struct ProxyUrlVisitor;
657
658impl Visitor<'_> for ProxyUrlVisitor {
659 type Value = ProxyUrl;
660
661 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
662 formatter.write_str("a valid proxy URL (e.g. \"socks5://localhost:9050\")")
663 }
664
665 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
666 where
667 E: SerdeError,
668 {
669 if value.is_empty() {
670 return Ok(ProxyUrl::Disabled);
671 }
672
673 match Url::from_str(value) {
674 Ok(uri) => Ok(ProxyUrl::Endpoint(uri)),
675 Err(e) => Err(E::custom(format!("could not parse {value:?}: {e}"))),
676 }
677 }
678}
679
680#[derive(Clone, Debug, Default, Deserialize)]
681pub struct Proxy {
682 /// How and where to proxy the client's requests to the homeserver.
683 url: Option<ProxyUrl>,
684
685 /// An optional value to include in the `Proxy-Authorization` header.
686 #[serde(default, deserialize_with = "deserialize_from_str_opt")]
687 auth: Option<HeaderValue>,
688
689 /// Optional headers to include in requests sent to the proxy.
690 #[serde(default, with = "http_serde::header_map")]
691 headers: HeaderMap,
692}
693
694impl Proxy {
695 pub fn values(self) -> ProxyValues {
696 ProxyValues {
697 url: self.url.unwrap_or_default(),
698 auth: self.auth,
699 headers: self.headers,
700 }
701 }
702}
703
704#[derive(Clone, Debug, Default)]
705pub struct ProxyValues {
706 pub url: ProxyUrl,
707 pub auth: Option<HeaderValue>,
708 pub headers: HeaderMap,
709}
710
711#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
712pub struct Mouse {
713 #[serde(default)]
714 pub enabled: bool,
715}
716
717#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
718pub struct Notifications {
719 #[serde(default)]
720 pub enabled: bool,
721 #[serde(default)]
722 pub via: NotifyVia,
723 #[serde(default = "default_true")]
724 pub show_message: bool,
725 #[serde(default)]
726 pub sound_hint: Option<String>,
727}
728
729#[derive(Clone)]
730pub struct ImagePreviewValues {
731 pub enabled: bool,
732 pub size: Size,
733 pub protocol: ImagePreviewProtocolValues,
734}
735
736#[derive(Clone, Debug, Default, Deserialize)]
737pub struct ImagePreview {
738 pub enabled: Option<bool>,
739 pub size: Option<Size>,
740 pub protocol: Option<ImagePreviewProtocolValues>,
741}
742
743impl ImagePreview {
744 pub fn values(self) -> ImagePreviewValues {
745 ImagePreviewValues {
746 enabled: self.enabled.unwrap_or(true),
747 size: self.size.unwrap_or(Size { width: 66, height: 10 }),
748 protocol: self.protocol.unwrap_or_default(),
749 }
750 }
751}
752
753#[derive(Clone, Debug, Deserialize, Default)]
754pub struct ImagePreviewProtocolValues {
755 pub r#type: Option<ProtocolType>,
756 pub filter: Option<FilterType>,
757 pub font_size: Option<(u16, u16)>,
758}
759
760#[derive(Clone)]
761pub struct SortValues {
762 pub chats: Vec<SortColumn<SortFieldRoom>>,
763 pub dms: Vec<SortColumn<SortFieldRoom>>,
764 pub rooms: Vec<SortColumn<SortFieldRoom>>,
765 pub spaces: Vec<SortColumn<SortFieldRoom>>,
766 pub members: Vec<SortColumn<SortFieldUser>>,
767}
768
769#[derive(Clone, Debug, Default, Deserialize)]
770pub struct SortOverrides {
771 pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
772 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
773 pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
774 pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
775 pub members: Option<Vec<SortColumn<SortFieldUser>>>,
776}
777
778impl SortOverrides {
779 fn merge(profile: Self, global: Self) -> Self {
780 Self {
781 chats: profile.chats.or(global.chats),
782 dms: profile.dms.or(global.dms),
783 rooms: profile.rooms.or(global.rooms),
784 spaces: profile.spaces.or(global.spaces),
785 members: profile.members.or(global.members),
786 }
787 }
788
789 pub fn values(self) -> SortValues {
790 let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
791 let chats = self.chats.unwrap_or_else(|| rooms.clone());
792 let dms = self.dms.unwrap_or_else(|| rooms.clone());
793 let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
794 let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
795
796 SortValues { rooms, members, chats, dms, spaces }
797 }
798}
799
800#[derive(Clone, Debug, Default, Deserialize)]
801pub struct Terminal {
802 pub cursor_shape: Option<CursorShape>,
803 pub enable_extended_keys: Option<bool>,
804 pub enable_title: Option<bool>,
805}
806
807impl Terminal {
808 fn merge(profile: Self, global: Self) -> Self {
809 Self {
810 cursor_shape: profile.cursor_shape.or(global.cursor_shape),
811 enable_extended_keys: profile.enable_extended_keys.or(global.enable_extended_keys),
812 enable_title: profile.enable_title.or(global.enable_title),
813 }
814 }
815
816 pub fn values(self) -> TerminalValues {
817 TerminalValues {
818 cursor_shape: self.cursor_shape.unwrap_or_default(),
819 enable_extended_keys: self.enable_extended_keys,
820 enable_title: self.enable_title.unwrap_or(DEFAULT_ENABLE_TITLE),
821 }
822 }
823}
824
825#[derive(Clone, Debug)]
826pub struct TerminalValues {
827 pub cursor_shape: CursorShape,
828 pub enable_extended_keys: Option<bool>,
829 pub enable_title: bool,
830}
831
832/// The configuration settings to run with, after merging the
833/// per-profile overrides on top of the global settings.
834#[derive(Clone)]
835pub struct TunableValues {
836 pub encryption: EncryptionValues,
837 pub default_markup: MarkupFormat,
838 pub ignorecase: bool,
839 pub log_level: String,
840 pub max_log_files: usize,
841 pub message_shortcode_display: bool,
842 pub normal_after_send: bool,
843 pub proxy: ProxyValues,
844 pub reaction_display: bool,
845 pub reaction_shortcode_display: bool,
846 pub read_receipt_send: bool,
847 pub read_receipt_trigger: ReadReceiptTrigger,
848 pub read_receipt_display: bool,
849 pub request_timeout: u64,
850 pub sort: SortValues,
851 pub state_event_display: bool,
852 pub typing_notice_send: bool,
853 pub typing_notice_display: bool,
854 pub users: UserOverrides,
855 pub username_display: UserDisplayStyle,
856 pub message_user_color: bool,
857 pub default_register: Option<Register>,
858 pub default_room: Option<String>,
859 pub default_via: Vec<OwnedServerName>,
860 pub open_command: Option<Vec<String>>,
861 pub mouse: Mouse,
862 pub notifications: Notifications,
863 pub terminal: TerminalValues,
864 pub image_preview: ImagePreviewValues,
865 pub user_gutter_width: usize,
866 pub external_edit_file_suffix: String,
867 pub tabstop: usize,
868 pub input_prompt: Option<String>,
869 pub members_split: Option<SplitDirection>,
870 pub default_split: SplitDirection,
871 pub ssl_verify: bool,
872 pub cache_policy: MediaRetentionPolicy,
873}
874
875#[derive(Clone, Debug, Default, Deserialize)]
876pub struct Tunables {
877 /// Subsection for overriding encryption-related settings.
878 #[serde(default)]
879 pub encryption: Encryption,
880
881 /// Subsection for configuring an HTTP(S) proxy.
882 pub proxy: Option<Proxy>,
883
884 /// Subsection for overriding sort orders in UI lists.
885 #[serde(default)]
886 pub sort: SortOverrides,
887
888 /// Subsection for overriding terminal settings.
889 #[serde(default)]
890 pub terminal: Terminal,
891
892 /// Subsection for overriding how specific Matrix users are rendered.
893 pub users: Option<UserOverrides>,
894
895 pub default_markup: Option<MarkupFormat>,
896 pub ignorecase: Option<bool>,
897 pub log_level: Option<String>,
898 pub max_log_files: Option<usize>,
899 pub message_shortcode_display: Option<bool>,
900 pub normal_after_send: Option<bool>,
901 pub reaction_display: Option<bool>,
902 pub reaction_shortcode_display: Option<bool>,
903 pub read_receipt_send: Option<bool>,
904 pub read_receipt_trigger: Option<ReadReceiptTrigger>,
905 pub read_receipt_display: Option<bool>,
906 pub request_timeout: Option<u64>,
907 pub state_event_display: Option<bool>,
908 pub typing_notice_send: Option<bool>,
909 pub typing_notice_display: Option<bool>,
910 pub username_display: Option<UserDisplayStyle>,
911 pub message_user_color: Option<bool>,
912 #[serde(default, deserialize_with = "deserialize_register")]
913 pub default_register: Option<Register>,
914 pub default_room: Option<String>,
915 pub default_via: Option<Vec<OwnedServerName>>,
916 pub open_command: Option<Vec<String>>,
917 pub mouse: Option<Mouse>,
918 pub notifications: Option<Notifications>,
919 pub image_preview: Option<ImagePreview>,
920 pub user_gutter_width: Option<usize>,
921 pub external_edit_file_suffix: Option<String>,
922 pub tabstop: Option<usize>,
923 pub input_prompt: Option<String>,
924 pub members_split: Option<SplitDirection>,
925 pub default_split: Option<SplitDirection>,
926 pub ssl_verify: Option<bool>,
927 pub cache_policy: Option<MediaRetentionPolicy>,
928}
929
930impl Tunables {
931 fn merge(self, other: Self) -> Self {
932 Tunables {
933 encryption: Encryption::merge(self.encryption, other.encryption),
934 sort: SortOverrides::merge(self.sort, other.sort),
935 terminal: Terminal::merge(self.terminal, other.terminal),
936 users: merge_maps(self.users, other.users),
937
938 // Proxy configuration sub-field do *not* get merged, so that a
939 // per-profile override won't inherit auth or headers from the
940 // global settings.
941 proxy: self.proxy.or(other.proxy),
942
943 default_markup: self.default_markup.or(other.default_markup),
944 ignorecase: self.ignorecase.or(other.ignorecase),
945 log_level: self.log_level.or(other.log_level),
946 max_log_files: self.max_log_files.or(other.max_log_files),
947 message_shortcode_display: self
948 .message_shortcode_display
949 .or(other.message_shortcode_display),
950 normal_after_send: self.normal_after_send.or(other.normal_after_send),
951 reaction_display: self.reaction_display.or(other.reaction_display),
952 reaction_shortcode_display: self
953 .reaction_shortcode_display
954 .or(other.reaction_shortcode_display),
955 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
956 read_receipt_trigger: self.read_receipt_trigger.or(other.read_receipt_trigger),
957 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
958 request_timeout: self.request_timeout.or(other.request_timeout),
959 state_event_display: self.state_event_display.or(other.state_event_display),
960 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
961 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
962 username_display: self.username_display.or(other.username_display),
963 message_user_color: self.message_user_color.or(other.message_user_color),
964 default_register: self.default_register.or(other.default_register),
965 default_room: self.default_room.or(other.default_room),
966 default_via: self.default_via.or(other.default_via),
967 open_command: self.open_command.or(other.open_command),
968 mouse: self.mouse.or(other.mouse),
969 notifications: self.notifications.or(other.notifications),
970 image_preview: self.image_preview.or(other.image_preview),
971 user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
972 external_edit_file_suffix: self
973 .external_edit_file_suffix
974 .or(other.external_edit_file_suffix),
975 tabstop: self.tabstop.or(other.tabstop),
976 input_prompt: self.input_prompt.or(other.input_prompt),
977 members_split: self.members_split.or(other.members_split),
978 default_split: self.default_split.or(other.default_split),
979 ssl_verify: self.ssl_verify.or(other.ssl_verify),
980 cache_policy: self.cache_policy.or(other.cache_policy),
981 }
982 }
983
984 fn values(self) -> TunableValues {
985 TunableValues {
986 encryption: self.encryption.values(),
987 proxy: self.proxy.unwrap_or_default().values(),
988 sort: self.sort.values(),
989 terminal: self.terminal.values(),
990 users: self.users.unwrap_or_default(),
991
992 default_markup: self.default_markup.unwrap_or_default(),
993 log_level: self.log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_owned()),
994 ignorecase: self.ignorecase.unwrap_or(false),
995 max_log_files: self.max_log_files.unwrap_or(7),
996 message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
997 normal_after_send: self.normal_after_send.unwrap_or(false),
998 reaction_display: self.reaction_display.unwrap_or(true),
999 reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
1000 read_receipt_send: self.read_receipt_send.unwrap_or(true),
1001 read_receipt_trigger: self.read_receipt_trigger.unwrap_or_default(),
1002 read_receipt_display: self.read_receipt_display.unwrap_or(true),
1003 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
1004 state_event_display: self.state_event_display.unwrap_or(true),
1005 typing_notice_send: self.typing_notice_send.unwrap_or(true),
1006 typing_notice_display: self.typing_notice_display.unwrap_or(true),
1007 username_display: self.username_display.unwrap_or_default(),
1008 message_user_color: self.message_user_color.unwrap_or(false),
1009 default_register: self.default_register,
1010 default_room: self.default_room,
1011 default_via: self.default_via.unwrap_or_else(|| vec![DEFAULT_VIA_SERVER.clone()]),
1012 open_command: self.open_command,
1013 mouse: self.mouse.unwrap_or_default(),
1014 notifications: self.notifications.unwrap_or_default(),
1015 image_preview: self.image_preview.unwrap_or_default().values(),
1016 user_gutter_width: self.user_gutter_width.unwrap_or(30),
1017 external_edit_file_suffix: self
1018 .external_edit_file_suffix
1019 .unwrap_or_else(|| ".md".to_string()),
1020 tabstop: self.tabstop.unwrap_or(4),
1021 input_prompt: self.input_prompt,
1022 members_split: self.members_split,
1023 default_split: self.default_split.unwrap_or_default(),
1024 ssl_verify: self.ssl_verify.unwrap_or(true),
1025 cache_policy: self.cache_policy.unwrap_or_default(),
1026 }
1027 }
1028}
1029
1030#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1031#[serde(rename_all = "kebab-case")]
1032#[repr(u8)]
1033pub enum CursorShape {
1034 Default,
1035 Block,
1036 Line,
1037 Underline,
1038 #[default]
1039 Auto,
1040}
1041
1042impl From<CursorShape> for modalkit::crossterm::cursor::SetCursorStyle {
1043 fn from(shape: CursorShape) -> Self {
1044 match shape {
1045 CursorShape::Default => Self::DefaultUserShape,
1046 CursorShape::Block => Self::SteadyBlock,
1047 CursorShape::Line => Self::SteadyBar,
1048 CursorShape::Underline => Self::SteadyUnderScore,
1049
1050 // use steady block at startup and switch to the correct value on first render
1051 CursorShape::Auto => Self::SteadyBlock,
1052 }
1053 }
1054}
1055
1056#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1057#[serde(rename_all = "kebab-case")]
1058#[repr(u8)]
1059pub enum MarkupFormat {
1060 Html,
1061 #[default]
1062 Markdown,
1063 Plaintext,
1064}
1065
1066#[derive(Clone)]
1067pub struct DirectoryValues {
1068 pub cache: PathBuf,
1069 pub data: PathBuf,
1070 pub logs: PathBuf,
1071 pub downloads: Option<PathBuf>,
1072}
1073
1074impl DirectoryValues {
1075 fn create_dir_all(&self) -> std::io::Result<()> {
1076 use std::fs::create_dir_all;
1077
1078 let Self { cache, data, logs, downloads } = self;
1079
1080 create_dir_all(cache)?;
1081 create_dir_all(data)?;
1082 create_dir_all(logs)?;
1083
1084 if let Some(downloads) = downloads {
1085 create_dir_all(downloads)?;
1086 }
1087
1088 Ok(())
1089 }
1090}
1091
1092#[derive(Clone, Default, Deserialize)]
1093pub struct Directories {
1094 pub cache: Option<String>,
1095 pub data: Option<String>,
1096 pub logs: Option<String>,
1097 pub downloads: Option<String>,
1098}
1099
1100impl Directories {
1101 fn merge(self, other: Self) -> Self {
1102 Directories {
1103 cache: self.cache.or(other.cache),
1104 data: self.data.or(other.data),
1105 logs: self.logs.or(other.logs),
1106 downloads: self.downloads.or(other.downloads),
1107 }
1108 }
1109
1110 fn values(self) -> DirectoryValues {
1111 let cache = self
1112 .cache
1113 .map(|dir| {
1114 let dir = shellexpand::full(&dir)
1115 .expect("unable to expand shell variables in dirs.cache");
1116 Path::new(dir.as_ref()).to_owned()
1117 })
1118 .or_else(|| {
1119 let mut dir = dirs::cache_dir()?;
1120 dir.push("iamb");
1121 dir.into()
1122 })
1123 .expect("no dirs.cache value configured!");
1124
1125 let data = self
1126 .data
1127 .map(|dir| {
1128 let dir = shellexpand::full(&dir)
1129 .expect("unable to expand shell variables in dirs.cache");
1130 Path::new(dir.as_ref()).to_owned()
1131 })
1132 .or_else(|| {
1133 let mut dir = dirs::data_dir()?;
1134 dir.push("iamb");
1135 dir.into()
1136 })
1137 .expect("no dirs.data value configured!");
1138
1139 let logs = self
1140 .logs
1141 .map(|dir| {
1142 let dir = shellexpand::full(&dir)
1143 .expect("unable to expand shell variables in dirs.cache");
1144 Path::new(dir.as_ref()).to_owned()
1145 })
1146 .unwrap_or_else(|| {
1147 let mut dir = cache.clone();
1148 dir.push("logs");
1149 dir
1150 });
1151
1152 let downloads = self
1153 .downloads
1154 .map(|dir| {
1155 let dir = shellexpand::full(&dir)
1156 .expect("unable to expand shell variables in dirs.cache");
1157 Path::new(dir.as_ref()).to_owned()
1158 })
1159 .or_else(dirs::download_dir);
1160
1161 DirectoryValues { cache, data, logs, downloads }
1162 }
1163}
1164
1165#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1166#[serde(untagged)]
1167pub enum WindowPath {
1168 AliasId(OwnedRoomAliasId),
1169 RoomId(OwnedRoomId),
1170 UserId(OwnedUserId),
1171 Window(IambId),
1172}
1173
1174#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
1175#[serde(untagged, deny_unknown_fields)]
1176pub enum WindowLayout {
1177 Window { window: WindowPath },
1178 Split { split: Vec<WindowLayout> },
1179}
1180
1181#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
1182#[serde(rename_all = "lowercase", tag = "style")]
1183pub enum Layout {
1184 /// Restore the layout from the previous session.
1185 #[default]
1186 Restore,
1187
1188 /// Open a single window using the `default_room` value.
1189 New,
1190
1191 /// Open the window layouts described under `tabs`.
1192 Config { tabs: Vec<WindowLayout> },
1193}
1194
1195#[derive(Clone, Deserialize)]
1196pub struct ProfileConfig {
1197 pub user_id: OwnedUserId,
1198 pub password_file: Option<PathBuf>,
1199 pub url: Option<Url>,
1200 pub settings: Option<Tunables>,
1201 pub dirs: Option<Directories>,
1202 pub layout: Option<Layout>,
1203 pub macros: Option<Macros>,
1204 pub aliases: Option<Aliases>,
1205}
1206
1207#[derive(Clone, Deserialize)]
1208pub struct IambConfig {
1209 pub profiles: BTreeMap<String, ProfileConfig>,
1210 pub default_profile: Option<String>,
1211 pub settings: Option<Tunables>,
1212 pub dirs: Option<Directories>,
1213 pub layout: Option<Layout>,
1214 pub macros: Option<Macros>,
1215 pub aliases: Option<Aliases>,
1216}
1217
1218impl IambConfig {
1219 pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
1220 let s = std::fs::read_to_string(path)?;
1221 let config = toml::from_str(&s)?;
1222
1223 Ok(config)
1224 }
1225
1226 pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
1227 let s = std::fs::read_to_string(path)?;
1228 let config = serde_json::from_str(&s)?;
1229
1230 Ok(config)
1231 }
1232}
1233
1234#[derive(Clone)]
1235pub struct ApplicationSettings {
1236 pub layout_json: PathBuf,
1237 pub session_json: PathBuf,
1238 pub session_json_old: PathBuf,
1239 pub sled_dir: PathBuf,
1240 pub sqlite_dir: PathBuf,
1241 pub sqlite_cache_dir: PathBuf,
1242 pub profile_name: String,
1243 pub profile: ProfileConfig,
1244 pub tunables: TunableValues,
1245 pub dirs: DirectoryValues,
1246 pub layout: Layout,
1247 pub macros: Macros,
1248 pub aliases: Aliases,
1249
1250 /// Whether to use the Kitty keyboard protocol. Resolved by
1251 /// [`ApplicationSettings::probe_enhanced_keys`] once the TUI starts, since
1252 /// it may require querying the terminal.
1253 pub enable_enhanced_keys: bool,
1254}
1255
1256impl ApplicationSettings {
1257 fn get_xdg_config_home() -> Option<PathBuf> {
1258 env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
1259 }
1260
1261 pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
1262 let mut config_dir = cli
1263 .config_directory
1264 .or_else(Self::get_xdg_config_home)
1265 .or_else(dirs::config_dir)
1266 .unwrap_or_else(|| {
1267 usage!(
1268 "No user configuration directory found;\
1269 please specify one via -C.\n\n
1270 For more information try '--help'"
1271 );
1272 });
1273
1274 config_dir.push("iamb");
1275 let config_json = config_dir.join("config.json");
1276 let config_toml = config_dir.join("config.toml");
1277
1278 let config = if config_toml.is_file() {
1279 IambConfig::load_toml(config_toml.as_path())?
1280 } else if config_json.is_file() {
1281 IambConfig::load_json(config_json.as_path())?
1282 } else {
1283 usage!(
1284 "Please create a configuration file at {}\n\n\
1285 For more information try '--help'",
1286 config_toml.display(),
1287 );
1288 };
1289
1290 let IambConfig {
1291 mut profiles,
1292 default_profile,
1293 dirs,
1294 settings: global,
1295 layout,
1296 macros,
1297 aliases,
1298 } = config;
1299
1300 validate_profile_names(&profiles);
1301
1302 let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
1303 profiles.remove_entry(&profile).unwrap_or_else(|| {
1304 usage!(
1305 "No configured profile with the name {:?} in {}",
1306 profile,
1307 config_json.display()
1308 );
1309 })
1310 } else if profiles.len() == 1 {
1311 profiles.into_iter().next().unwrap()
1312 } else {
1313 loop {
1314 println!("\nNo profile specified. Available profiles:");
1315 profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));
1316
1317 print!("Select a number or 'q' to quit: ");
1318 let _ = std::io::stdout().flush();
1319
1320 let mut input = String::new();
1321 let _ = std::io::stdin().read_line(&mut input);
1322
1323 if input.trim() == "q" {
1324 usage!(
1325 "No profile specified. \
1326 Please use -P or add \"default_profile\" to your configuration.\n\n\
1327 For more information try '--help'",
1328 );
1329 }
1330 if let Ok(i) = input.trim().parse::<usize>() &&
1331 i < profiles.len()
1332 {
1333 break profiles.into_iter().nth(i).unwrap();
1334 }
1335 println!("\nInvalid index.");
1336 }
1337 };
1338
1339 let aliases = merge_maps(profile.aliases.take(), aliases).unwrap_or_default();
1340 let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
1341 let layout = profile.layout.take().or(layout).unwrap_or_default();
1342
1343 let tunables = global.unwrap_or_default();
1344 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
1345 let tunables = tunables.values();
1346
1347 let dirs = dirs.unwrap_or_default();
1348 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
1349 let dirs = dirs.values();
1350
1351 // Create directories
1352 dirs.create_dir_all()?;
1353
1354 // Set up paths that live inside the profile's data directory.
1355 let mut profile_dir = config_dir.clone();
1356 profile_dir.push("profiles");
1357 profile_dir.push(profile_name.as_str());
1358
1359 let mut profile_data_dir = dirs.data.clone();
1360 profile_data_dir.push("profiles");
1361 profile_data_dir.push(profile_name.as_str());
1362
1363 let mut sled_dir = profile_dir.clone();
1364 sled_dir.push("matrix");
1365
1366 let mut sqlite_dir = profile_data_dir.clone();
1367 sqlite_dir.push("sqlite");
1368
1369 let mut session_json = profile_data_dir.clone();
1370 session_json.push("session.json");
1371
1372 let mut session_json_old = profile_dir;
1373 session_json_old.push("session.json");
1374
1375 // Set up paths that live inside the profile's cache directory.
1376 let mut cache_dir = dirs.cache.clone();
1377 cache_dir.push("profiles");
1378 cache_dir.push(profile_name.as_str());
1379
1380 let mut layout_json = cache_dir.clone();
1381 layout_json.push("layout.json");
1382
1383 let mut sqlite_cache_dir = cache_dir;
1384 sqlite_cache_dir.push("sqlite");
1385
1386 let settings = ApplicationSettings {
1387 sled_dir,
1388 layout_json,
1389 session_json,
1390 session_json_old,
1391 sqlite_dir,
1392 sqlite_cache_dir,
1393 profile_name,
1394 profile,
1395 tunables,
1396 dirs,
1397 layout,
1398 macros,
1399 aliases,
1400 enable_enhanced_keys: false,
1401 };
1402
1403 Ok(settings)
1404 }
1405
1406 /// Work out whether to use the Kitty keyboard protocol, asking the terminal
1407 /// when the user has not configured it explicitly.
1408 ///
1409 /// This queries the terminal, so it must only be called once, before the
1410 /// TUI starts reading input.
1411 pub fn probe_enhanced_keys(&mut self) {
1412 self.enable_enhanced_keys =
1413 self.tunables.terminal.enable_extended_keys.unwrap_or_else(|| {
1414 crossterm::terminal::supports_keyboard_enhancement()
1415 .inspect_err(|e| {
1416 tracing::warn!(
1417 err = %e,
1418 "Failed to determine whether the terminal supports keyboard enhancements"
1419 )
1420 })
1421 .unwrap_or_default()
1422 });
1423 }
1424
1425 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1426 let file = File::open(path)?;
1427 let reader = BufReader::new(file);
1428 let session = serde_json::from_reader(reader).map_err(IambError::from)?;
1429 Ok(session)
1430 }
1431
1432 pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
1433 let file = File::create(self.session_json.as_path())?;
1434 let writer = BufWriter::new(file);
1435 let session = Session::from(session);
1436 serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1437 Ok(())
1438 }
1439
1440 pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
1441 let (color, c) = self
1442 .tunables
1443 .users
1444 .get(user_id)
1445 .map(|user| {
1446 (
1447 user.color.as_ref().map(|c| c.0),
1448 user.name.as_ref().and_then(|s| s.chars().next()),
1449 )
1450 })
1451 .unwrap_or_default();
1452
1453 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1454 let style = user_style_from_color(color);
1455
1456 let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1457
1458 Span::styled(String::from(c), style)
1459 }
1460
1461 pub fn get_user_overrides(
1462 &self,
1463 user_id: &UserId,
1464 ) -> (Option<Color>, Option<Cow<'static, str>>) {
1465 self.tunables
1466 .users
1467 .get(user_id)
1468 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1469 .unwrap_or_default()
1470 }
1471
1472 pub fn get_user_color(&self, user_id: &UserId) -> Color {
1473 self.tunables
1474 .users
1475 .get(user_id)
1476 .and_then(|user| user.color.as_ref().map(|c| c.0))
1477 .unwrap_or_else(|| user_color(user_id.as_str()))
1478 }
1479
1480 pub fn get_user_style(&self, user_id: &UserId) -> Style {
1481 user_style_from_color(self.get_user_color(user_id))
1482 }
1483
1484 pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1485 let (color, name) = self.get_user_overrides(user_id);
1486
1487 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1488 let style = user_style_from_color(color);
1489 let name = match (name, &self.tunables.username_display) {
1490 (Some(name), _) => name,
1491 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1492 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1493 (None, UserDisplayStyle::DisplayName) => {
1494 if let Some(name) = info.display_names.get(user_id) {
1495 name
1496 } else {
1497 Cow::Borrowed(user_id.as_str())
1498 }
1499 },
1500 };
1501
1502 Span::styled(name, style)
1503 }
1504}
1505
1506#[cfg(test)]
1507mod tests {
1508 use super::*;
1509
1510 use std::convert::TryFrom;
1511
1512 use matrix_sdk::ruma::user_id;
1513
1514 use crate::tests::{TEST_USER1, mock_room, mock_settings};
1515
1516 #[test]
1517 fn test_get_user_span_borrowed() {
1518 // fix `StyleTreeNode::print` for `StyleTreeNode::UserId` if this breaks
1519 let info = mock_room();
1520 let settings = mock_settings();
1521 let span = settings.get_user_span(&TEST_USER1, &info);
1522
1523 assert!(matches!(span.content, Cow::Borrowed(_)));
1524 }
1525
1526 #[test]
1527 fn test_profile_name_invalid() {
1528 assert_eq!(validate_profile_name(""), false);
1529 assert_eq!(validate_profile_name(" "), false);
1530 assert_eq!(validate_profile_name("a b"), false);
1531 assert_eq!(validate_profile_name("foo^bar"), false);
1532 assert_eq!(validate_profile_name("FOO/BAR"), false);
1533 assert_eq!(validate_profile_name("-b-c"), false);
1534 assert_eq!(validate_profile_name("-B-c"), false);
1535 assert_eq!(validate_profile_name(".b-c"), false);
1536 assert_eq!(validate_profile_name(".B-c"), false);
1537 }
1538
1539 #[test]
1540 fn test_profile_name_valid() {
1541 assert_eq!(validate_profile_name("foo"), true);
1542 assert_eq!(validate_profile_name("FOO"), true);
1543 assert_eq!(validate_profile_name("a-b-c"), true);
1544 assert_eq!(validate_profile_name("a-B-c"), true);
1545 assert_eq!(validate_profile_name("a.b-c"), true);
1546 assert_eq!(validate_profile_name("a.B-c"), true);
1547 }
1548
1549 #[test]
1550 fn test_merge_users() {
1551 let a = None;
1552 let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1553 color: Some(UserColor(Color::Red)),
1554 name: Some("Hello".into()),
1555 })]
1556 .into_iter()
1557 .collect::<HashMap<_, _>>();
1558 let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1559 color: Some(UserColor(Color::Green)),
1560 name: Some("World".into()),
1561 })]
1562 .into_iter()
1563 .collect::<HashMap<_, _>>();
1564
1565 let res = merge_maps(a.clone(), a.clone());
1566 assert_eq!(res, None);
1567
1568 let res = merge_maps(a.clone(), Some(b.clone()));
1569 assert_eq!(res, Some(b.clone()));
1570
1571 let res = merge_maps(Some(b.clone()), a.clone());
1572 assert_eq!(res, Some(b.clone()));
1573
1574 let res = merge_maps(Some(b.clone()), Some(b.clone()));
1575 assert_eq!(res, Some(b.clone()));
1576
1577 let res = merge_maps(Some(b.clone()), Some(c.clone()));
1578 assert_eq!(res, Some(b.clone()));
1579
1580 let res = merge_maps(Some(c.clone()), Some(b.clone()));
1581 assert_eq!(res, Some(c.clone()));
1582 }
1583
1584 #[test]
1585 fn test_parse_tunables() {
1586 let res: Tunables = serde_json::from_str("{}").unwrap();
1587 assert_eq!(res.typing_notice_send, None);
1588 assert_eq!(res.typing_notice_display, None);
1589 assert_eq!(res.users, None);
1590
1591 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1592 assert_eq!(res.typing_notice_send, Some(true));
1593 assert_eq!(res.typing_notice_display, None);
1594 assert_eq!(res.users, None);
1595
1596 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1597 assert_eq!(res.typing_notice_send, Some(false));
1598 assert_eq!(res.typing_notice_display, None);
1599 assert_eq!(res.users, None);
1600
1601 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1602 assert_eq!(res.typing_notice_send, None);
1603 assert_eq!(res.typing_notice_display, None);
1604 assert_eq!(res.users, Some(HashMap::new()));
1605
1606 let res: Tunables = serde_json::from_str(
1607 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1608 )
1609 .unwrap();
1610 assert_eq!(res.typing_notice_send, None);
1611 assert_eq!(res.typing_notice_display, None);
1612 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1613 color: Some(UserColor(Color::Black)),
1614 name: Some("Tim".into()),
1615 })];
1616 assert_eq!(res.users, Some(users.into_iter().collect()));
1617 }
1618
1619 #[test]
1620 fn test_parse_tunables_username_display() {
1621 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1622 assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1623
1624 let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1625 assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1626
1627 let res: Tunables =
1628 serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1629 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1630 }
1631
1632 #[test]
1633 fn test_parse_tunables_sort() {
1634 let res: Tunables = serde_json::from_str(
1635 r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1636 )
1637 .unwrap();
1638 assert_eq!(
1639 res.sort.members,
1640 Some(vec![
1641 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1642 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1643 ])
1644 );
1645 assert_eq!(
1646 res.sort.spaces,
1647 Some(vec![
1648 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1649 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1650 ])
1651 );
1652 assert_eq!(res.sort.rooms, None);
1653 assert_eq!(res.sort.dms, None);
1654
1655 // Check that we get the right default "rooms" and "dms" values.
1656 let res = res.values();
1657 assert_eq!(res.sort.members, vec![
1658 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1659 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1660 ]);
1661 assert_eq!(res.sort.spaces, vec![
1662 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1663 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1664 ]);
1665 assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1666 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1667 }
1668
1669 #[test]
1670 fn test_parse_tunables_proxy_invalid() {
1671 let res =
1672 serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();
1673
1674 // Should result in a validation error:
1675 assert_eq!(res.classify(), serde_json::error::Category::Data);
1676 }
1677
1678 #[test]
1679 fn test_parse_tunables_proxy_empty() {
1680 let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
1681 let proxy = res.proxy.unwrap();
1682 assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
1683 }
1684
1685 #[test]
1686 fn test_parse_tunables_proxy_socks5() {
1687 let res: Tunables =
1688 serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1689 let proxy = res.proxy.unwrap();
1690 let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1691 panic!("should parse ProxyUrl::Endpoint")
1692 };
1693
1694 assert_eq!(url.scheme(), "socks5");
1695 assert_eq!(url.host_str().unwrap(), "localhost");
1696 assert_eq!(url.port().unwrap(), 1080);
1697 assert_eq!(url.authority(), "localhost:1080");
1698 }
1699
1700 #[test]
1701 fn test_parse_tunables_proxy_https() {
1702 let res: Tunables = serde_json::from_str(
1703 r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1704 ).unwrap();
1705 let proxy = res.proxy.unwrap();
1706 let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1707 panic!("should parse ProxyUrl::Endpoint")
1708 };
1709
1710 // Verify URL fields:
1711 assert_eq!(url.scheme(), "https");
1712 assert_eq!(url.host_str().unwrap(), "localhost");
1713 assert_eq!(url.port().unwrap(), 8080);
1714 assert_eq!(url.authority(), "localhost:8080");
1715
1716 // Verify our `Proxy-Authorization` value:
1717 assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");
1718
1719 // Verify our custom header is present:
1720 assert_eq!(proxy.headers.len(), 1);
1721 assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
1722 }
1723
1724 #[test]
1725 fn test_parse_tunables_proxy_merge() {
1726 let global: Tunables = serde_json::from_str(
1727 r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1728 ).unwrap();
1729 let profile: Tunables =
1730 serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1731
1732 // The configuration merge should select the entirety of the profile proxy config,
1733 // and not merge subfields, to ensure that things like `auth` and `headers` are
1734 // not ever sent to a `url` they were meant for.
1735 let merged = profile.merge(global).values();
1736 let ProxyUrl::Endpoint(url) = merged.proxy.url else {
1737 panic!("should parse ProxyUrl::Endpoint")
1738 };
1739 assert_eq!(url.scheme(), "socks5");
1740 assert_eq!(url.authority(), "localhost:1080");
1741 assert_eq!(merged.proxy.auth, None);
1742 assert_eq!(merged.proxy.headers.is_empty(), true);
1743 }
1744
1745 #[test]
1746 fn test_parse_tunables_default_register() {
1747 let reg_a: Tunables = serde_json::from_str(r#"{"default_register": "a"}"#).unwrap();
1748 assert_eq!(reg_a.default_register, Some(Register::Named('a')));
1749
1750 let reg_z: Tunables = serde_json::from_str(r#"{"default_register": "z"}"#).unwrap();
1751 assert_eq!(reg_z.default_register, Some(Register::Named('z')));
1752
1753 let reg_blackhole: Tunables = serde_json::from_str(r#"{"default_register": "_"}"#).unwrap();
1754 assert_eq!(reg_blackhole.default_register, Some(Register::Blackhole));
1755
1756 let res: Result<Tunables, _> = serde_json::from_str(r#"{"default_register": "A"}"#);
1757 assert!(res.is_err());
1758
1759 let res: Result<Tunables, _> = serde_json::from_str(r#"{"default_register": "0"}"#);
1760 assert!(res.is_err());
1761 }
1762
1763 #[test]
1764 fn test_parse_layout() {
1765 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1766 let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1767 let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1768 let dms = WindowPath::Window(IambId::DirectList);
1769 let welcome = WindowPath::Window(IambId::Welcome);
1770
1771 let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1772 assert_eq!(res, Layout::Restore);
1773
1774 let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1775 assert_eq!(res, Layout::New);
1776
1777 let res: Layout = serde_json::from_str(
1778 "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1779 )
1780 .unwrap();
1781 assert_eq!(res, Layout::Config {
1782 tabs: vec![WindowLayout::Window { window: user.clone() }]
1783 });
1784
1785 let res: Layout = serde_json::from_str(
1786 "{\
1787 \"style\": \"config\",\
1788 \"tabs\": [\
1789 {\"split\":[\
1790 {\"window\":\"@user:example.com\"},\
1791 {\"window\":\"#room:example.com\"}\
1792 ]},\
1793 {\"split\":[\
1794 {\"window\":\"!room:example.com\"},\
1795 {\"split\":[\
1796 {\"window\":\"iamb://dms\"},\
1797 {\"window\":\"iamb://welcome\"}\
1798 ]}\
1799 ]}\
1800 ]}",
1801 )
1802 .unwrap();
1803 let split1 = WindowLayout::Split {
1804 split: vec![
1805 WindowLayout::Window { window: user.clone() },
1806 WindowLayout::Window { window: alias },
1807 ],
1808 };
1809 let split2 = WindowLayout::Split {
1810 split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1811 window: welcome,
1812 }],
1813 };
1814 let split3 = WindowLayout::Split {
1815 split: vec![WindowLayout::Window { window: room }, split2],
1816 };
1817 let tabs = vec![split1, split3];
1818 assert_eq!(res, Layout::Config { tabs });
1819 }
1820
1821 #[test]
1822 fn test_parse_aliases() {
1823 let res: Aliases = serde_json::from_str("{\"c\":\"chats\"}").unwrap();
1824 assert_eq!(res.len(), 1);
1825
1826 let aliased = res.get("c").unwrap();
1827 assert_eq!(aliased, "chats");
1828 }
1829
1830 #[test]
1831 fn test_parse_aliases_preserves_order() {
1832 // Aliases are registered in order, which allows alias to refer to earlier ones, so
1833 // ensure we register in user-specified order:
1834 let res: Aliases = toml::from_str("c = \"chats\"\ncc = \"c\"\nd = \"download\"").unwrap();
1835 let order = res.keys().map(String::as_str).collect::<Vec<_>>();
1836
1837 assert_eq!(order, vec!["c", "cc", "d"]);
1838 }
1839
1840 #[test]
1841 fn test_merge_aliases_preserves_order() {
1842 let profile: Aliases = toml::from_str("c = \"chats\"\nz = \"redact\"").unwrap();
1843 let global: Aliases = toml::from_str("c = \"cancel\"\nd = \"download\"").unwrap();
1844
1845 let res = merge_maps(Some(profile), Some(global)).unwrap();
1846 let order = res.keys().map(String::as_str).collect::<Vec<_>>();
1847
1848 // The profile wins for keys in both, but doesn't get to move them.
1849 assert_eq!(order, vec!["c", "d", "z"]);
1850 assert_eq!(res.get("c").unwrap(), "chats");
1851 }
1852
1853 #[test]
1854 fn test_parse_macros() {
1855 let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1856 assert_eq!(res.len(), 1);
1857
1858 let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1859 let mapped = res.get(&modes).unwrap();
1860 assert_eq!(mapped.len(), 1);
1861
1862 let j = "j".parse::<TerminalKey>().unwrap();
1863 let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1864
1865 let jj = Keys(vec![j, j], "jj".into());
1866 let run = mapped.get(&jj).unwrap();
1867 let exp = Keys(vec![esc], "<Esc>".into());
1868 assert_eq!(run, &exp);
1869 }
1870
1871 #[test]
1872 fn test_parse_notify_via() {
1873 assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1874 assert_eq!(
1875 NotifyVia { bell: false, desktop: true },
1876 serde_json::from_str(r#""desktop""#).unwrap()
1877 );
1878 assert_eq!(
1879 NotifyVia { bell: true, desktop: false },
1880 serde_json::from_str(r#""bell""#).unwrap()
1881 );
1882 assert_eq!(
1883 NotifyVia { bell: true, desktop: true },
1884 serde_json::from_str(r#""bell|desktop""#).unwrap()
1885 );
1886 assert_eq!(
1887 NotifyVia { bell: true, desktop: true },
1888 serde_json::from_str(r#""desktop|bell""#).unwrap()
1889 );
1890 assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1891 assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1892 }
1893
1894 #[test]
1895 fn test_parse_cursor_shape() {
1896 assert_eq!(CursorShape::Auto, CursorShape::default());
1897 assert_eq!(CursorShape::Auto, serde_json::from_str(r#""auto""#).unwrap());
1898 assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap());
1899 assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap());
1900 assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap());
1901 assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap());
1902 assert!(serde_json::from_str::<CursorShape>(r#""beam""#).is_err());
1903 }
1904
1905 #[test]
1906 fn test_load_example_config_toml() {
1907 let path = PathBuf::from("config.example.toml");
1908 let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1909
1910 let IambConfig {
1911 profiles,
1912 default_profile,
1913 settings,
1914 dirs,
1915 layout,
1916 macros,
1917 aliases,
1918 } = &config;
1919
1920 // There should be an example object for each top-level field.
1921 assert!(!profiles.is_empty());
1922 assert!(default_profile.is_some());
1923 assert!(settings.is_some());
1924 assert!(dirs.is_some());
1925 assert!(layout.is_some());
1926 assert!(macros.is_some());
1927 assert!(aliases.is_some());
1928 }
1929
1930 #[test]
1931 fn test_encryption_indicator_enabled() {
1932 use EncryptionState::*;
1933
1934 let enc = Encryption {
1935 indicator: Some(EncryptionIndicator::Enabled),
1936 indicator_location: Some(EncryptionIndicatorLocation::TITLE),
1937 ..Default::default()
1938 };
1939 let enc = enc.values();
1940
1941 // Always shows in the title:
1942 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
1943 assert!(
1944 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1945 .is_some()
1946 );
1947 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1948
1949 // Doesn't show in the prompt:
1950 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1951 assert!(
1952 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1953 .is_none()
1954 );
1955 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1956 }
1957
1958 #[test]
1959 fn test_encryption_indicator_disabled() {
1960 use EncryptionState::*;
1961
1962 let enc = Encryption {
1963 indicator: Some(EncryptionIndicator::Disabled),
1964 indicator_location: Some(EncryptionIndicatorLocation::TITLE),
1965 ..Default::default()
1966 };
1967 let enc = enc.values();
1968
1969 // Never shows in the title or the prompt:
1970 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1971 assert!(
1972 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1973 .is_none()
1974 );
1975 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1976 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1977 assert!(
1978 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1979 .is_none()
1980 );
1981 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1982 }
1983
1984 #[test]
1985 fn test_encryption_indicator_only_encrypted() {
1986 use EncryptionState::*;
1987
1988 let enc = Encryption {
1989 indicator: Some(EncryptionIndicator::OnlyEncrypted),
1990 indicator_location: Some(EncryptionIndicatorLocation::PROMPT),
1991 ..Default::default()
1992 };
1993 let enc = enc.values();
1994
1995 // Shows in the prompt when encrypted or unknown:
1996 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_some());
1997 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1998
1999 // But is hidden when unencrypted:
2000 assert!(
2001 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
2002 .is_none()
2003 );
2004
2005 // Doesn't show in the title:
2006 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
2007 assert!(
2008 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
2009 .is_none()
2010 );
2011 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
2012 }
2013 #[test]
2014 fn test_encryption_indicator_only_unencrypted() {
2015 use EncryptionState::*;
2016
2017 let enc = Encryption {
2018 indicator: Some(EncryptionIndicator::OnlyUnencrypted),
2019 indicator_location: Some(EncryptionIndicatorLocation::all()),
2020 ..Default::default()
2021 };
2022 let enc = enc.values();
2023
2024 // Shows in both the prompt and title when unencrypted or unknown:
2025 assert!(
2026 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
2027 .is_some()
2028 );
2029 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
2030 assert!(
2031 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
2032 .is_some()
2033 );
2034 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
2035
2036 // But is hidden when encrypted:
2037 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
2038 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
2039 }
2040}