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