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