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