src/config.rs
1195 lines · 38660 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, Default, 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 #[default]
408 Desktop,
409}
410
411#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
412pub struct Notifications {
413 #[serde(default)]
414 pub enabled: bool,
415 #[serde(default)]
416 pub via: NotifyVia,
417 #[serde(default = "default_true")]
418 pub show_message: bool,
419}
420
421#[derive(Clone)]
422pub struct ImagePreviewValues {
423 pub size: ImagePreviewSize,
424 pub protocol: Option<ImagePreviewProtocolValues>,
425}
426
427#[derive(Clone, Default, Deserialize)]
428pub struct ImagePreview {
429 pub size: Option<ImagePreviewSize>,
430 pub protocol: Option<ImagePreviewProtocolValues>,
431}
432
433impl ImagePreview {
434 fn values(self) -> ImagePreviewValues {
435 ImagePreviewValues {
436 size: self.size.unwrap_or_default(),
437 protocol: self.protocol,
438 }
439 }
440}
441
442#[derive(Clone, Deserialize)]
443pub struct ImagePreviewSize {
444 pub width: usize,
445 pub height: usize,
446}
447
448impl Default for ImagePreviewSize {
449 fn default() -> Self {
450 ImagePreviewSize { width: 66, height: 10 }
451 }
452}
453
454#[derive(Clone, Deserialize)]
455pub struct ImagePreviewProtocolValues {
456 pub r#type: Option<ProtocolType>,
457 pub font_size: Option<(u16, u16)>,
458}
459
460#[derive(Clone)]
461pub struct SortValues {
462 pub chats: Vec<SortColumn<SortFieldRoom>>,
463 pub dms: Vec<SortColumn<SortFieldRoom>>,
464 pub rooms: Vec<SortColumn<SortFieldRoom>>,
465 pub spaces: Vec<SortColumn<SortFieldRoom>>,
466 pub members: Vec<SortColumn<SortFieldUser>>,
467}
468
469#[derive(Clone, Default, Deserialize)]
470pub struct SortOverrides {
471 pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
472 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
473 pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
474 pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
475 pub members: Option<Vec<SortColumn<SortFieldUser>>>,
476}
477
478impl SortOverrides {
479 pub fn values(self) -> SortValues {
480 let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
481 let chats = self.chats.unwrap_or_else(|| rooms.clone());
482 let dms = self.dms.unwrap_or_else(|| rooms.clone());
483 let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
484 let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));
485
486 SortValues { rooms, members, chats, dms, spaces }
487 }
488}
489
490#[derive(Clone)]
491pub struct TunableValues {
492 pub log_level: Level,
493 pub message_shortcode_display: bool,
494 pub reaction_display: bool,
495 pub reaction_shortcode_display: bool,
496 pub read_receipt_send: bool,
497 pub read_receipt_display: bool,
498 pub request_timeout: u64,
499 pub sort: SortValues,
500 pub typing_notice_send: bool,
501 pub typing_notice_display: bool,
502 pub users: UserOverrides,
503 pub username_display: UserDisplayStyle,
504 pub message_user_color: bool,
505 pub default_room: Option<String>,
506 pub open_command: Option<Vec<String>>,
507 pub notifications: Notifications,
508 pub image_preview: Option<ImagePreviewValues>,
509 pub user_gutter_width: usize,
510}
511
512#[derive(Clone, Default, Deserialize)]
513pub struct Tunables {
514 pub log_level: Option<LogLevel>,
515 pub message_shortcode_display: Option<bool>,
516 pub reaction_display: Option<bool>,
517 pub reaction_shortcode_display: Option<bool>,
518 pub read_receipt_send: Option<bool>,
519 pub read_receipt_display: Option<bool>,
520 pub request_timeout: Option<u64>,
521 #[serde(default)]
522 pub sort: SortOverrides,
523 pub typing_notice_send: Option<bool>,
524 pub typing_notice_display: Option<bool>,
525 pub users: Option<UserOverrides>,
526 pub username_display: Option<UserDisplayStyle>,
527 pub message_user_color: Option<bool>,
528 pub default_room: Option<String>,
529 pub open_command: Option<Vec<String>>,
530 pub notifications: Option<Notifications>,
531 pub image_preview: Option<ImagePreview>,
532 pub user_gutter_width: Option<usize>,
533}
534
535impl Tunables {
536 fn merge(self, other: Self) -> Self {
537 Tunables {
538 log_level: self.log_level.or(other.log_level),
539 message_shortcode_display: self
540 .message_shortcode_display
541 .or(other.message_shortcode_display),
542 reaction_display: self.reaction_display.or(other.reaction_display),
543 reaction_shortcode_display: self
544 .reaction_shortcode_display
545 .or(other.reaction_shortcode_display),
546 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
547 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
548 request_timeout: self.request_timeout.or(other.request_timeout),
549 sort: merge_sorts(self.sort, other.sort),
550 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
551 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
552 users: merge_maps(self.users, other.users),
553 username_display: self.username_display.or(other.username_display),
554 message_user_color: self.message_user_color.or(other.message_user_color),
555 default_room: self.default_room.or(other.default_room),
556 open_command: self.open_command.or(other.open_command),
557 notifications: self.notifications.or(other.notifications),
558 image_preview: self.image_preview.or(other.image_preview),
559 user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
560 }
561 }
562
563 fn values(self) -> TunableValues {
564 TunableValues {
565 log_level: self.log_level.map(Level::from).unwrap_or(Level::INFO),
566 message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
567 reaction_display: self.reaction_display.unwrap_or(true),
568 reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
569 read_receipt_send: self.read_receipt_send.unwrap_or(true),
570 read_receipt_display: self.read_receipt_display.unwrap_or(true),
571 request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
572 sort: self.sort.values(),
573 typing_notice_send: self.typing_notice_send.unwrap_or(true),
574 typing_notice_display: self.typing_notice_display.unwrap_or(true),
575 users: self.users.unwrap_or_default(),
576 username_display: self.username_display.unwrap_or_default(),
577 message_user_color: self.message_user_color.unwrap_or(false),
578 default_room: self.default_room,
579 open_command: self.open_command,
580 notifications: self.notifications.unwrap_or_default(),
581 image_preview: self.image_preview.map(ImagePreview::values),
582 user_gutter_width: self.user_gutter_width.unwrap_or(30),
583 }
584 }
585}
586
587#[derive(Clone)]
588pub struct DirectoryValues {
589 pub cache: PathBuf,
590 pub data: PathBuf,
591 pub logs: PathBuf,
592 pub downloads: Option<PathBuf>,
593 pub image_previews: PathBuf,
594}
595
596impl DirectoryValues {
597 fn create_dir_all(&self) -> std::io::Result<()> {
598 use std::fs::create_dir_all;
599
600 let Self { cache, data, logs, downloads, image_previews } = self;
601
602 create_dir_all(cache)?;
603 create_dir_all(data)?;
604 create_dir_all(logs)?;
605 create_dir_all(image_previews)?;
606
607 if let Some(downloads) = downloads {
608 create_dir_all(downloads)?;
609 }
610
611 Ok(())
612 }
613}
614
615#[derive(Clone, Default, Deserialize)]
616pub struct Directories {
617 pub cache: Option<PathBuf>,
618 pub data: Option<PathBuf>,
619 pub logs: Option<PathBuf>,
620 pub downloads: Option<PathBuf>,
621 pub image_previews: Option<PathBuf>,
622}
623
624impl Directories {
625 fn merge(self, other: Self) -> Self {
626 Directories {
627 cache: self.cache.or(other.cache),
628 data: self.data.or(other.data),
629 logs: self.logs.or(other.logs),
630 downloads: self.downloads.or(other.downloads),
631 image_previews: self.image_previews.or(other.image_previews),
632 }
633 }
634
635 fn values(self) -> DirectoryValues {
636 let cache = self
637 .cache
638 .or_else(|| {
639 let mut dir = dirs::cache_dir()?;
640 dir.push("iamb");
641 dir.into()
642 })
643 .expect("no dirs.cache value configured!");
644
645 let data = self
646 .data
647 .or_else(|| {
648 let mut dir = dirs::data_dir()?;
649 dir.push("iamb");
650 dir.into()
651 })
652 .expect("no dirs.data value configured!");
653
654 let logs = self.logs.unwrap_or_else(|| {
655 let mut dir = cache.clone();
656 dir.push("logs");
657 dir
658 });
659
660 let downloads = self.downloads.or_else(dirs::download_dir);
661
662 let image_previews = self.image_previews.unwrap_or_else(|| {
663 let mut dir = cache.clone();
664 dir.push("image_preview_downloads");
665 dir
666 });
667
668 DirectoryValues { cache, data, logs, downloads, image_previews }
669 }
670}
671
672#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
673#[serde(untagged)]
674pub enum WindowPath {
675 AliasId(OwnedRoomAliasId),
676 RoomId(OwnedRoomId),
677 UserId(OwnedUserId),
678 Window(IambId),
679}
680
681#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
682#[serde(untagged, deny_unknown_fields)]
683pub enum WindowLayout {
684 Window { window: WindowPath },
685 Split { split: Vec<WindowLayout> },
686}
687
688#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
689#[serde(rename_all = "lowercase", tag = "style")]
690pub enum Layout {
691 /// Restore the layout from the previous session.
692 #[default]
693 Restore,
694
695 /// Open a single window using the `default_room` value.
696 New,
697
698 /// Open the window layouts described under `tabs`.
699 Config { tabs: Vec<WindowLayout> },
700}
701
702#[derive(Clone, Deserialize)]
703pub struct ProfileConfig {
704 pub user_id: OwnedUserId,
705 pub url: Option<Url>,
706 pub settings: Option<Tunables>,
707 pub dirs: Option<Directories>,
708 pub layout: Option<Layout>,
709 pub macros: Option<Macros>,
710}
711
712#[derive(Clone, Deserialize)]
713pub struct IambConfig {
714 pub profiles: HashMap<String, ProfileConfig>,
715 pub default_profile: Option<String>,
716 pub settings: Option<Tunables>,
717 pub dirs: Option<Directories>,
718 pub layout: Option<Layout>,
719 pub macros: Option<Macros>,
720}
721
722impl IambConfig {
723 pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
724 let s = std::fs::read_to_string(path)?;
725 let config = toml::from_str(&s)?;
726
727 Ok(config)
728 }
729
730 pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
731 let s = std::fs::read_to_string(path)?;
732 let config = serde_json::from_str(&s)?;
733
734 Ok(config)
735 }
736}
737
738#[derive(Clone)]
739pub struct ApplicationSettings {
740 pub layout_json: PathBuf,
741 pub session_json: PathBuf,
742 pub session_json_old: PathBuf,
743 pub sled_dir: PathBuf,
744 pub sqlite_dir: PathBuf,
745 pub profile_name: String,
746 pub profile: ProfileConfig,
747 pub tunables: TunableValues,
748 pub dirs: DirectoryValues,
749 pub layout: Layout,
750 pub macros: Macros,
751}
752
753impl ApplicationSettings {
754 pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
755 let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
756 usage!(
757 "No user configuration directory found;\
758 please specify one via -C.\n\n
759 For more information try '--help'"
760 );
761 });
762
763 config_dir.push("iamb");
764 let config_json = config_dir.join("config.json");
765 let config_toml = config_dir.join("config.toml");
766
767 let config = if config_toml.is_file() {
768 IambConfig::load_toml(config_toml.as_path())?
769 } else if config_json.is_file() {
770 IambConfig::load_json(config_json.as_path())?
771 } else {
772 usage!(
773 "Please create a configuration file at {}\n\n\
774 For more information try '--help'",
775 config_toml.display(),
776 );
777 };
778
779 let IambConfig {
780 mut profiles,
781 default_profile,
782 dirs,
783 settings: global,
784 layout,
785 macros,
786 } = config;
787
788 validate_profile_names(&profiles);
789
790 let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
791 profiles.remove_entry(&profile).unwrap_or_else(|| {
792 usage!(
793 "No configured profile with the name {:?} in {}",
794 profile,
795 config_json.display()
796 );
797 })
798 } else if profiles.len() == 1 {
799 profiles.into_iter().next().unwrap()
800 } else {
801 usage!(
802 "No profile specified. \
803 Please use -P or add \"default_profile\" to your configuration.\n\n\
804 For more information try '--help'",
805 );
806 };
807
808 let macros = merge_maps(macros, profile.macros.take()).unwrap_or_default();
809 let layout = profile.layout.take().or(layout).unwrap_or_default();
810
811 let tunables = global.unwrap_or_default();
812 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
813 let tunables = tunables.values();
814
815 let dirs = dirs.unwrap_or_default();
816 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
817 let dirs = dirs.values();
818
819 // Create directories
820 dirs.create_dir_all()?;
821
822 // Set up paths that live inside the profile's data directory.
823 let mut profile_dir = config_dir.clone();
824 profile_dir.push("profiles");
825 profile_dir.push(profile_name.as_str());
826
827 let mut profile_data_dir = dirs.data.clone();
828 profile_data_dir.push("profiles");
829 profile_data_dir.push(profile_name.as_str());
830
831 let mut sled_dir = profile_dir.clone();
832 sled_dir.push("matrix");
833
834 let mut sqlite_dir = profile_data_dir.clone();
835 sqlite_dir.push("sqlite");
836
837 let mut session_json = profile_data_dir.clone();
838 session_json.push("session.json");
839
840 let mut session_json_old = profile_dir;
841 session_json_old.push("session.json");
842
843 // Set up paths that live inside the profile's cache directory.
844 let mut cache_dir = dirs.cache.clone();
845 cache_dir.push("profiles");
846 cache_dir.push(profile_name.as_str());
847
848 let mut layout_json = cache_dir.clone();
849 layout_json.push("layout.json");
850
851 let settings = ApplicationSettings {
852 sled_dir,
853 layout_json,
854 session_json,
855 session_json_old,
856 sqlite_dir,
857 profile_name,
858 profile,
859 tunables,
860 dirs,
861 layout,
862 macros,
863 };
864
865 Ok(settings)
866 }
867
868 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
869 let file = File::open(path)?;
870 let reader = BufReader::new(file);
871 let session = serde_json::from_reader(reader).map_err(IambError::from)?;
872 Ok(session)
873 }
874
875 pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
876 let file = File::create(self.session_json.as_path())?;
877 let writer = BufWriter::new(file);
878 let session = Session::from(session);
879 serde_json::to_writer(writer, &session).map_err(IambError::from)?;
880 Ok(())
881 }
882
883 pub fn get_user_char_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
884 let (color, c) = self
885 .tunables
886 .users
887 .get(user_id)
888 .map(|user| {
889 (
890 user.color.as_ref().map(|c| c.0),
891 user.name.as_ref().and_then(|s| s.chars().next()),
892 )
893 })
894 .unwrap_or_default();
895
896 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
897 let style = user_style_from_color(color);
898
899 let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
900
901 Span::styled(String::from(c), style)
902 }
903
904 pub fn get_user_overrides(
905 &self,
906 user_id: &UserId,
907 ) -> (Option<Color>, Option<Cow<'static, str>>) {
908 self.tunables
909 .users
910 .get(user_id)
911 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
912 .unwrap_or_default()
913 }
914
915 pub fn get_user_style(&self, user_id: &UserId) -> Style {
916 let color = self
917 .tunables
918 .users
919 .get(user_id)
920 .and_then(|user| user.color.as_ref().map(|c| c.0))
921 .unwrap_or_else(|| user_color(user_id.as_str()));
922
923 user_style_from_color(color)
924 }
925
926 pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
927 let (color, name) = self.get_user_overrides(user_id);
928
929 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
930 let style = user_style_from_color(color);
931 let name = match (name, &self.tunables.username_display) {
932 (Some(name), _) => name,
933 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
934 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
935 (None, UserDisplayStyle::DisplayName) => {
936 if let Some(display) = info.display_names.get(user_id) {
937 Cow::Borrowed(display.as_str())
938 } else {
939 Cow::Borrowed(user_id.as_str())
940 }
941 },
942 };
943
944 Span::styled(name, style)
945 }
946}
947
948#[cfg(test)]
949mod tests {
950 use super::*;
951 use matrix_sdk::ruma::user_id;
952 use std::convert::TryFrom;
953
954 #[test]
955 fn test_profile_name_invalid() {
956 assert_eq!(validate_profile_name(""), false);
957 assert_eq!(validate_profile_name(" "), false);
958 assert_eq!(validate_profile_name("a b"), false);
959 assert_eq!(validate_profile_name("foo^bar"), false);
960 assert_eq!(validate_profile_name("FOO/BAR"), false);
961 assert_eq!(validate_profile_name("-b-c"), false);
962 assert_eq!(validate_profile_name("-B-c"), false);
963 assert_eq!(validate_profile_name(".b-c"), false);
964 assert_eq!(validate_profile_name(".B-c"), false);
965 }
966
967 #[test]
968 fn test_profile_name_valid() {
969 assert_eq!(validate_profile_name("foo"), true);
970 assert_eq!(validate_profile_name("FOO"), true);
971 assert_eq!(validate_profile_name("a-b-c"), true);
972 assert_eq!(validate_profile_name("a-B-c"), true);
973 assert_eq!(validate_profile_name("a.b-c"), true);
974 assert_eq!(validate_profile_name("a.B-c"), true);
975 }
976
977 #[test]
978 fn test_merge_users() {
979 let a = None;
980 let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
981 color: Some(UserColor(Color::Red)),
982 name: Some("Hello".into()),
983 })]
984 .into_iter()
985 .collect::<HashMap<_, _>>();
986 let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
987 color: Some(UserColor(Color::Green)),
988 name: Some("World".into()),
989 })]
990 .into_iter()
991 .collect::<HashMap<_, _>>();
992
993 let res = merge_maps(a.clone(), a.clone());
994 assert_eq!(res, None);
995
996 let res = merge_maps(a.clone(), Some(b.clone()));
997 assert_eq!(res, Some(b.clone()));
998
999 let res = merge_maps(Some(b.clone()), a.clone());
1000 assert_eq!(res, Some(b.clone()));
1001
1002 let res = merge_maps(Some(b.clone()), Some(b.clone()));
1003 assert_eq!(res, Some(b.clone()));
1004
1005 let res = merge_maps(Some(b.clone()), Some(c.clone()));
1006 assert_eq!(res, Some(c.clone()));
1007
1008 let res = merge_maps(Some(c.clone()), Some(b.clone()));
1009 assert_eq!(res, Some(b.clone()));
1010 }
1011
1012 #[test]
1013 fn test_parse_tunables() {
1014 let res: Tunables = serde_json::from_str("{}").unwrap();
1015 assert_eq!(res.typing_notice_send, None);
1016 assert_eq!(res.typing_notice_display, None);
1017 assert_eq!(res.users, None);
1018
1019 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
1020 assert_eq!(res.typing_notice_send, Some(true));
1021 assert_eq!(res.typing_notice_display, None);
1022 assert_eq!(res.users, None);
1023
1024 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
1025 assert_eq!(res.typing_notice_send, Some(false));
1026 assert_eq!(res.typing_notice_display, None);
1027 assert_eq!(res.users, None);
1028
1029 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
1030 assert_eq!(res.typing_notice_send, None);
1031 assert_eq!(res.typing_notice_display, None);
1032 assert_eq!(res.users, Some(HashMap::new()));
1033
1034 let res: Tunables = serde_json::from_str(
1035 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
1036 )
1037 .unwrap();
1038 assert_eq!(res.typing_notice_send, None);
1039 assert_eq!(res.typing_notice_display, None);
1040 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
1041 color: Some(UserColor(Color::Black)),
1042 name: Some("Tim".into()),
1043 })];
1044 assert_eq!(res.users, Some(users.into_iter().collect()));
1045 }
1046
1047 #[test]
1048 fn test_parse_tunables_username_display() {
1049 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
1050 assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
1051
1052 let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
1053 assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
1054
1055 let res: Tunables =
1056 serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
1057 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
1058 }
1059
1060 #[test]
1061 fn test_parse_tunables_sort() {
1062 let res: Tunables = serde_json::from_str(
1063 r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
1064 )
1065 .unwrap();
1066 assert_eq!(
1067 res.sort.members,
1068 Some(vec![
1069 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1070 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1071 ])
1072 );
1073 assert_eq!(
1074 res.sort.spaces,
1075 Some(vec![
1076 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1077 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1078 ])
1079 );
1080 assert_eq!(res.sort.rooms, None);
1081 assert_eq!(res.sort.dms, None);
1082
1083 // Check that we get the right default "rooms" and "dms" values.
1084 let res = res.values();
1085 assert_eq!(res.sort.members, vec![
1086 SortColumn(SortFieldUser::Server, SortOrder::Ascending),
1087 SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
1088 ]);
1089 assert_eq!(res.sort.spaces, vec![
1090 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1091 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1092 ]);
1093 assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
1094 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1095 }
1096
1097 #[test]
1098 fn test_parse_layout() {
1099 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
1100 let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
1101 let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
1102 let dms = WindowPath::Window(IambId::DirectList);
1103 let welcome = WindowPath::Window(IambId::Welcome);
1104
1105 let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
1106 assert_eq!(res, Layout::Restore);
1107
1108 let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
1109 assert_eq!(res, Layout::New);
1110
1111 let res: Layout = serde_json::from_str(
1112 "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
1113 )
1114 .unwrap();
1115 assert_eq!(res, Layout::Config {
1116 tabs: vec![WindowLayout::Window { window: user.clone() }]
1117 });
1118
1119 let res: Layout = serde_json::from_str(
1120 "{\
1121 \"style\": \"config\",\
1122 \"tabs\": [\
1123 {\"split\":[\
1124 {\"window\":\"@user:example.com\"},\
1125 {\"window\":\"#room:example.com\"}\
1126 ]},\
1127 {\"split\":[\
1128 {\"window\":\"!room:example.com\"},\
1129 {\"split\":[\
1130 {\"window\":\"iamb://dms\"},\
1131 {\"window\":\"iamb://welcome\"}\
1132 ]}\
1133 ]}\
1134 ]}",
1135 )
1136 .unwrap();
1137 let split1 = WindowLayout::Split {
1138 split: vec![
1139 WindowLayout::Window { window: user.clone() },
1140 WindowLayout::Window { window: alias },
1141 ],
1142 };
1143 let split2 = WindowLayout::Split {
1144 split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
1145 window: welcome,
1146 }],
1147 };
1148 let split3 = WindowLayout::Split {
1149 split: vec![WindowLayout::Window { window: room }, split2],
1150 };
1151 let tabs = vec![split1, split3];
1152 assert_eq!(res, Layout::Config { tabs });
1153 }
1154
1155 #[test]
1156 fn test_parse_macros() {
1157 let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
1158 assert_eq!(res.len(), 1);
1159
1160 let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
1161 let mapped = res.get(&modes).unwrap();
1162 assert_eq!(mapped.len(), 1);
1163
1164 let j = "j".parse::<TerminalKey>().unwrap();
1165 let esc = "<Esc>".parse::<TerminalKey>().unwrap();
1166
1167 let jj = Keys(vec![j.clone(), j], "jj".into());
1168 let run = mapped.get(&jj).unwrap();
1169 let exp = Keys(vec![esc], "<Esc>".into());
1170 assert_eq!(run, &exp);
1171 }
1172
1173 #[test]
1174 fn test_load_example_config_toml() {
1175 let path = PathBuf::from("config.example.toml");
1176 let config = IambConfig::load_toml(&path).expect("can load example_config.toml");
1177
1178 let IambConfig {
1179 profiles,
1180 default_profile,
1181 settings,
1182 dirs,
1183 layout,
1184 macros,
1185 } = &config;
1186
1187 // There should be an example object for each top-level field.
1188 assert!(!profiles.is_empty());
1189 assert!(default_profile.is_some());
1190 assert!(settings.is_some());
1191 assert!(dirs.is_some());
1192 assert!(layout.is_some());
1193 assert!(macros.is_some());
1194 }
1195}