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