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