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