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