src/config.rs
1325 lines · 43106 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 pub tabstop: usize,
578}
579
580#[derive(Clone, Default, Deserialize)]
581pub struct Tunables {
582 pub log_level: Option<LogLevel>,
583 pub message_shortcode_display: Option<bool>,
584 pub reaction_display: Option<bool>,
585 pub reaction_shortcode_display: Option<bool>,
586 pub read_receipt_send: Option<bool>,
587 pub read_receipt_display: Option<bool>,
588 pub request_timeout: Option<u64>,
589 #[serde(default)]
590 pub sort: SortOverrides,
591 pub state_event_display: Option<bool>,
592 pub typing_notice_send: Option<bool>,
593 pub typing_notice_display: Option<bool>,
594 pub users: Option<UserOverrides>,
595 pub username_display: Option<UserDisplayStyle>,
596 pub message_user_color: Option<bool>,
597 pub default_room: Option<String>,
598 pub open_command: Option<Vec<String>>,
599 pub mouse: Option<Mouse>,
600 pub notifications: Option<Notifications>,
601 pub image_preview: Option<ImagePreview>,
602 pub user_gutter_width: Option<usize>,
603 pub external_edit_file_suffix: Option<String>,
604 pub tabstop: Option<usize>,
605}
606
607impl Tunables {
608 fn merge(self, other: Self) -> Self {
609 Tunables {
610 log_level: self.log_level.or(other.log_level),
611 message_shortcode_display: self
612 .message_shortcode_display
613 .or(other.message_shortcode_display),
614 reaction_display: self.reaction_display.or(other.reaction_display),
615 reaction_shortcode_display: self
616 .reaction_shortcode_display
617 .or(other.reaction_shortcode_display),
618 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
619 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
620 request_timeout: self.request_timeout.or(other.request_timeout),
621 sort: merge_sorts(self.sort, other.sort),
622 state_event_display: self.state_event_display.or(other.state_event_display),
623 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
624 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
625 users: merge_maps(self.users, other.users),
626 username_display: self.username_display.or(other.username_display),
627 message_user_color: self.message_user_color.or(other.message_user_color),
628 default_room: self.default_room.or(other.default_room),
629 open_command: self.open_command.or(other.open_command),
630 mouse: self.mouse.or(other.mouse),
631 notifications: self.notifications.or(other.notifications),
632 image_preview: self.image_preview.or(other.image_preview),
633 user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
634 external_edit_file_suffix: self
635 .external_edit_file_suffix
636 .or(other.external_edit_file_suffix),
637 tabstop: self.tabstop.or(other.tabstop),
638 }
639 }
640
641 fn values(self) -> TunableValues {
642 TunableValues {
643 log_level: self.log_level.map(Level::from).unwrap_or(Level::INFO),
644 message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
645 reaction_display: self.reaction_display.unwrap_or(true),
646 reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
647 read_receipt_send: self.read_receipt_send.unwrap_or(true),
648 read_receipt_display: self.read_receipt_display.unwrap_or(true),
649 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
650 sort: self.sort.values(),
651 state_event_display: self.state_event_display.unwrap_or(true),
652 typing_notice_send: self.typing_notice_send.unwrap_or(true),
653 typing_notice_display: self.typing_notice_display.unwrap_or(true),
654 users: self.users.unwrap_or_default(),
655 username_display: self.username_display.unwrap_or_default(),
656 message_user_color: self.message_user_color.unwrap_or(false),
657 default_room: self.default_room,
658 open_command: self.open_command,
659 mouse: self.mouse.unwrap_or_default(),
660 notifications: self.notifications.unwrap_or_default(),
661 image_preview: self.image_preview.map(ImagePreview::values),
662 user_gutter_width: self.user_gutter_width.unwrap_or(30),
663 external_edit_file_suffix: self
664 .external_edit_file_suffix
665 .unwrap_or_else(|| ".md".to_string()),
666 tabstop: self.tabstop.unwrap_or(4),
667 }
668 }
669}
670
671#[derive(Clone)]
672pub struct DirectoryValues {
673 pub cache: PathBuf,
674 pub data: PathBuf,
675 pub logs: PathBuf,
676 pub downloads: Option<PathBuf>,
677 pub image_previews: PathBuf,
678}
679
680impl DirectoryValues {
681 fn create_dir_all(&self) -> std::io::Result<()> {
682 use std::fs::create_dir_all;
683
684 let Self { cache, data, logs, downloads, image_previews } = self;
685
686 create_dir_all(cache)?;
687 create_dir_all(data)?;
688 create_dir_all(logs)?;
689 create_dir_all(image_previews)?;
690
691 if let Some(downloads) = downloads {
692 create_dir_all(downloads)?;
693 }
694
695 Ok(())
696 }
697}
698
699#[derive(Clone, Default, Deserialize)]
700pub struct Directories {
701 pub cache: Option<PathBuf>,
702 pub data: Option<PathBuf>,
703 pub logs: Option<PathBuf>,
704 pub downloads: Option<PathBuf>,
705 pub image_previews: Option<PathBuf>,
706}
707
708impl Directories {
709 fn merge(self, other: Self) -> Self {
710 Directories {
711 cache: self.cache.or(other.cache),
712 data: self.data.or(other.data),
713 logs: self.logs.or(other.logs),
714 downloads: self.downloads.or(other.downloads),
715 image_previews: self.image_previews.or(other.image_previews),
716 }
717 }
718
719 fn values(self) -> DirectoryValues {
720 let cache = self
721 .cache
722 .or_else(|| {
723 let mut dir = dirs::cache_dir()?;
724 dir.push("iamb");
725 dir.into()
726 })
727 .expect("no dirs.cache value configured!");
728
729 let data = self
730 .data
731 .or_else(|| {
732 let mut dir = dirs::data_dir()?;
733 dir.push("iamb");
734 dir.into()
735 })
736 .expect("no dirs.data value configured!");
737
738 let logs = self.logs.unwrap_or_else(|| {
739 let mut dir = cache.clone();
740 dir.push("logs");
741 dir
742 });
743
744 let downloads = self.downloads.or_else(dirs::download_dir);
745
746 let image_previews = self.image_previews.unwrap_or_else(|| {
747 let mut dir = cache.clone();
748 dir.push("image_preview_downloads");
749 dir
750 });
751
752 DirectoryValues { cache, data, logs, downloads, image_previews }
753 }
754}
755
756#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
757#[serde(untagged)]
758pub enum WindowPath {
759 AliasId(OwnedRoomAliasId),
760 RoomId(OwnedRoomId),
761 UserId(OwnedUserId),
762 Window(IambId),
763}
764
765#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
766#[serde(untagged, deny_unknown_fields)]
767pub enum WindowLayout {
768 Window { window: WindowPath },
769 Split { split: Vec<WindowLayout> },
770}
771
772#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
773#[serde(rename_all = "lowercase", tag = "style")]
774pub enum Layout {
775 /// Restore the layout from the previous session.
776 #[default]
777 Restore,
778
779 /// Open a single window using the `default_room` value.
780 New,
781
782 /// Open the window layouts described under `tabs`.
783 Config { tabs: Vec<WindowLayout> },
784}
785
786#[derive(Clone, Deserialize)]
787pub struct ProfileConfig {
788 pub user_id: OwnedUserId,
789 pub url: Option<Url>,
790 pub settings: Option<Tunables>,
791 pub dirs: Option<Directories>,
792 pub layout: Option<Layout>,
793 pub macros: Option<Macros>,
794}
795
796#[derive(Clone, Deserialize)]
797pub struct IambConfig {
798 pub profiles: BTreeMap<String, ProfileConfig>,
799 pub default_profile: Option<String>,
800 pub settings: Option<Tunables>,
801 pub dirs: Option<Directories>,
802 pub layout: Option<Layout>,
803 pub macros: Option<Macros>,
804}
805
806impl IambConfig {
807 pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
808 let s = std::fs::read_to_string(path)?;
809 let config = toml::from_str(&s)?;
810
811 Ok(config)
812 }
813
814 pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
815 let s = std::fs::read_to_string(path)?;
816 let config = serde_json::from_str(&s)?;
817
818 Ok(config)
819 }
820}
821
822#[derive(Clone)]
823pub struct ApplicationSettings {
824 pub layout_json: PathBuf,
825 pub session_json: PathBuf,
826 pub session_json_old: PathBuf,
827 pub sled_dir: PathBuf,
828 pub sqlite_dir: PathBuf,
829 pub profile_name: String,
830 pub profile: ProfileConfig,
831 pub tunables: TunableValues,
832 pub dirs: DirectoryValues,
833 pub layout: Layout,
834 pub macros: Macros,
835}
836
837impl ApplicationSettings {
838 pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
839 let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
840 usage!(
841 "No user configuration directory found;\
842 please specify one via -C.\n\n
843 For more information try '--help'"
844 );
845 });
846
847 config_dir.push("iamb");
848 let config_json = config_dir.join("config.json");
849 let config_toml = config_dir.join("config.toml");
850
851 let config = if config_toml.is_file() {
852 IambConfig::load_toml(config_toml.as_path())?
853 } else if config_json.is_file() {
854 IambConfig::load_json(config_json.as_path())?
855 } else {
856 usage!(
857 "Please create a configuration file at {}\n\n\
858 For more information try '--help'",
859 config_toml.display(),
860 );
861 };
862
863 let IambConfig {
864 mut profiles,
865 default_profile,
866 dirs,
867 settings: global,
868 layout,
869 macros,
870 } = config;
871
872 validate_profile_names(&profiles);
873
874 let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
875 profiles.remove_entry(&profile).unwrap_or_else(|| {
876 usage!(
877 "No configured profile with the name {:?} in {}",
878 profile,
879 config_json.display()
880 );
881 })
882 } else if profiles.len() == 1 {
883 profiles.into_iter().next().unwrap()
884 } else {
885 loop {
886 println!("\nNo profile specified. Available profiles:");
887 profiles
888 .keys()
889 .enumerate()
890 .for_each(|(i, name)| println!("{}: {}", i, name));
891
892 print!("Select a number or 'q' to quit: ");
893 let _ = std::io::stdout().flush();
894
895 let mut input = String::new();
896 let _ = std::io::stdin().read_line(&mut input);
897
898 if input.trim() == "q" {
899 usage!(
900 "No profile specified. \
901 Please use -P or add \"default_profile\" to your configuration.\n\n\
902 For more information try '--help'",
903 );
904 }
905 if let Ok(i) = input.trim().parse::<usize>() {
906 if i < profiles.len() {
907 break profiles.into_iter().nth(i).unwrap();
908 }
909 }
910 println!("\nInvalid index.");
911 }
912 };
913
914 let macros = merge_maps(macros, profile.macros.take()).unwrap_or_default();
915 let layout = profile.layout.take().or(layout).unwrap_or_default();
916
917 let tunables = global.unwrap_or_default();
918 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
919 let tunables = tunables.values();
920
921 let dirs = dirs.unwrap_or_default();
922 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
923 let dirs = dirs.values();
924
925 // Create directories
926 dirs.create_dir_all()?;
927
928 // Set up paths that live inside the profile's data directory.
929 let mut profile_dir = config_dir.clone();
930 profile_dir.push("profiles");
931 profile_dir.push(profile_name.as_str());
932
933 let mut profile_data_dir = dirs.data.clone();
934 profile_data_dir.push("profiles");
935 profile_data_dir.push(profile_name.as_str());
936
937 let mut sled_dir = profile_dir.clone();
938 sled_dir.push("matrix");
939
940 let mut sqlite_dir = profile_data_dir.clone();
941 sqlite_dir.push("sqlite");
942
943 let mut session_json = profile_data_dir.clone();
944 session_json.push("session.json");
945
946 let mut session_json_old = profile_dir;
947 session_json_old.push("session.json");
948
949 // Set up paths that live inside the profile's cache directory.
950 let mut cache_dir = dirs.cache.clone();
951 cache_dir.push("profiles");
952 cache_dir.push(profile_name.as_str());
953
954 let mut layout_json = cache_dir.clone();
955 layout_json.push("layout.json");
956
957 let settings = ApplicationSettings {
958 sled_dir,
959 layout_json,
960 session_json,
961 session_json_old,
962 sqlite_dir,
963 profile_name,
964 profile,
965 tunables,
966 dirs,
967 layout,
968 macros,
969 };
970
971 Ok(settings)
972 }
973
974 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
975 let file = File::open(path)?;
976 let reader = BufReader::new(file);
977 let session = serde_json::from_reader(reader).map_err(IambError::from)?;
978 Ok(session)
979 }
980
981 pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
982 let file = File::create(self.session_json.as_path())?;
983 let writer = BufWriter::new(file);
984 let session = Session::from(session);
985 serde_json::to_writer(writer, &session).map_err(IambError::from)?;
986 Ok(())
987 }
988
989 pub fn get_user_char_span(&self, user_id: &UserId) -> Span {
990 let (color, c) = self
991 .tunables
992 .users
993 .get(user_id)
994 .map(|user| {
995 (
996 user.color.as_ref().map(|c| c.0),
997 user.name.as_ref().and_then(|s| s.chars().next()),
998 )
999 })
1000 .unwrap_or_default();
1001
1002 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1003 let style = user_style_from_color(color);
1004
1005 let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
1006
1007 Span::styled(String::from(c), style)
1008 }
1009
1010 pub fn get_user_overrides(
1011 &self,
1012 user_id: &UserId,
1013 ) -> (Option<Color>, Option<Cow<'static, str>>) {
1014 self.tunables
1015 .users
1016 .get(user_id)
1017 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
1018 .unwrap_or_default()
1019 }
1020
1021 pub fn get_user_color(&self, user_id: &UserId) -> Color {
1022 self.tunables
1023 .users
1024 .get(user_id)
1025 .and_then(|user| user.color.as_ref().map(|c| c.0))
1026 .unwrap_or_else(|| user_color(user_id.as_str()))
1027 }
1028
1029 pub fn get_user_style(&self, user_id: &UserId) -> Style {
1030 user_style_from_color(self.get_user_color(user_id))
1031 }
1032
1033 pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
1034 let (color, name) = self.get_user_overrides(user_id);
1035
1036 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
1037 let style = user_style_from_color(color);
1038 let name = match (name, &self.tunables.username_display) {
1039 (Some(name), _) => name,
1040 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
1041 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
1042 (None, UserDisplayStyle::DisplayName) => {
1043 if let Some(display) = info.display_names.get(user_id) {
1044 Cow::Borrowed(display.as_str())
1045 } else {
1046 Cow::Borrowed(user_id.as_str())
1047 }
1048 },
1049 };
1050
1051 Span::styled(name, style)
1052 }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058 use matrix_sdk::ruma::user_id;
1059 use std::convert::TryFrom;
1060
1061 #[test]
1062 fn test_profile_name_invalid() {
1063 assert_eq!(validate_profile_name(""), false);
1064 assert_eq!(validate_profile_name(" "), false);
1065 assert_eq!(validate_profile_name("a b"), false);
1066 assert_eq!(validate_profile_name("foo^bar"), false);
1067 assert_eq!(validate_profile_name("FOO/BAR"), false);
1068 assert_eq!(validate_profile_name("-b-c"), false);
1069 assert_eq!(validate_profile_name("-B-c"), false);
1070 assert_eq!(validate_profile_name(".b-c"), false);
1071 assert_eq!(validate_profile_name(".B-c"), false);
1072 }
1073
1074 #[test]
1075 fn test_profile_name_valid() {
1076 assert_eq!(validate_profile_name("foo"), true);
1077 assert_eq!(validate_profile_name("FOO"), true);
1078 assert_eq!(validate_profile_name("a-b-c"), true);
1079 assert_eq!(validate_profile_name("a-B-c"), true);
1080 assert_eq!(validate_profile_name("a.b-c"), true);
1081 assert_eq!(validate_profile_name("a.B-c"), true);
1082 }
1083
1084 #[test]
1085 fn test_merge_users() {
1086 let a = None;
1087 let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1088 color: Some(UserColor(Color::Red)),
1089 name: Some("Hello".into()),
1090 })]
1091 .into_iter()
1092 .collect::<HashMap<_, _>>();
1093 let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1094 color: Some(UserColor(Color::Green)),
1095 name: Some("World".into()),
1096 })]
1097 .into_iter()
1098 .collect::<HashMap<_, _>>();
1099
1100 let res = merge_maps(a.clone(), a.clone());
1101 assert_eq!(res, None);
1102
1103 let res = merge_maps(a.clone(), Some(b.clone()));
1104 assert_eq!(res, Some(b.clone()));
1105
1106 let res = merge_maps(Some(b.clone()), a.clone());
1107 assert_eq!(res, Some(b.clone()));
1108
1109 let res = merge_maps(Some(b.clone()), Some(b.clone()));
1110 assert_eq!(res, Some(b.clone()));
1111
1112 let res = merge_maps(Some(b.clone()), Some(c.clone()));
1113 assert_eq!(res, Some(c.clone()));
1114
1115 let res = merge_maps(Some(c.clone()), Some(b.clone()));
1116 assert_eq!(res, Some(b.clone()));
1117 }
1118
1119 #[test]
1120 fn test_parse_tunables() {
1121 let res: Tunables = serde_json::from_str("{}").unwrap();
1122 assert_eq!(res.typing_notice_send, None);
1123 assert_eq!(res.typing_notice_display, None);
1124 assert_eq!(res.users, None);
1125
1126 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1127 assert_eq!(res.typing_notice_send, Some(true));
1128 assert_eq!(res.typing_notice_display, None);
1129 assert_eq!(res.users, None);
1130
1131 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1132 assert_eq!(res.typing_notice_send, Some(false));
1133 assert_eq!(res.typing_notice_display, None);
1134 assert_eq!(res.users, None);
1135
1136 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1137 assert_eq!(res.typing_notice_send, None);
1138 assert_eq!(res.typing_notice_display, None);
1139 assert_eq!(res.users, Some(HashMap::new()));
1140
1141 let res: Tunables = serde_json::from_str(
1142 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1143 )
1144 .unwrap();
1145 assert_eq!(res.typing_notice_send, None);
1146 assert_eq!(res.typing_notice_display, None);
1147 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1148 color: Some(UserColor(Color::Black)),
1149 name: Some("Tim".into()),
1150 })];
1151 assert_eq!(res.users, Some(users.into_iter().collect()));
1152 }
1153
1154 #[test]
1155 fn test_parse_tunables_username_display() {
1156 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1157 assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1158
1159 let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1160 assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1161
1162 let res: Tunables =
1163 serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1164 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1165 }
1166
1167 #[test]
1168 fn test_parse_tunables_sort() {
1169 let res: Tunables = serde_json::from_str(
1170 r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1171 )
1172 .unwrap();
1173 assert_eq!(
1174 res.sort.members,
1175 Some(vec![
1176 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1177 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1178 ])
1179 );
1180 assert_eq!(
1181 res.sort.spaces,
1182 Some(vec![
1183 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1184 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1185 ])
1186 );
1187 assert_eq!(res.sort.rooms, None);
1188 assert_eq!(res.sort.dms, None);
1189
1190 // Check that we get the right default "rooms" and "dms" values.
1191 let res = res.values();
1192 assert_eq!(res.sort.members, vec![
1193 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1194 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1195 ]);
1196 assert_eq!(res.sort.spaces, vec![
1197 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1198 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1199 ]);
1200 assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1201 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1202 }
1203
1204 #[test]
1205 fn test_parse_layout() {
1206 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1207 let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1208 let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1209 let dms = WindowPath::Window(IambId::DirectList);
1210 let welcome = WindowPath::Window(IambId::Welcome);
1211
1212 let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1213 assert_eq!(res, Layout::Restore);
1214
1215 let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1216 assert_eq!(res, Layout::New);
1217
1218 let res: Layout = serde_json::from_str(
1219 "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1220 )
1221 .unwrap();
1222 assert_eq!(res, Layout::Config {
1223 tabs: vec![WindowLayout::Window { window: user.clone() }]
1224 });
1225
1226 let res: Layout = serde_json::from_str(
1227 "{\
1228 \"style\": \"config\",\
1229 \"tabs\": [\
1230 {\"split\":[\
1231 {\"window\":\"@user:example.com\"},\
1232 {\"window\":\"#room:example.com\"}\
1233 ]},\
1234 {\"split\":[\
1235 {\"window\":\"!room:example.com\"},\
1236 {\"split\":[\
1237 {\"window\":\"iamb://dms\"},\
1238 {\"window\":\"iamb://welcome\"}\
1239 ]}\
1240 ]}\
1241 ]}",
1242 )
1243 .unwrap();
1244 let split1 = WindowLayout::Split {
1245 split: vec![
1246 WindowLayout::Window { window: user.clone() },
1247 WindowLayout::Window { window: alias },
1248 ],
1249 };
1250 let split2 = WindowLayout::Split {
1251 split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1252 window: welcome,
1253 }],
1254 };
1255 let split3 = WindowLayout::Split {
1256 split: vec![WindowLayout::Window { window: room }, split2],
1257 };
1258 let tabs = vec![split1, split3];
1259 assert_eq!(res, Layout::Config { tabs });
1260 }
1261
1262 #[test]
1263 fn test_parse_macros() {
1264 let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1265 assert_eq!(res.len(), 1);
1266
1267 let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1268 let mapped = res.get(&modes).unwrap();
1269 assert_eq!(mapped.len(), 1);
1270
1271 let j = "j".parse::<TerminalKey>().unwrap();
1272 let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1273
1274 let jj = Keys(vec![j, j], "jj".into());
1275 let run = mapped.get(&jj).unwrap();
1276 let exp = Keys(vec![esc], "<Esc>".into());
1277 assert_eq!(run, &exp);
1278 }
1279
1280 #[test]
1281 fn test_parse_notify_via() {
1282 assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
1283 assert_eq!(
1284 NotifyVia { bell: false, desktop: true },
1285 serde_json::from_str(r#""desktop""#).unwrap()
1286 );
1287 assert_eq!(
1288 NotifyVia { bell: true, desktop: false },
1289 serde_json::from_str(r#""bell""#).unwrap()
1290 );
1291 assert_eq!(
1292 NotifyVia { bell: true, desktop: true },
1293 serde_json::from_str(r#""bell|desktop""#).unwrap()
1294 );
1295 assert_eq!(
1296 NotifyVia { bell: true, desktop: true },
1297 serde_json::from_str(r#""desktop|bell""#).unwrap()
1298 );
1299 assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
1300 assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
1301 }
1302
1303 #[test]
1304 fn test_load_example_config_toml() {
1305 let path = PathBuf::from("config.example.toml");
1306 let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1307
1308 let IambConfig {
1309 profiles,
1310 default_profile,
1311 settings,
1312 dirs,
1313 layout,
1314 macros,
1315 } = &config;
1316
1317 // There should be an example object for each top-level field.
1318 assert!(!profiles.is_empty());
1319 assert!(default_profile.is_some());
1320 assert!(settings.is_some());
1321 assert!(dirs.is_some());
1322 assert!(layout.is_some());
1323 assert!(macros.is_some());
1324 }
1325}